text stringlengths 54 60.6k |
|---|
<commit_before>/** \file flag_records_as_available_in_tuebingen.cc
* \author Johannes Riedl
* \author Dr. Johannes Ruscheinski
*
* Adds an ITA field with a $a subfield set to "1", if a record represents an object that is
* available in Tübingen.
*/
/*
Copyright (C) 2017-2018, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <iostream>
#include <cstring>
#include "Compiler.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " spr_augmented_marc_input marc_output\n";
std::cerr << " Notice that this program requires the SPR tag for superior works\n";
std::cerr << " to be set for appropriate results\n\n";
std::exit(EXIT_FAILURE);
}
void ProcessSuperiorRecord(const MARC::Record &record, RegexMatcher * const tue_sigil_matcher,
std::unordered_set<std::string> * const de21_superior_ppns, unsigned * const extracted_count)
{
// We are done if this is not a superior work
if (not record.hasFieldWithTag("SPR"))
return;
std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> local_block_boundaries;
record.findAllLocalDataBlocks(&local_block_boundaries);
for (const auto &block_start_and_end : local_block_boundaries) {
for (const auto &field : record.findFieldsInLocalBlock("852", block_start_and_end.first)) {
std::string sigil;
if (field.extractSubfieldWithPattern('a', *tue_sigil_matcher, &sigil)) {
de21_superior_ppns->insert(record.getControlNumber());
++*extracted_count;
}
}
}
}
void LoadDE21PPNs(MARC::Reader * const marc_reader, RegexMatcher * const tue_sigil_matcher, std::unordered_set<std::string> * const de21_superior_ppns,
unsigned * const extracted_count)
{
while (const MARC::Record record = marc_reader->read())
ProcessSuperiorRecord(record, tue_sigil_matcher, de21_superior_ppns, extracted_count);
LOG_DEBUG("Finished extracting " + std::to_string(*extracted_count) + " superior records");
}
void CollectSuperiorPPNs(const MARC::Record &record, std::unordered_set<std::string> * const superior_ppn_set) {
static RegexMatcher * const superior_ppn_matcher(RegexMatcher::RegexMatcherFactory(".DE-576.(.*)"));
// Determine superior PPNs from 800w:810w:830w:773w:776w
const std::vector<std::string> tags({ "800", "810", "830", "773", "776" });
for (const auto &tag : tags) {
std::vector<std::string> superior_ppn_vector;
const auto field(record.findTag(tag));
if (field != record.end()) {
// Remove superfluous prefixes
for (auto &superior_ppn : field->getSubfields().extractSubfields('w')) {
std::string err_msg;
if (not superior_ppn_matcher->matched(superior_ppn, &err_msg)) {
if (not err_msg.empty())
LOG_ERROR("Error with regex für superior works " + err_msg);
continue;
}
superior_ppn = (*superior_ppn_matcher)[1];
}
std::copy(superior_ppn_vector.begin(), superior_ppn_vector.end(), std::inserter(*superior_ppn_set,
superior_ppn_set->end()));
}
}
}
void FlagRecordAsInTuebingenAvailable(MARC::Record * const record, unsigned * const modified_count) {
record->insertField("ITA", { { 'a', "1" } });
++*modified_count;
}
bool AlreadyHasLOK852DE21(const MARC::Record &record, RegexMatcher * const tue_sigil_matcher) {
std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> local_block_boundaries;
if (record.findAllLocalDataBlocks(&local_block_boundaries) == 0)
return false;
for (const auto &block_start_and_end : local_block_boundaries) {
for (const auto &field : record.findFieldsInLocalBlock("852", block_start_and_end.first)) {
std::string sigil;
if (field.extractSubfieldWithPattern('a', *tue_sigil_matcher, &sigil)) {
return true;
}
}
}
return false;
}
void ProcessRecord(MARC::Record * const record, MARC::Writer * const marc_writer, RegexMatcher * const tue_sigil_matcher,
std::unordered_set<std::string> * const de21_superior_ppns, unsigned * const modified_count) {
if (AlreadyHasLOK852DE21(*record, tue_sigil_matcher)) {
FlagRecordAsInTuebingenAvailable(record, modified_count);
marc_writer->write(*record);
return;
}
if (not record->isArticle()) {
marc_writer->write(*record);
return;
}
std::unordered_set<std::string> superior_ppn_set;
CollectSuperiorPPNs(*record, &superior_ppn_set);
// Do we have superior PPN that has DE-21
for (const auto &superior_ppn : superior_ppn_set) {
if (de21_superior_ppns->find(superior_ppn) != de21_superior_ppns->end()) {
FlagRecordAsInTuebingenAvailable(record, modified_count);
marc_writer->write(*record);
return;
}
}
marc_writer->write(*record);
}
void AugmentRecords(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
RegexMatcher * const tue_sigil_matcher, std::unordered_set<std::string> * const de21_superior_ppn,
unsigned * const extracted_count, unsigned * const modified_count) {
marc_reader->rewind();
while (MARC::Record record = marc_reader->read())
ProcessRecord(&record, marc_writer, tue_sigil_matcher, de21_superior_ppn, modified_count);
LOG_INFO("Extracted " + std::to_string(*extracted_count) + " superior PPNs with DE-21 and modified "
+ std::to_string(*modified_count) + " records");
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc != 3)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string marc_output_filename(argv[2]);
const std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename));
const std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename));
unsigned extracted_count(0), modified_count(0);
const std::unique_ptr<RegexMatcher> tue_sigil_matcher(RegexMatcher::RegexMatcherFactory("^DE-21.*"));
std::unordered_set<std::string> de21_superior_ppns;
LoadDE21PPNs(marc_reader.get(), tue_sigil_matcher.get(), &de21_superior_ppns, &extracted_count);
AugmentRecords(marc_reader.get(), marc_writer.get(), tue_sigil_matcher.get(), &de21_superior_ppns, &extracted_count, &modified_count);
return EXIT_SUCCESS;
}
<commit_msg>Make tag vector static<commit_after>/** \file flag_records_as_available_in_tuebingen.cc
* \author Johannes Riedl
* \author Dr. Johannes Ruscheinski
*
* Adds an ITA field with a $a subfield set to "1", if a record represents an object that is
* available in Tübingen.
*/
/*
Copyright (C) 2017-2018, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <iostream>
#include <cstring>
#include "Compiler.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " spr_augmented_marc_input marc_output\n";
std::cerr << " Notice that this program requires the SPR tag for superior works\n";
std::cerr << " to be set for appropriate results\n\n";
std::exit(EXIT_FAILURE);
}
void ProcessSuperiorRecord(const MARC::Record &record, RegexMatcher * const tue_sigil_matcher,
std::unordered_set<std::string> * const de21_superior_ppns, unsigned * const extracted_count)
{
// We are done if this is not a superior work
if (not record.hasFieldWithTag("SPR"))
return;
std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> local_block_boundaries;
record.findAllLocalDataBlocks(&local_block_boundaries);
for (const auto &block_start_and_end : local_block_boundaries) {
for (const auto &field : record.findFieldsInLocalBlock("852", block_start_and_end.first)) {
std::string sigil;
if (field.extractSubfieldWithPattern('a', *tue_sigil_matcher, &sigil)) {
de21_superior_ppns->insert(record.getControlNumber());
++*extracted_count;
}
}
}
}
void LoadDE21PPNs(MARC::Reader * const marc_reader, RegexMatcher * const tue_sigil_matcher, std::unordered_set<std::string> * const de21_superior_ppns,
unsigned * const extracted_count)
{
while (const MARC::Record record = marc_reader->read())
ProcessSuperiorRecord(record, tue_sigil_matcher, de21_superior_ppns, extracted_count);
LOG_DEBUG("Finished extracting " + std::to_string(*extracted_count) + " superior records");
}
void CollectSuperiorPPNs(const MARC::Record &record, std::unordered_set<std::string> * const superior_ppn_set) {
static RegexMatcher * const superior_ppn_matcher(RegexMatcher::RegexMatcherFactory(".DE-576.(.*)"));
static const std::vector<std::string> tags{ "800", "810", "830", "773", "776" };
for (const auto &tag : tags) {
std::vector<std::string> superior_ppn_vector;
const auto field(record.findTag(tag));
if (field != record.end()) {
// Remove superfluous prefixes
for (auto &superior_ppn : field->getSubfields().extractSubfields('w')) {
std::string err_msg;
if (not superior_ppn_matcher->matched(superior_ppn, &err_msg)) {
if (not err_msg.empty())
LOG_ERROR("Error with regex für superior works " + err_msg);
continue;
}
superior_ppn = (*superior_ppn_matcher)[1];
}
std::copy(superior_ppn_vector.begin(), superior_ppn_vector.end(), std::inserter(*superior_ppn_set,
superior_ppn_set->end()));
}
}
}
void FlagRecordAsInTuebingenAvailable(MARC::Record * const record, unsigned * const modified_count) {
record->insertField("ITA", { { 'a', "1" } });
++*modified_count;
}
bool AlreadyHasLOK852DE21(const MARC::Record &record, RegexMatcher * const tue_sigil_matcher) {
std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> local_block_boundaries;
if (record.findAllLocalDataBlocks(&local_block_boundaries) == 0)
return false;
for (const auto &block_start_and_end : local_block_boundaries) {
for (const auto &field : record.findFieldsInLocalBlock("852", block_start_and_end.first)) {
std::string sigil;
if (field.extractSubfieldWithPattern('a', *tue_sigil_matcher, &sigil)) {
return true;
}
}
}
return false;
}
void ProcessRecord(MARC::Record * const record, MARC::Writer * const marc_writer, RegexMatcher * const tue_sigil_matcher,
std::unordered_set<std::string> * const de21_superior_ppns, unsigned * const modified_count) {
if (AlreadyHasLOK852DE21(*record, tue_sigil_matcher)) {
FlagRecordAsInTuebingenAvailable(record, modified_count);
marc_writer->write(*record);
return;
}
if (not record->isArticle()) {
marc_writer->write(*record);
return;
}
std::unordered_set<std::string> superior_ppn_set;
CollectSuperiorPPNs(*record, &superior_ppn_set);
// Do we have superior PPN that has DE-21
for (const auto &superior_ppn : superior_ppn_set) {
if (de21_superior_ppns->find(superior_ppn) != de21_superior_ppns->end()) {
FlagRecordAsInTuebingenAvailable(record, modified_count);
marc_writer->write(*record);
return;
}
}
marc_writer->write(*record);
}
void AugmentRecords(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
RegexMatcher * const tue_sigil_matcher, std::unordered_set<std::string> * const de21_superior_ppn,
unsigned * const extracted_count, unsigned * const modified_count) {
marc_reader->rewind();
while (MARC::Record record = marc_reader->read())
ProcessRecord(&record, marc_writer, tue_sigil_matcher, de21_superior_ppn, modified_count);
LOG_INFO("Extracted " + std::to_string(*extracted_count) + " superior PPNs with DE-21 and modified "
+ std::to_string(*modified_count) + " records");
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc != 3)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string marc_output_filename(argv[2]);
const std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename));
const std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename));
unsigned extracted_count(0), modified_count(0);
const std::unique_ptr<RegexMatcher> tue_sigil_matcher(RegexMatcher::RegexMatcherFactory("^DE-21.*"));
std::unordered_set<std::string> de21_superior_ppns;
LoadDE21PPNs(marc_reader.get(), tue_sigil_matcher.get(), &de21_superior_ppns, &extracted_count);
AugmentRecords(marc_reader.get(), marc_writer.get(), tue_sigil_matcher.get(), &de21_superior_ppns, &extracted_count, &modified_count);
return EXIT_SUCCESS;
}
<|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 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) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author <a href="mailto:david_n_bertoni@lotus.com">David N. Bertoni</a>
*/
#include "StylesheetConstructionContextDefault.hpp"
#include <algorithm>
#include <Include/STLHelper.hpp>
#include <PlatformSupport/URISupport.hpp>
#include <XPath/XObjectFactory.hpp>
#include <XPath/XPathEnvSupport.hpp>
#include <XPath/XPathFactory.hpp>
#include <XPath/XPathProcessorImpl.hpp>
#include "ElemTemplateElement.hpp"
#include "StylesheetRoot.hpp"
#include "XSLTEngineImpl.hpp"
#include "XSLTInputSource.hpp"
StylesheetConstructionContextDefault::StylesheetConstructionContextDefault(
XSLTEngineImpl& processor,
XPathFactory& xpathFactory,
VectorAllocatorSizeType theAllocatorSize) :
StylesheetConstructionContext(),
m_processor(processor),
m_xpathFactory(xpathFactory),
m_xpathProcessor(new XPathProcessorImpl),
m_stylesheets(),
m_stringPool(),
m_xalanDOMCharVectorAllocator(theAllocatorSize),
m_tempBuffer()
{
}
StylesheetConstructionContextDefault::~StylesheetConstructionContextDefault()
{
reset();
}
void
StylesheetConstructionContextDefault::error(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
m_processor.error(msg, sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::error(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
if (locator != 0)
{
m_processor.error(msg, *locator, sourceNode);
}
else
{
m_processor.error(msg, sourceNode);
}
}
void
StylesheetConstructionContextDefault::error(
const char* msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
error(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::error(
const char* msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
error(TranscodeFromLocalCodePage(msg), sourceNode, locator);
}
void
StylesheetConstructionContextDefault::warn(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
m_processor.warn(msg, sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::warn(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
if (locator != 0)
{
m_processor.warn(msg, *locator, sourceNode);
}
else
{
m_processor.warn(msg, sourceNode);
}
}
void
StylesheetConstructionContextDefault::warn(
const char* msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
warn(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::warn(
const char* msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
warn(TranscodeFromLocalCodePage(msg), sourceNode, locator);
}
void
StylesheetConstructionContextDefault::message(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
m_processor.message(msg, sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::message(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
if (locator != 0)
{
m_processor.message(msg, *locator, sourceNode);
}
else
{
m_processor.message(msg, sourceNode);
}
}
void
StylesheetConstructionContextDefault::message(
const char* msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
message(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::message(
const char* msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
message(TranscodeFromLocalCodePage(msg), sourceNode, locator);
}
void
StylesheetConstructionContextDefault::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
for_each(m_stylesheets.begin(),
m_stylesheets.end(),
DeleteFunctor<StylesheetRoot>());
m_stylesheets.clear();
m_xpathFactory.reset();
}
StylesheetRoot*
StylesheetConstructionContextDefault::create(const XalanDOMString& theBaseIdentifier)
{
StylesheetRoot* const theStylesheetRoot =
new StylesheetRoot(theBaseIdentifier, *this);
m_stylesheets.insert(theStylesheetRoot);
return theStylesheetRoot;
}
StylesheetRoot*
StylesheetConstructionContextDefault::create(const XSLTInputSource& theInputSource)
{
const XMLCh* const theSystemID =
theInputSource.getSystemId();
const XalanDOMString theBaseIdentifier =
theSystemID == 0 ? XalanDOMString() :
XalanDOMString(theSystemID);
return create(theBaseIdentifier);
}
Stylesheet*
StylesheetConstructionContextDefault::create(
StylesheetRoot& theStylesheetRoot,
const XalanDOMString& theBaseIdentifier)
{
Stylesheet* const theStylesheet =
new Stylesheet(
theStylesheetRoot,
theBaseIdentifier,
*this);
return theStylesheet;
}
void
StylesheetConstructionContextDefault::destroy(StylesheetRoot* theStylesheetRoot)
{
const StylesheetSetType::iterator i =
m_stylesheets.find(theStylesheetRoot);
if (i != m_stylesheets.end())
{
m_stylesheets.erase(i);
delete theStylesheetRoot;
}
}
StylesheetConstructionContextDefault::URLAutoPtrType
StylesheetConstructionContextDefault::getURLFromString(const XalanDOMString& urlString)
{
return URISupport::getURLFromString(urlString);
}
XalanDOMString
StylesheetConstructionContextDefault::getURLStringFromString(const XalanDOMString& urlString)
{
return URISupport::getURLStringFromString(urlString);
}
StylesheetConstructionContextDefault::URLAutoPtrType
StylesheetConstructionContextDefault::getURLFromString(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
return URISupport::getURLFromString(urlString, base);
}
XalanDOMString
StylesheetConstructionContextDefault::getURLStringFromString(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
return URISupport::getURLStringFromString(urlString, base);
}
const XalanDOMString&
StylesheetConstructionContextDefault::getXSLTNamespaceURI() const
{
return XSLTEngineImpl::getXSLNameSpaceURL();
}
XPath*
StylesheetConstructionContextDefault::createMatchPattern(
const Locator* locator,
const XalanDOMString& str,
const PrefixResolver& resolver)
{
XPath* const xpath = m_xpathFactory.create();
// Note that we use the current locator from the
// processing stack, and not the locator passed in.
// This is because the locator on the stack is active,
// during construction, while the locator passed in
// will be used at run-time.
m_xpathProcessor->initMatchPattern(
*xpath,
str,
resolver,
getLocatorFromStack());
xpath->setInStylesheet(true);
xpath->setLocator(locator);
return xpath;
}
XPath*
StylesheetConstructionContextDefault::createMatchPattern(
const Locator* locator,
const XalanDOMChar* str,
const PrefixResolver& resolver)
{
assert(str != 0);
assign(m_tempBuffer, str);
return createMatchPattern(locator, m_tempBuffer, resolver);
}
XPath*
StylesheetConstructionContextDefault::createXPath(
const Locator* locator,
const XalanDOMString& str,
const PrefixResolver& resolver)
{
XPath* const xpath = m_xpathFactory.create();
// Note that we use the current locator from the
// processing stack, and not the locator passed in.
// This is because the locator on the stack is active,
// during construction, while the locator passed in
// will be used at run-time.
m_xpathProcessor->initXPath(
*xpath,
str,
resolver,
getLocatorFromStack());
xpath->setInStylesheet(true);
xpath->setLocator(locator);
return xpath;
}
XPath*
StylesheetConstructionContextDefault::createXPath(
const Locator* locator,
const XalanDOMChar* str,
const PrefixResolver& resolver)
{
assert(str != 0);
assign(m_tempBuffer, str);
return createXPath(locator, m_tempBuffer, resolver);
}
const Locator*
StylesheetConstructionContextDefault::getLocatorFromStack() const
{
return m_processor.getLocatorFromStack();
}
void
StylesheetConstructionContextDefault::pushLocatorOnStack(const Locator* locator)
{
m_processor.pushLocatorOnStack(locator);
}
void
StylesheetConstructionContextDefault::popLocatorStack()
{
m_processor.popLocatorStack();
}
const XalanDOMString&
StylesheetConstructionContextDefault::getXalanXSLNameSpaceURL() const
{
return XSLTEngineImpl::getXalanXSLNameSpaceURL();
}
XalanDocument*
StylesheetConstructionContextDefault::parseXML(
const XalanDOMString& urlString,
DocumentHandler* docHandler,
XalanDocument* docToRegister)
{
return m_processor.parseXML(urlString, docHandler, docToRegister);
}
int
StylesheetConstructionContextDefault::getElementToken(const XalanDOMString& name) const
{
return m_processor.getElementToken(name);
}
double
StylesheetConstructionContextDefault::getXSLTVersionSupported() const
{
return XSLTEngineImpl::getXSLTVerSupported();
}
const XalanDOMString&
StylesheetConstructionContextDefault::getPooledString(const XalanDOMString& theString)
{
return m_stringPool.get(theString);
}
const XalanDOMString&
StylesheetConstructionContextDefault::getPooledString(
const XalanDOMChar* theString,
XalanDOMString::size_type theLength)
{
return m_stringPool.get(theString, theLength);
}
XalanDOMChar*
StylesheetConstructionContextDefault::allocateVector(XalanDOMString::size_type theLength)
{
return m_xalanDOMCharVectorAllocator.allocate(theLength);
}
XalanDOMChar*
StylesheetConstructionContextDefault::allocateVector(
const XalanDOMChar* theString,
XalanDOMString::size_type theLength,
bool fTerminate)
{
assert(theString != 0);
const XalanDOMString::size_type theActualLength =
theLength == XalanDOMString::npos ? XalanDOMString::length(theString) : theLength;
XalanDOMChar* const theVector =
m_xalanDOMCharVectorAllocator.allocate(fTerminate == true ? theActualLength + 1 : theActualLength);
#if !defined(XALAN_NO_NAMESPACES)
using std::copy;
#endif
XalanDOMChar* const theEnd =
std::copy(theString, theString + theActualLength, theVector);
if (fTerminate == true)
{
*theEnd = XalanDOMChar(0);
}
return theVector;
}
<commit_msg>Removed std::.<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 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) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author <a href="mailto:david_n_bertoni@lotus.com">David N. Bertoni</a>
*/
#include "StylesheetConstructionContextDefault.hpp"
#include <algorithm>
#include <Include/STLHelper.hpp>
#include <PlatformSupport/URISupport.hpp>
#include <XPath/XObjectFactory.hpp>
#include <XPath/XPathEnvSupport.hpp>
#include <XPath/XPathFactory.hpp>
#include <XPath/XPathProcessorImpl.hpp>
#include "ElemTemplateElement.hpp"
#include "StylesheetRoot.hpp"
#include "XSLTEngineImpl.hpp"
#include "XSLTInputSource.hpp"
StylesheetConstructionContextDefault::StylesheetConstructionContextDefault(
XSLTEngineImpl& processor,
XPathFactory& xpathFactory,
VectorAllocatorSizeType theAllocatorSize) :
StylesheetConstructionContext(),
m_processor(processor),
m_xpathFactory(xpathFactory),
m_xpathProcessor(new XPathProcessorImpl),
m_stylesheets(),
m_stringPool(),
m_xalanDOMCharVectorAllocator(theAllocatorSize),
m_tempBuffer()
{
}
StylesheetConstructionContextDefault::~StylesheetConstructionContextDefault()
{
reset();
}
void
StylesheetConstructionContextDefault::error(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
m_processor.error(msg, sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::error(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
if (locator != 0)
{
m_processor.error(msg, *locator, sourceNode);
}
else
{
m_processor.error(msg, sourceNode);
}
}
void
StylesheetConstructionContextDefault::error(
const char* msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
error(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::error(
const char* msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
error(TranscodeFromLocalCodePage(msg), sourceNode, locator);
}
void
StylesheetConstructionContextDefault::warn(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
m_processor.warn(msg, sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::warn(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
if (locator != 0)
{
m_processor.warn(msg, *locator, sourceNode);
}
else
{
m_processor.warn(msg, sourceNode);
}
}
void
StylesheetConstructionContextDefault::warn(
const char* msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
warn(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::warn(
const char* msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
warn(TranscodeFromLocalCodePage(msg), sourceNode, locator);
}
void
StylesheetConstructionContextDefault::message(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
m_processor.message(msg, sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::message(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
if (locator != 0)
{
m_processor.message(msg, *locator, sourceNode);
}
else
{
m_processor.message(msg, sourceNode);
}
}
void
StylesheetConstructionContextDefault::message(
const char* msg,
const XalanNode* sourceNode,
const ElemTemplateElement* styleNode) const
{
message(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::message(
const char* msg,
const XalanNode* sourceNode,
const Locator* locator) const
{
message(TranscodeFromLocalCodePage(msg), sourceNode, locator);
}
void
StylesheetConstructionContextDefault::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
for_each(m_stylesheets.begin(),
m_stylesheets.end(),
DeleteFunctor<StylesheetRoot>());
m_stylesheets.clear();
m_xpathFactory.reset();
}
StylesheetRoot*
StylesheetConstructionContextDefault::create(const XalanDOMString& theBaseIdentifier)
{
StylesheetRoot* const theStylesheetRoot =
new StylesheetRoot(theBaseIdentifier, *this);
m_stylesheets.insert(theStylesheetRoot);
return theStylesheetRoot;
}
StylesheetRoot*
StylesheetConstructionContextDefault::create(const XSLTInputSource& theInputSource)
{
const XMLCh* const theSystemID =
theInputSource.getSystemId();
const XalanDOMString theBaseIdentifier =
theSystemID == 0 ? XalanDOMString() :
XalanDOMString(theSystemID);
return create(theBaseIdentifier);
}
Stylesheet*
StylesheetConstructionContextDefault::create(
StylesheetRoot& theStylesheetRoot,
const XalanDOMString& theBaseIdentifier)
{
Stylesheet* const theStylesheet =
new Stylesheet(
theStylesheetRoot,
theBaseIdentifier,
*this);
return theStylesheet;
}
void
StylesheetConstructionContextDefault::destroy(StylesheetRoot* theStylesheetRoot)
{
const StylesheetSetType::iterator i =
m_stylesheets.find(theStylesheetRoot);
if (i != m_stylesheets.end())
{
m_stylesheets.erase(i);
delete theStylesheetRoot;
}
}
StylesheetConstructionContextDefault::URLAutoPtrType
StylesheetConstructionContextDefault::getURLFromString(const XalanDOMString& urlString)
{
return URISupport::getURLFromString(urlString);
}
XalanDOMString
StylesheetConstructionContextDefault::getURLStringFromString(const XalanDOMString& urlString)
{
return URISupport::getURLStringFromString(urlString);
}
StylesheetConstructionContextDefault::URLAutoPtrType
StylesheetConstructionContextDefault::getURLFromString(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
return URISupport::getURLFromString(urlString, base);
}
XalanDOMString
StylesheetConstructionContextDefault::getURLStringFromString(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
return URISupport::getURLStringFromString(urlString, base);
}
const XalanDOMString&
StylesheetConstructionContextDefault::getXSLTNamespaceURI() const
{
return XSLTEngineImpl::getXSLNameSpaceURL();
}
XPath*
StylesheetConstructionContextDefault::createMatchPattern(
const Locator* locator,
const XalanDOMString& str,
const PrefixResolver& resolver)
{
XPath* const xpath = m_xpathFactory.create();
// Note that we use the current locator from the
// processing stack, and not the locator passed in.
// This is because the locator on the stack is active,
// during construction, while the locator passed in
// will be used at run-time.
m_xpathProcessor->initMatchPattern(
*xpath,
str,
resolver,
getLocatorFromStack());
xpath->setInStylesheet(true);
xpath->setLocator(locator);
return xpath;
}
XPath*
StylesheetConstructionContextDefault::createMatchPattern(
const Locator* locator,
const XalanDOMChar* str,
const PrefixResolver& resolver)
{
assert(str != 0);
assign(m_tempBuffer, str);
return createMatchPattern(locator, m_tempBuffer, resolver);
}
XPath*
StylesheetConstructionContextDefault::createXPath(
const Locator* locator,
const XalanDOMString& str,
const PrefixResolver& resolver)
{
XPath* const xpath = m_xpathFactory.create();
// Note that we use the current locator from the
// processing stack, and not the locator passed in.
// This is because the locator on the stack is active,
// during construction, while the locator passed in
// will be used at run-time.
m_xpathProcessor->initXPath(
*xpath,
str,
resolver,
getLocatorFromStack());
xpath->setInStylesheet(true);
xpath->setLocator(locator);
return xpath;
}
XPath*
StylesheetConstructionContextDefault::createXPath(
const Locator* locator,
const XalanDOMChar* str,
const PrefixResolver& resolver)
{
assert(str != 0);
assign(m_tempBuffer, str);
return createXPath(locator, m_tempBuffer, resolver);
}
const Locator*
StylesheetConstructionContextDefault::getLocatorFromStack() const
{
return m_processor.getLocatorFromStack();
}
void
StylesheetConstructionContextDefault::pushLocatorOnStack(const Locator* locator)
{
m_processor.pushLocatorOnStack(locator);
}
void
StylesheetConstructionContextDefault::popLocatorStack()
{
m_processor.popLocatorStack();
}
const XalanDOMString&
StylesheetConstructionContextDefault::getXalanXSLNameSpaceURL() const
{
return XSLTEngineImpl::getXalanXSLNameSpaceURL();
}
XalanDocument*
StylesheetConstructionContextDefault::parseXML(
const XalanDOMString& urlString,
DocumentHandler* docHandler,
XalanDocument* docToRegister)
{
return m_processor.parseXML(urlString, docHandler, docToRegister);
}
int
StylesheetConstructionContextDefault::getElementToken(const XalanDOMString& name) const
{
return m_processor.getElementToken(name);
}
double
StylesheetConstructionContextDefault::getXSLTVersionSupported() const
{
return XSLTEngineImpl::getXSLTVerSupported();
}
const XalanDOMString&
StylesheetConstructionContextDefault::getPooledString(const XalanDOMString& theString)
{
return m_stringPool.get(theString);
}
const XalanDOMString&
StylesheetConstructionContextDefault::getPooledString(
const XalanDOMChar* theString,
XalanDOMString::size_type theLength)
{
return m_stringPool.get(theString, theLength);
}
XalanDOMChar*
StylesheetConstructionContextDefault::allocateVector(XalanDOMString::size_type theLength)
{
return m_xalanDOMCharVectorAllocator.allocate(theLength);
}
XalanDOMChar*
StylesheetConstructionContextDefault::allocateVector(
const XalanDOMChar* theString,
XalanDOMString::size_type theLength,
bool fTerminate)
{
assert(theString != 0);
const XalanDOMString::size_type theActualLength =
theLength == XalanDOMString::npos ? XalanDOMString::length(theString) : theLength;
XalanDOMChar* const theVector =
m_xalanDOMCharVectorAllocator.allocate(fTerminate == true ? theActualLength + 1 : theActualLength);
#if !defined(XALAN_NO_NAMESPACES)
using std::copy;
#endif
XalanDOMChar* const theEnd =
copy(theString, theString + theActualLength, theVector);
if (fTerminate == true)
{
*theEnd = XalanDOMChar(0);
}
return theVector;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkEnSightMasterServerReader.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkEnSightMasterServerReader.h"
#include "vtkObjectFactory.h"
#include <vtkstd/string>
//----------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkEnSightMasterServerReader, "1.8");
vtkStandardNewMacro(vtkEnSightMasterServerReader);
static int vtkEnSightMasterServerReaderStartsWith(const char* str1, const char* str2)
{
if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
{
return 0;
}
return !strncmp(str1, str2, strlen(str2));
}
//----------------------------------------------------------------------------
vtkEnSightMasterServerReader::vtkEnSightMasterServerReader()
{
this->PieceCaseFileName = 0;
this->MaxNumberOfPieces = 0;
this->CurrentPiece = -1;
}
//----------------------------------------------------------------------------
vtkEnSightMasterServerReader::~vtkEnSightMasterServerReader()
{
this->SetPieceCaseFileName(0);
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::Execute()
{
if ( !this->MaxNumberOfPieces )
{
vtkErrorMacro("No pices to read");
return;
}
if ( this->CurrentPiece < 0 ||
this->CurrentPiece >= this->MaxNumberOfPieces )
{
vtkErrorMacro("Current piece has to be set before reading the file");
return;
}
if ( this->DetermineFileName(this->CurrentPiece) != VTK_OK )
{
vtkErrorMacro("Cannot update piece: " << this->CurrentPiece);
return;
}
if ( !this->Reader )
{
this->Reader = vtkGenericEnSightReader::New();
}
this->Reader->SetCaseFileName(this->PieceCaseFileName);
if ( !this->Reader->GetFilePath() )
{
this->Reader->SetFilePath( this->GetFilePath() );
}
this->Superclass::Execute();
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::ExecuteInformation()
{
if ( this->DetermineFileName(-1) != VTK_OK )
{
vtkErrorMacro("Problem parsing the case file");
return;
}
}
//----------------------------------------------------------------------------
int vtkEnSightMasterServerReader::DetermineFileName(int piece)
{
if (!this->CaseFileName)
{
vtkErrorMacro("A case file name must be specified.");
return VTK_ERROR;
}
vtkstd::string sfilename;
if (this->FilePath)
{
sfilename = this->FilePath;
sfilename += this->CaseFileName;
vtkDebugMacro("full path to case file: " << sfilename.c_str());
}
else
{
sfilename = this->CaseFileName;
}
this->IS = new ifstream(sfilename.c_str(), ios::in);
if (this->IS->fail())
{
vtkErrorMacro("Unable to open file: " << sfilename.c_str());
delete this->IS;
this->IS = NULL;
return 0;
}
char result[1024];
int servers = 0;
int numberservers = 0;
int currentserver = 0;
while ( this->ReadNextDataLine(result) )
{
if ( strcmp(result, "FORMAT") == 0 )
{
// Format
}
else if ( strcmp(result, "SERVERS") == 0 )
{
servers = 1;
}
else if ( servers &&
vtkEnSightMasterServerReaderStartsWith(result, "number of servers:") )
{
sscanf(result, "number of servers: %i", &numberservers);
if ( !numberservers )
{
vtkErrorMacro("The case file is corrupted");
break;
}
}
else if ( servers &&
vtkEnSightMasterServerReaderStartsWith(result, "casefile:") )
{
if ( currentserver == piece )
{
char filename[1024] = "";
sscanf(result, "casefile: %s", filename);
if ( filename[0] == 0 )
{
vtkErrorMacro("Problem parsing file name from: " << result);
return VTK_ERROR;
}
this->SetPieceCaseFileName(filename);
break;
}
currentserver ++;
}
}
if ( piece == -1 && currentserver != numberservers )
{
//cout << "Number of servers (" << numberservers
//<< ") is not equal to the actual number of servers ("
//<< currentserver << ")" << endl;
return VTK_ERROR;
}
this->MaxNumberOfPieces = numberservers;
delete this->IS;
this->IS = 0;
return VTK_OK;
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Current piece: " << this->CurrentPiece << endl;
os << indent << "Piece Case File name: "
<< (this->PieceCaseFileName?this->PieceCaseFileName:"<none>") << endl;
os << indent << "Maximum numbe of pieces: " << this->MaxNumberOfPieces
<< endl;
}
<commit_msg>ERR: Fixed spelling in error message.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkEnSightMasterServerReader.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkEnSightMasterServerReader.h"
#include "vtkObjectFactory.h"
#include <vtkstd/string>
//----------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkEnSightMasterServerReader, "1.8.2.1");
vtkStandardNewMacro(vtkEnSightMasterServerReader);
static int vtkEnSightMasterServerReaderStartsWith(const char* str1, const char* str2)
{
if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
{
return 0;
}
return !strncmp(str1, str2, strlen(str2));
}
//----------------------------------------------------------------------------
vtkEnSightMasterServerReader::vtkEnSightMasterServerReader()
{
this->PieceCaseFileName = 0;
this->MaxNumberOfPieces = 0;
this->CurrentPiece = -1;
}
//----------------------------------------------------------------------------
vtkEnSightMasterServerReader::~vtkEnSightMasterServerReader()
{
this->SetPieceCaseFileName(0);
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::Execute()
{
if ( !this->MaxNumberOfPieces )
{
vtkErrorMacro("No pieces to read");
return;
}
if ( this->CurrentPiece < 0 ||
this->CurrentPiece >= this->MaxNumberOfPieces )
{
vtkErrorMacro("Current piece has to be set before reading the file");
return;
}
if ( this->DetermineFileName(this->CurrentPiece) != VTK_OK )
{
vtkErrorMacro("Cannot update piece: " << this->CurrentPiece);
return;
}
if ( !this->Reader )
{
this->Reader = vtkGenericEnSightReader::New();
}
this->Reader->SetCaseFileName(this->PieceCaseFileName);
if ( !this->Reader->GetFilePath() )
{
this->Reader->SetFilePath( this->GetFilePath() );
}
this->Superclass::Execute();
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::ExecuteInformation()
{
if ( this->DetermineFileName(-1) != VTK_OK )
{
vtkErrorMacro("Problem parsing the case file");
return;
}
}
//----------------------------------------------------------------------------
int vtkEnSightMasterServerReader::DetermineFileName(int piece)
{
if (!this->CaseFileName)
{
vtkErrorMacro("A case file name must be specified.");
return VTK_ERROR;
}
vtkstd::string sfilename;
if (this->FilePath)
{
sfilename = this->FilePath;
sfilename += this->CaseFileName;
vtkDebugMacro("full path to case file: " << sfilename.c_str());
}
else
{
sfilename = this->CaseFileName;
}
this->IS = new ifstream(sfilename.c_str(), ios::in);
if (this->IS->fail())
{
vtkErrorMacro("Unable to open file: " << sfilename.c_str());
delete this->IS;
this->IS = NULL;
return 0;
}
char result[1024];
int servers = 0;
int numberservers = 0;
int currentserver = 0;
while ( this->ReadNextDataLine(result) )
{
if ( strcmp(result, "FORMAT") == 0 )
{
// Format
}
else if ( strcmp(result, "SERVERS") == 0 )
{
servers = 1;
}
else if ( servers &&
vtkEnSightMasterServerReaderStartsWith(result, "number of servers:") )
{
sscanf(result, "number of servers: %i", &numberservers);
if ( !numberservers )
{
vtkErrorMacro("The case file is corrupted");
break;
}
}
else if ( servers &&
vtkEnSightMasterServerReaderStartsWith(result, "casefile:") )
{
if ( currentserver == piece )
{
char filename[1024] = "";
sscanf(result, "casefile: %s", filename);
if ( filename[0] == 0 )
{
vtkErrorMacro("Problem parsing file name from: " << result);
return VTK_ERROR;
}
this->SetPieceCaseFileName(filename);
break;
}
currentserver ++;
}
}
if ( piece == -1 && currentserver != numberservers )
{
//cout << "Number of servers (" << numberservers
//<< ") is not equal to the actual number of servers ("
//<< currentserver << ")" << endl;
return VTK_ERROR;
}
this->MaxNumberOfPieces = numberservers;
delete this->IS;
this->IS = 0;
return VTK_OK;
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Current piece: " << this->CurrentPiece << endl;
os << indent << "Piece Case File name: "
<< (this->PieceCaseFileName?this->PieceCaseFileName:"<none>") << endl;
os << indent << "Maximum numbe of pieces: " << this->MaxNumberOfPieces
<< endl;
}
<|endoftext|> |
<commit_before>#include "Gdx2DPixmap.h"
#include "gdx2d.h"
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: load
* Signature: ([J[BII)Ljava/nio/ByteBuffer;
*/
JNIEXPORT jobject JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_load
(JNIEnv *env, jclass, jlongArray nativeData, jbyteArray buffer, jint len, jint req_format) {
const unsigned char* p_buffer = (const char*)env->GetPrimitiveArrayCritical(buffer, 0);
gdx2d_pixmap* pixmap = gdx2d_load(p_buffer, len, req_format);
env->ReleasePrimitiveArrayCritical(buffer, (char*)p_buffer, 0);
if(pixmap==0)
return 0;
jobject pixel_buffer = env->NewDirectByteBuffer((void*)pixmap->pixels, pixmap->width * pixmap->height * pixmap->format);
jlong* p_native_data = (jlong*)env->GetPrimitiveArrayCritical(nativeData, 0);
p_native_data[0] = (jlong)pixmap;
p_native_data[1] = pixmap->width;
p_native_data[2] = pixmap->height;
p_native_data[3] = pixmap->format;
env->ReleasePrimitiveArrayCritical(nativeData, p_native_data, 0);
return pixel_buffer;
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: newPixmap
* Signature: ([JIII)Ljava/nio/ByteBuffer;
*/
JNIEXPORT jobject JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_newPixmap
(JNIEnv *env, jclass, jlongArray nativeData, jint width, jint height, jint format) {
gdx2d_pixmap* pixmap = gdx2d_new(width, height, format);
if(pixmap==0)
return 0;
jobject pixel_buffer = env->NewDirectByteBuffer((void*)pixmap->pixels, pixmap->width * pixmap->height * pixmap->format);
jlong* p_native_data = (jlong*)env->GetPrimitiveArrayCritical(nativeData, 0);
p_native_data[0] = (jlong)pixmap;
p_native_data[1] = pixmap->width;
p_native_data[2] = pixmap->height;
p_native_data[3] = pixmap->format;
env->ReleasePrimitiveArrayCritical(nativeData, p_native_data, 0);
return pixel_buffer;
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: free
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_free
(JNIEnv *, jclass, jlong pixmap) {
gdx2d_free((gdx2d_pixmap*)pixmap);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: clear
* Signature: (JI)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_clear
(JNIEnv *, jclass, jlong pixmap, jint color) {
gdx2d_clear((gdx2d_pixmap*)pixmap, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: setPixel
* Signature: (JIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_setPixel
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint color) {
gdx2d_set_pixel((gdx2d_pixmap*)pixmap, x, y, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: drawLine
* Signature: (JIIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_drawLine
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint x2, jint y2, jint color) {
gdx2d_draw_line((gdx2d_pixmap*)pixmap, x, y, x2, y2, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: drawRect
* Signature: (JIIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_drawRect
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint width, jint height, jint color) {
gdx2d_draw_rect((gdx2d_pixmap*)pixmap, x, y, width, height, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: drawCircle
* Signature: (JIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_drawCircle
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint radius, jint color) {
gdx2d_draw_circle((gdx2d_pixmap*)pixmap, x, y, radius, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: fillRect
* Signature: (JIIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_fillRect
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint width, jint height, jint color) {
gdx2d_fill_rect((gdx2d_pixmap*)pixmap, x, y, width, height, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: fillCircle
* Signature: (JIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_fillCircle
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint radius, jint color) {
gdx2d_fill_circle((gdx2d_pixmap*)pixmap, x, y, radius, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: drawPixmap
* Signature: (JJIIIIIIIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_drawPixmap
(JNIEnv *, jclass, jlong src, jlong dst, jint src_x, jint src_y, jint src_width, jint src_height, jint dst_x, jint dst_y, jint dst_width, jint dst_height) {
gdx2d_draw_pixmap((gdx2d_pixmap*)src, (gdx2d_pixmap*)dst, src_x, src_y, src_width, src_height, dst_x, dst_y, dst_width, dst_height);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: setBlend
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_setBlend
(JNIEnv *, jclass, jint blend) {
gdx2d_set_blend(blend);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: setScale
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_setScale
(JNIEnv *, jclass, jint scale) {
gdx2d_set_scale(scale);
}
<commit_msg>[fixed] const char* in Gdx2DPixmap<commit_after>#include "Gdx2DPixmap.h"
#include "gdx2d.h"
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: load
* Signature: ([J[BII)Ljava/nio/ByteBuffer;
*/
JNIEXPORT jobject JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_load
(JNIEnv *env, jclass, jlongArray nativeData, jbyteArray buffer, jint len, jint req_format) {
const unsigned char* p_buffer = (const unsigned char*)env->GetPrimitiveArrayCritical(buffer, 0);
gdx2d_pixmap* pixmap = gdx2d_load(p_buffer, len, req_format);
env->ReleasePrimitiveArrayCritical(buffer, (char*)p_buffer, 0);
if(pixmap==0)
return 0;
jobject pixel_buffer = env->NewDirectByteBuffer((void*)pixmap->pixels, pixmap->width * pixmap->height * pixmap->format);
jlong* p_native_data = (jlong*)env->GetPrimitiveArrayCritical(nativeData, 0);
p_native_data[0] = (jlong)pixmap;
p_native_data[1] = pixmap->width;
p_native_data[2] = pixmap->height;
p_native_data[3] = pixmap->format;
env->ReleasePrimitiveArrayCritical(nativeData, p_native_data, 0);
return pixel_buffer;
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: newPixmap
* Signature: ([JIII)Ljava/nio/ByteBuffer;
*/
JNIEXPORT jobject JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_newPixmap
(JNIEnv *env, jclass, jlongArray nativeData, jint width, jint height, jint format) {
gdx2d_pixmap* pixmap = gdx2d_new(width, height, format);
if(pixmap==0)
return 0;
jobject pixel_buffer = env->NewDirectByteBuffer((void*)pixmap->pixels, pixmap->width * pixmap->height * pixmap->format);
jlong* p_native_data = (jlong*)env->GetPrimitiveArrayCritical(nativeData, 0);
p_native_data[0] = (jlong)pixmap;
p_native_data[1] = pixmap->width;
p_native_data[2] = pixmap->height;
p_native_data[3] = pixmap->format;
env->ReleasePrimitiveArrayCritical(nativeData, p_native_data, 0);
return pixel_buffer;
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: free
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_free
(JNIEnv *, jclass, jlong pixmap) {
gdx2d_free((gdx2d_pixmap*)pixmap);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: clear
* Signature: (JI)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_clear
(JNIEnv *, jclass, jlong pixmap, jint color) {
gdx2d_clear((gdx2d_pixmap*)pixmap, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: setPixel
* Signature: (JIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_setPixel
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint color) {
gdx2d_set_pixel((gdx2d_pixmap*)pixmap, x, y, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: drawLine
* Signature: (JIIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_drawLine
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint x2, jint y2, jint color) {
gdx2d_draw_line((gdx2d_pixmap*)pixmap, x, y, x2, y2, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: drawRect
* Signature: (JIIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_drawRect
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint width, jint height, jint color) {
gdx2d_draw_rect((gdx2d_pixmap*)pixmap, x, y, width, height, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: drawCircle
* Signature: (JIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_drawCircle
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint radius, jint color) {
gdx2d_draw_circle((gdx2d_pixmap*)pixmap, x, y, radius, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: fillRect
* Signature: (JIIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_fillRect
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint width, jint height, jint color) {
gdx2d_fill_rect((gdx2d_pixmap*)pixmap, x, y, width, height, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: fillCircle
* Signature: (JIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_fillCircle
(JNIEnv *, jclass, jlong pixmap, jint x, jint y, jint radius, jint color) {
gdx2d_fill_circle((gdx2d_pixmap*)pixmap, x, y, radius, color);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: drawPixmap
* Signature: (JJIIIIIIIIII)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_drawPixmap
(JNIEnv *, jclass, jlong src, jlong dst, jint src_x, jint src_y, jint src_width, jint src_height, jint dst_x, jint dst_y, jint dst_width, jint dst_height) {
gdx2d_draw_pixmap((gdx2d_pixmap*)src, (gdx2d_pixmap*)dst, src_x, src_y, src_width, src_height, dst_x, dst_y, dst_width, dst_height);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: setBlend
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_setBlend
(JNIEnv *, jclass, jint blend) {
gdx2d_set_blend(blend);
}
/*
* Class: com_badlogic_gdx_graphics_Gdx2DPixmap
* Method: setScale
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_badlogic_gdx_graphics_Gdx2DPixmap_setScale
(JNIEnv *, jclass, jint scale) {
gdx2d_set_scale(scale);
}
<|endoftext|> |
<commit_before>//
// QtOneLineTextWidget.cpp
// MusicPlayer
//
// Created by Albert Zeyer on 23.01.14.
// Copyright (c) 2014 Albert Zeyer. All rights reserved.
//
#include "QtOneLineTextWidget.hpp"
#include "QtApp.hpp"
#include "Builders.hpp"
#include "PythonHelpers.h"
#include "PyUtils.h"
#include <string>
#include <assert.h>
RegisterControl(OneLineText)
QtOneLineTextWidget::QtOneLineTextWidget(PyQtGuiObject* control) : QtBaseWidget(control) {
PyScopedGIL gil;
long w = attrChain_int_default(control->attr, "width", -1);
long h = attrChain_int_default(control->attr, "height", -1);
if(w < 0) w = 30;
if(h < 0) h = 22;
control->PresetSize = Vec((int)w, (int)h);
resize(w, h);
setBaseSize(w, h);
lineEditWidget = new QLineEdit(this);
lineEditWidget->resize(w, h);
lineEditWidget->show();
bool withBorder = attrChain_bool_default(control->attr, "withBorder", false);
// [self setBordered:NO];
/*
if(withBorder) {
[self setBezeled:YES];
[self setBezelStyle:NSTextFieldRoundedBezel];
}
[self setDrawsBackground:NO];
[self setEditable:NO];
[[self cell] setUsesSingleLineMode:YES];
[[self cell] setLineBreakMode:NSLineBreakByTruncatingTail];
*/
}
void QtOneLineTextWidget::resizeEvent(QResizeEvent *) {
lineEditWidget->resize(size());
}
PyObject* QtOneLineTextWidget::getTextObj() {
PyQtGuiObject* control = getControl();
PyObject* textObj = control ? control->subjectObject : NULL;
Py_XINCREF(textObj);
Py_XDECREF(control);
return textObj;
}
void QtOneLineTextWidget::updateContent() {
PyQtGuiObject* control = NULL;
std::string s = "???";
{
PyScopedGIL gil;
control = getControl();
if(!control) return;
control->updateSubjectObject();
{
PyObject* labelContent = getTextObj();
if(!labelContent && PyErr_Occurred()) PyErr_Print();
if(labelContent) {
if(!pyStr(labelContent, s)) {
if(PyErr_Occurred()) PyErr_Print();
}
}
}
}
WeakRef selfRefCopy(*this);
// Note: We had this async before. But I think other code wants to know the actual size
// and we only get it after we set the text.
execInMainThread_sync([=]() {
PyScopedGIL gil;
ScopedRef selfRef(selfRefCopy.scoped());
if(selfRef) {
auto self = dynamic_cast<QtOneLineTextWidget*>(selfRef.get());
assert(self);
assert(self->lineEditWidget);
self->lineEditWidget->setText(QString::fromStdString(s));
PyScopedGIL gil;
/*
NSColor* color = backgroundColor(control);
if(color) {
[self setDrawsBackground:YES];
[self setBackgroundColor:color];
}
*/
//[self setTextColor:foregroundColor(control)];
bool autosizeWidth = attrChain_bool_default(control->attr, "autosizeWidth", false);
if(autosizeWidth) {
self->lineEditWidget->adjustSize();
self->adjustSize(); // adjust size to the text content
PyObject* res = PyObject_CallMethod((PyObject*) control, (char*)"layoutLine", NULL);
if(!res && PyErr_Occurred()) PyErr_Print();
Py_XDECREF(res);
}
}
Py_DECREF(control);
});
}
<commit_msg>autoresizeWidth for qt label<commit_after>//
// QtOneLineTextWidget.cpp
// MusicPlayer
//
// Created by Albert Zeyer on 23.01.14.
// Copyright (c) 2014 Albert Zeyer. All rights reserved.
//
#include "QtOneLineTextWidget.hpp"
#include "QtApp.hpp"
#include "Builders.hpp"
#include "PythonHelpers.h"
#include "PyUtils.h"
#include <string>
#include <assert.h>
RegisterControl(OneLineText)
QtOneLineTextWidget::QtOneLineTextWidget(PyQtGuiObject* control) : QtBaseWidget(control) {
PyScopedGIL gil;
long w = attrChain_int_default(control->attr, "width", -1);
long h = attrChain_int_default(control->attr, "height", -1);
if(w < 0) w = 30;
if(h < 0) h = 22;
control->PresetSize = Vec((int)w, (int)h);
resize(w, h);
setBaseSize(w, h);
lineEditWidget = new QLineEdit(this);
lineEditWidget->resize(w, h);
lineEditWidget->show();
bool withBorder = attrChain_bool_default(control->attr, "withBorder", false);
// [self setBordered:NO];
/*
if(withBorder) {
[self setBezeled:YES];
[self setBezelStyle:NSTextFieldRoundedBezel];
}
[self setDrawsBackground:NO];
[self setEditable:NO];
[[self cell] setUsesSingleLineMode:YES];
[[self cell] setLineBreakMode:NSLineBreakByTruncatingTail];
*/
}
void QtOneLineTextWidget::resizeEvent(QResizeEvent *) {
lineEditWidget->resize(size());
}
PyObject* QtOneLineTextWidget::getTextObj() {
PyQtGuiObject* control = getControl();
PyObject* textObj = control ? control->subjectObject : NULL;
Py_XINCREF(textObj);
Py_XDECREF(control);
return textObj;
}
void QtOneLineTextWidget::updateContent() {
PyQtGuiObject* control = NULL;
std::string s = "???";
{
PyScopedGIL gil;
control = getControl();
if(!control) return;
control->updateSubjectObject();
{
PyObject* labelContent = getTextObj();
if(!labelContent && PyErr_Occurred()) PyErr_Print();
if(labelContent) {
if(!pyStr(labelContent, s)) {
if(PyErr_Occurred()) PyErr_Print();
}
}
}
}
WeakRef selfRefCopy(*this);
// Note: We had this async before. But I think other code wants to know the actual size
// and we only get it after we set the text.
execInMainThread_sync([=]() {
PyScopedGIL gil;
ScopedRef selfRef(selfRefCopy.scoped());
if(selfRef) {
auto self = dynamic_cast<QtOneLineTextWidget*>(selfRef.get());
assert(self);
assert(self->lineEditWidget);
self->lineEditWidget->setText(QString::fromStdString(s));
PyScopedGIL gil;
/*
NSColor* color = backgroundColor(control);
if(color) {
[self setDrawsBackground:YES];
[self setBackgroundColor:color];
}
*/
//[self setTextColor:foregroundColor(control)];
bool autosizeWidth = attrChain_bool_default(control->attr, "autosizeWidth", false);
if(autosizeWidth) {
QFontMetrics metrics(self->lineEditWidget->fontMetrics());
int w = metrics.boundingRect(self->lineEditWidget->text()).width();
self->resize(w, self->height());
PyObject* res = PyObject_CallMethod((PyObject*) control, (char*)"layoutLine", NULL);
if(!res && PyErr_Occurred()) PyErr_Print();
Py_XDECREF(res);
}
}
Py_DECREF(control);
});
}
<|endoftext|> |
<commit_before>/*
* guide_algorithm_resistswitch.cpp
* PHD Guiding
*
* Created by Bret McKee
* Copyright (c) 2012 Bret McKee
* All rights reserved.
*
* Based upon work by Craig Stark.
* Copyright (c) 2006-2010 Craig Stark.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Bret McKee, Dad Dog Development,
* Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "phd.h"
static const double DefaultMinMove = 0.2;
static const double DefaultAggression = 1.0;
GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitch(Mount *pMount, GuideAxis axis)
: GuideAlgorithm(pMount, axis)
{
double minMove = pConfig->Profile.GetDouble(GetConfigPath() + "/minMove", DefaultMinMove);
SetMinMove(minMove);
double aggr = pConfig->Profile.GetDouble(GetConfigPath() + "/aggression", DefaultAggression);
SetAggression(aggr);
bool enable = pConfig->Profile.GetBoolean(GetConfigPath() + "/fastSwitch", true);
SetFastSwitchEnabled(enable);
reset();
}
GuideAlgorithmResistSwitch::~GuideAlgorithmResistSwitch(void)
{
}
GUIDE_ALGORITHM GuideAlgorithmResistSwitch::Algorithm(void)
{
return GUIDE_ALGORITHM_RESIST_SWITCH;
}
void GuideAlgorithmResistSwitch::reset(void)
{
m_history.Empty();
while (m_history.GetCount() < HISTORY_SIZE)
{
m_history.Add(0.0);
}
m_currentSide = 0;
}
static int sign(double x)
{
int iReturn = 0;
if (x > 0.0)
{
iReturn = 1;
}
else if (x < 0.0)
{
iReturn = -1;
}
return iReturn;
}
double GuideAlgorithmResistSwitch::result(double input)
{
double dReturn = input;
m_history.Add(input);
m_history.RemoveAt(0);
try
{
if (fabs(input) < m_minMove)
{
throw THROW_INFO("input < m_minMove");
}
if (m_fastSwitchEnabled)
{
double thresh = 3.0 * m_minMove;
if (sign(input) != m_currentSide && fabs(input) > thresh)
{
Debug.Write(wxString::Format("resist switch: large excursion: input %.2f thresh %.2f direction from %d to %d\n", input, thresh, m_currentSide, sign(input)));
// force switch
m_currentSide = 0;
int i;
for (i = 0; i < HISTORY_SIZE - 3; i++)
m_history[i] = 0.0;
for (; i < HISTORY_SIZE; i++)
m_history[i] = input;
}
}
int decHistory = 0;
for (unsigned int i = 0; i < m_history.GetCount(); i++)
{
if (fabs(m_history[i]) > m_minMove)
{
decHistory += sign(m_history[i]);
}
}
if (m_currentSide == 0 || sign(m_currentSide) == -sign(decHistory))
{
if (abs(decHistory) < 3)
{
throw THROW_INFO("not compelling enough");
}
double oldest = 0.0;
double newest = 0.0;
for (int i = 0; i < 3; i++)
{
oldest += m_history[i];
newest += m_history[m_history.GetCount() - (i + 1)];
}
if (fabs(newest) <= fabs(oldest))
{
throw THROW_INFO("Not getting worse");
}
Debug.Write(wxString::Format("switching direction from %d to %d - decHistory=%d oldest=%.2f newest=%.2f\n", m_currentSide, sign(decHistory), decHistory, oldest, newest));
m_currentSide = sign(decHistory);
}
if (m_currentSide != sign(input))
{
throw THROW_INFO("must have overshot -- vetoing move");
}
}
catch (const wxString& Msg)
{
POSSIBLY_UNUSED(Msg);
dReturn = 0.0;
}
Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::Result() returns %.2f from input %.2f\n", dReturn, input));
return dReturn * m_aggression;
}
bool GuideAlgorithmResistSwitch::SetMinMove(double minMove)
{
bool bError = false;
try
{
if (minMove <= 0.0)
{
throw ERROR_INFO("invalid minMove");
}
m_minMove = minMove;
m_currentSide = 0;
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
m_minMove = DefaultMinMove;
}
pConfig->Profile.SetDouble(GetConfigPath() + "/minMove", m_minMove);
Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetMinMove() returns %d, m_minMove=%.2f\n", bError, m_minMove));
return bError;
}
bool GuideAlgorithmResistSwitch::SetAggression(double aggr)
{
bool bError = false;
try
{
if (aggr <= 0.0 || aggr > 1.0)
{
throw ERROR_INFO("invalid aggression");
}
m_aggression = aggr;
}
catch (const wxString& Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
m_aggression = DefaultAggression;
}
pConfig->Profile.SetDouble(GetConfigPath() + "/aggression", m_aggression);
Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetAggression() returns %d, m_aggression=%.2f\n", bError, m_aggression));
return bError;
}
void GuideAlgorithmResistSwitch::SetFastSwitchEnabled(bool enable)
{
m_fastSwitchEnabled = enable;
pConfig->Profile.SetBoolean(GetConfigPath() + "/fastSwitch", m_fastSwitchEnabled);
Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetFastSwitchEnabled(%d)\n", m_fastSwitchEnabled));
}
wxString GuideAlgorithmResistSwitch::GetSettingsSummary()
{
// return a loggable summary of current mount settings
return wxString::Format("Minimum move = %.3f Aggression = %.f%% FastSwitch = %s\n",
GetMinMove(), GetAggression() * 100.0, GetFastSwitchEnabled() ? "enabled" : "disabled");
}
ConfigDialogPane *GuideAlgorithmResistSwitch::GetConfigDialogPane(wxWindow *pParent)
{
return new GuideAlgorithmResistSwitchConfigDialogPane(pParent, this);
}
GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchConfigDialogPane::
GuideAlgorithmResistSwitchConfigDialogPane(wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm)
: ConfigDialogPane(_("ResistSwitch Guide Algorithm"), pParent)
{
int width;
m_pGuideAlgorithm = pGuideAlgorithm;
width = StringWidth(_T("000"));
m_pAggression = new wxSpinCtrlDouble(pParent, wxID_ANY, _T(""), wxPoint(-1, -1),
wxSize(width + 30, -1), wxSP_ARROW_KEYS, 1.0, 100.0, 100.0, 5.0, _T("Aggression"));
m_pAggression->SetDigits(0);
DoAdd(_("Aggression"), m_pAggression,
wxString::Format(_("Aggression factor, percent. Default = %.f%%"), DefaultAggression * 100.0));
width = StringWidth(_T("00.00"));
m_pMinMove = new wxSpinCtrlDouble(pParent, wxID_ANY,_T(""), wxPoint(-1,-1),
wxSize(width+30, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.05, _T("MinMove"));
m_pMinMove->SetDigits(2);
DoAdd(_("Minimum Move (pixels)"), m_pMinMove,
wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? Default = %.2f"), DefaultMinMove));
m_pFastSwitch = new wxCheckBox(pParent, wxID_ANY, _("Fast switch for large deflections"));
DoAdd(m_pFastSwitch, _("Ordinarily the Resist Switch algortithm waits several frames before switching direction. With Fast Switch enabled PHD2 will switch direction immediately if it sees a very large deflection. Enable this option if your mount has a substantial amount of backlash and PHD2 sometimes overcorrects."));
}
GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchConfigDialogPane::
~GuideAlgorithmResistSwitchConfigDialogPane(void)
{
}
void GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchConfigDialogPane::
LoadValues(void)
{
m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove());
m_pAggression->SetValue(m_pGuideAlgorithm->GetAggression() * 100.0);
m_pFastSwitch->SetValue(m_pGuideAlgorithm->GetFastSwitchEnabled());
}
void GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchConfigDialogPane::
UnloadValues(void)
{
m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue());
m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0);
m_pGuideAlgorithm->SetFastSwitchEnabled(m_pFastSwitch->GetValue());
}
GraphControlPane *GuideAlgorithmResistSwitch::GetGraphControlPane(wxWindow *pParent, const wxString& label)
{
return new GuideAlgorithmResistSwitchGraphControlPane(pParent, this, label);
}
GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchGraphControlPane::
GuideAlgorithmResistSwitchGraphControlPane(wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm, const wxString& label)
: GraphControlPane(pParent, label)
{
int width;
m_pGuideAlgorithm = pGuideAlgorithm;
// Aggression
width = StringWidth(_T("000"));
m_pAggression = new wxSpinCtrlDouble(this, wxID_ANY, _T(""), wxPoint(-1, -1),
wxSize(width + 30, -1), wxSP_ARROW_KEYS, 1.0, 100.0, 100.0, 5.0, _T("Aggression"));
m_pAggression->SetDigits(0);
m_pAggression->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnAggressionSpinCtrlDouble, this);
DoAdd(m_pAggression, _T("Agr"));
m_pAggression->SetValue(m_pGuideAlgorithm->GetAggression() * 100.0);
// Min move
width = StringWidth(_T("00.00"));
m_pMinMove = new wxSpinCtrlDouble(this, wxID_ANY, _T(""), wxPoint(-1,-1),
wxSize(width+30, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.05, _T("MinMove"));
m_pMinMove->SetDigits(2);
m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnMinMoveSpinCtrlDouble, this);
DoAdd(m_pMinMove,_T("MnMo"));
m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove());
}
GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchGraphControlPane::
~GuideAlgorithmResistSwitchGraphControlPane(void)
{
}
void GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchGraphControlPane::
OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& WXUNUSED(evt))
{
m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue());
GuideLog.SetGuidingParam(m_pGuideAlgorithm->GetAxis() + " Resist switch minimum motion", m_pMinMove->GetValue());
}
void GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchGraphControlPane::
OnAggressionSpinCtrlDouble(wxSpinDoubleEvent& WXUNUSED(evt))
{
m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0);
GuideLog.SetGuidingParam(m_pGuideAlgorithm->GetAxis() + " Resist switch aggression", m_pAggression->GetValue());
}
<commit_msg>fix Linux compile error<commit_after>/*
* guide_algorithm_resistswitch.cpp
* PHD Guiding
*
* Created by Bret McKee
* Copyright (c) 2012 Bret McKee
* All rights reserved.
*
* Based upon work by Craig Stark.
* Copyright (c) 2006-2010 Craig Stark.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Bret McKee, Dad Dog Development,
* Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "phd.h"
static const double DefaultMinMove = 0.2;
static const double DefaultAggression = 1.0;
GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitch(Mount *pMount, GuideAxis axis)
: GuideAlgorithm(pMount, axis)
{
double minMove = pConfig->Profile.GetDouble(GetConfigPath() + "/minMove", DefaultMinMove);
SetMinMove(minMove);
double aggr = pConfig->Profile.GetDouble(GetConfigPath() + "/aggression", DefaultAggression);
SetAggression(aggr);
bool enable = pConfig->Profile.GetBoolean(GetConfigPath() + "/fastSwitch", true);
SetFastSwitchEnabled(enable);
reset();
}
GuideAlgorithmResistSwitch::~GuideAlgorithmResistSwitch(void)
{
}
GUIDE_ALGORITHM GuideAlgorithmResistSwitch::Algorithm(void)
{
return GUIDE_ALGORITHM_RESIST_SWITCH;
}
void GuideAlgorithmResistSwitch::reset(void)
{
m_history.Empty();
while (m_history.GetCount() < HISTORY_SIZE)
{
m_history.Add(0.0);
}
m_currentSide = 0;
}
static int sign(double x)
{
int iReturn = 0;
if (x > 0.0)
{
iReturn = 1;
}
else if (x < 0.0)
{
iReturn = -1;
}
return iReturn;
}
double GuideAlgorithmResistSwitch::result(double input)
{
double dReturn = input;
m_history.Add(input);
m_history.RemoveAt(0);
try
{
if (fabs(input) < m_minMove)
{
throw THROW_INFO("input < m_minMove");
}
if (m_fastSwitchEnabled)
{
double thresh = 3.0 * m_minMove;
if (sign(input) != m_currentSide && fabs(input) > thresh)
{
Debug.Write(wxString::Format("resist switch: large excursion: input %.2f thresh %.2f direction from %d to %d\n", input, thresh, m_currentSide, sign(input)));
// force switch
m_currentSide = 0;
unsigned int i;
for (i = 0; i < HISTORY_SIZE - 3; i++)
m_history[i] = 0.0;
for (; i < HISTORY_SIZE; i++)
m_history[i] = input;
}
}
int decHistory = 0;
for (unsigned int i = 0; i < m_history.GetCount(); i++)
{
if (fabs(m_history[i]) > m_minMove)
{
decHistory += sign(m_history[i]);
}
}
if (m_currentSide == 0 || sign(m_currentSide) == -sign(decHistory))
{
if (abs(decHistory) < 3)
{
throw THROW_INFO("not compelling enough");
}
double oldest = 0.0;
double newest = 0.0;
for (int i = 0; i < 3; i++)
{
oldest += m_history[i];
newest += m_history[m_history.GetCount() - (i + 1)];
}
if (fabs(newest) <= fabs(oldest))
{
throw THROW_INFO("Not getting worse");
}
Debug.Write(wxString::Format("switching direction from %d to %d - decHistory=%d oldest=%.2f newest=%.2f\n", m_currentSide, sign(decHistory), decHistory, oldest, newest));
m_currentSide = sign(decHistory);
}
if (m_currentSide != sign(input))
{
throw THROW_INFO("must have overshot -- vetoing move");
}
}
catch (const wxString& Msg)
{
POSSIBLY_UNUSED(Msg);
dReturn = 0.0;
}
Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::Result() returns %.2f from input %.2f\n", dReturn, input));
return dReturn * m_aggression;
}
bool GuideAlgorithmResistSwitch::SetMinMove(double minMove)
{
bool bError = false;
try
{
if (minMove <= 0.0)
{
throw ERROR_INFO("invalid minMove");
}
m_minMove = minMove;
m_currentSide = 0;
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
m_minMove = DefaultMinMove;
}
pConfig->Profile.SetDouble(GetConfigPath() + "/minMove", m_minMove);
Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetMinMove() returns %d, m_minMove=%.2f\n", bError, m_minMove));
return bError;
}
bool GuideAlgorithmResistSwitch::SetAggression(double aggr)
{
bool bError = false;
try
{
if (aggr <= 0.0 || aggr > 1.0)
{
throw ERROR_INFO("invalid aggression");
}
m_aggression = aggr;
}
catch (const wxString& Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
m_aggression = DefaultAggression;
}
pConfig->Profile.SetDouble(GetConfigPath() + "/aggression", m_aggression);
Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetAggression() returns %d, m_aggression=%.2f\n", bError, m_aggression));
return bError;
}
void GuideAlgorithmResistSwitch::SetFastSwitchEnabled(bool enable)
{
m_fastSwitchEnabled = enable;
pConfig->Profile.SetBoolean(GetConfigPath() + "/fastSwitch", m_fastSwitchEnabled);
Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetFastSwitchEnabled(%d)\n", m_fastSwitchEnabled));
}
wxString GuideAlgorithmResistSwitch::GetSettingsSummary()
{
// return a loggable summary of current mount settings
return wxString::Format("Minimum move = %.3f Aggression = %.f%% FastSwitch = %s\n",
GetMinMove(), GetAggression() * 100.0, GetFastSwitchEnabled() ? "enabled" : "disabled");
}
ConfigDialogPane *GuideAlgorithmResistSwitch::GetConfigDialogPane(wxWindow *pParent)
{
return new GuideAlgorithmResistSwitchConfigDialogPane(pParent, this);
}
GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchConfigDialogPane::
GuideAlgorithmResistSwitchConfigDialogPane(wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm)
: ConfigDialogPane(_("ResistSwitch Guide Algorithm"), pParent)
{
int width;
m_pGuideAlgorithm = pGuideAlgorithm;
width = StringWidth(_T("000"));
m_pAggression = new wxSpinCtrlDouble(pParent, wxID_ANY, _T(""), wxPoint(-1, -1),
wxSize(width + 30, -1), wxSP_ARROW_KEYS, 1.0, 100.0, 100.0, 5.0, _T("Aggression"));
m_pAggression->SetDigits(0);
DoAdd(_("Aggression"), m_pAggression,
wxString::Format(_("Aggression factor, percent. Default = %.f%%"), DefaultAggression * 100.0));
width = StringWidth(_T("00.00"));
m_pMinMove = new wxSpinCtrlDouble(pParent, wxID_ANY,_T(""), wxPoint(-1,-1),
wxSize(width+30, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.05, _T("MinMove"));
m_pMinMove->SetDigits(2);
DoAdd(_("Minimum Move (pixels)"), m_pMinMove,
wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? Default = %.2f"), DefaultMinMove));
m_pFastSwitch = new wxCheckBox(pParent, wxID_ANY, _("Fast switch for large deflections"));
DoAdd(m_pFastSwitch, _("Ordinarily the Resist Switch algortithm waits several frames before switching direction. With Fast Switch enabled PHD2 will switch direction immediately if it sees a very large deflection. Enable this option if your mount has a substantial amount of backlash and PHD2 sometimes overcorrects."));
}
GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchConfigDialogPane::
~GuideAlgorithmResistSwitchConfigDialogPane(void)
{
}
void GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchConfigDialogPane::
LoadValues(void)
{
m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove());
m_pAggression->SetValue(m_pGuideAlgorithm->GetAggression() * 100.0);
m_pFastSwitch->SetValue(m_pGuideAlgorithm->GetFastSwitchEnabled());
}
void GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchConfigDialogPane::
UnloadValues(void)
{
m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue());
m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0);
m_pGuideAlgorithm->SetFastSwitchEnabled(m_pFastSwitch->GetValue());
}
GraphControlPane *GuideAlgorithmResistSwitch::GetGraphControlPane(wxWindow *pParent, const wxString& label)
{
return new GuideAlgorithmResistSwitchGraphControlPane(pParent, this, label);
}
GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchGraphControlPane::
GuideAlgorithmResistSwitchGraphControlPane(wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm, const wxString& label)
: GraphControlPane(pParent, label)
{
int width;
m_pGuideAlgorithm = pGuideAlgorithm;
// Aggression
width = StringWidth(_T("000"));
m_pAggression = new wxSpinCtrlDouble(this, wxID_ANY, _T(""), wxPoint(-1, -1),
wxSize(width + 30, -1), wxSP_ARROW_KEYS, 1.0, 100.0, 100.0, 5.0, _T("Aggression"));
m_pAggression->SetDigits(0);
m_pAggression->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnAggressionSpinCtrlDouble, this);
DoAdd(m_pAggression, _T("Agr"));
m_pAggression->SetValue(m_pGuideAlgorithm->GetAggression() * 100.0);
// Min move
width = StringWidth(_T("00.00"));
m_pMinMove = new wxSpinCtrlDouble(this, wxID_ANY, _T(""), wxPoint(-1,-1),
wxSize(width+30, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.05, _T("MinMove"));
m_pMinMove->SetDigits(2);
m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnMinMoveSpinCtrlDouble, this);
DoAdd(m_pMinMove,_T("MnMo"));
m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove());
}
GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchGraphControlPane::
~GuideAlgorithmResistSwitchGraphControlPane(void)
{
}
void GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchGraphControlPane::
OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& WXUNUSED(evt))
{
m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue());
GuideLog.SetGuidingParam(m_pGuideAlgorithm->GetAxis() + " Resist switch minimum motion", m_pMinMove->GetValue());
}
void GuideAlgorithmResistSwitch::
GuideAlgorithmResistSwitchGraphControlPane::
OnAggressionSpinCtrlDouble(wxSpinDoubleEvent& WXUNUSED(evt))
{
m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0);
GuideLog.SetGuidingParam(m_pGuideAlgorithm->GetAxis() + " Resist switch aggression", m_pAggression->GetValue());
}
<|endoftext|> |
<commit_before>// Transaction.cpp
#include "Transaction.h"
#include "Timer.h"
#include "Model.h"
#include "MarketModel.h"
#include <string>
#include <vector>
// initialize static variables
int Transaction::next_trans_id_ = 1;
// Database table for transactions
table_ptr Transaction::trans_table = new Table("Transactions");
table_ptr Transaction::trans_resource_table = new Table("TransactedResources");
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction::Transaction(Model* creator, TransType type, rsrc_ptr res,
const double price, const double minfrac) : price_(price), minfrac_(minfrac) {
type_ = type;
this->setResource(res);
supplier_ = NULL;
requester_ = NULL;
if (type == OFFER) {
supplier_ = creator;
} else {
requester_ = creator;
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction::~Transaction() { }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction* Transaction::clone() {
// clones resource_ and gives copy to the transaction clone
Transaction* trans = new Transaction(*this);
trans->setResource(resource_);
return trans;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::approveTransfer() {
std::vector<rsrc_ptr> manifest;
try {
manifest = supplier_->removeResource(*this);
requester_->addResource(*this, manifest);
} catch (CycException err) {
CLOG(LEV_ERROR) << "Material transfer failed from "
<< supplier_->ID() << " to " << requester_->ID() << ": "
<< err.what();
return;
}
// register that this transaction occured
this->Transaction::addTransToTable();
int nResources = manifest.size();
for (int pos = 0; pos < nResources; pos++) {
// MUST PRECEDE 'addResourceToTable' call! record the resource with its state
// because this can potentially update the material's stateID
manifest.at(pos)->addToTable();
// record that what resources belong to this transaction
this->Transaction::addResourceToTable(pos + 1, manifest.at(pos));
}
CLOG(LEV_INFO3) << "Material sent from " << supplier_->ID() << " to "
<< requester_->ID() << ".";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::matchWith(Transaction& other) {
if (other.type_ == type_) {
throw CycTransMismatchException();
}
if (type_ == OFFER) {
requester_ = other.requester();
other.supplier_ = supplier();
} else {
supplier_ = other.supplier();
other.requester_ = requester();
}
trans_id_ = next_trans_id_++;
other.trans_id_ = trans_id_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MarketModel* Transaction::market() const {
// put here to make explicit that this method throws
MarketModel* market;
try {
market = MarketModel::marketForCommod(commod_);
} catch(CycMarketlessCommodException e) {
throw e;
}
return market;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Transaction::supplier() const {
if (supplier_ == NULL) {
std::string err_msg = "Uninitilized message supplier.";
throw CycNullMsgParamException(err_msg);
}
return supplier_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Transaction::requester() const {
if (requester_ == NULL) {
std::string err_msg = "Uninitilized message requester.";
throw CycNullMsgParamException(err_msg);
}
return requester_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string Transaction::commod() const {
return commod_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setCommod(std::string new_commod) {
commod_ = new_commod;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool Transaction::isOffer() const {
return type_ == OFFER;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Transaction::price() const {
return price_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setPrice(double new_price) {
price_ = new_price;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
rsrc_ptr Transaction::resource() const {
return resource_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setResource(rsrc_ptr new_resource) {
if (new_resource.get()) {
resource_ = new_resource->clone();
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Transaction::minfrac() const {
return minfrac_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setMinFrac(double new_minfrac) {
minfrac_ = new_minfrac;
}
///////////////////////////////////////////////////////////////////////////////
////////////// Output db recording code ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void Transaction::define_trans_table(){
// declare the table columns
trans_table->addField("ID","INTEGER");
trans_table->addField("SenderID","INTEGER");
trans_table->addField("ReceiverID","INTEGER");
trans_table->addField("Time","INTEGER");
trans_table->addField("Price","REAL");
// declare the table's primary key
primary_key pk;
pk.push_back("ID");
trans_table->setPrimaryKey(pk);
// add foreign keys
foreign_key_ref *fkref;
foreign_key *fk;
key myk, theirk;
// Agents table foreign keys
theirk.push_back("ID");
fkref = new foreign_key_ref("Agents",theirk);
// the sender id
myk.push_back("SenderID");
fk = new foreign_key(myk, (*fkref) );
trans_table->addForeignKey( (*fk) ); // sender id references agents' id
myk.clear();
// the reciever id
myk.push_back("ReceiverID");
fk = new foreign_key(myk, (*fkref) );
trans_table->addForeignKey( (*fk) ); // receiver id references agents' id
myk.clear();
theirk.clear();
// we've now defined the table
trans_table->tableDefined();
}
void Transaction::addTransToTable() {
// if we haven't logged a message yet, define the table
if ( !trans_table->defined() )
Transaction::define_trans_table();
// make a row
// declare data
data an_id(trans_id_), a_sender( supplier_->ID() ),
a_receiver( requester_->ID() ), a_time( TI->time() ),
a_price( price_ );
// declare entries
entry id("ID",an_id), sender("SenderID",a_sender),
receiver("ReceiverID",a_receiver), time("Time",a_time),
price("Price",a_price);
// declare row
row aRow;
aRow.push_back(id), aRow.push_back(sender), aRow.push_back(receiver),
aRow.push_back(time),aRow.push_back(price);
// add the row
trans_table->addRow(aRow);
// record this primary key
pkref_trans_.push_back(id);
}
void Transaction::define_trans_resource_table(){
// declare the table columns
trans_resource_table->addField("TransactionID","INTEGER");
trans_resource_table->addField("Position","INTEGER");
trans_resource_table->addField("ResourceID","INTEGER");
trans_resource_table->addField("StateID","INTEGER");
trans_resource_table->addField("Quantity","REAL");
// declare the table's primary key
primary_key pk;
pk.push_back("TransactionID"), pk.push_back("Position");
trans_resource_table->setPrimaryKey(pk);
// add foreign keys
foreign_key_ref *fkref;
foreign_key *fk;
key myk, theirk;
// Transactions table foreign keys
theirk.push_back("ID");
fkref = new foreign_key_ref("Transactions",theirk);
// the transaction id
myk.push_back("TransactionID");
fk = new foreign_key(myk, (*fkref) );
trans_resource_table->addForeignKey( (*fk) ); // transid references transaction's id
myk.clear(), theirk.clear();
// Resource table foreign keys
theirk.push_back("ID");
fkref = new foreign_key_ref("Resources",theirk);
// the resource id
myk.push_back("ResourceID");
fk = new foreign_key(myk, (*fkref) );
trans_resource_table->addForeignKey( (*fk) ); // resourceid references resource's id
// we've now defined the table
trans_resource_table->tableDefined();
}
void Transaction::addResourceToTable(int transPos, rsrc_ptr r){
// if we haven't logged a message yet, define the table
if ( !trans_resource_table->defined() )
Transaction::define_trans_resource_table();
// make a row
// declare data
data an_id(trans_id_), a_pos(transPos),
a_resource(r->originalID()), a_state(r->stateID()), an_amt(r->quantity());
// declare entries
entry id("TransactionID",an_id), pos("Position",a_pos),
resource("ResourceID",a_resource), state("StateID", a_state), amt("Quantity",an_amt);
// declare row
row aRow;
aRow.push_back(id), aRow.push_back(pos),
aRow.push_back(resource), aRow.push_back(state), aRow.push_back(amt);
// add the row
trans_resource_table->addRow(aRow);
// record this primary key
pkref_rsrc_.push_back(id);
pkref_rsrc_.push_back(pos);
}
<commit_msg>adds marketID column to transactions table, it references the ID for the market in the markets table.<commit_after>// Transaction.cpp
#include "Transaction.h"
#include "Timer.h"
#include "Model.h"
#include "MarketModel.h"
#include <string>
#include <vector>
// initialize static variables
int Transaction::next_trans_id_ = 1;
// Database table for transactions
table_ptr Transaction::trans_table = new Table("Transactions");
table_ptr Transaction::trans_resource_table = new Table("TransactedResources");
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction::Transaction(Model* creator, TransType type, rsrc_ptr res,
const double price, const double minfrac) : price_(price), minfrac_(minfrac) {
type_ = type;
this->setResource(res);
supplier_ = NULL;
requester_ = NULL;
if (type == OFFER) {
supplier_ = creator;
} else {
requester_ = creator;
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction::~Transaction() { }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction* Transaction::clone() {
// clones resource_ and gives copy to the transaction clone
Transaction* trans = new Transaction(*this);
trans->setResource(resource_);
return trans;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::approveTransfer() {
std::vector<rsrc_ptr> manifest;
try {
manifest = supplier_->removeResource(*this);
requester_->addResource(*this, manifest);
} catch (CycException err) {
CLOG(LEV_ERROR) << "Material transfer failed from "
<< supplier_->ID() << " to " << requester_->ID() << ": "
<< err.what();
return;
}
// register that this transaction occured
this->Transaction::addTransToTable();
int nResources = manifest.size();
for (int pos = 0; pos < nResources; pos++) {
// MUST PRECEDE 'addResourceToTable' call! record the resource with its state
// because this can potentially update the material's stateID
manifest.at(pos)->addToTable();
// record that what resources belong to this transaction
this->Transaction::addResourceToTable(pos + 1, manifest.at(pos));
}
CLOG(LEV_INFO3) << "Material sent from " << supplier_->ID() << " to "
<< requester_->ID() << ".";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::matchWith(Transaction& other) {
if (other.type_ == type_) {
throw CycTransMismatchException();
}
if (type_ == OFFER) {
requester_ = other.requester();
other.supplier_ = supplier();
} else {
supplier_ = other.supplier();
other.requester_ = requester();
}
trans_id_ = next_trans_id_++;
other.trans_id_ = trans_id_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MarketModel* Transaction::market() const {
// put here to make explicit that this method throws
MarketModel* market;
try {
market = MarketModel::marketForCommod(commod_);
} catch(CycMarketlessCommodException e) {
throw e;
}
return market;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Transaction::supplier() const {
if (supplier_ == NULL) {
std::string err_msg = "Uninitilized message supplier.";
throw CycNullMsgParamException(err_msg);
}
return supplier_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Transaction::requester() const {
if (requester_ == NULL) {
std::string err_msg = "Uninitilized message requester.";
throw CycNullMsgParamException(err_msg);
}
return requester_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string Transaction::commod() const {
return commod_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setCommod(std::string new_commod) {
commod_ = new_commod;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool Transaction::isOffer() const {
return type_ == OFFER;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Transaction::price() const {
return price_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setPrice(double new_price) {
price_ = new_price;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
rsrc_ptr Transaction::resource() const {
return resource_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setResource(rsrc_ptr new_resource) {
if (new_resource.get()) {
resource_ = new_resource->clone();
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Transaction::minfrac() const {
return minfrac_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setMinFrac(double new_minfrac) {
minfrac_ = new_minfrac;
}
///////////////////////////////////////////////////////////////////////////////
////////////// Output db recording code ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void Transaction::define_trans_table(){
// declare the table columns
trans_table->addField("ID","INTEGER");
trans_table->addField("SenderID","INTEGER");
trans_table->addField("ReceiverID","INTEGER");
trans_table->addField("MarketID","INTEGER");
trans_table->addField("Time","INTEGER");
trans_table->addField("Price","REAL");
// declare the table's primary key
primary_key pk;
pk.push_back("ID");
trans_table->setPrimaryKey(pk);
// add foreign keys
foreign_key_ref *fkref, *fkref_m;
foreign_key *fk;
key myk, theirk, theirk_m;
// Agents table foreign keys
theirk.push_back("ID");
fkref = new foreign_key_ref("Agents",theirk);
// Markets table foreigh keys
theirk_m.push_back("ID");
fkref_m = new foreign_key_ref("Markets",theirk_m);
// the sender id
myk.push_back("SenderID");
fk = new foreign_key(myk, (*fkref) );
trans_table->addForeignKey( (*fk) ); // sender id references agents' id
myk.clear();
// the reciever id
myk.push_back("ReceiverID");
fk = new foreign_key(myk, (*fkref) );
trans_table->addForeignKey( (*fk) ); // receiver id references agents' id
myk.clear();
theirk.clear();
// the market id
myk.push_back("MarketID");
fk = new foreign_key(myk, (*fkref_m) );
trans_table->addForeignKey( (*fk) ); // this market id references markets' id
myk.clear();
theirk_m.clear();
// we've now defined the table
trans_table->tableDefined();
}
void Transaction::addTransToTable() {
// if we haven't logged a message yet, define the table
if ( !trans_table->defined() )
Transaction::define_trans_table();
// make a row
// declare data
data an_id(trans_id_),
a_sender( supplier_->ID() ),
a_receiver( requester_->ID() ),
a_market( market()->ID() ),
a_time( TI->time() ),
a_price( price_ );
// declare entries
entry id("ID",an_id),
sender("SenderID",a_sender),
receiver("ReceiverID",a_receiver),
market("ReceiverID",a_market),
time("Time",a_time),
price("Price",a_price);
// declare row
row aRow;
aRow.push_back(id),
aRow.push_back(sender),
aRow.push_back(receiver),
aRow.push_back(market),
aRow.push_back(time),
aRow.push_back(price);
// add the row
trans_table->addRow(aRow);
// record this primary key
pkref_trans_.push_back(id);
}
void Transaction::define_trans_resource_table(){
// declare the table columns
trans_resource_table->addField("TransactionID","INTEGER");
trans_resource_table->addField("Position","INTEGER");
trans_resource_table->addField("ResourceID","INTEGER");
trans_resource_table->addField("StateID","INTEGER");
trans_resource_table->addField("Quantity","REAL");
// declare the table's primary key
primary_key pk;
pk.push_back("TransactionID"), pk.push_back("Position");
trans_resource_table->setPrimaryKey(pk);
// add foreign keys
foreign_key_ref *fkref;
foreign_key *fk;
key myk, theirk;
// Transactions table foreign keys
theirk.push_back("ID");
fkref = new foreign_key_ref("Transactions",theirk);
// the transaction id
myk.push_back("TransactionID");
fk = new foreign_key(myk, (*fkref) );
trans_resource_table->addForeignKey( (*fk) ); // transid references transaction's id
myk.clear(), theirk.clear();
// Resource table foreign keys
theirk.push_back("ID");
fkref = new foreign_key_ref("Resources",theirk);
// the resource id
myk.push_back("ResourceID");
fk = new foreign_key(myk, (*fkref) );
trans_resource_table->addForeignKey( (*fk) ); // resourceid references resource's id
// we've now defined the table
trans_resource_table->tableDefined();
}
void Transaction::addResourceToTable(int transPos, rsrc_ptr r){
// if we haven't logged a message yet, define the table
if ( !trans_resource_table->defined() )
Transaction::define_trans_resource_table();
// make a row
// declare data
data an_id(trans_id_), a_pos(transPos),
a_resource(r->originalID()), a_state(r->stateID()), an_amt(r->quantity());
// declare entries
entry id("TransactionID",an_id), pos("Position",a_pos),
resource("ResourceID",a_resource), state("StateID", a_state), amt("Quantity",an_amt);
// declare row
row aRow;
aRow.push_back(id), aRow.push_back(pos),
aRow.push_back(resource), aRow.push_back(state), aRow.push_back(amt);
// add the row
trans_resource_table->addRow(aRow);
// record this primary key
pkref_rsrc_.push_back(id);
pkref_rsrc_.push_back(pos);
}
<|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 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) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XERCESBRIDGENAVIGATOR_HEADER_GUARD_1357924680)
#define XERCESBRIDGENAVIGATOR_HEADER_GUARD_1357924680
#include <XercesParserLiaison/XercesParserLiaisonDefinitions.hpp>
#include <cassert>
class DOM_Attr;
class DOM_Node;
class XercesDocumentBridge;
class XalanAttr;
class XalanElement;
class XalanNode;
class XalanText;
class DOM_Text;
class XALAN_XERCESPARSERLIAISON_EXPORT XercesBridgeNavigator
{
public:
XercesBridgeNavigator(XercesDocumentBridge* theOwnerDocument);
XercesBridgeNavigator(const XercesBridgeNavigator& theSource);
virtual
~XercesBridgeNavigator();
XercesBridgeNavigator&
operator=(const XercesBridgeNavigator& theRHS);
virtual XercesDocumentBridge*
getOwnerDocument() const;
virtual XalanNode*
mapNode(const DOM_Node& theXercesNode) const;
virtual XalanAttr*
mapNode(const DOM_Attr& theXercesNode) const;
virtual DOM_Node
mapNode(const XalanNode* theXalanNode) const;
virtual DOM_Attr
mapNode(const XalanAttr* theXercesNode) const;
virtual XalanNode*
getParentNode(const DOM_Node& theXercesNode) const;
virtual XalanNode*
getPreviousSibling(const DOM_Node& theXercesNode) const;
virtual XalanNode*
getNextSibling(const DOM_Node& theXercesNode) const;
virtual XalanNode*
getFirstChild(const DOM_Node& theXercesNode) const;
virtual XalanNode*
getLastChild(const DOM_Node& theXercesNode) const;
virtual XalanNode*
insertBefore(
DOM_Node& theXercesParent,
XalanNode* newChild,
XalanNode* refChild) const;
virtual XalanNode*
replaceChild(
DOM_Node& theXercesParent,
XalanNode* newChild,
XalanNode* oldChild) const;
virtual XalanNode*
removeChild(
DOM_Node& theXercesParent,
XalanNode* oldChild) const;
virtual XalanNode*
appendChild(
DOM_Node& theXercesParent,
XalanNode* newChild) const;
virtual XalanElement*
getOwnerElement(const DOM_Attr& theXercesAttr) const;
virtual XalanNode*
cloneNode(
const XalanNode* theXalanNode,
const DOM_Node& theXercesNode,
bool deep) const;
virtual XalanText*
splitText(
DOM_Text& theXercesText,
unsigned int offset) const;
private:
// Not implemented...
bool
operator==(const XercesBridgeNavigator& theRHS) const;
// Data members...
XercesDocumentBridge* const m_ownerDocument;
};
#endif // !defined(XERCESBRIDGENAVIGATOR_HEADER_GUARD_1357924680)
<commit_msg>Made constructor explicit.<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 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) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XERCESBRIDGENAVIGATOR_HEADER_GUARD_1357924680)
#define XERCESBRIDGENAVIGATOR_HEADER_GUARD_1357924680
#include <XercesParserLiaison/XercesParserLiaisonDefinitions.hpp>
#include <cassert>
class DOM_Attr;
class DOM_Node;
class XercesDocumentBridge;
class XalanAttr;
class XalanElement;
class XalanNode;
class XalanText;
class DOM_Text;
class XALAN_XERCESPARSERLIAISON_EXPORT XercesBridgeNavigator
{
public:
explicit
XercesBridgeNavigator(XercesDocumentBridge* theOwnerDocument);
XercesBridgeNavigator(const XercesBridgeNavigator& theSource);
virtual
~XercesBridgeNavigator();
XercesBridgeNavigator&
operator=(const XercesBridgeNavigator& theRHS);
virtual XercesDocumentBridge*
getOwnerDocument() const;
virtual XalanNode*
mapNode(const DOM_Node& theXercesNode) const;
virtual XalanAttr*
mapNode(const DOM_Attr& theXercesNode) const;
virtual DOM_Node
mapNode(const XalanNode* theXalanNode) const;
virtual DOM_Attr
mapNode(const XalanAttr* theXercesNode) const;
virtual XalanNode*
getParentNode(const DOM_Node& theXercesNode) const;
virtual XalanNode*
getPreviousSibling(const DOM_Node& theXercesNode) const;
virtual XalanNode*
getNextSibling(const DOM_Node& theXercesNode) const;
virtual XalanNode*
getFirstChild(const DOM_Node& theXercesNode) const;
virtual XalanNode*
getLastChild(const DOM_Node& theXercesNode) const;
virtual XalanNode*
insertBefore(
DOM_Node& theXercesParent,
XalanNode* newChild,
XalanNode* refChild) const;
virtual XalanNode*
replaceChild(
DOM_Node& theXercesParent,
XalanNode* newChild,
XalanNode* oldChild) const;
virtual XalanNode*
removeChild(
DOM_Node& theXercesParent,
XalanNode* oldChild) const;
virtual XalanNode*
appendChild(
DOM_Node& theXercesParent,
XalanNode* newChild) const;
virtual XalanElement*
getOwnerElement(const DOM_Attr& theXercesAttr) const;
virtual XalanNode*
cloneNode(
const XalanNode* theXalanNode,
const DOM_Node& theXercesNode,
bool deep) const;
virtual XalanText*
splitText(
DOM_Text& theXercesText,
unsigned int offset) const;
private:
// Not implemented...
bool
operator==(const XercesBridgeNavigator& theRHS) const;
// Data members...
XercesDocumentBridge* const m_ownerDocument;
};
#endif // !defined(XERCESBRIDGENAVIGATOR_HEADER_GUARD_1357924680)
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkXMLUnstructuredGridWriter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkXMLUnstructuredGridWriter.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkErrorCode.h"
#include "vtkInformation.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnstructuredGrid.h"
#define vtkOffsetsManager_DoNotInclude
#include "vtkOffsetsManagerArray.h"
#undef vtkOffsetsManager_DoNotInclude
#include <assert.h>
vtkCxxRevisionMacro(vtkXMLUnstructuredGridWriter, "1.13");
vtkStandardNewMacro(vtkXMLUnstructuredGridWriter);
//----------------------------------------------------------------------------
vtkXMLUnstructuredGridWriter::vtkXMLUnstructuredGridWriter()
{
this->CellsOM = new OffsetsManagerArray;
}
//----------------------------------------------------------------------------
vtkXMLUnstructuredGridWriter::~vtkXMLUnstructuredGridWriter()
{
delete this->CellsOM;
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
//----------------------------------------------------------------------------
vtkUnstructuredGrid* vtkXMLUnstructuredGridWriter::GetInput()
{
return static_cast<vtkUnstructuredGrid*>(this->Superclass::GetInput());
}
//----------------------------------------------------------------------------
const char* vtkXMLUnstructuredGridWriter::GetDataSetName()
{
return "UnstructuredGrid";
}
//----------------------------------------------------------------------------
const char* vtkXMLUnstructuredGridWriter::GetDefaultFileExtension()
{
return "vtu";
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteInlinePieceAttributes()
{
this->Superclass::WriteInlinePieceAttributes();
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
vtkUnstructuredGrid* input = this->GetInput();
this->WriteScalarAttribute("NumberOfCells", input->GetNumberOfCells());
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteInlinePiece(vtkIndent indent)
{
vtkUnstructuredGrid* input = this->GetInput();
// Split progress range by the approximate fraction of data written
// by each step in this method.
float progressRange[2] = {0,0};
this->GetProgressRange(progressRange);
float fractions[3];
this->CalculateSuperclassFraction(fractions);
// Set the range of progress for superclass.
this->SetProgressRange(progressRange, 0, fractions);
// Let the superclass write its data.
this->Superclass::WriteInlinePiece(indent);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
// Set range of progress for the cell specifications.
this->SetProgressRange(progressRange, 1, fractions);
// Write the cell specifications.
this->WriteCellsInline("Cells", input->GetCells(),
input->GetCellTypesArray(), indent);
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::AllocatePositionArrays()
{
this->Superclass::AllocatePositionArrays();
this->NumberOfCellsPositions = new unsigned long[this->NumberOfPieces];
this->CellsOM->Allocate(this->NumberOfPieces,3,this->NumberOfTimeSteps);
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::DeletePositionArrays()
{
this->Superclass::DeletePositionArrays();
delete [] this->NumberOfCellsPositions;
this->NumberOfCellsPositions = NULL;
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPieceAttributes(int index)
{
this->Superclass::WriteAppendedPieceAttributes(index);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
this->NumberOfCellsPositions[index] =
this->ReserveAttributeSpace("NumberOfCells");
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPiece(int index,
vtkIndent indent)
{
vtkUnstructuredGrid* input = this->GetInput();
this->Superclass::WriteAppendedPiece(index, indent);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
this->WriteCellsAppended("Cells", input->GetCellTypesArray(), indent,
&this->CellsOM->GetPiece(index));
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPieceData(int index)
{
ostream& os = *(this->Stream);
vtkUnstructuredGrid* input = this->GetInput();
unsigned long returnPosition = os.tellp();
os.seekp(this->NumberOfCellsPositions[index]);
this->WriteScalarAttribute("NumberOfCells", input->GetNumberOfCells());
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
os.seekp(returnPosition);
// Split progress range by the approximate fraction of data written
// by each step in this method.
float progressRange[2] = {0,0};
this->GetProgressRange(progressRange);
float fractions[3];
this->CalculateSuperclassFraction(fractions);
// Set the range of progress for superclass.
this->SetProgressRange(progressRange, 0, fractions);
// Let the superclass write its data.
this->Superclass::WriteAppendedPieceData(index);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
// Set range of progress for the cell specifications.
this->SetProgressRange(progressRange, 1, fractions);
// Write the cell specification arrays.
this->WriteCellsAppendedData( input->GetCells(),
input->GetCellTypesArray(), this->CurrentTimeIndex,
&this->CellsOM->GetPiece(index));
}
//----------------------------------------------------------------------------
vtkIdType vtkXMLUnstructuredGridWriter::GetNumberOfInputCells()
{
return this->GetInput()->GetNumberOfCells();
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::CalculateSuperclassFraction(float* fractions)
{
vtkUnstructuredGrid* input = this->GetInput();
// The superclass will write point/cell data and point specifications.
int pdArrays = input->GetPointData()->GetNumberOfArrays();
int cdArrays = input->GetCellData()->GetNumberOfArrays();
vtkIdType pdSize = pdArrays*this->GetNumberOfInputPoints();
vtkIdType cdSize = cdArrays*this->GetNumberOfInputCells();
vtkIdType pointsSize = this->GetNumberOfInputPoints();
// This class will write cell specifications.
vtkIdType connectSize = (input->GetCells()->GetData()->GetNumberOfTuples() -
input->GetNumberOfCells());
vtkIdType offsetSize = input->GetNumberOfCells();
vtkIdType typesSize = input->GetNumberOfCells();
int total = (pdSize+cdSize+pointsSize+connectSize+offsetSize+typesSize);
if(total == 0)
{
total = 1;
}
fractions[0] = 0;
fractions[1] = float(pdSize+cdSize+pointsSize)/total;
fractions[2] = 1;
}
//----------------------------------------------------------------------------
int vtkXMLUnstructuredGridWriter::FillInputPortInformation(
int vtkNotUsed(port), vtkInformation* info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkUnstructuredGrid");
return 1;
}
<commit_msg>BUG:Fixed the case of an empty dataset<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkXMLUnstructuredGridWriter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkXMLUnstructuredGridWriter.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkErrorCode.h"
#include "vtkInformation.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnstructuredGrid.h"
#define vtkOffsetsManager_DoNotInclude
#include "vtkOffsetsManagerArray.h"
#undef vtkOffsetsManager_DoNotInclude
#include <assert.h>
vtkCxxRevisionMacro(vtkXMLUnstructuredGridWriter, "1.14");
vtkStandardNewMacro(vtkXMLUnstructuredGridWriter);
//----------------------------------------------------------------------------
vtkXMLUnstructuredGridWriter::vtkXMLUnstructuredGridWriter()
{
this->CellsOM = new OffsetsManagerArray;
}
//----------------------------------------------------------------------------
vtkXMLUnstructuredGridWriter::~vtkXMLUnstructuredGridWriter()
{
delete this->CellsOM;
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
//----------------------------------------------------------------------------
vtkUnstructuredGrid* vtkXMLUnstructuredGridWriter::GetInput()
{
return static_cast<vtkUnstructuredGrid*>(this->Superclass::GetInput());
}
//----------------------------------------------------------------------------
const char* vtkXMLUnstructuredGridWriter::GetDataSetName()
{
return "UnstructuredGrid";
}
//----------------------------------------------------------------------------
const char* vtkXMLUnstructuredGridWriter::GetDefaultFileExtension()
{
return "vtu";
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteInlinePieceAttributes()
{
this->Superclass::WriteInlinePieceAttributes();
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
vtkUnstructuredGrid* input = this->GetInput();
this->WriteScalarAttribute("NumberOfCells", input->GetNumberOfCells());
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteInlinePiece(vtkIndent indent)
{
vtkUnstructuredGrid* input = this->GetInput();
// Split progress range by the approximate fraction of data written
// by each step in this method.
float progressRange[2] = {0,0};
this->GetProgressRange(progressRange);
float fractions[3];
this->CalculateSuperclassFraction(fractions);
// Set the range of progress for superclass.
this->SetProgressRange(progressRange, 0, fractions);
// Let the superclass write its data.
this->Superclass::WriteInlinePiece(indent);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
// Set range of progress for the cell specifications.
this->SetProgressRange(progressRange, 1, fractions);
// Write the cell specifications.
this->WriteCellsInline("Cells", input->GetCells(),
input->GetCellTypesArray(), indent);
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::AllocatePositionArrays()
{
this->Superclass::AllocatePositionArrays();
this->NumberOfCellsPositions = new unsigned long[this->NumberOfPieces];
this->CellsOM->Allocate(this->NumberOfPieces,3,this->NumberOfTimeSteps);
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::DeletePositionArrays()
{
this->Superclass::DeletePositionArrays();
delete [] this->NumberOfCellsPositions;
this->NumberOfCellsPositions = NULL;
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPieceAttributes(int index)
{
this->Superclass::WriteAppendedPieceAttributes(index);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
this->NumberOfCellsPositions[index] =
this->ReserveAttributeSpace("NumberOfCells");
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPiece(int index,
vtkIndent indent)
{
vtkUnstructuredGrid* input = this->GetInput();
this->Superclass::WriteAppendedPiece(index, indent);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
this->WriteCellsAppended("Cells", input->GetCellTypesArray(), indent,
&this->CellsOM->GetPiece(index));
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPieceData(int index)
{
ostream& os = *(this->Stream);
vtkUnstructuredGrid* input = this->GetInput();
unsigned long returnPosition = os.tellp();
os.seekp(this->NumberOfCellsPositions[index]);
this->WriteScalarAttribute("NumberOfCells", input->GetNumberOfCells());
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
os.seekp(returnPosition);
// Split progress range by the approximate fraction of data written
// by each step in this method.
float progressRange[2] = {0,0};
this->GetProgressRange(progressRange);
float fractions[3];
this->CalculateSuperclassFraction(fractions);
// Set the range of progress for superclass.
this->SetProgressRange(progressRange, 0, fractions);
// Let the superclass write its data.
this->Superclass::WriteAppendedPieceData(index);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
return;
}
// Set range of progress for the cell specifications.
this->SetProgressRange(progressRange, 1, fractions);
// Write the cell specification arrays.
this->WriteCellsAppendedData( input->GetCells(),
input->GetCellTypesArray(), this->CurrentTimeIndex,
&this->CellsOM->GetPiece(index));
}
//----------------------------------------------------------------------------
vtkIdType vtkXMLUnstructuredGridWriter::GetNumberOfInputCells()
{
return this->GetInput()->GetNumberOfCells();
}
//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::CalculateSuperclassFraction(float* fractions)
{
vtkUnstructuredGrid* input = this->GetInput();
// The superclass will write point/cell data and point specifications.
int pdArrays = input->GetPointData()->GetNumberOfArrays();
int cdArrays = input->GetCellData()->GetNumberOfArrays();
vtkIdType pdSize = pdArrays*this->GetNumberOfInputPoints();
vtkIdType cdSize = cdArrays*this->GetNumberOfInputCells();
vtkIdType pointsSize = this->GetNumberOfInputPoints();
// This class will write cell specifications.
vtkIdType connectSize;
if(input->GetCells()==0)
{
connectSize=0;
}
else
{
connectSize = (input->GetCells()->GetData()->GetNumberOfTuples() -
input->GetNumberOfCells());
}
vtkIdType offsetSize = input->GetNumberOfCells();
vtkIdType typesSize = input->GetNumberOfCells();
int total = (pdSize+cdSize+pointsSize+connectSize+offsetSize+typesSize);
if(total == 0)
{
total = 1;
}
fractions[0] = 0;
fractions[1] = float(pdSize+cdSize+pointsSize)/total;
fractions[2] = 1;
}
//----------------------------------------------------------------------------
int vtkXMLUnstructuredGridWriter::FillInputPortInformation(
int vtkNotUsed(port), vtkInformation* info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkUnstructuredGrid");
return 1;
}
<|endoftext|> |
<commit_before>/*
* qiesmap.cpp
*
* Copyright (c) 2016 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <getopt.h>
#include <iostream>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#include "QI/Util.h"
#include "QI/Sequences/SteadyStateSequence.cpp"
#include "Filters/ApplyAlgorithmFilter.h"
using namespace std;
using namespace Eigen;
// Helper Functions
void SemiaxesToHoff(const double A, const double B, const double c,
double &a, double &b) {
b = (-c*A + sqrt(c*c*A*A - (c*c + B*B)*(A*A - B*B)))/(c*c + B*B);
a = B / (b*B + c*sqrt(1-b*b));
}
void EllipseToMRI(const double a, const double b, const double scale, const double th, const double TR, const double flip,
float &M, float &T1, float &T2, float &df0) {
const double ca = cos(flip);
T1 = -TR / (log(a-b + (1.-a*b)*a*ca) - log(a*(1.-a*b) + (a-b)*ca));
T2 = -TR / log(a);
M = (scale/sqrt(a))*(1-b*b)/(1-a*b);
df0 = th / (2.*M_PI*TR);
}
class ESAlgo : public QI::ApplyXF::Algorithm {
protected:
size_t m_size = 0;
shared_ptr<QI::SSFP_GS> m_sequence = nullptr;
public:
size_t numInputs() const override { return 1; }
size_t numConsts() const override { return 1; }
size_t numOutputs() const override { return 6; }
const float &zero(const size_t i) const override { static float zero = 0; return zero; }
const vector<string> & names() const {
static vector<string> _names = {"M", "T1", "T2", "th", "a", "b"};
return _names;
}
size_t dataSize() const override { return m_size; }
void setSize(const size_t s) { m_size = s; }
virtual std::vector<float> defaultConsts() const override {
std::vector<float> def(1, 1.0f); // B1
return def;
}
void SetSequence(const shared_ptr<QI::SSFP_GS> &s) { m_sequence = s;}
MatrixXd buildS(const ArrayXd &x, const ArrayXd &y) const {
Matrix<double, Dynamic, 6> D(x.rows(), 6);
D.col(0) = x*x;
D.col(1) = 2*x*y;
D.col(2) = y*y;
D.col(3) = 2*x;
D.col(4) = 2*y;
D.col(5).setConstant(1);
return D.transpose() * D;
}
MatrixXd fitzC() const {
typedef Matrix<double, 6, 6> Matrix6d;
Matrix6d C = Matrix6d::Zero();
// FitZ[5]ibbon et al
C(0,2) = -2; C(1,1) = 1; C(2,0) = -2;
return C;
}
MatrixXd hyperC(const ArrayXd &x, const ArrayXd &y) const {
typedef Matrix<double, 6, 6> Matrix6d;
Matrix6d C = Matrix6d::Zero();
// FitZ[5]ibbon et al
//C(0,2) = -2; C(1,1) = 1; C(2,0) = -2;
// Hyper Ellipse
const double N = x.cols();
const double xc = x.sum() / N;
const double yc = y.sum() / N;
const double sx = x.square().sum() / N;
const double sy = y.square().sum() / N;
const double xy = (x * y).sum() / N;
C << 6*sx, 6*xy, sx+sy, 6*xc, 2*yc, 1,
6*xy, 4*(sx+sy), 6*xy, 4*yc, 4*xc, 0,
sx + sy, 6*xy, 6*sy, 2*xc, 6*yc, 1,
6*xc, 4*yc, 2*xc, 4, 0, 0,
2*yc, 4*xc, 6*yc, 0, 4, 0,
1, 0, 1, 0, 0, 0;
return C;
}
virtual void apply(const std::vector<TInput> &inputs, const std::vector<TConst> &consts,
std::vector<TOutput> &outputs, TConst &residual,
TInput &resids, TIters &its) const override
{
typedef Matrix<double, 6, 6> Matrix6d;
typedef Matrix<double, 6, 1> Vector6d;
const double B1 = consts[0];
Eigen::Map<const Eigen::ArrayXcf> indata(inputs[0].GetDataPointer(), inputs[0].Size());
ArrayXcd data = indata.cast<complex<double>>();
const double scale = data.abs().maxCoeff();
ArrayXd x = data.real() / scale;
ArrayXd y = data.imag() / scale;
MatrixXd S = buildS(x, y);
Matrix6d C = hyperC(x, y);
// Note A and B are swapped so we can use GES
GeneralizedSelfAdjointEigenSolver<MatrixXd> solver(C, S);
ArrayXd Z;
if (fabs(solver.eigenvalues()[5]) > fabs(solver.eigenvalues()[0]))
Z = solver.eigenvectors().col(5);
else
Z = solver.eigenvectors().col(0);
const double dsc=(Z[1]*Z[1]-Z[0]*Z[2]);
const double xc = (Z[2]*Z[3]-Z[1]*Z[4])/dsc;
const double yc = (Z[0]*Z[4]-Z[1]*Z[3])/dsc;
const double th = atan2(yc,xc);
const double num = 2*(Z[0]*(Z[4]*Z[4])+Z[2]*(Z[3]*Z[3])+Z[5]*(Z[1]*Z[1])-2*Z[1]*Z[3]*Z[4]-Z[0]*Z[2]*Z[5]);
double A = sqrt(num/(dsc*(sqrt((Z[0]-Z[2])*(Z[0]-Z[2]) + 4*Z[1]*Z[1])-(Z[0]+Z[2]))));
double B = sqrt(num/(dsc*(-sqrt((Z[0]-Z[2])*(Z[0]-Z[2]) + 4*Z[1]*Z[1])-(Z[0]+Z[2]))));
if (A > B) {
std::swap(A, B);
}
double a, b;
double c = sqrt(xc*xc+yc*yc);
SemiaxesToHoff(A, B, c, a, b);
EllipseToMRI(a, b, c*scale, th, m_sequence->TR(), B1 * m_sequence->flip()[0],
outputs[0], outputs[1], outputs[2], outputs[3]);
outputs[4] = a;
outputs[5] = b;
}
};
//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: qiesmap [options] input \n\
\n\
A utility for calculating T1,T2,PD and f0 maps from SSFP data.\n\
Input must be a single complex image with at least 6 phase increments.\n\
\n\
Options:\n\
--help, -h : Print this message.\n\
--verbose, -v : Print more information.\n\
--out, -o path : Specify an output prefix.\n\
--mask, -m file : Mask input with specified file.\n\
--B1, -b file : B1 Map file (ratio)\n\
--threads, -T N : Use N threads (default=hardware limit).\n"
};
bool verbose = false;
static size_t num_threads = 4;
static string outPrefix;
const struct option long_opts[] = {
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"out", required_argument, 0, 'o'},
{"mask", required_argument, 0, 'm'},
{"B1", required_argument, 0, 'b'},
{"threads", required_argument, 0, 'T'},
{0, 0, 0, 0}
};
const char *short_opts = "hvo:m:b:T:";
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
Eigen::initParallel();
QI::VolumeF::Pointer mask = ITK_NULLPTR;
QI::VolumeF::Pointer B1 = ITK_NULLPTR;
shared_ptr<ESAlgo> algo = make_shared<ESAlgo>();
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'm':
if (verbose) cout << "Opening mask file " << optarg << endl;
mask = QI::ReadImage(optarg);
break;
case 'o':
outPrefix = optarg;
if (verbose) cout << "Output prefix will be: " << outPrefix << endl;
break;
case 'b':
if (verbose) cout << "Opening B1 file: " << optarg << endl;
B1 = QI::ReadImage(optarg);
break;
case 'T':
num_threads = stoi(optarg);
if (num_threads == 0)
num_threads = std::thread::hardware_concurrency();
break;
case 'h':
cout << QI::GetVersion() << endl << usage << endl;
return EXIT_SUCCESS;
case '?': // getopt will print an error message
return EXIT_FAILURE;
default:
cout << "Unhandled option " << string(1, c) << endl;
return EXIT_FAILURE;
}
}
if ((argc - optind) != 1) {
cout << "Incorrect number of arguments." << endl << usage << endl;
return EXIT_FAILURE;
}
string inputFilename = argv[optind++];
if (verbose) cout << "Opening file: " << inputFilename << endl;
auto data = QI::ReadVectorImage<complex<float>>(inputFilename);
shared_ptr<QI::SSFP_GS> seq = make_shared<QI::SSFP_GS>(cin, true);
if (verbose) cout << *seq;
auto apply = QI::ApplyXF::New();
algo->setSize(data->GetNumberOfComponentsPerPixel());
algo->SetSequence(seq);
apply->SetAlgorithm(algo);
apply->SetPoolsize(num_threads);
apply->SetInput(0, data);
if (mask)
apply->SetMask(mask);
if (B1)
apply->SetConst(0, B1);
if (verbose) {
cout << "Processing" << endl;
auto monitor = QI::GenericMonitor::New();
apply->AddObserver(itk::ProgressEvent(), monitor);
}
apply->Update();
if (verbose) {
cout << "Elapsed time was " << apply->GetTotalTime() << "s" << endl;
cout << "Mean time per voxel was " << apply->GetMeanTime() << "s" << endl;
cout << "Writing results files." << endl;
}
outPrefix = outPrefix + "ES_";
for (int i = 0; i < algo->numOutputs(); i++) {
QI::WriteImage(apply->GetOutput(i), outPrefix + algo->names().at(i) + QI::OutExt());
}
if (verbose) cout << "Finished." << endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: Updated to Option, added clamping.<commit_after>/*
* qiesmap.cpp
*
* Copyright (c) 2016 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <iostream>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#include "QI/Util.h"
#include "QI/Option.h"
#include "QI/Sequences/SteadyStateSequence.cpp"
#include "Filters/ApplyAlgorithmFilter.h"
using namespace std;
using namespace Eigen;
// Helper Functions
void SemiaxesToHoff(const double A, const double B, const double c,
double &a, double &b) {
b = (-c*A + sqrt(c*c*A*A - (c*c + B*B)*(A*A - B*B)))/(c*c + B*B);
a = B / (b*B + c*sqrt(1-b*b));
}
void EllipseToMRI(const double a, const double b, const double scale, const double th, const double TR, const double flip,
float &M, float &T1, float &T2, float &df0) {
const double cosf = cos(flip);
const double upper = exp(-TR / 4.3);
const double clampa = QI::clamp(a, 0.0, upper);
T2 = -TR / log(clampa);
T1 = -TR / (log(clampa-b + (1.-clampa*b)*clampa*cosf) - log(clampa*(1.-clampa*b) + (clampa-b)*cosf));
M = (scale/sqrt(clampa))*(1-b*b)/(1-clampa*b);
df0 = th / (2.*M_PI*TR);
}
class ESAlgo : public QI::ApplyXF::Algorithm {
protected:
size_t m_size = 0;
shared_ptr<QI::SSFP_GS> m_sequence = nullptr;
public:
size_t numInputs() const override { return 1; }
size_t numConsts() const override { return 1; }
size_t numOutputs() const override { return 6; }
const float &zero(const size_t i) const override { static float zero = 0; return zero; }
const vector<string> & names() const {
static vector<string> _names = {"M", "T1", "T2", "th", "a", "b"};
return _names;
}
size_t dataSize() const override { return m_size; }
void setSize(const size_t s) { m_size = s; }
virtual std::vector<float> defaultConsts() const override {
std::vector<float> def(1, 1.0f); // B1
return def;
}
void SetSequence(const shared_ptr<QI::SSFP_GS> &s) { m_sequence = s;}
MatrixXd buildS(const ArrayXd &x, const ArrayXd &y) const {
Matrix<double, Dynamic, 6> D(x.rows(), 6);
D.col(0) = x*x;
D.col(1) = 2*x*y;
D.col(2) = y*y;
D.col(3) = 2*x;
D.col(4) = 2*y;
D.col(5).setConstant(1);
return D.transpose() * D;
}
MatrixXd fitzC() const {
typedef Matrix<double, 6, 6> Matrix6d;
Matrix6d C = Matrix6d::Zero();
// FitZ[5]ibbon et al
C(0,2) = -2; C(1,1) = 1; C(2,0) = -2;
return C;
}
MatrixXd hyperC(const ArrayXd &x, const ArrayXd &y) const {
typedef Matrix<double, 6, 6> Matrix6d;
Matrix6d C = Matrix6d::Zero();
// FitZ[5]ibbon et al
//C(0,2) = -2; C(1,1) = 1; C(2,0) = -2;
// Hyper Ellipse
const double N = x.cols();
const double xc = x.sum() / N;
const double yc = y.sum() / N;
const double sx = x.square().sum() / N;
const double sy = y.square().sum() / N;
const double xy = (x * y).sum() / N;
C << 6*sx, 6*xy, sx+sy, 6*xc, 2*yc, 1,
6*xy, 4*(sx+sy), 6*xy, 4*yc, 4*xc, 0,
sx + sy, 6*xy, 6*sy, 2*xc, 6*yc, 1,
6*xc, 4*yc, 2*xc, 4, 0, 0,
2*yc, 4*xc, 6*yc, 0, 4, 0,
1, 0, 1, 0, 0, 0;
return C;
}
virtual void apply(const std::vector<TInput> &inputs, const std::vector<TConst> &consts,
std::vector<TOutput> &outputs, TConst &residual,
TInput &resids, TIters &its) const override
{
typedef Matrix<double, 6, 6> Matrix6d;
typedef Matrix<double, 6, 1> Vector6d;
const double B1 = consts[0];
Eigen::Map<const Eigen::ArrayXcf> indata(inputs[0].GetDataPointer(), inputs[0].Size());
ArrayXcd data = indata.cast<complex<double>>();
const double scale = data.abs().maxCoeff();
ArrayXd x = data.real() / scale;
ArrayXd y = data.imag() / scale;
MatrixXd S = buildS(x, y);
Matrix6d C = hyperC(x, y);
// Note A and B are swapped so we can use GES
GeneralizedSelfAdjointEigenSolver<MatrixXd> solver(C, S);
ArrayXd Z;
if (fabs(solver.eigenvalues()[5]) > fabs(solver.eigenvalues()[0]))
Z = solver.eigenvectors().col(5);
else
Z = solver.eigenvectors().col(0);
const double dsc=(Z[1]*Z[1]-Z[0]*Z[2]);
const double xc = (Z[2]*Z[3]-Z[1]*Z[4])/dsc;
const double yc = (Z[0]*Z[4]-Z[1]*Z[3])/dsc;
const double th = atan2(yc,xc);
const double num = 2*(Z[0]*(Z[4]*Z[4])+Z[2]*(Z[3]*Z[3])+Z[5]*(Z[1]*Z[1])-2*Z[1]*Z[3]*Z[4]-Z[0]*Z[2]*Z[5]);
double A = sqrt(num/(dsc*(sqrt((Z[0]-Z[2])*(Z[0]-Z[2]) + 4*Z[1]*Z[1])-(Z[0]+Z[2]))));
double B = sqrt(num/(dsc*(-sqrt((Z[0]-Z[2])*(Z[0]-Z[2]) + 4*Z[1]*Z[1])-(Z[0]+Z[2]))));
if (A > B) {
std::swap(A, B);
}
double a, b;
double c = sqrt(xc*xc+yc*yc);
SemiaxesToHoff(A, B, c, a, b);
EllipseToMRI(a, b, c*scale, th, m_sequence->TR(), B1 * m_sequence->flip()[0],
outputs[0], outputs[1], outputs[2], outputs[3]);
outputs[4] = a;
outputs[5] = b;
}
};
int main(int argc, char **argv) {
Eigen::initParallel();
QI::OptionList opts("Usage is: qiesmap [options] input_file\n\nA utility for calculating T1,T2,PD and f0 maps from SSFP data.\nInput must be a single complex image with at least 6 phase increments.");
QI::Option<int> num_threads(4,'T',"threads","Use N threads (default=4, 0=hardware limit)", opts);
QI::Option<std::string> outPrefix("", 'o', "out","Prefix output filenames", opts);
QI::ImageOption<QI::VolumeF> mask('m', "mask", "Mask input with specified file", opts);
QI::ImageOption<QI::VolumeF> B1('b', "B1", "B1 Map file (ratio)", opts);
QI::EnumOption algorithm("lwnb",'l','a',"algo","Choose algorithm (f/h/c)", opts);
QI::Switch suppress('n',"no-prompt","Suppress input prompts", opts);
QI::Switch verbose('v',"verbose","Print more information", opts);
QI::Help help(opts);
std::vector<std::string> nonopts = opts.parse(argc, argv);
if (nonopts.size() != 1) {
std::cerr << opts << std::endl;
std::cerr << "No input filename specified." << std::endl;
return EXIT_FAILURE;
}
shared_ptr<ESAlgo> algo = make_shared<ESAlgo>();
if (*verbose) cout << "Opening file: " << nonopts[0] << endl;
auto data = QI::ReadVectorImage<complex<float>>(nonopts[0]);
shared_ptr<QI::SSFP_GS> seq = make_shared<QI::SSFP_GS>(cin, !*suppress);
if (*verbose) cout << *seq;
auto apply = QI::ApplyXF::New();
algo->setSize(data->GetNumberOfComponentsPerPixel());
algo->SetSequence(seq);
apply->SetAlgorithm(algo);
apply->SetPoolsize(*num_threads);
apply->SetInput(0, data);
apply->SetMask(*mask);
apply->SetConst(0, *B1);
if (*verbose) {
cout << "Processing" << endl;
auto monitor = QI::GenericMonitor::New();
apply->AddObserver(itk::ProgressEvent(), monitor);
}
apply->Update();
if (*verbose) {
cout << "Elapsed time was " << apply->GetTotalTime() << "s" << endl;
cout << "Mean time per voxel was " << apply->GetMeanTime() << "s" << endl;
cout << "Writing results files." << endl;
}
*outPrefix = *outPrefix + "ES_";
for (int i = 0; i < algo->numOutputs(); i++) {
QI::WriteImage(apply->GetOutput(i), *outPrefix + algo->names().at(i) + QI::OutExt());
}
if (*verbose) cout << "Finished." << endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*!
* \file painter_draw.hpp
* \brief file painter_draw.hpp
*
* Copyright 2016 by Intel.
*
* Contact: kevin.rogovin@intel.com
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <kevin.rogovin@intel.com>
*
*/
#pragma once
#include <fastuidraw/util/reference_counted.hpp>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/matrix.hpp>
#include <fastuidraw/util/c_array.hpp>
#include <fastuidraw/util/gpu_dirty_state.hpp>
#include <fastuidraw/painter/painter_attribute.hpp>
#include <fastuidraw/painter/painter_shader.hpp>
#include <fastuidraw/painter/backend/painter_shader_group.hpp>
namespace fastuidraw
{
/*!\addtogroup PainterBackend
* @{
*/
/*!
* \brief
* Store for attributes, indices of items and shared data of
* items for items to draw. Indices (stored in \ref m_indices)
* are -ALWAYS- in groups of three where each group is a single
* triangle and each index is an index into \ref m_attributes.
*/
class PainterDraw:
public reference_counted<PainterDraw>::default_base
{
public:
/*!
* \brief
* A delayed action is an action that is to be called
* just before the buffers of a \ref PainterDraw are to
* be unmapped. Typically, this is used to write values
* using information that is ready after the original
* values are written by \ref Painter. A fixed \ref
* DelayedAction object may only be added to one \ref
* PainterDraw object, but a single \ref PainterDraw
* can have many \ref DelayedAction objects added to it.
*/
class DelayedAction:public reference_counted<DelayedAction>::default_base
{
public:
/*!
* Ctor.
*/
DelayedAction(void);
~DelayedAction();
/*!
* Perform the action of this DelayedAction object
* and remove it from the list of delayed actions of
* the PainterDraw.
*/
void
perform_action(void);
protected:
/*!
* To be implemented by a derived class to execute its delayed action.
* \param h handle to PainterDraw on which the action has
* been placed
*/
virtual
void
action(const reference_counted_ptr<const PainterDraw> &h) = 0;
private:
friend class PainterDraw;
void *m_d;
};
/*!
* An \ref APIBase is a common base class that is used to pass
* graphics API specific data/environment. For example, for
* API's such as Vulkan or Metal it can be used to pass around
* the command buffer to which a backend for those API's is
* adding commands.
*/
class APIBase
{
public:
virtual
~APIBase()
{}
};
/*!\brief
* An \ref Action represents an action to be executed
* between two indices to be fed the the GPU; an Action
* will imply an draw break in the underlying 3D API.
*/
class Action:public reference_counted<Action>::non_concurrent
{
public:
/*!
* To be implemented by a derived class to execute
* the action and to return what portions of the
* GPU state are made dirty by the action.
* \param api_base APIBase object active when the Action
* is called, some backends may make this
* value nullptr (for example the GL/GLES
* backends have this as nullptr).
*/
virtual
gpu_dirty_state
execute(APIBase *api_base) const = 0;
};
/*!
* Location to which to place attribute data,
* the store is understood to be write only.
*/
c_array<PainterAttribute> m_attributes;
/*!
* Location to which to place the attribute data
* storing the header _locations_ in \ref m_store.
* The size of \ref m_header_attributes must be the
* same as the size of \ref m_attributes, the store
* is understood to be write only.
*/
c_array<uint32_t> m_header_attributes;
/*!
* Location to which to place index data. Values
* are indices into m_attributes,
* the store is understood to be write only.
*/
c_array<PainterIndex> m_indices;
/*!
* Generic store for data that is shared between
* vertices within an item and possibly between
* items. The store is understood to be write
* only.
*/
c_array<generic_data> m_store;
/*!
* Ctor, a derived class will set \ref m_attributes,
* \ref m_header_attributes, \ref m_indices and
* \ref m_store.
*/
PainterDraw(void);
~PainterDraw();
/*!
* Called to indicate a change in value to the
* painter header that this PainterDraw needs
* to record. The most common case is to insert API
* state changes (or just break a draw) for when a
* \ref PainterBackend cannot accomodate a Painter
* state change without changing the 3D API state.
* \param old_groups PainterShaderGroup before state change
* \param new_groups PainterShaderGroup after state change
* \param indices_written total number of indices written to m_indices -before- the change
* \returns true if the \ref PainterShaderGroup resulted in a draw break
*/
virtual
bool
draw_break(const PainterShaderGroup &old_groups,
const PainterShaderGroup &new_groups,
unsigned int indices_written) = 0;
/*!
* Called to execute an action (and thus also cause a draw-call break).
* Implementations are to assume that \ref Action reference is non-null.
* Implementations are to return true if the draw_break triggers an extra
* draw call.
* \param action action to execute
* \param indices_written total number of indices written to \ref m_indices
* -before- the break
*/
virtual
bool
draw_break(const reference_counted_ptr<const Action> &action,
unsigned int indices_written) = 0;
/*!
* Adds a delayed action to the action list.
* \param h handle to action to add.
*/
void
add_action(const reference_counted_ptr<DelayedAction> &h) const;
/*!
* Signals this PainterDraw to be unmapped.
* Actual unmapping is delayed until all actions that
* have been added with add_action() have been
* called.
* \param attributes_written number of elements written to \ref
* m_attributes and \ref m_header_attributes.
* \param indices_written number of elements written to \ref m_indices
* \param data_store_written number of elements written to \ref m_store
*/
void
unmap(unsigned int attributes_written,
unsigned int indices_written,
unsigned int data_store_written);
/*!
* Returns true if and only if this PainterDraw
* is unmapped.
*/
bool
unmapped(void) const;
/*!
* To be implemented by a derived class to draw the
* contents. Must be performed after unmap() is called.
* In addition, may only be called within a
* PainterBackend::on_pre_draw() /
* PainterBackend::on_post_draw() pair of the \ref
* PainterBackend whose PainterBackend::map_draw()
* created this object.
*/
virtual
void
draw(void) const = 0;
protected:
/*!
* To be implemented by a derived class to unmap
* the arrays m_store, m_attributes
* and m_indices. Once unmapped, the store
* can no longer be written to.
* \param attributes_written only the range [0,floats_written) of
* m_attributes must be uploaded to
* 3D API
* \param indices_written only the range [0,uints_written) of
* m_indices specify indices to use.
* \param data_store_written only the range [0,data_store_written) of
* m_store must be uploaded to 3D API
*/
virtual
void
unmap_implement(unsigned int attributes_written,
unsigned int indices_written,
unsigned int data_store_written) = 0;
private:
void
complete_unmapping(void);
void *m_d;
};
/*! @} */
}
<commit_msg>fastuidraw/painter/backend/painter_draw: make PainterDraw reference counting NOT thread safe<commit_after>/*!
* \file painter_draw.hpp
* \brief file painter_draw.hpp
*
* Copyright 2016 by Intel.
*
* Contact: kevin.rogovin@intel.com
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <kevin.rogovin@intel.com>
*
*/
#pragma once
#include <fastuidraw/util/reference_counted.hpp>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/matrix.hpp>
#include <fastuidraw/util/c_array.hpp>
#include <fastuidraw/util/gpu_dirty_state.hpp>
#include <fastuidraw/painter/painter_attribute.hpp>
#include <fastuidraw/painter/painter_shader.hpp>
#include <fastuidraw/painter/backend/painter_shader_group.hpp>
namespace fastuidraw
{
/*!\addtogroup PainterBackend
* @{
*/
/*!
* \brief
* Store for attributes, indices of items and shared data of
* items for items to draw. Indices (stored in \ref m_indices)
* are -ALWAYS- in groups of three where each group is a single
* triangle and each index is an index into \ref m_attributes.
* The PainterDraw object is NOT thread safe, neither is its
* reference count. A PainterDraw object is used \ref Painter
* to send attributer and index data to a \ref PainterBackend.
*/
class PainterDraw:
public reference_counted<PainterDraw>::non_concurrent
{
public:
/*!
* \brief
* A delayed action is an action that is to be called
* just before the buffers of a \ref PainterDraw are to
* be unmapped. Typically, this is used to write values
* using information that is ready after the original
* values are written by \ref Painter. A fixed \ref
* DelayedAction object may only be added to one \ref
* PainterDraw object, but a single \ref PainterDraw
* can have many \ref DelayedAction objects added to it.
*/
class DelayedAction:public reference_counted<DelayedAction>::non_concurrent
{
public:
/*!
* Ctor.
*/
DelayedAction(void);
~DelayedAction();
/*!
* Perform the action of this DelayedAction object
* and remove it from the list of delayed actions of
* the PainterDraw.
*/
void
perform_action(void);
protected:
/*!
* To be implemented by a derived class to execute its delayed action.
* \param h handle to PainterDraw on which the action has
* been placed
*/
virtual
void
action(const reference_counted_ptr<const PainterDraw> &h) = 0;
private:
friend class PainterDraw;
void *m_d;
};
/*!
* An \ref APIBase is a common base class that is used to pass
* graphics API specific data/environment. For example, for
* API's such as Vulkan or Metal it can be used to pass around
* the command buffer to which a backend for those API's is
* adding commands.
*/
class APIBase
{
public:
virtual
~APIBase()
{}
};
/*!\brief
* An \ref Action represents an action to be executed
* between two indices to be fed the the GPU; an Action
* will imply an draw break in the underlying 3D API.
*/
class Action:public reference_counted<Action>::non_concurrent
{
public:
/*!
* To be implemented by a derived class to execute
* the action and to return what portions of the
* GPU state are made dirty by the action.
* \param api_base APIBase object active when the Action
* is called, some backends may make this
* value nullptr (for example the GL/GLES
* backends have this as nullptr).
*/
virtual
gpu_dirty_state
execute(APIBase *api_base) const = 0;
};
/*!
* Location to which to place attribute data,
* the store is understood to be write only.
*/
c_array<PainterAttribute> m_attributes;
/*!
* Location to which to place the attribute data
* storing the header _locations_ in \ref m_store.
* The size of \ref m_header_attributes must be the
* same as the size of \ref m_attributes, the store
* is understood to be write only.
*/
c_array<uint32_t> m_header_attributes;
/*!
* Location to which to place index data. Values
* are indices into m_attributes,
* the store is understood to be write only.
*/
c_array<PainterIndex> m_indices;
/*!
* Generic store for data that is shared between
* vertices within an item and possibly between
* items. The store is understood to be write
* only.
*/
c_array<generic_data> m_store;
/*!
* Ctor, a derived class will set \ref m_attributes,
* \ref m_header_attributes, \ref m_indices and
* \ref m_store.
*/
PainterDraw(void);
~PainterDraw();
/*!
* Called to indicate a change in value to the
* painter header that this PainterDraw needs
* to record. The most common case is to insert API
* state changes (or just break a draw) for when a
* \ref PainterBackend cannot accomodate a Painter
* state change without changing the 3D API state.
* \param old_groups PainterShaderGroup before state change
* \param new_groups PainterShaderGroup after state change
* \param indices_written total number of indices written to m_indices -before- the change
* \returns true if the \ref PainterShaderGroup resulted in a draw break
*/
virtual
bool
draw_break(const PainterShaderGroup &old_groups,
const PainterShaderGroup &new_groups,
unsigned int indices_written) = 0;
/*!
* Called to execute an action (and thus also cause a draw-call break).
* Implementations are to assume that \ref Action reference is non-null.
* Implementations are to return true if the draw_break triggers an extra
* draw call.
* \param action action to execute
* \param indices_written total number of indices written to \ref m_indices
* -before- the break
*/
virtual
bool
draw_break(const reference_counted_ptr<const Action> &action,
unsigned int indices_written) = 0;
/*!
* Adds a delayed action to the action list.
* \param h handle to action to add.
*/
void
add_action(const reference_counted_ptr<DelayedAction> &h) const;
/*!
* Signals this PainterDraw to be unmapped.
* Actual unmapping is delayed until all actions that
* have been added with add_action() have been
* called.
* \param attributes_written number of elements written to \ref
* m_attributes and \ref m_header_attributes.
* \param indices_written number of elements written to \ref m_indices
* \param data_store_written number of elements written to \ref m_store
*/
void
unmap(unsigned int attributes_written,
unsigned int indices_written,
unsigned int data_store_written);
/*!
* Returns true if and only if this PainterDraw
* is unmapped.
*/
bool
unmapped(void) const;
/*!
* To be implemented by a derived class to draw the
* contents. Must be performed after unmap() is called.
* In addition, may only be called within a
* PainterBackend::on_pre_draw() /
* PainterBackend::on_post_draw() pair of the \ref
* PainterBackend whose PainterBackend::map_draw()
* created this object.
*/
virtual
void
draw(void) const = 0;
protected:
/*!
* To be implemented by a derived class to unmap
* the arrays m_store, m_attributes
* and m_indices. Once unmapped, the store
* can no longer be written to.
* \param attributes_written only the range [0,floats_written) of
* m_attributes must be uploaded to
* 3D API
* \param indices_written only the range [0,uints_written) of
* m_indices specify indices to use.
* \param data_store_written only the range [0,data_store_written) of
* m_store must be uploaded to 3D API
*/
virtual
void
unmap_implement(unsigned int attributes_written,
unsigned int indices_written,
unsigned int data_store_written) = 0;
private:
void
complete_unmapping(void);
void *m_d;
};
/*! @} */
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <chrono>
#include <memory>
#include <cmath>
#include <signal.h>
#include <SmurffCpp/Types.h>
#include <SmurffCpp/DataMatrices/Data.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Model.h>
#include <SmurffCpp/VMatrixIterator.hpp>
#include <SmurffCpp/ConstVMatrixIterator.hpp>
#include <SmurffCpp/VMatrixExprIterator.hpp>
#include <SmurffCpp/ConstVMatrixExprIterator.hpp>
#include <Utils/Error.h>
#include <SmurffCpp/Utils/SaveState.h>
namespace smurff {
Model::Model()
: m_num_latent(-1), m_dims(0)
{
}
//num_latent - size of latent dimension
//dims - dimentions of train data
//init_model_type - samples initialization type
void Model::init(int num_latent, const PVec<>& dims, ModelInitTypes model_init_type, bool save_model, bool aggregate)
{
size_t nmodes = dims.size();
m_num_latent = num_latent;
m_dims = dims;
m_collect_aggr = aggregate;
m_save_model = save_model;
m_num_aggr = std::vector<int>(dims.size(), 0);
m_factors.resize(nmodes);
m_link_matrices.resize(nmodes);
m_mus.resize(nmodes);
for(size_t i = 0; i < nmodes; ++i)
{
Matrix& mat = m_factors.at(i);
mat.resize(dims[i], m_num_latent);
switch(model_init_type)
{
case ModelInitTypes::random:
mat = Matrix::NullaryExpr(mat.rows(), mat.cols(), RandNormalGenerator());
break;
case ModelInitTypes::zero:
mat.setZero();
break;
default:
{
THROWERROR("Invalid model init type");
}
}
if (aggregate)
{
m_aggr_sum.push_back(Matrix::Zero(dims[i], m_num_latent));
m_aggr_dot.push_back(Matrix::Zero(dims[i], m_num_latent * m_num_latent));
}
}
Pcache.init(Array1D::Ones(m_num_latent));
}
Matrix &Model::getLinkMatrix(int mode)
{
return m_link_matrices.at(mode);
}
Vector &Model::getMu(int mode)
{
return m_mus.at(mode);
}
const Matrix &Model::getLinkMatrix(int mode) const
{
return m_link_matrices.at(mode);
}
const Vector &Model::getMu(int mode) const
{
return m_mus.at(mode);
}
double Model::predict(const PVec<> &pos) const
{
if (nmodes() == 2)
{
return row(0, pos[0]).dot(row(1, pos[1]));
}
auto &P = Pcache.local();
P.setOnes();
for(uint32_t d = 0; d < nmodes(); ++d)
P *= row(d, pos.at(d)).array();
return P.sum();
}
const Matrix &Model::U(uint32_t f) const
{
return m_factors.at(f);
}
Matrix &Model::U(uint32_t f)
{
return m_factors[f];
}
VMatrixIterator<Matrix> Model::Vbegin(std::uint32_t mode)
{
return VMatrixIterator<Matrix>(this, mode, 0);
}
VMatrixIterator<Matrix> Model::Vend()
{
return VMatrixIterator<Matrix>(m_factors.size());
}
ConstVMatrixIterator<Matrix> Model::CVbegin(std::uint32_t mode) const
{
return ConstVMatrixIterator<Matrix>(this, mode, 0);
}
ConstVMatrixIterator<Matrix> Model::CVend() const
{
return ConstVMatrixIterator<Matrix>(m_factors.size());
}
Matrix::ConstRowXpr Model::row(int f, int i) const
{
return U(f).row(i);
}
std::uint64_t Model::nmodes() const
{
return m_factors.size();
}
int Model::nlatent() const
{
return m_num_latent;
}
int Model::nsamples() const
{
return std::accumulate(m_factors.begin(), m_factors.end(), 0,
[](const int &a, const Matrix &b) { return a + b.rows(); });
}
const PVec<>& Model::getDims() const
{
return m_dims;
}
SubModel Model::full()
{
return SubModel(*this);
}
void Model::updateAggr(int m, int i)
{
if (!m_collect_aggr) return;
const auto &r = row(m, i);
Matrix cov = (r.transpose() * r);
m_aggr_sum.at(m).row(i) += r;
m_aggr_dot.at(m).row(i) += Eigen::Map<Vector>(cov.data(), nlatent() * nlatent());
}
void Model::updateAggr(int m)
{
m_num_aggr.at(m)++;
}
void Model::save(SaveState &sf) const
{
sf.putModel(m_factors);
for (std::uint64_t m = 0; m < nmodes(); ++m)
{
sf.putLinkMatrix(m, m_link_matrices.at(m));
sf.putMu(m, m_mus.at(m));
if (m_collect_aggr && m_save_aggr)
{
double n = m_num_aggr.at(m);
const Matrix &Usum = m_aggr_sum.at(m);
const Matrix &Uprod = m_aggr_dot.at(m);
Matrix mu = Matrix::Zero(Usum.rows(), Usum.cols());
// inverse of the covariance
Matrix prec = Matrix::Zero(Uprod.rows(), Uprod.cols());
// calculate real mu and Lambda
for (int i = 0; i < U(m).rows(); i++)
{
Vector sum = Usum.row(i);
Matrix prod = Eigen::Map<const Matrix>(Uprod.row(i).data(), nlatent(), nlatent());
Matrix prec_i = ((prod - (sum.transpose() * sum / n)) / (n - 1)).inverse();
prec.row(i) = Eigen::Map<Vector>(prec_i.data(), nlatent() * nlatent());
mu.row(i) = sum / n;
}
sf.putPostMuLambda(m, mu, prec);
}
}
}
void Model::restore(const SaveState &sf, int skip_mode)
{
unsigned nmodes = sf.getNModes();
m_factors.clear();
m_dims = PVec<>(nmodes);
m_factors.resize(nmodes);
for (std::uint64_t i = 0; i < nmodes; ++i)
{
if ((int)i != skip_mode)
{
auto &U = m_factors.at(i);
sf.readModel(i, U);
m_dims.at(i) = U.rows();
m_num_latent = U.cols();
}
else
{
m_dims.at(i) = -1;
}
}
m_link_matrices.resize(nmodes);
m_mus.resize(nmodes);
for(int i=0; i<nmodes; ++i)
{
sf.readLinkMatrix(i, m_link_matrices.at(i));
sf.readMu(i, m_mus.at(i));
}
Pcache.init(Array1D::Ones(m_num_latent));
}
std::ostream& Model::info(std::ostream &os, std::string indent) const
{
os << indent << "Num-latents: " << m_num_latent << std::endl;
return os;
}
std::ostream& Model::status(std::ostream &os, std::string indent) const
{
os << indent << " Umean: " << std::endl;
for(std::uint64_t d = 0; d < nmodes(); ++d)
os << indent << " U(" << d << ").colwise().mean: "
<< U(d).colwise().mean()
<< std::endl;
return os;
}
Matrix::ConstBlockXpr SubModel::U(int f) const
{
const Matrix &u = m_model.U(f); //force const
return u.block(m_off.at(f), 0, m_dims.at(f), m_model.nlatent());
}
ConstVMatrixExprIterator<Matrix::ConstBlockXpr> SubModel::CVbegin(std::uint32_t mode) const
{
return ConstVMatrixExprIterator<Matrix::ConstBlockXpr>(&m_model, m_off, m_dims, mode, 0);
}
ConstVMatrixExprIterator<Matrix::ConstBlockXpr> SubModel::CVend() const
{
return ConstVMatrixExprIterator<Matrix::ConstBlockXpr>(m_model.nmodes());
}
} // end namespace smurff
<commit_msg>FIX: unsigned compare warning<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <chrono>
#include <memory>
#include <cmath>
#include <signal.h>
#include <SmurffCpp/Types.h>
#include <SmurffCpp/DataMatrices/Data.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Model.h>
#include <SmurffCpp/VMatrixIterator.hpp>
#include <SmurffCpp/ConstVMatrixIterator.hpp>
#include <SmurffCpp/VMatrixExprIterator.hpp>
#include <SmurffCpp/ConstVMatrixExprIterator.hpp>
#include <Utils/Error.h>
#include <SmurffCpp/Utils/SaveState.h>
namespace smurff {
Model::Model()
: m_num_latent(-1), m_dims(0)
{
}
//num_latent - size of latent dimension
//dims - dimentions of train data
//init_model_type - samples initialization type
void Model::init(int num_latent, const PVec<>& dims, ModelInitTypes model_init_type, bool save_model, bool aggregate)
{
size_t nmodes = dims.size();
m_num_latent = num_latent;
m_dims = dims;
m_collect_aggr = aggregate;
m_save_model = save_model;
m_num_aggr = std::vector<int>(dims.size(), 0);
m_factors.resize(nmodes);
m_link_matrices.resize(nmodes);
m_mus.resize(nmodes);
for(size_t i = 0; i < nmodes; ++i)
{
Matrix& mat = m_factors.at(i);
mat.resize(dims[i], m_num_latent);
switch(model_init_type)
{
case ModelInitTypes::random:
mat = Matrix::NullaryExpr(mat.rows(), mat.cols(), RandNormalGenerator());
break;
case ModelInitTypes::zero:
mat.setZero();
break;
default:
{
THROWERROR("Invalid model init type");
}
}
if (aggregate)
{
m_aggr_sum.push_back(Matrix::Zero(dims[i], m_num_latent));
m_aggr_dot.push_back(Matrix::Zero(dims[i], m_num_latent * m_num_latent));
}
}
Pcache.init(Array1D::Ones(m_num_latent));
}
Matrix &Model::getLinkMatrix(int mode)
{
return m_link_matrices.at(mode);
}
Vector &Model::getMu(int mode)
{
return m_mus.at(mode);
}
const Matrix &Model::getLinkMatrix(int mode) const
{
return m_link_matrices.at(mode);
}
const Vector &Model::getMu(int mode) const
{
return m_mus.at(mode);
}
double Model::predict(const PVec<> &pos) const
{
if (nmodes() == 2)
{
return row(0, pos[0]).dot(row(1, pos[1]));
}
auto &P = Pcache.local();
P.setOnes();
for(uint32_t d = 0; d < nmodes(); ++d)
P *= row(d, pos.at(d)).array();
return P.sum();
}
const Matrix &Model::U(uint32_t f) const
{
return m_factors.at(f);
}
Matrix &Model::U(uint32_t f)
{
return m_factors[f];
}
VMatrixIterator<Matrix> Model::Vbegin(std::uint32_t mode)
{
return VMatrixIterator<Matrix>(this, mode, 0);
}
VMatrixIterator<Matrix> Model::Vend()
{
return VMatrixIterator<Matrix>(m_factors.size());
}
ConstVMatrixIterator<Matrix> Model::CVbegin(std::uint32_t mode) const
{
return ConstVMatrixIterator<Matrix>(this, mode, 0);
}
ConstVMatrixIterator<Matrix> Model::CVend() const
{
return ConstVMatrixIterator<Matrix>(m_factors.size());
}
Matrix::ConstRowXpr Model::row(int f, int i) const
{
return U(f).row(i);
}
std::uint64_t Model::nmodes() const
{
return m_factors.size();
}
int Model::nlatent() const
{
return m_num_latent;
}
int Model::nsamples() const
{
return std::accumulate(m_factors.begin(), m_factors.end(), 0,
[](const int &a, const Matrix &b) { return a + b.rows(); });
}
const PVec<>& Model::getDims() const
{
return m_dims;
}
SubModel Model::full()
{
return SubModel(*this);
}
void Model::updateAggr(int m, int i)
{
if (!m_collect_aggr) return;
const auto &r = row(m, i);
Matrix cov = (r.transpose() * r);
m_aggr_sum.at(m).row(i) += r;
m_aggr_dot.at(m).row(i) += Eigen::Map<Vector>(cov.data(), nlatent() * nlatent());
}
void Model::updateAggr(int m)
{
m_num_aggr.at(m)++;
}
void Model::save(SaveState &sf) const
{
sf.putModel(m_factors);
for (std::uint64_t m = 0; m < nmodes(); ++m)
{
sf.putLinkMatrix(m, m_link_matrices.at(m));
sf.putMu(m, m_mus.at(m));
if (m_collect_aggr && m_save_aggr)
{
double n = m_num_aggr.at(m);
const Matrix &Usum = m_aggr_sum.at(m);
const Matrix &Uprod = m_aggr_dot.at(m);
Matrix mu = Matrix::Zero(Usum.rows(), Usum.cols());
// inverse of the covariance
Matrix prec = Matrix::Zero(Uprod.rows(), Uprod.cols());
// calculate real mu and Lambda
for (int i = 0; i < U(m).rows(); i++)
{
Vector sum = Usum.row(i);
Matrix prod = Eigen::Map<const Matrix>(Uprod.row(i).data(), nlatent(), nlatent());
Matrix prec_i = ((prod - (sum.transpose() * sum / n)) / (n - 1)).inverse();
prec.row(i) = Eigen::Map<Vector>(prec_i.data(), nlatent() * nlatent());
mu.row(i) = sum / n;
}
sf.putPostMuLambda(m, mu, prec);
}
}
}
void Model::restore(const SaveState &sf, int skip_mode)
{
unsigned nmodes = sf.getNModes();
m_factors.clear();
m_dims = PVec<>(nmodes);
m_factors.resize(nmodes);
for (std::uint64_t i = 0; i < nmodes; ++i)
{
if ((int)i != skip_mode)
{
auto &U = m_factors.at(i);
sf.readModel(i, U);
m_dims.at(i) = U.rows();
m_num_latent = U.cols();
}
else
{
m_dims.at(i) = -1;
}
}
m_link_matrices.resize(nmodes);
m_mus.resize(nmodes);
for(unsigned i=0; i<nmodes; ++i)
{
sf.readLinkMatrix(i, m_link_matrices.at(i));
sf.readMu(i, m_mus.at(i));
}
Pcache.init(Array1D::Ones(m_num_latent));
}
std::ostream& Model::info(std::ostream &os, std::string indent) const
{
os << indent << "Num-latents: " << m_num_latent << std::endl;
return os;
}
std::ostream& Model::status(std::ostream &os, std::string indent) const
{
os << indent << " Umean: " << std::endl;
for(std::uint64_t d = 0; d < nmodes(); ++d)
os << indent << " U(" << d << ").colwise().mean: "
<< U(d).colwise().mean()
<< std::endl;
return os;
}
Matrix::ConstBlockXpr SubModel::U(int f) const
{
const Matrix &u = m_model.U(f); //force const
return u.block(m_off.at(f), 0, m_dims.at(f), m_model.nlatent());
}
ConstVMatrixExprIterator<Matrix::ConstBlockXpr> SubModel::CVbegin(std::uint32_t mode) const
{
return ConstVMatrixExprIterator<Matrix::ConstBlockXpr>(&m_model, m_off, m_dims, mode, 0);
}
ConstVMatrixExprIterator<Matrix::ConstBlockXpr> SubModel::CVend() const
{
return ConstVMatrixExprIterator<Matrix::ConstBlockXpr>(m_model.nmodes());
}
} // end namespace smurff
<|endoftext|> |
<commit_before>#include <opencv2/ts/ts.hpp>
#include "clustering.hpp"
class TestClusteringMethods : public cvtest::BaseTest
{
public:
TestClusteringMethods(){}
protected:
void compareIndexTransition(IndexTransition& expected, IndexTransition& actual)
{
ASSERT_TRUE( expected.same_position( actual ) );
ASSERT_EQ(expected.transition, actual.transition);
}
void compareIndexTransitionCluster( IndexTransitionCluster const & expected, IndexTransitionCluster const & actual )
{
ASSERT_EQ(expected.row, actual.row);
ASSERT_EQ(expected.col, actual.col);
ASSERT_EQ(expected.transition, actual.transition);
ASSERT_EQ(expected.clusterNumber, actual.clusterNumber);
}
void compareIndexTransitionClusterVec( std::vector<IndexTransitionCluster> const & expected, std::vector<IndexTransitionCluster> const & actual )
{
ASSERT_EQ( expected, actual );
}
};
class TestClustering : public TestClusteringMethods
{
public:
int siz0;
int siz1;
double eps;
uint minPts;
std::vector<IndexTransition> vIndexTransition;
Clustering objectClustering;
TestClustering(): siz0{10}, siz1{2}, eps{2.0}, minPts{3}, vIndexTransition{ {1, 2, lToR}, {4, 2, lToR}, {11, 2, lToR},
{12, 2, lToR}, {9, 2, lToR}, {6, 8, rToL}, {8, 8, rToL}, {2, 3, rToL}, {3, 4, rToL}, {5, 7, rToL} },
objectClustering( vIndexTransition, Distance::distance_fast, eps, minPts)
{
}
};
class ClusteringConstructor : public TestClustering
{
public:
protected:
void run(int)
{
std::vector<IndexTransitionCluster>& actual = objectClustering.vIndexTransitionCluster;
// np.testing.assert_equal(objectClustering.vIndexTransitionCluster,
std::vector<IndexTransitionCluster> expected{ IndexTransition{1, 2, lToR}, IndexTransition{2, 3, rToL}, IndexTransition{3, 4, rToL},
IndexTransition{4, 2, lToR}, IndexTransition{5, 7, rToL}, IndexTransition{6, 8, rToL},
IndexTransition{8, 8, rToL}, IndexTransition{9, 2, lToR}, IndexTransition{11, 2, lToR}, IndexTransition{12, 2, lToR}};
/*std::vector<IndexTransitionCluster> expected{{1, 2, lToR, 0}, {2, 3, rToL, 0}, {3, 4, rToL, 0}, {4, 2, lToR, 0}, {5, 7, rToL, 0},
{6, 8, rToL, 0}, {8, 8, rToL, 0}, {9, 2, lToR, 0}, {11, 2, lToR, 0}, {12, 2, lToR, 0}};*/
ASSERT_EQ(expected, actual);
}
};
TEST(ClusteringSuite, ClusteringConstructor)
{
ClusteringConstructor clusteringConstructor;
clusteringConstructor.safe_run();
}
/*
def setUp(self):
self.siz0 = 10
self.siz1 = 2
self.npArray = np.array([[1, 2], [4, 2], [11, 2], [12, 2], [9, 2], [6, 8], [8, 8], [2, 3], [3, 4], [5, 7]],
dtype=np.int)
self.eps = 2
self.minPts = 3
self.objectClustering = clustering.Clustering(self.npArray, clustering.Distance.distance_fast, self.eps, self.minPts)
def test_init_clustering(self):
self.assertEqual(self.objectClustering.clusters.shape, (self.siz0, self.siz1 + 1), 'missed size')
np.testing.assert_equal(self.objectClustering.clusters, np.array([[1, 2, 0], [2, 3, 0], [3, 4, 0], [4, 2, 0], [5, 7, 0],
[6, 8, 0], [8, 8, 0], [9, 2, 0], [11, 2, 0], [12, 2, 0]], dtype=np.int), 'not sorted or missing cluster number')
def test_remove_small_clusters_and_noise_first(self):
self.objectClustering.clusters[1:4,2] = 1
self.objectClustering.clusters[6:9, 2] = 6
self.objectClustering.remove_small_clusters_and_noise()
np.testing.assert_equal(self.objectClustering.clusters, np.array([[2, 3, 1], [3, 4, 1], [4, 2, 1],
[8, 8, 6], [9, 2, 6], [11, 2, 6]], dtype=np.int), 'not removing correctly')
def test_remove_small_clusters_and_noise_second(self):
self.objectClustering.clusters[1:4,2] = 1
self.objectClustering.clusters[7:9, 2] = 6
self.objectClustering.remove_small_clusters_and_noise()
np.testing.assert_equal(self.objectClustering.clusters, np.array([[2, 3, 1], [3, 4, 1], [4, 2, 1]], dtype=np.int), 'not removing correctly')
def test_remove_small_clusters_and_noise_third(self):
self.objectClustering.minPts = 12
self.objectClustering.clusters[1:4,2] = 1
self.objectClustering.clusters[6:9, 2] = 6
self.objectClustering.remove_small_clusters_and_noise()
np.testing.assert_equal(self.objectClustering.clusters, np.empty([0, 3], dtype=np.int), 'problem with no big cluster')
def test_remove_small_clusters_and_noise_fourth(self):
self.objectClustering.minPts = 12
self.objectClustering.remove_small_clusters_and_noise()
np.testing.assert_equal(self.objectClustering.clusters, np.empty([0, 3], dtype=np.int), 'problem with no cluster')
def test_point_zone_linear_first(self):
self.objectClustering.check_point_zone_linear(2)
np.testing.assert_equal(self.objectClustering.clusters, np.array([[1, 2, 0], [2, 3, 1], [3, 4, 1], [4, 2, 0], [5, 7, 0],
[6, 8, 0], [8, 8, 0], [9, 2, 0], [11, 2, 0], [12, 2, 0]], dtype=np.int), '')
def test_point_zone_linear_second(self):
self.objectClustering.eps = 5
self.objectClustering.check_point_zone_linear(2)
np.testing.assert_equal(self.objectClustering.clusters, np.array([[1, 2, 1], [2, 3, 1], [3, 4, 1], [4, 2, 1], [5, 7, 1],
[6, 8, 0], [8, 8, 0], [9, 2, 0], [11, 2, 0], [12, 2, 0]], dtype=np.int), '')
def test_distance_fast(self):
pixelA = np.array([1, 3, 7])
pixelB = np.array([1, 3, 7])
self.assertEqual(clustering.Distance.distance_fast(pixelA, pixelB), 0, 'fast distance function problem')
pixelB = np.array([0, 1, 7])
self.assertEqual(clustering.Distance.distance_fast(pixelA, pixelB), 3, 'fast distance function problem')
pixelB = np.array([0, 10, 2])
self.assertEqual(clustering.Distance.distance_fast(pixelA, pixelB), 8, 'fast distance function problem')
pixelA = np.array([3, 4, 1])
pixelB = np.array(self.objectClustering.clusters[3])
self.assertEqual(clustering.Distance.distance_fast(pixelA, pixelB), 3, 'fast distance function problem')
def test_points_clustering_first(self):
self.objectClustering.eps = 3
self.objectClustering.points_clustering(self.objectClustering.check_point_zone_linear)
np.testing.assert_equal(self.objectClustering.clusters, np.array([[1, 2, 1], [2, 3, 1], [3, 4, 1], [4, 2, 1], [5, 7, 2],
[6, 8, 2], [8, 8, 2], [9, 2, 3], [11, 2, 3], [12, 2, 3]], dtype=np.int), '')
def test_points_clustering_second(self):
self.objectClustering.eps = 3
self.objectClustering.minPts = 4
self.objectClustering.points_clustering(self.objectClustering.check_point_zone_linear)
np.testing.assert_equal(self.objectClustering.clusters, np.array([[1, 2, 1], [2, 3, 1], [3, 4, 1], [4, 2, 1]], dtype=np.int), '')
*/<commit_msg>first test2<commit_after>#include <opencv2/ts/ts.hpp>
#include "clustering.hpp"
class TestClusteringMethods : public cvtest::BaseTest
{
public:
TestClusteringMethods(){}
protected:
void compareIndexTransition(IndexTransition& expected, IndexTransition& actual)
{
ASSERT_TRUE( expected.same_position( actual ) );
ASSERT_EQ(expected.transition, actual.transition);
}
void compareIndexTransitionCluster( IndexTransitionCluster const & expected, IndexTransitionCluster const & actual )
{
ASSERT_EQ(expected.row, actual.row);
ASSERT_EQ(expected.col, actual.col);
ASSERT_EQ(expected.transition, actual.transition);
ASSERT_EQ(expected.clusterNumber, actual.clusterNumber);
}
void compareIndexTransitionClusterVec( std::vector<IndexTransitionCluster> const & expected, std::vector<IndexTransitionCluster> const & actual )
{
ASSERT_EQ( expected, actual );
}
};
class TestClustering : public TestClusteringMethods
{
public:
int siz0;
int siz1;
double eps;
uint minPts;
std::vector<IndexTransition> vIndexTransition;
Clustering objectClustering;
TestClustering(): siz0{10}, siz1{2}, eps{2.0}, minPts{3}, vIndexTransition{ {1, 2, lToR}, {4, 2, lToR}, {11, 2, lToR},
{12, 2, lToR}, {9, 2, lToR}, {6, 8, rToL}, {8, 8, rToL}, {2, 3, rToL}, {3, 4, rToL}, {5, 7, rToL} },
objectClustering( vIndexTransition, Distance::distance_fast, eps, minPts)
{
}
};
class ClusteringConstructor : public TestClustering
{
public:
protected:
void run(int)
{
std::vector<IndexTransitionCluster>& actual = objectClustering.vIndexTransitionCluster;
std::vector<IndexTransitionCluster> expected{ IndexTransition{1, 2, lToR}, IndexTransition{2, 3, rToL}, IndexTransition{3, 4, rToL},
IndexTransition{4, 2, lToR}, IndexTransition{5, 7, rToL}, IndexTransition{6, 8, rToL},
IndexTransition{8, 8, rToL}, IndexTransition{9, 2, lToR}, IndexTransition{11, 2, lToR}, IndexTransition{12, 2, lToR}};
ASSERT_EQ(expected, actual);
/*std::vector<IndexTransitionCluster> expected{{1, 2, lToR, 0}, {2, 3, rToL, 0}, {3, 4, rToL, 0}, {4, 2, lToR, 0}, {5, 7, rToL, 0},
{6, 8, rToL, 0}, {8, 8, rToL, 0}, {9, 2, lToR, 0}, {11, 2, lToR, 0}, {12, 2, lToR, 0}};*/
}
};
TEST(ClusteringSuite, ClusteringConstructor)
{
ClusteringConstructor clusteringConstructor;
clusteringConstructor.safe_run();
}
class ClusteringSmallAndNoise : public TestClustering
{
public:
protected:
void run(int)
{
std::vector<IndexTransitionCluster>& actual = objectClustering.vIndexTransitionCluster;
std::vector<IndexTransitionCluster> expected{ IndexTransition{1, 2, lToR}, IndexTransition{2, 3, rToL}, IndexTransition{3, 4, rToL},
IndexTransition{4, 2, lToR}, IndexTransition{5, 7, rToL}, IndexTransition{6, 8, rToL},
IndexTransition{8, 8, rToL}, IndexTransition{9, 2, lToR}, IndexTransition{11, 2, lToR}, IndexTransition{12, 2, lToR}};
ASSERT_EQ(expected, actual);
/*std::vector<IndexTransitionCluster> expected{{1, 2, lToR, 0}, {2, 3, rToL, 0}, {3, 4, rToL, 0}, {4, 2, lToR, 0}, {5, 7, rToL, 0},
{6, 8, rToL, 0}, {8, 8, rToL, 0}, {9, 2, lToR, 0}, {11, 2, lToR, 0}, {12, 2, lToR, 0}};*/
}
};
TEST(ClusteringSuite, ClusteringSmallAndNoise)
{
ClusteringSmallAndNoise clusteringSmallAndNoise;
clusteringSmallAndNoise.safe_run();
}
/*
def test_remove_small_clusters_and_noise_first(self):
self.objectClustering.clusters[1:4,2] = 1
self.objectClustering.clusters[6:9, 2] = 6
self.objectClustering.remove_small_clusters_and_noise()
np.testing.assert_equal(self.objectClustering.clusters, np.array([[2, 3, 1], [3, 4, 1], [4, 2, 1],
[8, 8, 6], [9, 2, 6], [11, 2, 6]], dtype=np.int), 'not removing correctly')
def test_remove_small_clusters_and_noise_second(self):
self.objectClustering.clusters[1:4,2] = 1
self.objectClustering.clusters[7:9, 2] = 6
self.objectClustering.remove_small_clusters_and_noise()
np.testing.assert_equal(self.objectClustering.clusters, np.array([[2, 3, 1], [3, 4, 1], [4, 2, 1]], dtype=np.int), 'not removing correctly')
def test_remove_small_clusters_and_noise_third(self):
self.objectClustering.minPts = 12
self.objectClustering.clusters[1:4,2] = 1
self.objectClustering.clusters[6:9, 2] = 6
self.objectClustering.remove_small_clusters_and_noise()
np.testing.assert_equal(self.objectClustering.clusters, np.empty([0, 3], dtype=np.int), 'problem with no big cluster')
def test_remove_small_clusters_and_noise_fourth(self):
self.objectClustering.minPts = 12
self.objectClustering.remove_small_clusters_and_noise()
np.testing.assert_equal(self.objectClustering.clusters, np.empty([0, 3], dtype=np.int), 'problem with no cluster')
def test_point_zone_linear_first(self):
self.objectClustering.check_point_zone_linear(2)
np.testing.assert_equal(self.objectClustering.clusters, np.array([[1, 2, 0], [2, 3, 1], [3, 4, 1], [4, 2, 0], [5, 7, 0],
[6, 8, 0], [8, 8, 0], [9, 2, 0], [11, 2, 0], [12, 2, 0]], dtype=np.int), '')
def test_point_zone_linear_second(self):
self.objectClustering.eps = 5
self.objectClustering.check_point_zone_linear(2)
np.testing.assert_equal(self.objectClustering.clusters, np.array([[1, 2, 1], [2, 3, 1], [3, 4, 1], [4, 2, 1], [5, 7, 1],
[6, 8, 0], [8, 8, 0], [9, 2, 0], [11, 2, 0], [12, 2, 0]], dtype=np.int), '')
def test_distance_fast(self):
pixelA = np.array([1, 3, 7])
pixelB = np.array([1, 3, 7])
self.assertEqual(clustering.Distance.distance_fast(pixelA, pixelB), 0, 'fast distance function problem')
pixelB = np.array([0, 1, 7])
self.assertEqual(clustering.Distance.distance_fast(pixelA, pixelB), 3, 'fast distance function problem')
pixelB = np.array([0, 10, 2])
self.assertEqual(clustering.Distance.distance_fast(pixelA, pixelB), 8, 'fast distance function problem')
pixelA = np.array([3, 4, 1])
pixelB = np.array(self.objectClustering.clusters[3])
self.assertEqual(clustering.Distance.distance_fast(pixelA, pixelB), 3, 'fast distance function problem')
def test_points_clustering_first(self):
self.objectClustering.eps = 3
self.objectClustering.points_clustering(self.objectClustering.check_point_zone_linear)
np.testing.assert_equal(self.objectClustering.clusters, np.array([[1, 2, 1], [2, 3, 1], [3, 4, 1], [4, 2, 1], [5, 7, 2],
[6, 8, 2], [8, 8, 2], [9, 2, 3], [11, 2, 3], [12, 2, 3]], dtype=np.int), '')
def test_points_clustering_second(self):
self.objectClustering.eps = 3
self.objectClustering.minPts = 4
self.objectClustering.points_clustering(self.objectClustering.check_point_zone_linear)
np.testing.assert_equal(self.objectClustering.clusters, np.array([[1, 2, 1], [2, 3, 1], [3, 4, 1], [4, 2, 1]], dtype=np.int), '')
*/
/* def setUp(self):
self.siz0 = 10
self.siz1 = 2
self.npArray = np.array([[1, 2], [4, 2], [11, 2], [12, 2], [9, 2], [6, 8], [8, 8], [2, 3], [3, 4], [5, 7]],
dtype=np.int)
self.eps = 2
self.minPts = 3
self.objectClustering = clustering.Clustering(self.npArray, clustering.Distance.distance_fast, self.eps, self.minPts)
def test_init_clustering(self):
self.assertEqual(self.objectClustering.clusters.shape, (self.siz0, self.siz1 + 1), 'missed size')
np.testing.assert_equal(self.objectClustering.clusters, np.array([[1, 2, 0], [2, 3, 0], [3, 4, 0], [4, 2, 0], [5, 7, 0],
[6, 8, 0], [8, 8, 0], [9, 2, 0], [11, 2, 0], [12, 2, 0]], dtype=np.int), 'not sorted or missing cluster number')
*/<|endoftext|> |
<commit_before>#include "message_queue.h"
#include "reliable_connection.h"
#include <halley/support/exception.h>
#include <network_packet.h>
using namespace Halley;
ChannelSettings::ChannelSettings(bool reliable, bool ordered, bool keepLastSent)
: reliable(reliable)
, ordered(ordered)
, keepLastSent(keepLastSent)
{}
void MessageQueue::Channel::getReadyMessages(std::vector<std::unique_ptr<NetworkMessage>>& out)
{
if (settings.ordered) {
bool trying = true;
// Oh my god
while (trying && !receiveQueue.empty()) {
trying = false;
for (size_t i = 0; i < receiveQueue.size(); ++i) {
auto& m = receiveQueue[i];
if (m->seq == lastReceived + 1) {
trying = true;
out.push_back(std::move(m));
receiveQueue.erase(receiveQueue.begin() + i);
lastReceived++;
break;
}
}
}
} else {
for (auto& m: receiveQueue) {
out.emplace_back(std::move(m));
}
receiveQueue.clear();
}
}
MessageQueue::MessageQueue(std::shared_ptr<ReliableConnection> connection)
: connection(connection)
, channels(32)
{
Expects(connection);
connection->addAckListener(*this);
}
MessageQueue::~MessageQueue()
{
connection->removeAckListener(*this);
}
void MessageQueue::setChannel(int channel, ChannelSettings settings)
{
Expects(channel >= 0);
Expects(channel < 32);
if (channels[channel].initialized) {
throw Exception("Channel " + String::integerToString(channel) + " already set");
}
auto& c = channels[channel];
c.settings = settings;
c.initialized = true;
}
void MessageQueue::addFactory(std::unique_ptr<NetworkMessageFactoryBase> factory)
{
typeToMsgIndex[factory->getTypeIndex()] = int(factories.size());
factories.emplace_back(std::move(factory));
}
std::vector<std::unique_ptr<NetworkMessage>> MessageQueue::receiveAll()
{
if (connection->getStatus() == ConnectionStatus::OPEN) {
receiveMessages();
}
std::vector<std::unique_ptr<NetworkMessage>> result;
for (auto& c: channels) {
c.getReadyMessages(result);
}
return result;
}
void MessageQueue::enqueue(std::unique_ptr<NetworkMessage> msg, int channelNumber)
{
Expects(channelNumber >= 0);
Expects(channelNumber < 32);
if (!channels[channelNumber].initialized) {
throw Exception("Channel " + String::integerToString(channelNumber) + " has not been set up");
}
auto& channel = channels[channelNumber];
msg->channel = channelNumber;
msg->seq = ++channel.lastSeq;
pendingMsgs.push_back(std::move(msg));
}
void MessageQueue::sendAll()
{
int firstTag = nextPacketId;
std::vector<ReliableSubPacket> toSend;
// Add packets which need to be re-sent
checkReSend(toSend);
// Create packets of pending messages
while (!pendingMsgs.empty()) {
toSend.emplace_back(createPacket());
}
// Send and update sequences
connection->sendTagged(toSend);
for (auto& pending: toSend) {
pendingPackets[pending.tag].seq = pending.seq;
}
}
void MessageQueue::onPacketAcked(int tag)
{
auto i = pendingPackets.find(tag);
if (i != pendingPackets.end()) {
auto& packet = i->second;
for (auto& m : packet.msgs) {
auto& channel = channels[m->channel];
if (m->seq - channel.lastAckSeq < 0x7FFFFFFF) {
channel.lastAckSeq = m->seq;
if (channel.settings.keepLastSent) {
channel.lastAck = std::move(m);
}
}
}
// Remove pending
pendingPackets.erase(tag);
}
}
void MessageQueue::checkReSend(std::vector<ReliableSubPacket>& collect)
{
auto next = pendingPackets.begin();
for (auto iter = pendingPackets.begin(); iter != pendingPackets.end(); iter = next) {
++next;
auto& pending = iter->second;
// Check how long it's been waiting
float elapsed = std::chrono::duration<float>(std::chrono::steady_clock::now() - pending.timeSent).count();
if (elapsed > 0.1f && elapsed > connection->getLatency() * 2.0f) {
// Re-send if it's reliable
if (pending.reliable) {
collect.push_back(ReliableSubPacket(serializeMessages(pending.msgs, pending.size), pending.seq));
}
pendingPackets.erase(iter);
}
}
}
ReliableSubPacket MessageQueue::createPacket()
{
std::vector<std::unique_ptr<NetworkMessage>> sentMsgs;
size_t maxSize = 1200;
size_t size = 0;
bool first = true;
bool packetReliable = false;
// Figure out what messages are going in this packet
auto next = pendingMsgs.begin();
for (auto iter = pendingMsgs.begin(); iter != pendingMsgs.end(); iter = next) {
++next;
auto& msg = *iter;
// Check if this message is compatible
auto& channel = channels[msg->channel];
bool isReliable = channel.settings.reliable;
bool isOrdered = channel.settings.ordered;
if (first || isReliable == packetReliable) {
// Check if the message fits
size_t msgSize = (*iter)->getSerializedSize();
size_t headerSize = 1 + (isOrdered ? 2 : 0) + (msgSize >= 128 ? 2 : 1);
size_t totalSize = headerSize + msgSize;
if (size + totalSize <= maxSize) {
// It fits, so add it
size += totalSize;
sentMsgs.push_back(std::move(*iter));
pendingMsgs.erase(iter);
first = false;
packetReliable = isReliable;
}
}
}
if (sentMsgs.empty()) {
throw Exception("Was not able to fit any messages into packet!");
}
// Serialize
auto data = serializeMessages(sentMsgs, size);
// Track data in this packet
int tag = nextPacketId++;
auto& pendingData = pendingPackets[tag];
pendingData.msgs = std::move(sentMsgs);
pendingData.size = size;
pendingData.reliable = packetReliable;
pendingData.timeSent = std::chrono::steady_clock::now();
return ReliableSubPacket(std::move(data));
}
std::vector<gsl::byte> MessageQueue::serializeMessages(const std::vector<std::unique_ptr<NetworkMessage>>& msgs, size_t size) const
{
std::vector<gsl::byte> result(size);
size_t pos = 0;
for (auto& msg: msgs) {
size_t msgSize = msg->getSerializedSize();
auto idxIter = typeToMsgIndex.find(std::type_index(typeid(msg)));
if (idxIter == typeToMsgIndex.end()) {
throw Exception("No appropriate factory for this type of message: " + String(typeid(msg).name()));
}
int msgType = idxIter->second;
char channelN = msg->channel;
auto& channel = channels[channelN];
bool isOrdered = channel.settings.ordered;
// Write header
memcpy(&result[pos], &channelN, 1);
pos += 1;
if (isOrdered) {
unsigned short sequence = static_cast<unsigned short>(msg->seq);
memcpy(&result[pos], &sequence, 2);
pos += 2;
}
if (msgSize >= 128) {
std::array<unsigned char, 2> bytes;
bytes[0] = static_cast<unsigned char>(msgSize >> 8) | 0x80;
bytes[1] = static_cast<unsigned char>(msgSize & 0xFF);
memcpy(&result[pos], bytes.data(), 2);
pos += 2;
} else {
unsigned char byte = msgSize & 0x7F;
memcpy(&result[pos], &byte, 1);
pos += 1;
}
if (msgType >= 128) {
std::array<unsigned char, 2> bytes;
bytes[0] = static_cast<unsigned char>(msgType >> 8) | 0x80;
bytes[1] = static_cast<unsigned char>(msgType & 0xFF);
memcpy(&result[pos], bytes.data(), 2);
pos += 2;
}
else {
unsigned char byte = msgType & 0x7F;
memcpy(&result[pos], &byte, 1);
pos += 1;
}
// Write message
msg->serializeTo(gsl::span<gsl::byte>(result).subspan(pos, msgSize));
pos += msgSize;
}
return result;
}
void MessageQueue::receiveMessages()
{
try {
InboundNetworkPacket packet;
while (connection->receive(packet)) {
auto data = packet.getBytes();
while (data.size() > 0) {
// Read channel
char channelN;
memcpy(&channelN, data.data(), 1);
data = data.subspan(1);
if (channelN < 0 || channelN >= 32) {
throw Exception("Received invalid channel");
}
auto& channel = channels[channelN];
// Read sequence
unsigned short sequence = 0;
if (channel.settings.ordered) {
if (data.size() < 2) {
throw Exception("Missing sequence data");
}
memcpy(&sequence, data.data(), 2);
data = data.subspan(2);
}
// Read size
size_t size;
unsigned char b0;
if (data.size() < 1) {
throw Exception("Missing size data");
}
memcpy(&b0, data.data(), 1);
data = data.subspan(1);
if (b0 & 0x80) {
if (data.size() < 1) {
throw Exception("Missing size data");
}
unsigned char b1;
memcpy(&b1, data.data(), 1);
data = data.subspan(1);
size = (static_cast<unsigned short>(b0 & 0x7F) << 8) | static_cast<unsigned short>(b1);
} else {
size = b0;
}
// Read message type
unsigned short msgType;
if (data.size() < 1) {
throw Exception("Missing msgType data");
}
memcpy(&b0, data.data(), 1);
data = data.subspan(1);
if (b0 & 0x80) {
if (data.size() < 1) {
throw Exception("Missing msgType data");
}
unsigned char b1;
memcpy(&b1, data.data(), 1);
data = data.subspan(1);
msgType = (static_cast<unsigned short>(b0 & 0x7F) << 8) | static_cast<unsigned short>(b1);
} else {
msgType = b0;
}
// Read message
if (data.size() < signed(size)) {
throw Exception("Message does not contain enough data");
}
channel.receiveQueue.emplace_back(deserializeMessage(data.subspan(0, size), msgType, sequence));
data = data.subspan(size);
}
}
}
catch (...) {
connection->close();
}
}
std::unique_ptr<NetworkMessage> MessageQueue::deserializeMessage(gsl::span<const gsl::byte> data, unsigned short msgType, unsigned short seq)
{
auto msg = factories.at(msgType)->create();
msg->deserializeFrom(data);
return std::move(msg);
}
<commit_msg>Fixes for ordered channels.<commit_after>#include "message_queue.h"
#include "reliable_connection.h"
#include <halley/support/exception.h>
#include <network_packet.h>
using namespace Halley;
ChannelSettings::ChannelSettings(bool reliable, bool ordered, bool keepLastSent)
: reliable(reliable)
, ordered(ordered)
, keepLastSent(keepLastSent)
{}
void MessageQueue::Channel::getReadyMessages(std::vector<std::unique_ptr<NetworkMessage>>& out)
{
if (settings.ordered) {
if (settings.reliable) {
bool trying = true;
// Oh my god, this is horrible
while (trying && !receiveQueue.empty()) {
trying = false;
for (size_t i = 0; i < receiveQueue.size(); ++i) {
auto& m = receiveQueue[i];
if (m->seq == lastReceived + 1) {
trying = true;
out.push_back(std::move(m));
receiveQueue.erase(receiveQueue.begin() + i);
lastReceived++;
break;
}
}
}
} else {
unsigned short bestDist = 0;
size_t fail = size_t(-1);
size_t best = fail;
// Look for the highest seq message, as long as it's above lastReceived
for (size_t i = 0; i < receiveQueue.size(); ++i) {
auto& m = receiveQueue[i];
unsigned short dist = m->seq - lastReceived;
if (dist < 0x7FFF) {
if (dist > bestDist) {
bestDist = dist;
best = i;
}
}
}
if (best != fail) {
lastReceived = receiveQueue[best]->seq;
out.push_back(std::move(receiveQueue[best]));
receiveQueue.clear();
}
}
} else {
for (auto& m: receiveQueue) {
out.emplace_back(std::move(m));
}
receiveQueue.clear();
}
}
MessageQueue::MessageQueue(std::shared_ptr<ReliableConnection> connection)
: connection(connection)
, channels(32)
{
Expects(connection);
connection->addAckListener(*this);
}
MessageQueue::~MessageQueue()
{
connection->removeAckListener(*this);
}
void MessageQueue::setChannel(int channel, ChannelSettings settings)
{
Expects(channel >= 0);
Expects(channel < 32);
if (channels[channel].initialized) {
throw Exception("Channel " + String::integerToString(channel) + " already set");
}
auto& c = channels[channel];
c.settings = settings;
c.initialized = true;
}
void MessageQueue::addFactory(std::unique_ptr<NetworkMessageFactoryBase> factory)
{
typeToMsgIndex[factory->getTypeIndex()] = int(factories.size());
factories.emplace_back(std::move(factory));
}
std::vector<std::unique_ptr<NetworkMessage>> MessageQueue::receiveAll()
{
if (connection->getStatus() == ConnectionStatus::OPEN) {
receiveMessages();
}
std::vector<std::unique_ptr<NetworkMessage>> result;
for (auto& c: channels) {
c.getReadyMessages(result);
}
return result;
}
void MessageQueue::enqueue(std::unique_ptr<NetworkMessage> msg, int channelNumber)
{
Expects(channelNumber >= 0);
Expects(channelNumber < 32);
if (!channels[channelNumber].initialized) {
throw Exception("Channel " + String::integerToString(channelNumber) + " has not been set up");
}
auto& channel = channels[channelNumber];
msg->channel = channelNumber;
msg->seq = ++channel.lastSeq;
pendingMsgs.push_back(std::move(msg));
}
void MessageQueue::sendAll()
{
int firstTag = nextPacketId;
std::vector<ReliableSubPacket> toSend;
// Add packets which need to be re-sent
checkReSend(toSend);
// Create packets of pending messages
while (!pendingMsgs.empty()) {
toSend.emplace_back(createPacket());
}
// Send and update sequences
connection->sendTagged(toSend);
for (auto& pending: toSend) {
pendingPackets[pending.tag].seq = pending.seq;
}
}
void MessageQueue::onPacketAcked(int tag)
{
auto i = pendingPackets.find(tag);
if (i != pendingPackets.end()) {
auto& packet = i->second;
for (auto& m : packet.msgs) {
auto& channel = channels[m->channel];
if (m->seq - channel.lastAckSeq < 0x7FFFFFFF) {
channel.lastAckSeq = m->seq;
if (channel.settings.keepLastSent) {
channel.lastAck = std::move(m);
}
}
}
// Remove pending
pendingPackets.erase(tag);
}
}
void MessageQueue::checkReSend(std::vector<ReliableSubPacket>& collect)
{
auto next = pendingPackets.begin();
for (auto iter = pendingPackets.begin(); iter != pendingPackets.end(); iter = next) {
++next;
auto& pending = iter->second;
// Check how long it's been waiting
float elapsed = std::chrono::duration<float>(std::chrono::steady_clock::now() - pending.timeSent).count();
if (elapsed > 0.1f && elapsed > connection->getLatency() * 2.0f) {
// Re-send if it's reliable
if (pending.reliable) {
collect.push_back(ReliableSubPacket(serializeMessages(pending.msgs, pending.size), pending.seq));
}
pendingPackets.erase(iter);
}
}
}
ReliableSubPacket MessageQueue::createPacket()
{
std::vector<std::unique_ptr<NetworkMessage>> sentMsgs;
size_t maxSize = 1200;
size_t size = 0;
bool first = true;
bool packetReliable = false;
// Figure out what messages are going in this packet
auto next = pendingMsgs.begin();
for (auto iter = pendingMsgs.begin(); iter != pendingMsgs.end(); iter = next) {
++next;
auto& msg = *iter;
// Check if this message is compatible
auto& channel = channels[msg->channel];
bool isReliable = channel.settings.reliable;
bool isOrdered = channel.settings.ordered;
if (first || isReliable == packetReliable) {
// Check if the message fits
size_t msgSize = (*iter)->getSerializedSize();
size_t headerSize = 1 + (isOrdered ? 2 : 0) + (msgSize >= 128 ? 2 : 1);
size_t totalSize = headerSize + msgSize;
if (size + totalSize <= maxSize) {
// It fits, so add it
size += totalSize;
sentMsgs.push_back(std::move(*iter));
pendingMsgs.erase(iter);
first = false;
packetReliable = isReliable;
}
}
}
if (sentMsgs.empty()) {
throw Exception("Was not able to fit any messages into packet!");
}
// Serialize
auto data = serializeMessages(sentMsgs, size);
// Track data in this packet
int tag = nextPacketId++;
auto& pendingData = pendingPackets[tag];
pendingData.msgs = std::move(sentMsgs);
pendingData.size = size;
pendingData.reliable = packetReliable;
pendingData.timeSent = std::chrono::steady_clock::now();
return ReliableSubPacket(std::move(data));
}
std::vector<gsl::byte> MessageQueue::serializeMessages(const std::vector<std::unique_ptr<NetworkMessage>>& msgs, size_t size) const
{
std::vector<gsl::byte> result(size);
size_t pos = 0;
for (auto& msg: msgs) {
size_t msgSize = msg->getSerializedSize();
auto idxIter = typeToMsgIndex.find(std::type_index(typeid(msg)));
if (idxIter == typeToMsgIndex.end()) {
throw Exception("No appropriate factory for this type of message: " + String(typeid(msg).name()));
}
int msgType = idxIter->second;
char channelN = msg->channel;
auto& channel = channels[channelN];
bool isOrdered = channel.settings.ordered;
// Write header
memcpy(&result[pos], &channelN, 1);
pos += 1;
if (isOrdered) {
unsigned short sequence = static_cast<unsigned short>(msg->seq);
memcpy(&result[pos], &sequence, 2);
pos += 2;
}
if (msgSize >= 128) {
std::array<unsigned char, 2> bytes;
bytes[0] = static_cast<unsigned char>(msgSize >> 8) | 0x80;
bytes[1] = static_cast<unsigned char>(msgSize & 0xFF);
memcpy(&result[pos], bytes.data(), 2);
pos += 2;
} else {
unsigned char byte = msgSize & 0x7F;
memcpy(&result[pos], &byte, 1);
pos += 1;
}
if (msgType >= 128) {
std::array<unsigned char, 2> bytes;
bytes[0] = static_cast<unsigned char>(msgType >> 8) | 0x80;
bytes[1] = static_cast<unsigned char>(msgType & 0xFF);
memcpy(&result[pos], bytes.data(), 2);
pos += 2;
}
else {
unsigned char byte = msgType & 0x7F;
memcpy(&result[pos], &byte, 1);
pos += 1;
}
// Write message
msg->serializeTo(gsl::span<gsl::byte>(result).subspan(pos, msgSize));
pos += msgSize;
}
return result;
}
void MessageQueue::receiveMessages()
{
try {
InboundNetworkPacket packet;
while (connection->receive(packet)) {
auto data = packet.getBytes();
while (data.size() > 0) {
// Read channel
char channelN;
memcpy(&channelN, data.data(), 1);
data = data.subspan(1);
if (channelN < 0 || channelN >= 32) {
throw Exception("Received invalid channel");
}
auto& channel = channels[channelN];
// Read sequence
unsigned short sequence = 0;
if (channel.settings.ordered) {
if (data.size() < 2) {
throw Exception("Missing sequence data");
}
memcpy(&sequence, data.data(), 2);
data = data.subspan(2);
}
// Read size
size_t size;
unsigned char b0;
if (data.size() < 1) {
throw Exception("Missing size data");
}
memcpy(&b0, data.data(), 1);
data = data.subspan(1);
if (b0 & 0x80) {
if (data.size() < 1) {
throw Exception("Missing size data");
}
unsigned char b1;
memcpy(&b1, data.data(), 1);
data = data.subspan(1);
size = (static_cast<unsigned short>(b0 & 0x7F) << 8) | static_cast<unsigned short>(b1);
} else {
size = b0;
}
// Read message type
unsigned short msgType;
if (data.size() < 1) {
throw Exception("Missing msgType data");
}
memcpy(&b0, data.data(), 1);
data = data.subspan(1);
if (b0 & 0x80) {
if (data.size() < 1) {
throw Exception("Missing msgType data");
}
unsigned char b1;
memcpy(&b1, data.data(), 1);
data = data.subspan(1);
msgType = (static_cast<unsigned short>(b0 & 0x7F) << 8) | static_cast<unsigned short>(b1);
} else {
msgType = b0;
}
// Read message
if (data.size() < signed(size)) {
throw Exception("Message does not contain enough data");
}
channel.receiveQueue.emplace_back(deserializeMessage(data.subspan(0, size), msgType, sequence));
data = data.subspan(size);
}
}
}
catch (...) {
connection->close();
}
}
std::unique_ptr<NetworkMessage> MessageQueue::deserializeMessage(gsl::span<const gsl::byte> data, unsigned short msgType, unsigned short seq)
{
auto msg = factories.at(msgType)->create();
msg->deserializeFrom(data);
return std::move(msg);
}
<|endoftext|> |
<commit_before>#ifndef LIBBITCOIN_NET_SHARED_CONST_BUFFER_H
#define LIBBITCOIN_NET_SHARED_CONST_BUFFER_H
#include <boost/asio.hpp>
#include <bitcoin/types.hpp>
#include <bitcoin/util/serializer.hpp>
namespace libbitcoin {
// A reference-counted non-modifiable buffer class.
class shared_const_buffer
{
public:
// Construct from a stream object
explicit shared_const_buffer(const data_chunk& user_data)
: data(new data_chunk(user_data.begin(), user_data.end())),
buffer(boost::asio::buffer(*data))
{
}
// Implement the ConstBufferSequence requirements.
typedef boost::asio::const_buffer value_type;
typedef const value_type* const_iterator;
const_iterator begin() const
{
return &buffer;
}
const_iterator end() const
{
return &buffer + 1;
}
private:
boost::shared_ptr<data_chunk> data;
value_type buffer;
};
} // libbitcoin
#endif
<commit_msg>Improved shared_const_buffer to use std overridable allocator and std::begin/end free functions.<commit_after>#ifndef LIBBITCOIN_NET_SHARED_CONST_BUFFER_H
#define LIBBITCOIN_NET_SHARED_CONST_BUFFER_H
#include <boost/asio.hpp>
#include <bitcoin/types.hpp>
#include <bitcoin/util/serializer.hpp>
namespace libbitcoin {
// A reference-counted non-modifiable buffer class.
class shared_const_buffer
{
public:
// Construct from a stream object
explicit shared_const_buffer(const data_chunk& user_data)
: data_(std::make_shared<data_chunk>(
std::begin(user_data), std::end(user_data))),
buffer_(boost::asio::buffer(*data_))
{
}
// Implement the ConstBufferSequence requirements.
typedef boost::asio::const_buffer value_type;
typedef const value_type* const_iterator;
const_iterator begin() const
{
return &buffer_;
}
const_iterator end() const
{
return &buffer_ + 1;
}
private:
std::shared_ptr<data_chunk> data_;
value_type buffer_;
};
} // libbitcoin
#endif
<|endoftext|> |
<commit_before>/*
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <map>
#include <gtest/gtest.h>
#include <qi/qi.hpp>
#include <qi/application.hpp>
#include <qitype/genericobject.hpp>
#include <qitype/genericobjectbuilder.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/servicedirectory.hpp>
#include <testsession/testsessionpair.hpp>
static qi::Promise<int> *payload;
void onFire(const int& pl)
{
std::cout << "onFire:" << pl << std::endl;
std::cout.flush();
payload->setValue(pl);
}
class TestObject: public ::testing::Test
{
public:
TestObject()
{
qi::GenericObjectBuilder ob;
ob.advertiseEvent<void (*)(const int&)>("fire");
oserver = ob.object();
}
protected:
void SetUp()
{
// In nightmare mode, there is a hidden service registered...
unsigned int nbServices = TestMode::getTestMode() == TestMode::Mode_Nightmare ? 2 : 1;
ASSERT_GT(p.server()->registerService("coin", oserver), 0);
EXPECT_EQ(nbServices, p.server()->services(qi::Session::ServiceLocality_Local).value().size());
std::vector<qi::ServiceInfo> services = p.client()->services();
if (TestMode::getTestMode() == TestMode::Mode_Direct)
EXPECT_EQ(3U, services.size());
else
EXPECT_EQ(2U, services.size());
oclient = p.client()->service("coin");
ASSERT_TRUE(oclient != 0);
payload = &prom;
}
void TearDown()
{
payload = 0;
}
public:
TestSessionPair p;
qi::Promise<int> prom;
qi::ObjectPtr oserver;
qi::ObjectPtr oclient;
};
TEST_F(TestObject, Simple)
{
int linkId = oclient->connect("fire", &onFire);
EXPECT_LT(0, linkId);
oserver->emitEvent("fire", 42);
ASSERT_TRUE(payload->future().wait(2000));
EXPECT_EQ(42, payload->future().value());
}
TEST_F(TestObject, RemoteEmit)
{
int linkId = oclient->connect("fire", &onFire);
EXPECT_LT(0, linkId);
oclient->emitEvent("fire", 43);
ASSERT_TRUE(payload->future().wait(2000));
EXPECT_EQ(43, payload->future().value());
}
TEST_F(TestObject, CoDeco)
{
for (unsigned i=0; i<5; ++i)
{
payload->reset();
int linkId = oclient->connect("fire", &onFire);
int exp;
EXPECT_GE(linkId, 0);
oserver->emitEvent("fire", (int)(50 + i));
ASSERT_TRUE(payload->future().wait(2000));
exp = 50 + i;
EXPECT_EQ(exp, payload->future().value());
payload->reset();
oserver->emitEvent("fire", (int)(51 + i));
ASSERT_TRUE(payload->future().wait(2000));
exp = 51 + i;
EXPECT_EQ(exp, payload->future().value());
oclient->disconnect(linkId).wait();
payload->reset();
oserver->emitEvent("fire", (int)(50 + i));
ASSERT_FALSE(payload->future().wait(200));
}
}
int main(int argc, char *argv[])
{
#if defined(__APPLE__) || defined(__linux__)
setsid();
#endif
qi::Application app(argc, argv);
::testing::InitGoogleTest(&argc, argv);
TestMode::initTestMode(argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>test_event_remote: fix the test.<commit_after>/*
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <map>
#include <gtest/gtest.h>
#include <qi/qi.hpp>
#include <qi/application.hpp>
#include <qitype/genericobject.hpp>
#include <qitype/genericobjectbuilder.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/servicedirectory.hpp>
#include <testsession/testsessionpair.hpp>
static qi::Promise<int> *payload;
void onFire(const int& pl)
{
std::cout << "onFire:" << pl << std::endl;
std::cout.flush();
payload->setValue(pl);
}
class TestObject: public ::testing::Test
{
public:
TestObject()
{
qi::GenericObjectBuilder ob;
ob.advertiseEvent<void (*)(const int&)>("fire");
oserver = ob.object();
}
protected:
void SetUp()
{
// In nightmare mode, there is a hidden service registered...
unsigned int nbServices = TestMode::getTestMode() == TestMode::Mode_Nightmare ? 2 : 1;
ASSERT_GT(p.server()->registerService("coin", oserver), 0);
EXPECT_EQ(nbServices, p.server()->services(qi::Session::ServiceLocality_Local).value().size());
std::vector<qi::ServiceInfo> services = p.client()->services();
if (TestMode::getTestMode() == TestMode::Mode_Direct)
EXPECT_EQ(2U, services.size());
oclient = p.client()->service("coin");
ASSERT_TRUE(oclient != 0);
payload = &prom;
}
void TearDown()
{
payload = 0;
}
public:
TestSessionPair p;
qi::Promise<int> prom;
qi::ObjectPtr oserver;
qi::ObjectPtr oclient;
};
TEST_F(TestObject, Simple)
{
int linkId = oclient->connect("fire", &onFire);
EXPECT_LT(0, linkId);
oserver->emitEvent("fire", 42);
ASSERT_TRUE(payload->future().wait(2000));
EXPECT_EQ(42, payload->future().value());
}
TEST_F(TestObject, RemoteEmit)
{
int linkId = oclient->connect("fire", &onFire);
EXPECT_LT(0, linkId);
oclient->emitEvent("fire", 43);
ASSERT_TRUE(payload->future().wait(2000));
EXPECT_EQ(43, payload->future().value());
}
TEST_F(TestObject, CoDeco)
{
for (unsigned i=0; i<5; ++i)
{
payload->reset();
int linkId = oclient->connect("fire", &onFire);
int exp;
EXPECT_GE(linkId, 0);
oserver->emitEvent("fire", (int)(50 + i));
ASSERT_TRUE(payload->future().wait(2000));
exp = 50 + i;
EXPECT_EQ(exp, payload->future().value());
payload->reset();
oserver->emitEvent("fire", (int)(51 + i));
ASSERT_TRUE(payload->future().wait(2000));
exp = 51 + i;
EXPECT_EQ(exp, payload->future().value());
oclient->disconnect(linkId).wait();
payload->reset();
oserver->emitEvent("fire", (int)(50 + i));
ASSERT_FALSE(payload->future().wait(200));
}
}
int main(int argc, char *argv[])
{
#if defined(__APPLE__) || defined(__linux__)
setsid();
#endif
qi::Application app(argc, argv);
::testing::InitGoogleTest(&argc, argv);
TestMode::initTestMode(argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2012-2013 Red Hat, Inc.
*
* 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.
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdexcept>
#include <map>
#include <unistd.h>
#include <xorg/gtest/xorg-gtest.h>
#include <linux/input.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include <stdexcept>
#include <fstream>
#include <xorg/gtest/xorg-gtest.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include <xorg/wacom-properties.h>
#include <xorg/xserver-properties.h>
#include <unistd.h>
#include "xit-server-input-test.h"
#include "device-interface.h"
#include "helpers.h"
#define NUM_ELEMS_MATRIX 9
typedef struct Matrix {
float elem[NUM_ELEMS_MATRIX];
} Matrix;
/**
* Wacom driver test class. This class takes a struct Tablet that defines
* which device should be initialised.
*/
class WacomMatrixTest : public XITServerInputTest,
public DeviceInterface {
public:
/**
* Initializes a standard tablet device.
*/
virtual void SetUp() {
SetDevice("tablets/Wacom-Intuos5-touch-M-Pen.desc");
XITServerInputTest::SetUp();
}
/**
* Sets up an xorg.conf for a single mouse CorePointer device based on
* the evemu device.
*/
virtual void SetUpConfigAndLog() {
config.AddDefaultScreenWithDriver();
config.AddInputSection("wacom", "Stylus",
"Option \"CorePointer\" \"on\"\n"
"Option \"Type\" \"stylus\"\n"
"Option \"Device\" \"" + dev->GetDeviceNode() + "\"\n");
config.WriteConfig();
}
protected:
int xrandr_event, xrandr_error;
};
TEST_F(WacomMatrixTest, DevicePresent)
{
XORG_TESTCASE("Test presence of tools as defined in the xorg.conf");
int ndevices;
XIDeviceInfo *info;
info = XIQueryDevice(Display(), XIAllDevices, &ndevices);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "Stylus") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
ASSERT_EQ(found, true);
XIFreeDeviceInfo(info);
}
bool set_input_matrix (Display *dpy, int deviceid, Matrix *matrix)
{
Atom prop_float, prop_matrix;
union {
unsigned char *c;
float *f;
} data;
int format_return;
Atom type_return;
unsigned long nitems;
unsigned long bytes_after;
int rc;
prop_float = XInternAtom(dpy, "FLOAT", False);
prop_matrix = XInternAtom(dpy, XI_PROP_TRANSFORM, False);
if (!prop_float)
return False;
if (!prop_matrix)
return False;
rc = XIGetProperty(dpy, deviceid, prop_matrix, 0, 9, False, prop_float,
&type_return, &format_return, &nitems, &bytes_after,
&data.c);
if (rc != Success || prop_float != type_return || format_return != 32 ||
nitems != NUM_ELEMS_MATRIX || bytes_after != 0)
return False;
memcpy(data.f, matrix->elem, sizeof(matrix->elem));
XIChangeProperty(dpy, deviceid, prop_matrix, prop_float,
format_return, PropModeReplace, data.c, nitems);
XFree(data.c);
return True;
}
/**
* compute the input trarnsformation matrix to match the area specified
* by the given (x,y) width x height.
*/
Bool compute_input_matrix (Display *dpy, int x, int y, int width, int height, Matrix *matrix)
{
// Reset matrix to no transformation by default
matrix->elem[0] = 1.0f;
matrix->elem[1] = 0.0f;
matrix->elem[2] = 0.0f;
matrix->elem[3] = 0.0f;
matrix->elem[4] = 1.0f;
matrix->elem[5] = 0.0f;
matrix->elem[6] = 0.0f;
matrix->elem[7] = 0.0f;
matrix->elem[8] = 1.0f;
int screen_x = 0;
int screen_y = 0;
int screen_width = WidthOfScreen (DefaultScreenOfDisplay (dpy));
int screen_height = HeightOfScreen (DefaultScreenOfDisplay (dpy));
if ((x < screen_x) ||
(y < screen_y) ||
(x + width > screen_x + screen_width) ||
(y + height > screen_y + screen_height))
return False;
float x_scale = (float) x / screen_width;
float y_scale = (float) y / screen_height;
float width_scale = (float) width / screen_width;
float height_scale = (float) height / screen_height;
matrix->elem[0] = width_scale;
matrix->elem[1] = 0.0f;
matrix->elem[2] = x_scale;
matrix->elem[3] = 0.0f;
matrix->elem[4] = height_scale;
matrix->elem[5] = y_scale;
matrix->elem[6] = 0.0f;
matrix->elem[7] = 0.0f;
matrix->elem[8] = 1.0f;
return True;
}
/**
* Moves the stylus from positon (x, y) by n steps in the
* direction (code) ABS_X or ABS_Y.
*/
void move_stylus (xorg::testing::evemu::Device *dev,
int x, int y, int steps, int code)
{
int i;
// Move to device coord (x, y)
dev->PlayOne(EV_ABS, ABS_X, x, True);
dev->PlayOne(EV_ABS, ABS_Y, y, True);
dev->PlayOne(EV_ABS, ABS_DISTANCE, 0, True);
dev->PlayOne(EV_KEY, BTN_TOOL_PEN, 1, True);
for (i = 0; i < steps; i++) {
if (code == ABS_X)
dev->PlayOne(EV_ABS, ABS_X, x + i, True);
else
dev->PlayOne(EV_ABS, ABS_Y, y + i, True);
dev->PlayOne(EV_ABS, ABS_DISTANCE, i, True);
}
dev->PlayOne(EV_KEY, BTN_TOOL_PEN, 0, True);
}
void test_area (Display *dpy, xorg::testing::evemu::Device *dev,
int deviceid, int x, int y, int width, int height)
{
XEvent ev;
Matrix matrix;
compute_input_matrix (dpy, x, y, width, height, &matrix);
ASSERT_TRUE (set_input_matrix (dpy, deviceid, &matrix));
XSync(dpy, True);
// Simulate stylus movement for the entire tablet resolution
int minx, maxx;
int miny, maxy;
dev->GetAbsData(ABS_X, &minx, &maxx);
dev->GetAbsData(ABS_Y, &miny, &maxy);
move_stylus (dev, 0, 0, maxx, ABS_X);
move_stylus (dev, maxx, 0, maxy, ABS_Y);
move_stylus (dev, 0, 0, maxy, ABS_Y);
move_stylus (dev, 0, maxy, maxx, ABS_X);
XSync (dpy, False);
EXPECT_NE(XPending(dpy), 0) << "No event received??" << std::endl;
// Capture motion events and check they remain within the mapped area
XSync (dpy, False);
while(XCheckMaskEvent (dpy, PointerMotionMask, &ev)) {
EXPECT_GE (ev.xmotion.x_root, x);
EXPECT_LT (ev.xmotion.x_root, x + width);
EXPECT_GE (ev.xmotion.y_root, y);
EXPECT_LE (ev.xmotion.y_root, y + height);
}
XSync(dpy, True);
}
TEST_F(WacomMatrixTest, InputMatrix)
{
XORG_TESTCASE("Test input transformation matrix");
/* the server takes a while to start up but the devices may not respond
to events yet. Add a noop call that just delays everything long
enough for this test to work */
XInternAtom(Display(), "foo", True);
XFlush(Display());
EXPECT_TRUE(InitRandRSupport(Display(), &xrandr_event, &xrandr_error));
int monitor_x, monitor_y, monitor_width, monitor_height;
int n_monitors = GetNMonitors (Display());
monitor_x = 0;
monitor_y = 0;
monitor_width = WidthOfScreen (DefaultScreenOfDisplay (Display()));
monitor_height = HeightOfScreen (DefaultScreenOfDisplay (Display()));
if (n_monitors > 0)
GetMonitorGeometry (Display(), 0, &monitor_x, &monitor_y, &monitor_width, &monitor_height);
int deviceid;
FindInputDeviceByName(Display(), "Stylus", &deviceid);
ASSERT_NE (deviceid, 0);
XSelectInput(Display(), DefaultRootWindow(Display()), PointerMotionMask |
ButtonMotionMask);
XSync(Display(), False);
// Check with upper right quarter
test_area (Display(), dev.get(), deviceid, monitor_x, monitor_y, monitor_width / 2, monitor_height / 2);
// Check with upper left quarter
test_area (Display(), dev.get(), deviceid, monitor_x + monitor_width / 2, monitor_y, monitor_width / 2, monitor_height / 2);
// Check with bottom right quarter
test_area (Display(), dev.get(), deviceid, monitor_x, monitor_y + monitor_height / 2, monitor_width / 2, monitor_height / 2);
// Check with bottom left quarter
test_area (Display(), dev.get(), deviceid, monitor_x + monitor_width / 2, monitor_y + monitor_height / 2, monitor_width / 2, monitor_height / 2);
}
<commit_msg>input/wacom: reduce the number of events in input matrix test<commit_after>/*
* Copyright © 2012-2013 Red Hat, Inc.
*
* 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.
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdexcept>
#include <map>
#include <unistd.h>
#include <xorg/gtest/xorg-gtest.h>
#include <linux/input.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include <stdexcept>
#include <fstream>
#include <xorg/gtest/xorg-gtest.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include <xorg/wacom-properties.h>
#include <xorg/xserver-properties.h>
#include <unistd.h>
#include "xit-server-input-test.h"
#include "device-interface.h"
#include "helpers.h"
#define NUM_ELEMS_MATRIX 9
typedef struct Matrix {
float elem[NUM_ELEMS_MATRIX];
} Matrix;
/**
* Wacom driver test class. This class takes a struct Tablet that defines
* which device should be initialised.
*/
class WacomMatrixTest : public XITServerInputTest,
public DeviceInterface {
public:
/**
* Initializes a standard tablet device.
*/
virtual void SetUp() {
SetDevice("tablets/Wacom-Intuos5-touch-M-Pen.desc");
XITServerInputTest::SetUp();
}
/**
* Sets up an xorg.conf for a single mouse CorePointer device based on
* the evemu device.
*/
virtual void SetUpConfigAndLog() {
config.AddDefaultScreenWithDriver();
config.AddInputSection("wacom", "Stylus",
"Option \"CorePointer\" \"on\"\n"
"Option \"Type\" \"stylus\"\n"
"Option \"Device\" \"" + dev->GetDeviceNode() + "\"\n");
config.WriteConfig();
}
protected:
int xrandr_event, xrandr_error;
};
TEST_F(WacomMatrixTest, DevicePresent)
{
XORG_TESTCASE("Test presence of tools as defined in the xorg.conf");
int ndevices;
XIDeviceInfo *info;
info = XIQueryDevice(Display(), XIAllDevices, &ndevices);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "Stylus") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
ASSERT_EQ(found, true);
XIFreeDeviceInfo(info);
}
bool set_input_matrix (Display *dpy, int deviceid, Matrix *matrix)
{
Atom prop_float, prop_matrix;
union {
unsigned char *c;
float *f;
} data;
int format_return;
Atom type_return;
unsigned long nitems;
unsigned long bytes_after;
int rc;
prop_float = XInternAtom(dpy, "FLOAT", False);
prop_matrix = XInternAtom(dpy, XI_PROP_TRANSFORM, False);
if (!prop_float)
return False;
if (!prop_matrix)
return False;
rc = XIGetProperty(dpy, deviceid, prop_matrix, 0, 9, False, prop_float,
&type_return, &format_return, &nitems, &bytes_after,
&data.c);
if (rc != Success || prop_float != type_return || format_return != 32 ||
nitems != NUM_ELEMS_MATRIX || bytes_after != 0)
return False;
memcpy(data.f, matrix->elem, sizeof(matrix->elem));
XIChangeProperty(dpy, deviceid, prop_matrix, prop_float,
format_return, PropModeReplace, data.c, nitems);
XFree(data.c);
return True;
}
/**
* compute the input trarnsformation matrix to match the area specified
* by the given (x,y) width x height.
*/
Bool compute_input_matrix (Display *dpy, int x, int y, int width, int height, Matrix *matrix)
{
// Reset matrix to no transformation by default
matrix->elem[0] = 1.0f;
matrix->elem[1] = 0.0f;
matrix->elem[2] = 0.0f;
matrix->elem[3] = 0.0f;
matrix->elem[4] = 1.0f;
matrix->elem[5] = 0.0f;
matrix->elem[6] = 0.0f;
matrix->elem[7] = 0.0f;
matrix->elem[8] = 1.0f;
int screen_x = 0;
int screen_y = 0;
int screen_width = WidthOfScreen (DefaultScreenOfDisplay (dpy));
int screen_height = HeightOfScreen (DefaultScreenOfDisplay (dpy));
if ((x < screen_x) ||
(y < screen_y) ||
(x + width > screen_x + screen_width) ||
(y + height > screen_y + screen_height))
return False;
float x_scale = (float) x / screen_width;
float y_scale = (float) y / screen_height;
float width_scale = (float) width / screen_width;
float height_scale = (float) height / screen_height;
matrix->elem[0] = width_scale;
matrix->elem[1] = 0.0f;
matrix->elem[2] = x_scale;
matrix->elem[3] = 0.0f;
matrix->elem[4] = height_scale;
matrix->elem[5] = y_scale;
matrix->elem[6] = 0.0f;
matrix->elem[7] = 0.0f;
matrix->elem[8] = 1.0f;
return True;
}
/**
* Moves the stylus from x1/y1 to x2/y2 in 3 steps
*/
void move_stylus (xorg::testing::evemu::Device *dev,
int x1, int y1, int x2, int y2)
{
dev->PlayOne(EV_ABS, ABS_X, x1, True);
dev->PlayOne(EV_ABS, ABS_Y, y1, True);
dev->PlayOne(EV_ABS, ABS_DISTANCE, 0, True);
dev->PlayOne(EV_KEY, BTN_TOOL_PEN, 1, True);
dev->PlayOne(EV_ABS, ABS_X, x1 + (x2 - x1)/2, True);
dev->PlayOne(EV_ABS, ABS_Y, y1 + (y2 - y1)/2, True);
dev->PlayOne(EV_ABS, ABS_DISTANCE, 0, True);
dev->PlayOne(EV_KEY, BTN_TOOL_PEN, 1, True);
dev->PlayOne(EV_ABS, ABS_X, x2, True);
dev->PlayOne(EV_ABS, ABS_Y, y2, True);
dev->PlayOne(EV_ABS, ABS_DISTANCE, 0, True);
dev->PlayOne(EV_KEY, BTN_TOOL_PEN, 1, True);
dev->PlayOne(EV_KEY, BTN_TOOL_PEN, 0, True);
}
void test_area (Display *dpy, xorg::testing::evemu::Device *dev,
int deviceid, int x, int y, int width, int height)
{
XEvent ev;
Matrix matrix;
compute_input_matrix (dpy, x, y, width, height, &matrix);
ASSERT_TRUE (set_input_matrix (dpy, deviceid, &matrix));
XSync(dpy, True);
// Simulate stylus movement for the entire tablet resolution
int minx, maxx;
int miny, maxy;
dev->GetAbsData(ABS_X, &minx, &maxx);
dev->GetAbsData(ABS_Y, &miny, &maxy);
move_stylus (dev, 0, 0, maxx, 0);
move_stylus (dev, maxx, 0, maxx, maxy);
move_stylus (dev, maxx, maxy, 0, maxy);
move_stylus (dev, 0, maxy, 0, 0);
XSync (dpy, False);
EXPECT_NE(XPending(dpy), 0) << "No event received??" << std::endl;
// Capture motion events and check they remain within the mapped area
XSync (dpy, False);
while(XCheckMaskEvent (dpy, PointerMotionMask, &ev)) {
EXPECT_GE (ev.xmotion.x_root, x);
EXPECT_LT (ev.xmotion.x_root, x + width);
EXPECT_GE (ev.xmotion.y_root, y);
EXPECT_LE (ev.xmotion.y_root, y + height);
}
XSync(dpy, True);
}
TEST_F(WacomMatrixTest, InputMatrix)
{
XORG_TESTCASE("Test input transformation matrix");
/* the server takes a while to start up but the devices may not respond
to events yet. Add a noop call that just delays everything long
enough for this test to work */
XInternAtom(Display(), "foo", True);
XFlush(Display());
EXPECT_TRUE(InitRandRSupport(Display(), &xrandr_event, &xrandr_error));
int monitor_x, monitor_y, monitor_width, monitor_height;
int n_monitors = GetNMonitors (Display());
monitor_x = 0;
monitor_y = 0;
monitor_width = WidthOfScreen (DefaultScreenOfDisplay (Display()));
monitor_height = HeightOfScreen (DefaultScreenOfDisplay (Display()));
if (n_monitors > 0)
GetMonitorGeometry (Display(), 0, &monitor_x, &monitor_y, &monitor_width, &monitor_height);
int deviceid;
FindInputDeviceByName(Display(), "Stylus", &deviceid);
ASSERT_NE (deviceid, 0);
XSelectInput(Display(), DefaultRootWindow(Display()), PointerMotionMask |
ButtonMotionMask);
XSync(Display(), False);
// Check with upper right quarter
test_area (Display(), dev.get(), deviceid, monitor_x, monitor_y, monitor_width / 2, monitor_height / 2);
// Check with upper left quarter
test_area (Display(), dev.get(), deviceid, monitor_x + monitor_width / 2, monitor_y, monitor_width / 2, monitor_height / 2);
// Check with bottom right quarter
test_area (Display(), dev.get(), deviceid, monitor_x, monitor_y + monitor_height / 2, monitor_width / 2, monitor_height / 2);
// Check with bottom left quarter
test_area (Display(), dev.get(), deviceid, monitor_x + monitor_width / 2, monitor_y + monitor_height / 2, monitor_width / 2, monitor_height / 2);
}
<|endoftext|> |
<commit_before>#include <cmath>
#include "Ball.h"
#include "Brick.h"
#include "Log.h"
Ball::Ball(Window* window, const std::string& textureName, int xPos, int yPos, Entity* linkedPaddle) :
Entity(window, textureName, xPos, yPos)
{
this->typeId = TYPEID_BALL;
this->linkedPaddle = linkedPaddle;
lives = 3;
yVelocity = 0;
xVelocity = 0;
}
void Ball::update()
{
// don't render the ball if there are no lives left
if (lives <= 0)
return;
// if the ball is still on the paddle, make it move in sync with the paddle
if (onPaddle)
{
xPos = linkedPaddle->getX() + (linkedPaddle->getWidth()/2) - getWidth()/2;
yPos = linkedPaddle->getY() - getHeight();
window->renderTexture(texture, xPos, yPos);
return;
}
// first move the ball according to its current velocity
xPos += xVelocity;
yPos += yVelocity;
// then we check to see if the ball is somewhere that it shouldn't be
// if it is, correct that
// if the ball goes off the left side of the screen
if (xPos < 0)
{
xPos = 0;
xVelocity = -xVelocity;
}
// if the ball goes off the right side of the screen
if(xPos > window->getWidth() - getWidth())
{
xPos = window->getWidth() - getWidth();
xVelocity = -xVelocity;
}
// if the ball goes off the top of the screen
if (yPos < 0)
{
yPos = 0;
yVelocity = -yVelocity;
}
// if the ball goes off the bottom of the screen
if (yPos > window->getHeight() - height)
{
lives--;
Log::info("Lives left: " + std::to_string(lives));
setOnPaddle(true);
}
// actually render the ball at its new position to the screen
window->renderTexture(texture, xPos, yPos);
}
void Ball::handleCollision(Entity* entity)
{
if (!entity->isActive())
return;
Log::info("Ball hit something!");
double totalSpeed = sqrt(xVelocity*xVelocity + yVelocity*yVelocity);
double ballCenter = xPos + (width / 2);
double entityCenter = entity->getX() + (entity->getWidth() / 2);
//double ballY = yPos + (width / 2);
//double entityY = entity->getY() + (entity->getWidth() / 2);
//double verticalDifference = std::abs(ballY - entityY);
if (entity->getTypeId() == TYPEID_BRICK)
{
double checkRight = std::abs(entity->getX() - (xPos + width));
double checkLeft = std::abs((entity->getX() + entity->getWidth()) - xPos );
double checkHorizontal;
if (checkLeft < checkRight)
{
checkHorizontal = checkLeft;
}
else
{
checkHorizontal = checkRight;
}
double checkUp = std::abs((entity->getY() + entity->getHeight()) - yPos);
double checkDown = std::abs(entity->getY() - (yPos + height));
double checkVertical;
if (checkUp < checkDown)
{
checkVertical = checkUp;
}
else
{
checkVertical = checkDown;
}
if (checkHorizontal > checkVertical)
yVelocity = -yVelocity;
else if (std::abs(checkHorizontal - checkVertical)<1.2)
{
yVelocity = -yVelocity;
xVelocity = -xVelocity;
}
else
xVelocity = -xVelocity;
/*Log::info("Vdiff: " + std::to_string(checkVertical));
Log::info("Hdiff: " + std::to_string(checkHorizontal));
Log::info("difference: " + std::to_string(checkHorizontal - checkVertical));
Log::info("");*/
}
else
{
double horizontalDifference = ballCenter - entityCenter;
totalSpeed += 1;
if (totalSpeed > 15)
totalSpeed = 15;
double w = entity->getWidth()/2.0;
double angle = horizontalDifference / w;
xVelocity = angle*totalSpeed*.8;
yVelocity = 0 - sqrt(totalSpeed*totalSpeed - xVelocity*xVelocity);
if (std::abs(yVelocity) < .8)
yVelocity = -1;
}
}
void Ball::setOnPaddle(bool apply)
{
if (apply)
Log::info("Placed ball on paddle.");
else
Log::info("Freed ball from paddle.");
onPaddle = apply;
}
void Ball::setLives(int count)
{
lives = count;
Log::info("Set new life count to " + std::to_string(count));
}
void Ball::detach()
{
Log::info("Detached ball from paddle.");
onPaddle = false;
// launch the ball in the direction the paddle is moving
xVelocity = linkedPaddle->isMoving(MOVE_LEFT) ? -5 : 5;
yVelocity = -5;
}
<commit_msg>Adjusted ball speed cap from 15 to 10<commit_after>#include <cmath>
#include "Ball.h"
#include "Brick.h"
#include "Log.h"
Ball::Ball(Window* window, const std::string& textureName, int xPos, int yPos, Entity* linkedPaddle) :
Entity(window, textureName, xPos, yPos)
{
this->typeId = TYPEID_BALL;
this->linkedPaddle = linkedPaddle;
lives = 3;
yVelocity = 0;
xVelocity = 0;
}
void Ball::update()
{
// don't render the ball if there are no lives left
if (lives <= 0)
return;
// if the ball is still on the paddle, make it move in sync with the paddle
if (onPaddle)
{
xPos = linkedPaddle->getX() + (linkedPaddle->getWidth()/2) - getWidth()/2;
yPos = linkedPaddle->getY() - getHeight();
window->renderTexture(texture, xPos, yPos);
return;
}
// first move the ball according to its current velocity
xPos += xVelocity;
yPos += yVelocity;
// then we check to see if the ball is somewhere that it shouldn't be
// if it is, correct that
// if the ball goes off the left side of the screen
if (xPos < 0)
{
xPos = 0;
xVelocity = -xVelocity;
}
// if the ball goes off the right side of the screen
if(xPos > window->getWidth() - getWidth())
{
xPos = window->getWidth() - getWidth();
xVelocity = -xVelocity;
}
// if the ball goes off the top of the screen
if (yPos < 0)
{
yPos = 0;
yVelocity = -yVelocity;
}
// if the ball goes off the bottom of the screen
if (yPos > window->getHeight() - height)
{
lives--;
Log::info("Lives left: " + std::to_string(lives));
setOnPaddle(true);
}
// actually render the ball at its new position to the screen
window->renderTexture(texture, xPos, yPos);
}
void Ball::handleCollision(Entity* entity)
{
if (!entity->isActive())
return;
Log::info("Ball hit something!");
double totalSpeed = sqrt(xVelocity*xVelocity + yVelocity*yVelocity);
double ballCenter = xPos + (width / 2);
double entityCenter = entity->getX() + (entity->getWidth() / 2);
//double ballY = yPos + (width / 2);
//double entityY = entity->getY() + (entity->getWidth() / 2);
//double verticalDifference = std::abs(ballY - entityY);
if (entity->getTypeId() == TYPEID_BRICK)
{
double checkRight = std::abs(entity->getX() - (xPos + width));
double checkLeft = std::abs((entity->getX() + entity->getWidth()) - xPos );
double checkHorizontal;
if (checkLeft < checkRight)
{
checkHorizontal = checkLeft;
}
else
{
checkHorizontal = checkRight;
}
double checkUp = std::abs((entity->getY() + entity->getHeight()) - yPos);
double checkDown = std::abs(entity->getY() - (yPos + height));
double checkVertical;
if (checkUp < checkDown)
{
checkVertical = checkUp;
}
else
{
checkVertical = checkDown;
}
if (checkHorizontal > checkVertical)
yVelocity = -yVelocity;
else if (std::abs(checkHorizontal - checkVertical)<1.2)
{
yVelocity = -yVelocity;
xVelocity = -xVelocity;
}
else
xVelocity = -xVelocity;
/*Log::info("Vdiff: " + std::to_string(checkVertical));
Log::info("Hdiff: " + std::to_string(checkHorizontal));
Log::info("difference: " + std::to_string(checkHorizontal - checkVertical));
Log::info("");*/
}
else
{
double horizontalDifference = ballCenter - entityCenter;
totalSpeed += 1;
if (totalSpeed > 10)
totalSpeed = 10;
double w = entity->getWidth()/2.0;
double angle = horizontalDifference / w;
xVelocity = angle*totalSpeed*.8;
yVelocity = 0 - sqrt(totalSpeed*totalSpeed - xVelocity*xVelocity);
if (std::abs(yVelocity) < .8)
yVelocity = -1;
}
}
void Ball::setOnPaddle(bool apply)
{
if (apply)
Log::info("Placed ball on paddle.");
else
Log::info("Freed ball from paddle.");
onPaddle = apply;
}
void Ball::setLives(int count)
{
lives = count;
Log::info("Set new life count to " + std::to_string(count));
}
void Ball::detach()
{
Log::info("Detached ball from paddle.");
onPaddle = false;
// launch the ball in the direction the paddle is moving
xVelocity = linkedPaddle->isMoving(MOVE_LEFT) ? -5 : 5;
yVelocity = -5;
}
<|endoftext|> |
<commit_before>#pragma once
// expressly better bencoder
// Copyright (C) 2013 Igor Kaplounenko
// Licensed under MIT License
#include <cinttypes>
#include <cstdint>
#include <cassert>
#include <cstdio>
#include <array>
#include <tuple>
#include <vector>
#include <cstring>
#include <string>
namespace ebb {
namespace internal {
// http://stackoverflow.com/questions/7858817/unpacking-a-tuple-to-call-a-matching-function-pointer?lq=1
template<int...> struct seq {};
template<int N, int... S> struct gen_seq : gen_seq<N-1, N-1, S...> {};
// generated sequence specialization / endpoint
template<int... S> struct gen_seq<0, S...> { typedef seq<S...> type; };
// for list and dict start/end tokens, i.e. 'd', 'l', 'e'
struct bencode_token {
const unsigned char token;
};
template<typename> struct is_unsigned_char_array : std::false_type {};
template<size_t N> struct is_unsigned_char_array<std::array<unsigned char, N>>
: std::true_type {};
template<size_t N> struct is_unsigned_char_array<std::array<unsigned char, N>&>
: std::true_type {};
template<size_t N> struct is_unsigned_char_array<
const std::array<unsigned char, N>> : std::true_type {};
template<size_t N> struct is_unsigned_char_array<
const std::array<unsigned char, N>&> : std::true_type {};
template<typename A> void assert_valid_key_type() {
static_assert(std::is_convertible<A, std::vector<unsigned char>>::value
|| std::is_convertible<A, const char*>::value
|| std::is_convertible<A, std::string>::value
|| is_unsigned_char_array<A>::value
, "Bencoded dictionary key must be a char*, an std::vector<unsigned char>"
", or an std::array<unsigned char, N>.");
}
template<typename Head> void assert_valid_key_types() {
assert_valid_key_type<Head>();
}
template<typename Head, typename Middle, typename... Tail>
void assert_valid_key_types() {
assert_valid_key_type<Head>();
assert_valid_key_types<Middle, Tail...>();
}
}
const static internal::bencode_token bdict_begin = {'d'};
const static internal::bencode_token bdict_end = {'e'};
const static internal::bencode_token blist_begin = {'l'};
const static internal::bencode_token blist_end = {'e'};
template<typename A, typename B> std::tuple<A, B> k_v(A &&a, B &&b) {
internal::assert_valid_key_type<A>();
return std::forward_as_tuple(a, b);
}
template<typename... Arguments> std::tuple<internal::bencode_token, Arguments...,
internal::bencode_token> blist(Arguments&&... remaining) {
return std::forward_as_tuple(blist_begin, remaining..., blist_end);
}
template<typename... A, typename... B> std::tuple<internal::bencode_token,
std::tuple<A,B>..., internal::bencode_token> bdict(
std::tuple<A, B>&&... remaining) {
internal::assert_valid_key_types<A...>();
return std::forward_as_tuple(bdict_begin, remaining..., bdict_end);
}
class bencoder {
private:
unsigned char* buffer;
int64_t len;
public:
bencoder(unsigned char* buffer, int64_t len = -1):
buffer(buffer), len(len) {};
template<typename... Arguments> unsigned char* operator()
(Arguments&&... remaining) {
assert(buffer);
return bencode(remaining...);
}
private:
unsigned char* bencode() {
return buffer;
}
template<typename... Arguments> unsigned char* bencode(int64_t value,
Arguments&&... remaining) {
long written = snprintf(reinterpret_cast<char*>(buffer), len,
"i%" PRId64 "e", value);
if (written > len) {
buffer = NULL;
return NULL;
}
buffer += written;
len -= written;
return bencode(remaining...);
}
template<typename... Arguments> unsigned char* bencode(char const *value,
Arguments&&... remaining) {
long written = snprintf(reinterpret_cast<char*>(buffer), len, "%zu:%s",
strlen(value), value);
if (written > len) {
buffer = NULL;
return NULL;
}
buffer += written;
len -= written;
return bencode(remaining...);
}
template<typename... Arguments> unsigned char* bencode(
std::vector<unsigned char> const &value, Arguments&&... remaining) {
long written = snprintf(reinterpret_cast<char*>(buffer), len, "%zu:",
value.size());
if (written + value.size() > len) {
buffer = NULL;
return NULL;
}
std::memcpy(buffer + written, &(value[0]), value.size());
buffer += written + value.size();
len -= written + value.size();
return bencode(remaining...);
}
template<typename... Arguments> unsigned char* bencode(
std::string const &value, Arguments&&... remaining) {
long written = snprintf(reinterpret_cast<char*>(buffer), len, "%zu:",
value.size());
if (written + value.size() > len) {
buffer = NULL;
return NULL;
}
std::memcpy(buffer + written, &(value[0]), value.size());
buffer += written + value.size();
len -= written + value.size();
return bencode(remaining...);
}
template<size_t N, typename... Arguments> unsigned char* bencode(
std::array<unsigned char, N> const &value, Arguments&&... remaining) {
long written = snprintf(reinterpret_cast<char*>(buffer), len, "%zu:", N);
if (written + N > len) {
buffer = NULL;
return NULL;
}
std::memcpy(buffer + written, &(value[0]), N);
buffer += written + N;
len -= written + N;
return bencode(remaining...);
}
template<typename... Arguments> unsigned char* bencode(
internal::bencode_token const value, Arguments&&... remaining) {
if (len == 0) {
buffer = NULL;
return NULL;
}
*buffer = value.token;
buffer++;
len--;
return bencode(remaining...);
}
template<typename... TupleTypes, typename... Arguments>
unsigned char* bencode(std::tuple<TupleTypes...> const &value,
Arguments... remaining) {
return bencode(typename internal::gen_seq<sizeof...(TupleTypes)>::type(),
value, remaining...);
}
template<int... S, typename... TupleTypes, typename... Arguments>
unsigned char* bencode(internal::seq<S...>,
std::tuple<TupleTypes...> const &value, Arguments... remaining) {
return bencode(std::get<S>(value)..., remaining...);
}
};
}
<commit_msg>support writing vector<char><commit_after>#pragma once
// expressly better bencoder
// Copyright (C) 2013 Igor Kaplounenko
// Licensed under MIT License
#include <cinttypes>
#include <cstdint>
#include <cassert>
#include <cstdio>
#include <array>
#include <tuple>
#include <vector>
#include <cstring>
#include <string>
namespace ebb {
namespace internal {
// http://stackoverflow.com/questions/7858817/unpacking-a-tuple-to-call-a-matching-function-pointer?lq=1
template<int...> struct seq {};
template<int N, int... S> struct gen_seq : gen_seq<N-1, N-1, S...> {};
// generated sequence specialization / endpoint
template<int... S> struct gen_seq<0, S...> { typedef seq<S...> type; };
// for list and dict start/end tokens, i.e. 'd', 'l', 'e'
struct bencode_token {
const unsigned char token;
};
template<typename> struct is_unsigned_char_array : std::false_type {};
template<size_t N> struct is_unsigned_char_array<std::array<unsigned char, N>>
: std::true_type {};
template<size_t N> struct is_unsigned_char_array<std::array<unsigned char, N>&>
: std::true_type {};
template<size_t N> struct is_unsigned_char_array<
const std::array<unsigned char, N>> : std::true_type {};
template<size_t N> struct is_unsigned_char_array<
const std::array<unsigned char, N>&> : std::true_type {};
template<typename A> void assert_valid_key_type() {
static_assert(std::is_convertible<A, std::vector<unsigned char>>::value
|| std::is_convertible<A, std::vector<char>>::value
|| std::is_convertible<A, const char*>::value
|| std::is_convertible<A, std::string>::value
|| is_unsigned_char_array<A>::value
, "Bencoded dictionary key must be a char*, an std::vector<unsigned char>"
", or an std::array<unsigned char, N>.");
}
template<typename Head> void assert_valid_key_types() {
assert_valid_key_type<Head>();
}
template<typename Head, typename Middle, typename... Tail>
void assert_valid_key_types() {
assert_valid_key_type<Head>();
assert_valid_key_types<Middle, Tail...>();
}
}
const static internal::bencode_token bdict_begin = {'d'};
const static internal::bencode_token bdict_end = {'e'};
const static internal::bencode_token blist_begin = {'l'};
const static internal::bencode_token blist_end = {'e'};
template<typename A, typename B> std::tuple<A, B> k_v(A &&a, B &&b) {
internal::assert_valid_key_type<A>();
return std::forward_as_tuple(a, b);
}
template<typename... Arguments> std::tuple<internal::bencode_token, Arguments...,
internal::bencode_token> blist(Arguments&&... remaining) {
return std::forward_as_tuple(blist_begin, remaining..., blist_end);
}
template<typename... A, typename... B> std::tuple<internal::bencode_token,
std::tuple<A,B>..., internal::bencode_token> bdict(
std::tuple<A, B>&&... remaining) {
internal::assert_valid_key_types<A...>();
return std::forward_as_tuple(bdict_begin, remaining..., bdict_end);
}
class bencoder {
private:
unsigned char* buffer;
int64_t len;
public:
bencoder(unsigned char* buffer, int64_t len = -1):
buffer(buffer), len(len) {};
template<typename... Arguments> unsigned char* operator()
(Arguments&&... remaining) {
assert(buffer);
return bencode(remaining...);
}
private:
unsigned char* bencode() {
return buffer;
}
template<typename... Arguments> unsigned char* bencode(int64_t value,
Arguments&&... remaining) {
long written = snprintf(reinterpret_cast<char*>(buffer), len,
"i%" PRId64 "e", value);
if (written > len) {
buffer = NULL;
return NULL;
}
buffer += written;
len -= written;
return bencode(remaining...);
}
template<typename... Arguments> unsigned char* bencode(char const *value,
Arguments&&... remaining) {
long written = snprintf(reinterpret_cast<char*>(buffer), len, "%zu:%s",
strlen(value), value);
if (written > len) {
buffer = NULL;
return NULL;
}
buffer += written;
len -= written;
return bencode(remaining...);
}
template<typename... Arguments> unsigned char* bencode(
std::vector<unsigned char> const &value, Arguments&&... remaining) {
long written = snprintf(reinterpret_cast<char*>(buffer), len, "%zu:",
value.size());
if (written + value.size() > len) {
buffer = NULL;
return NULL;
}
std::memcpy(buffer + written, &value[0], value.size());
buffer += written + value.size();
len -= written + value.size();
return bencode(remaining...);
}
template<typename... Arguments> unsigned char* bencode(
std::vector<char> const &value, Arguments&&... remaining) {
long written = snprintf(reinterpret_cast<char*>(buffer), len, "%zu:",
value.size());
if (written + value.size() > len) {
buffer = NULL;
return NULL;
}
std::memcpy(buffer + written, (unsigned char*)&value[0], value.size());
buffer += written + value.size();
len -= written + value.size();
return bencode(remaining...);
}
template<typename... Arguments> unsigned char* bencode(
std::string const &value, Arguments&&... remaining) {
long written = snprintf(reinterpret_cast<char*>(buffer), len, "%zu:",
value.size());
if (written + value.size() > len) {
buffer = NULL;
return NULL;
}
std::memcpy(buffer + written, &(value[0]), value.size());
buffer += written + value.size();
len -= written + value.size();
return bencode(remaining...);
}
template<size_t N, typename... Arguments> unsigned char* bencode(
std::array<unsigned char, N> const &value, Arguments&&... remaining) {
long written = snprintf(reinterpret_cast<char*>(buffer), len, "%zu:", N);
if (written + N > len) {
buffer = NULL;
return NULL;
}
std::memcpy(buffer + written, &(value[0]), N);
buffer += written + N;
len -= written + N;
return bencode(remaining...);
}
template<typename... Arguments> unsigned char* bencode(
internal::bencode_token const value, Arguments&&... remaining) {
if (len == 0) {
buffer = NULL;
return NULL;
}
*buffer = value.token;
buffer++;
len--;
return bencode(remaining...);
}
template<typename... TupleTypes, typename... Arguments>
unsigned char* bencode(std::tuple<TupleTypes...> const &value,
Arguments... remaining) {
return bencode(typename internal::gen_seq<sizeof...(TupleTypes)>::type(),
value, remaining...);
}
template<int... S, typename... TupleTypes, typename... Arguments>
unsigned char* bencode(internal::seq<S...>,
std::tuple<TupleTypes...> const &value, Arguments... remaining) {
return bencode(std::get<S>(value)..., remaining...);
}
};
}
<|endoftext|> |
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* 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 <iomanip>
#include <CSVStackFile.hpp>
#include <Tensile/Utils.hpp>
namespace Tensile
{
namespace Client
{
CSVStackFile::CSVStackFile(std::string const& filename)
: m_stream(new std::ofstream(filename.c_str()))
{
}
void null_deleter(void * ptr) {}
CSVStackFile::CSVStackFile(std::ostream & stream)
: m_stream(&stream, null_deleter)
{
}
CSVStackFile::CSVStackFile(std::shared_ptr<std::ostream> stream)
: m_stream(stream)
{
}
CSVStackFile::~CSVStackFile()
{
}
void CSVStackFile::setHeaderForKey(std::string const& key, std::string const& header)
{
if(m_headers.find(key) == m_headers.end())
m_keyOrder.push_back(key);
m_headers[key] = header;
}
void CSVStackFile::push()
{
m_stack.push_back(m_currentRow);
}
void CSVStackFile::pop()
{
m_currentRow = m_stack.back();
m_stack.pop_back();
}
void CSVStackFile::writeCurrentRow()
{
if(m_firstRow && !m_headers.empty())
writeRow(m_headers);
m_firstRow = false;
writeRow(m_currentRow);
if(m_stack.empty())
m_currentRow.clear();
else
m_currentRow = m_stack.back();
}
void CSVStackFile::writeRow(std::unordered_map<std::string, std::string> const& row)
{
bool firstCol = true;
for(auto const& key: m_keyOrder)
{
if(!firstCol)
(*m_stream) << ", ";
std::string value = "";
auto it = row.find(key);
if(it != row.end())
value = escape(it->second);
(*m_stream) << value;
firstCol = false;
}
(*m_stream) << std::endl;
}
std::string CSVStackFile::escape(std::string const& value)
{
// An actual quote needs more attention.
if(value.find('"') != std::string::npos)
return escapeQuote(value);
bool needQuote = false;
std::string badValues = ",\n\r";
for(char c: badValues)
{
if(value.find(c) != std::string::npos)
{
needQuote = true;
break;
}
}
if(needQuote)
return concatenate("\"", value, "\"");
return value;
}
std::string CSVStackFile::escapeQuote(std::string const& value)
{
std::ostringstream rv;
rv << '"';
for(char c: value)
{
if(c == '"')
rv << "\"\"";
else
rv << c;
}
rv << '"';
return rv.str();
}
void CSVStackFile::setValueForKey(std::string const& key, std::string const& value)
{
m_currentRow[key] = value;
}
void CSVStackFile::setValueForKey(std::string const& key, double const& value)
{
if (value > 0.1)
{
std::ostringstream ss;
ss << std::fixed << std::setprecision(2) << value;
ss << value;
setValueForKey(key, ss.str());
}
else
setValueForKey(key, boost::lexical_cast<std::string>(value));
}
}
}
<commit_msg>Set double precision threshold to 1.0<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* 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 <iomanip>
#include <CSVStackFile.hpp>
#include <Tensile/Utils.hpp>
namespace Tensile
{
namespace Client
{
CSVStackFile::CSVStackFile(std::string const& filename)
: m_stream(new std::ofstream(filename.c_str()))
{
}
void null_deleter(void * ptr) {}
CSVStackFile::CSVStackFile(std::ostream & stream)
: m_stream(&stream, null_deleter)
{
}
CSVStackFile::CSVStackFile(std::shared_ptr<std::ostream> stream)
: m_stream(stream)
{
}
CSVStackFile::~CSVStackFile()
{
}
void CSVStackFile::setHeaderForKey(std::string const& key, std::string const& header)
{
if(m_headers.find(key) == m_headers.end())
m_keyOrder.push_back(key);
m_headers[key] = header;
}
void CSVStackFile::push()
{
m_stack.push_back(m_currentRow);
}
void CSVStackFile::pop()
{
m_currentRow = m_stack.back();
m_stack.pop_back();
}
void CSVStackFile::writeCurrentRow()
{
if(m_firstRow && !m_headers.empty())
writeRow(m_headers);
m_firstRow = false;
writeRow(m_currentRow);
if(m_stack.empty())
m_currentRow.clear();
else
m_currentRow = m_stack.back();
}
void CSVStackFile::writeRow(std::unordered_map<std::string, std::string> const& row)
{
bool firstCol = true;
for(auto const& key: m_keyOrder)
{
if(!firstCol)
(*m_stream) << ", ";
std::string value = "";
auto it = row.find(key);
if(it != row.end())
value = escape(it->second);
(*m_stream) << value;
firstCol = false;
}
(*m_stream) << std::endl;
}
std::string CSVStackFile::escape(std::string const& value)
{
// An actual quote needs more attention.
if(value.find('"') != std::string::npos)
return escapeQuote(value);
bool needQuote = false;
std::string badValues = ",\n\r";
for(char c: badValues)
{
if(value.find(c) != std::string::npos)
{
needQuote = true;
break;
}
}
if(needQuote)
return concatenate("\"", value, "\"");
return value;
}
std::string CSVStackFile::escapeQuote(std::string const& value)
{
std::ostringstream rv;
rv << '"';
for(char c: value)
{
if(c == '"')
rv << "\"\"";
else
rv << c;
}
rv << '"';
return rv.str();
}
void CSVStackFile::setValueForKey(std::string const& key, std::string const& value)
{
m_currentRow[key] = value;
}
void CSVStackFile::setValueForKey(std::string const& key, double const& value)
{
if (value > 1.0)
{
std::ostringstream ss;
ss << std::fixed << std::setprecision(2) << value;
ss << value;
setValueForKey(key, ss.str());
}
else
setValueForKey(key, boost::lexical_cast<std::string>(value));
}
}
}
<|endoftext|> |
<commit_before>/*
* $Id: XMReceiverMediaPatch.cpp,v 1.36 2008/10/11 17:57:02 hfriederich Exp $
*
* Copyright (c) 2005-2007 XMeeting Project ("http://xmeeting.sf.net").
* All rights reserved.
* Copyright (c) 2005-2007 Hannes Friederich. All rights reserved.
*/
#include "XMReceiverMediaPatch.h"
#include <opal/mediastrm.h>
#include <opal/mediacmd.h>
#include <opal/connection.h>
#include <opal/call.h>
#include "XMMediaFormats.h"
#include "XMMediaStream.h"
#include "XMCallbackBridge.h"
#include "XMAudioTester.h"
#define XM_PACKET_POOL_GRANULARITY 8
#define XM_FRAME_BUFFER_SIZE 352*288*4
#define XM_RTP_DATA_SIZE 2000
XMReceiverMediaPatch::XMReceiverMediaPatch(OpalMediaStream & src)
: OpalMediaPatch(src),
packetReassembler(NULL)
{
}
XMReceiverMediaPatch::~XMReceiverMediaPatch()
{
}
void XMReceiverMediaPatch::Start()
{
// quit any running audio test if needed
XMAudioTester::Stop();
OpalMediaPatch::Start();
}
void XMReceiverMediaPatch::SetCommandNotifier(const PNotifier & notifier, bool fromSink)
{
commandNotifier = notifier;
OpalMediaPatch::SetCommandNotifier(notifier, fromSink);
}
void XMReceiverMediaPatch::Main()
{
///////////////////////////////////////////////////////////////////////////////////////////////
// The receiving algorithm tries to achieve best-possible data integrity and builds upon
// the following assumptions:
//
// 1) The chance for packets actually being lost/dropped is very small
// 2) The chance of packets being delayed across timestamp boundaries is much smaller than
// the chance of packets being reordered within the same timestamp (the same video frame)
//
// First, the frames will be read and put into a sorted linked list with ascending sequence
// numbers. If a packet group is complete, the packet payloads are put together and the
// resulting frame is sent to the XMMediaReceiver class for decompression and display.
// A packet group is considered to be complete IF
//
// a) The first packet has the next ascending sequence number to the sequence number of the
// last packet of the previous packet group or the packet contains the beginning of a
// coded frame (picture start codes in H.261 / H.263) AND
// b) The sequence numbers of the packets in the list are ascending with no sequence number
// missing AND
// c) The last packet has the marker bit set
//
// This algorithm makes it possible to process packets of a packet group even if they arrive
// after the last packet of the packet group with the marker bit set. This works well if
// assumptions 1) and 2) are true.
//
// If a packet group is incomplete and the first packet of the next packet group arrives
// (indicated by a different timestamp), the incomplete packet group is either dropped
// or processed, depending on the codec being used. If the incomplete packet group is
// processed, the processing happens delayed since the first packet of the next packet
// group arrived, leading to inconstant display intervals. As long as assumption 1)
// is met, this is not a big drawback.
//
// If either packets are missing or the decompression of the frame fails, an
// fast update request is being sent to the remote party.
///////////////////////////////////////////////////////////////////////////////////////////////
// Allocating a pool of XMRTPPacket instances to reduce
// buffer allocation overhead.
// The pool size increases in steps of 8 packets with an initial size of 8 packets.
// These 8 packets are allocated initially.
// The packets 9-xx are allocated on demand
unsigned allocatedPackets = XM_PACKET_POOL_GRANULARITY;
XMRTPPacket **packets = (XMRTPPacket **)malloc(allocatedPackets * sizeof(XMRTPPacket *));
unsigned packetIndex = 0;
for (unsigned i = 0; i < allocatedPackets; i++) {
packets[i] = new XMRTPPacket(XM_RTP_DATA_SIZE);
}
// make sure the RTP session does NOT ignore out of order packets
OpalRTPMediaStream & rtpStream = (OpalRTPMediaStream &)source;
rtpStream.GetRtpSession().SetIgnoreOutOfOrderPackets(false);
BYTE *frameBuffer = (BYTE *)malloc(sizeof(BYTE) * XM_FRAME_BUFFER_SIZE);
// Read the first packet
bool firstReadSuccesful = source.ReadPacket(*(packets[0]));
// Access the media format
const OpalMediaFormat & mediaFormat = source.GetMediaFormat();
if (firstReadSuccesful == true) {
// Tell the media receiver to prepare processing packets
XMCodecIdentifier codecIdentifier = _XMGetMediaFormatCodec(mediaFormat);
unsigned sessionID = 2;
RTP_DataFrame::PayloadTypes payloadType = packets[0]->GetPayloadType();
// initialize the packet processing variables
DWORD currentTimestamp = packets[0]->GetTimestamp();
WORD firstSeqNrOfPacketGroup = 0;
XMRTPPacket *firstPacketOfPacketGroup = NULL;
XMRTPPacket *lastPacketOfPacketGroup = NULL;
switch (codecIdentifier) {
case XMCodecIdentifier_H261:
packetReassembler = new XMH261RTPPacketReassembler();
break;
case XMCodecIdentifier_H263:
if (_XMGetIsRFC2429(mediaFormat) || mediaFormat == XM_MEDIA_FORMAT_H263PLUS) {
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
} else {
int result = _XMDetermineH263PacketizationScheme(packets[0]->GetPayloadPtr(), packets[0]->GetPayloadSize());
if (result == 0) {
// cannot determine. Last hope is to look at the payload code
if (payloadType == RTP_DataFrame::H263) {
cout << "Receiving RFC2190" << endl;
packetReassembler = new XMH263RTPPacketReassembler();
} else {
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
}
} else if (result == 1) {
cout << "Receiving RFC2190" << endl;
packetReassembler = new XMH263RTPPacketReassembler();
} else {
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
}
}
break;
case XMCodecIdentifier_H264:
packetReassembler = new XMH264RTPPacketReassembler();
break;
default:
break;
}
_XMStartMediaReceiving(sessionID, codecIdentifier);
unsigned decodingFailures = 0; // tracks the # of successive failed frames
// loop to receive packets and process them
do {
inUse.StartRead();
bool processingSuccessful = true;
unsigned numberOfPacketsToRelease = 0;
XMRTPPacket *packet = packets[packetIndex];
packet->next = NULL;
packet->prev = NULL;
// processing the packet
DWORD timestamp = packet->GetTimestamp();
WORD sequenceNumber = packet->GetSequenceNumber();
// take into account that the timestamp might wrap around
if (timestamp < currentTimestamp && (currentTimestamp - timestamp) > (0x01 << 31)) {
// This packet group is already processed
// By changing the sequenceNumber parameter,
// the expected beginning of the current packet group
// can be adjusted
if (firstSeqNrOfPacketGroup <= sequenceNumber) {
firstSeqNrOfPacketGroup = sequenceNumber + 1;
}
} else {
// also take into account that the timestamp might wrap around
if (timestamp > currentTimestamp || (timestamp < currentTimestamp && (currentTimestamp - timestamp) > (0x01 << 31))) {
if (firstPacketOfPacketGroup != NULL) {
// Try to process the old packet although not complete
bool result = true;
PINDEX frameBufferSize = 0;
result = packetReassembler->CopyIncompletePacketsIntoFrameBuffer(firstPacketOfPacketGroup, frameBuffer, &frameBufferSize);
if (result == true) {
_XMProcessFrame(GetSource().GetConnection().GetCall().GetToken(), sessionID, frameBuffer, frameBufferSize);
}
firstSeqNrOfPacketGroup = lastPacketOfPacketGroup->GetSequenceNumber() + 1;
firstPacketOfPacketGroup = NULL;
lastPacketOfPacketGroup = NULL;
processingSuccessful = false;
PTRACE(1, "XMeetingReceiverMediaPatch\tIncomplete old packet group");
// There are (packetIndex + 1) packets in the buffer, but only the last one
// ist still needed
numberOfPacketsToRelease = packetIndex;
}
currentTimestamp = timestamp;
}
if (lastPacketOfPacketGroup != NULL) {
XMRTPPacket *previousPacket = lastPacketOfPacketGroup;
do {
WORD previousSequenceNumber = previousPacket->GetSequenceNumber();
// take into account that the sequence number might wrap around
if (sequenceNumber > previousSequenceNumber ||
(sequenceNumber < previousSequenceNumber && (previousSequenceNumber - sequenceNumber) > (0x01 << 15))) {
// ordering is correct, insert at this point
packet->next = previousPacket->next;
previousPacket->next = packet;
packet->prev = previousPacket;
if (previousPacket == lastPacketOfPacketGroup) {
lastPacketOfPacketGroup = packet;
}
break;
} else if (sequenceNumber == previousSequenceNumber) {
break;
}
if (previousPacket == firstPacketOfPacketGroup) {
// inserting this packet at the beginning of
// the packet group
packet->next = previousPacket;
previousPacket->prev = packet;
firstPacketOfPacketGroup = packet;
break;
}
previousPacket = previousPacket->prev;
} while (true);
} else {
firstPacketOfPacketGroup = packet;
lastPacketOfPacketGroup = packet;
}
}
/////////////////////////////////////////////////////////
// checking whether the packet group is complete or not
/////////////////////////////////////////////////////////
bool packetGroupIsComplete = false;
WORD expectedSequenceNumber = firstSeqNrOfPacketGroup;
XMRTPPacket *thePacket = firstPacketOfPacketGroup;
bool isFirstPacket = false;
if (expectedSequenceNumber == thePacket->GetSequenceNumber()) {
isFirstPacket = true;
} else {
// the sequence number is not the expected one. Try to analyze
// the bitstream to determine whether this is the first packet
// of a packet group or not
isFirstPacket = packetReassembler->IsFirstPacketOfFrame(thePacket);
}
if (isFirstPacket == true) {
expectedSequenceNumber = thePacket->GetSequenceNumber();
do {
if (expectedSequenceNumber != thePacket->GetSequenceNumber()) {
break;
}
expectedSequenceNumber++;
if (thePacket->next == NULL) {
// no more packets in the packet group.
// If the marker bit is set, the group is complete
if (thePacket->GetMarker() == true) {
packetGroupIsComplete = true;
}
break;
}
thePacket = thePacket->next;
} while (true);
}
/////////////////////////////////////////////////////
// If the packet group is complete, copy the packets
// into a frame and send it to the XMMediaReceiver
// system.
/////////////////////////////////////////////////////
if (packetGroupIsComplete == true) {
bool result = true;
PINDEX frameBufferSize = 0;
result = packetReassembler->CopyPacketsIntoFrameBuffer(firstPacketOfPacketGroup, frameBuffer, &frameBufferSize);
if (result == true) {
result = _XMProcessFrame(GetSource().GetConnection().GetCall().GetToken(), sessionID, frameBuffer, frameBufferSize);
if (result == false) {
PTRACE(1, "XMeetingReceiverMediaPatch\tDecompression of the frame failed");
processingSuccessful = false;
}
} else {
PTRACE(1, "XMeetingReceiverMediaPatch\tCould not copy packets into frame buffer");
processingSuccessful = false;
}
firstSeqNrOfPacketGroup = lastPacketOfPacketGroup->GetSequenceNumber() + 1;
firstPacketOfPacketGroup = NULL;
lastPacketOfPacketGroup = NULL;
// Release all packets in the pool
numberOfPacketsToRelease = packetIndex + 1;
}
if (processingSuccessful == false) {
// avoid flooding the remote party with update commands
decodingFailures++;
if (decodingFailures < 3 || (decodingFailures % 10) == 0) {
IssueVideoUpdatePictureCommand();
}
processingSuccessful = true;
} else {
decodingFailures = 0; // reset the failure counter
}
// Of not all packets can be released, the remaining packets are
// put at the beginning of the packet pool.
if (numberOfPacketsToRelease != 0) {
for (unsigned i = 0; i < (packetIndex + 1 - numberOfPacketsToRelease); i++) {
// swapping the remaining frames
XMRTPPacket *packet = packets[i];
packets[i] = packets[i + numberOfPacketsToRelease];
packets[i + numberOfPacketsToRelease] = packet;
}
packetIndex = packetIndex + 1 - numberOfPacketsToRelease;
} else {
// increment the packetIndex, allocate a new XMRTPPacket if needed.
// Also increase the size of the packet pool if required
packetIndex++;
if (packetIndex == allocatedPackets) {
if (allocatedPackets % XM_PACKET_POOL_GRANULARITY == 0) {
packets = (XMRTPPacket **)realloc(packets, (allocatedPackets + XM_PACKET_POOL_GRANULARITY) * sizeof(XMRTPPacket *));
}
packets[packetIndex] = new XMRTPPacket(XM_RTP_DATA_SIZE);
allocatedPackets++;
}
}
// check for loop termination conditions
PINDEX len = sinks.GetSize();
inUse.EndRead();
if (len == 0) {
break;
}
} while (source.ReadPacket(*(packets[packetIndex])) == true);
// End the media processing
_XMStopMediaReceiving(sessionID);
}
// release the used RTP_DataFrames
for (unsigned i = 0; i < allocatedPackets; i++) {
XMRTPPacket *dataFrame = packets[i];
delete dataFrame;
}
free(packets);
free(frameBuffer);
if (packetReassembler != NULL) {
free(packetReassembler);
}
}
void XMReceiverMediaPatch::IssueVideoUpdatePictureCommand()
{
OpalVideoUpdatePicture command = OpalVideoUpdatePicture(-1, -1, -1);
if (!commandNotifier.IsNULL()) {
commandNotifier(command, 0);
}
}
<commit_msg>- MINOR: Really throttle rate of video uptate picture commands sent. Important to not flood the remote party with too many commands. When using SIP, this will create a separate transport each time, including a PSemaphore instance. If the video stream isn't decodable, we'll soon run out of semaphores / file descriptors...<commit_after>/*
* $Id: XMReceiverMediaPatch.cpp,v 1.37 2008/10/14 21:35:10 hfriederich Exp $
*
* Copyright (c) 2005-2007 XMeeting Project ("http://xmeeting.sf.net").
* All rights reserved.
* Copyright (c) 2005-2007 Hannes Friederich. All rights reserved.
*/
#include "XMReceiverMediaPatch.h"
#include <opal/mediastrm.h>
#include <opal/mediacmd.h>
#include <opal/connection.h>
#include <opal/call.h>
#include "XMMediaFormats.h"
#include "XMMediaStream.h"
#include "XMCallbackBridge.h"
#include "XMAudioTester.h"
#define XM_PACKET_POOL_GRANULARITY 8
#define XM_FRAME_BUFFER_SIZE 352*288*4
#define XM_RTP_DATA_SIZE 2000
XMReceiverMediaPatch::XMReceiverMediaPatch(OpalMediaStream & src)
: OpalMediaPatch(src),
packetReassembler(NULL)
{
}
XMReceiverMediaPatch::~XMReceiverMediaPatch()
{
}
void XMReceiverMediaPatch::Start()
{
// quit any running audio test if needed
XMAudioTester::Stop();
OpalMediaPatch::Start();
}
void XMReceiverMediaPatch::SetCommandNotifier(const PNotifier & notifier, bool fromSink)
{
commandNotifier = notifier;
OpalMediaPatch::SetCommandNotifier(notifier, fromSink);
}
void XMReceiverMediaPatch::Main()
{
///////////////////////////////////////////////////////////////////////////////////////////////
// The receiving algorithm tries to achieve best-possible data integrity and builds upon
// the following assumptions:
//
// 1) The chance for packets actually being lost/dropped is very small
// 2) The chance of packets being delayed across timestamp boundaries is much smaller than
// the chance of packets being reordered within the same timestamp (the same video frame)
//
// First, the frames will be read and put into a sorted linked list with ascending sequence
// numbers. If a packet group is complete, the packet payloads are put together and the
// resulting frame is sent to the XMMediaReceiver class for decompression and display.
// A packet group is considered to be complete IF
//
// a) The first packet has the next ascending sequence number to the sequence number of the
// last packet of the previous packet group or the packet contains the beginning of a
// coded frame (picture start codes in H.261 / H.263) AND
// b) The sequence numbers of the packets in the list are ascending with no sequence number
// missing AND
// c) The last packet has the marker bit set
//
// This algorithm makes it possible to process packets of a packet group even if they arrive
// after the last packet of the packet group with the marker bit set. This works well if
// assumptions 1) and 2) are true.
//
// If a packet group is incomplete and the first packet of the next packet group arrives
// (indicated by a different timestamp), the incomplete packet group is either dropped
// or processed, depending on the codec being used. If the incomplete packet group is
// processed, the processing happens delayed since the first packet of the next packet
// group arrived, leading to inconstant display intervals. As long as assumption 1)
// is met, this is not a big drawback.
//
// If either packets are missing or the decompression of the frame fails, an
// fast update request is being sent to the remote party.
///////////////////////////////////////////////////////////////////////////////////////////////
// Allocating a pool of XMRTPPacket instances to reduce
// buffer allocation overhead.
// The pool size increases in steps of 8 packets with an initial size of 8 packets.
// These 8 packets are allocated initially.
// The packets 9-xx are allocated on demand
unsigned allocatedPackets = XM_PACKET_POOL_GRANULARITY;
XMRTPPacket **packets = (XMRTPPacket **)malloc(allocatedPackets * sizeof(XMRTPPacket *));
unsigned packetIndex = 0;
for (unsigned i = 0; i < allocatedPackets; i++) {
packets[i] = new XMRTPPacket(XM_RTP_DATA_SIZE);
}
// make sure the RTP session does NOT ignore out of order packets
OpalRTPMediaStream & rtpStream = (OpalRTPMediaStream &)source;
rtpStream.GetRtpSession().SetIgnoreOutOfOrderPackets(false);
BYTE *frameBuffer = (BYTE *)malloc(sizeof(BYTE) * XM_FRAME_BUFFER_SIZE);
// Read the first packet
bool firstReadSuccesful = source.ReadPacket(*(packets[0]));
// Access the media format
const OpalMediaFormat & mediaFormat = source.GetMediaFormat();
if (firstReadSuccesful == true) {
// Tell the media receiver to prepare processing packets
XMCodecIdentifier codecIdentifier = _XMGetMediaFormatCodec(mediaFormat);
unsigned sessionID = 2;
RTP_DataFrame::PayloadTypes payloadType = packets[0]->GetPayloadType();
// initialize the packet processing variables
DWORD currentTimestamp = packets[0]->GetTimestamp();
WORD firstSeqNrOfPacketGroup = 0;
XMRTPPacket *firstPacketOfPacketGroup = NULL;
XMRTPPacket *lastPacketOfPacketGroup = NULL;
switch (codecIdentifier) {
case XMCodecIdentifier_H261:
packetReassembler = new XMH261RTPPacketReassembler();
break;
case XMCodecIdentifier_H263:
if (_XMGetIsRFC2429(mediaFormat) || mediaFormat == XM_MEDIA_FORMAT_H263PLUS) {
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
} else {
int result = _XMDetermineH263PacketizationScheme(packets[0]->GetPayloadPtr(), packets[0]->GetPayloadSize());
if (result == 0) {
// cannot determine. Last hope is to look at the payload code
if (payloadType == RTP_DataFrame::H263) {
cout << "Receiving RFC2190" << endl;
packetReassembler = new XMH263RTPPacketReassembler();
} else {
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
}
} else if (result == 1) {
cout << "Receiving RFC2190" << endl;
packetReassembler = new XMH263RTPPacketReassembler();
} else {
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
}
}
break;
case XMCodecIdentifier_H264:
packetReassembler = new XMH264RTPPacketReassembler();
break;
default:
break;
}
_XMStartMediaReceiving(sessionID, codecIdentifier);
unsigned decodingFailures = 0; // tracks the # of successive failed frames
// loop to receive packets and process them
do {
inUse.StartRead();
bool completePacketGroup = true;
bool decodingSuccessful = true;
unsigned numberOfPacketsToRelease = 0;
XMRTPPacket *packet = packets[packetIndex];
packet->next = NULL;
packet->prev = NULL;
// processing the packet
DWORD timestamp = packet->GetTimestamp();
WORD sequenceNumber = packet->GetSequenceNumber();
// take into account that the timestamp might wrap around
if (timestamp < currentTimestamp && (currentTimestamp - timestamp) > (0x01 << 31)) {
// This packet group is already processed
// By changing the sequenceNumber parameter,
// the expected beginning of the current packet group
// can be adjusted
if (firstSeqNrOfPacketGroup <= sequenceNumber) {
firstSeqNrOfPacketGroup = sequenceNumber + 1;
}
} else {
// also take into account that the timestamp might wrap around
if (timestamp > currentTimestamp || (timestamp < currentTimestamp && (currentTimestamp - timestamp) > (0x01 << 31))) {
if (firstPacketOfPacketGroup != NULL) {
// Try to process the old packet although not complete
bool result = true;
PINDEX frameBufferSize = 0;
result = packetReassembler->CopyIncompletePacketsIntoFrameBuffer(firstPacketOfPacketGroup, frameBuffer, &frameBufferSize);
if (result == true) {
_XMProcessFrame(GetSource().GetConnection().GetCall().GetToken(), sessionID, frameBuffer, frameBufferSize);
}
firstSeqNrOfPacketGroup = lastPacketOfPacketGroup->GetSequenceNumber() + 1;
firstPacketOfPacketGroup = NULL;
lastPacketOfPacketGroup = NULL;
completePacketGroup = false;
PTRACE(1, "XMeetingReceiverMediaPatch\tIncomplete old packet group");
// There are (packetIndex + 1) packets in the buffer, but only the last one
// ist still needed
numberOfPacketsToRelease = packetIndex;
}
currentTimestamp = timestamp;
}
if (lastPacketOfPacketGroup != NULL) {
XMRTPPacket *previousPacket = lastPacketOfPacketGroup;
do {
WORD previousSequenceNumber = previousPacket->GetSequenceNumber();
// take into account that the sequence number might wrap around
if (sequenceNumber > previousSequenceNumber ||
(sequenceNumber < previousSequenceNumber && (previousSequenceNumber - sequenceNumber) > (0x01 << 15))) {
// ordering is correct, insert at this point
packet->next = previousPacket->next;
previousPacket->next = packet;
packet->prev = previousPacket;
if (previousPacket == lastPacketOfPacketGroup) {
lastPacketOfPacketGroup = packet;
}
break;
} else if (sequenceNumber == previousSequenceNumber) {
break;
}
if (previousPacket == firstPacketOfPacketGroup) {
// inserting this packet at the beginning of
// the packet group
packet->next = previousPacket;
previousPacket->prev = packet;
firstPacketOfPacketGroup = packet;
break;
}
previousPacket = previousPacket->prev;
} while (true);
} else {
firstPacketOfPacketGroup = packet;
lastPacketOfPacketGroup = packet;
}
}
/////////////////////////////////////////////////////////
// checking whether the packet group is complete or not
/////////////////////////////////////////////////////////
bool packetGroupIsComplete = false;
WORD expectedSequenceNumber = firstSeqNrOfPacketGroup;
XMRTPPacket *thePacket = firstPacketOfPacketGroup;
bool isFirstPacket = false;
if (expectedSequenceNumber == thePacket->GetSequenceNumber()) {
isFirstPacket = true;
} else {
// the sequence number is not the expected one. Try to analyze
// the bitstream to determine whether this is the first packet
// of a packet group or not
isFirstPacket = packetReassembler->IsFirstPacketOfFrame(thePacket);
}
if (isFirstPacket == true) {
expectedSequenceNumber = thePacket->GetSequenceNumber();
do {
if (expectedSequenceNumber != thePacket->GetSequenceNumber()) {
break;
}
expectedSequenceNumber++;
if (thePacket->next == NULL) {
// no more packets in the packet group.
// If the marker bit is set, the group is complete
if (thePacket->GetMarker() == true) {
packetGroupIsComplete = true;
}
break;
}
thePacket = thePacket->next;
} while (true);
}
/////////////////////////////////////////////////////
// If the packet group is complete, copy the packets
// into a frame and send it to the XMMediaReceiver
// system.
/////////////////////////////////////////////////////
if (packetGroupIsComplete == true) {
bool result = true;
PINDEX frameBufferSize = 0;
result = packetReassembler->CopyPacketsIntoFrameBuffer(firstPacketOfPacketGroup, frameBuffer, &frameBufferSize);
if (result == true) {
result = _XMProcessFrame(GetSource().GetConnection().GetCall().GetToken(), sessionID, frameBuffer, frameBufferSize);
if (result == false) {
PTRACE(1, "XMeetingReceiverMediaPatch\tDecompression of the frame failed");
decodingSuccessful = false;
decodingFailures++;
} else {
decodingFailures = 0;
}
} else {
PTRACE(1, "XMeetingReceiverMediaPatch\tCould not copy packets into frame buffer");
decodingSuccessful = false;
}
firstSeqNrOfPacketGroup = lastPacketOfPacketGroup->GetSequenceNumber() + 1;
firstPacketOfPacketGroup = NULL;
lastPacketOfPacketGroup = NULL;
// Release all packets in the pool
numberOfPacketsToRelease = packetIndex + 1;
}
if (completePacketGroup == false) {
IssueVideoUpdatePictureCommand();
} else if (decodingSuccessful == false) {
// avoid flooding the remote party with update commands
if (decodingFailures < 3 || (decodingFailures % 30) == 0) {
IssueVideoUpdatePictureCommand();
}
}
// If not all packets can be released, the remaining packets are
// put at the beginning of the packet pool.
if (numberOfPacketsToRelease != 0) {
for (unsigned i = 0; i < (packetIndex + 1 - numberOfPacketsToRelease); i++) {
// swapping the remaining frames
XMRTPPacket *packet = packets[i];
packets[i] = packets[i + numberOfPacketsToRelease];
packets[i + numberOfPacketsToRelease] = packet;
}
packetIndex = packetIndex + 1 - numberOfPacketsToRelease;
} else {
// increment the packetIndex, allocate a new XMRTPPacket if needed.
// Also increase the size of the packet pool if required
packetIndex++;
if (packetIndex == allocatedPackets) {
if (allocatedPackets % XM_PACKET_POOL_GRANULARITY == 0) {
packets = (XMRTPPacket **)realloc(packets, (allocatedPackets + XM_PACKET_POOL_GRANULARITY) * sizeof(XMRTPPacket *));
}
packets[packetIndex] = new XMRTPPacket(XM_RTP_DATA_SIZE);
allocatedPackets++;
}
}
// check for loop termination conditions
PINDEX len = sinks.GetSize();
inUse.EndRead();
if (len == 0) {
break;
}
} while (source.ReadPacket(*(packets[packetIndex])) == true);
// End the media processing
_XMStopMediaReceiving(sessionID);
}
// release the used RTP_DataFrames
for (unsigned i = 0; i < allocatedPackets; i++) {
XMRTPPacket *dataFrame = packets[i];
delete dataFrame;
}
free(packets);
free(frameBuffer);
if (packetReassembler != NULL) {
free(packetReassembler);
}
}
void XMReceiverMediaPatch::IssueVideoUpdatePictureCommand()
{
OpalVideoUpdatePicture command = OpalVideoUpdatePicture(-1, -1, -1);
if (!commandNotifier.IsNULL()) {
commandNotifier(command, 0);
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2010-2015 Joshua Boyce
// See the file COPYING for copying permission.
#pragma once
#include <windows.h>
#include <setupapi.h>
#include <wincrypt.h>
#include <hadesmem/config.hpp>
#include <hadesmem/detail/assert.hpp>
#include <hadesmem/detail/trace.hpp>
#include <hadesmem/error.hpp>
namespace hadesmem
{
namespace detail
{
template <typename Policy> class SmartHandleImpl
{
public:
using HandleT = typename Policy::HandleT;
HADESMEM_DETAIL_CONSTEXPR SmartHandleImpl() HADESMEM_DETAIL_NOEXCEPT
{
}
explicit HADESMEM_DETAIL_CONSTEXPR
SmartHandleImpl(HandleT handle) HADESMEM_DETAIL_NOEXCEPT : handle_{handle}
{
}
SmartHandleImpl(SmartHandleImpl const& other) = delete;
SmartHandleImpl& operator=(SmartHandleImpl const& other) = delete;
SmartHandleImpl& operator=(HandleT handle) HADESMEM_DETAIL_NOEXCEPT
{
CleanupUnchecked();
handle_ = handle;
return *this;
}
SmartHandleImpl(SmartHandleImpl&& other) HADESMEM_DETAIL_NOEXCEPT
: handle_{other.handle_}
{
other.handle_ = GetInvalid();
}
SmartHandleImpl& operator=(SmartHandleImpl&& other) HADESMEM_DETAIL_NOEXCEPT
{
CleanupUnchecked();
handle_ = other.handle_;
other.handle_ = other.GetInvalid();
return *this;
}
~SmartHandleImpl()
{
CleanupUnchecked();
}
HandleT GetHandle() const HADESMEM_DETAIL_NOEXCEPT
{
return handle_;
}
HandleT GetInvalid() const HADESMEM_DETAIL_NOEXCEPT
{
return Policy::GetInvalid();
}
bool IsValid() const HADESMEM_DETAIL_NOEXCEPT
{
return GetHandle() != GetInvalid();
}
void Cleanup()
{
if (handle_ == GetInvalid())
{
return;
}
if (!Policy::Cleanup(handle_))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(
Error{} << ErrorString{"SmartHandle cleanup failed."}
<< ErrorCodeWinLast{last_error});
}
handle_ = GetInvalid();
}
// WARNING: This detaches the handle from the smart handle. The
// caller is responsible for managing the lifetime of the handle
// after this point.
HandleT Detach()
{
HandleT const handle = handle_;
handle_ = GetInvalid();
return handle;
}
private:
void CleanupUnchecked() HADESMEM_DETAIL_NOEXCEPT
{
try
{
Cleanup();
}
catch (...)
{
// WARNING: Handle is leaked if 'Cleanup' fails.
HADESMEM_DETAIL_TRACE_A(
boost::current_exception_diagnostic_information().c_str());
HADESMEM_DETAIL_ASSERT(false);
handle_ = GetInvalid();
}
}
HandleT handle_{GetInvalid()};
};
struct HandlePolicy
{
using HandleT = HANDLE;
static HADESMEM_DETAIL_CONSTEXPR HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::CloseHandle(handle) != 0;
}
};
using SmartHandle = SmartHandleImpl<HandlePolicy>;
struct SnapPolicy
{
using HandleT = HANDLE;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return INVALID_HANDLE_VALUE;
}
static bool Cleanup(HandleT handle)
{
return ::CloseHandle(handle) != 0;
}
};
using SmartSnapHandle = SmartHandleImpl<SnapPolicy>;
struct LibraryPolicy
{
using HandleT = HMODULE;
static HADESMEM_DETAIL_CONSTEXPR HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::FreeLibrary(handle) != 0;
}
};
using SmartModuleHandle = SmartHandleImpl<LibraryPolicy>;
struct FilePolicy
{
using HandleT = HANDLE;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return INVALID_HANDLE_VALUE;
}
static bool Cleanup(HandleT handle)
{
return ::CloseHandle(handle) != 0;
}
};
using SmartFileHandle = SmartHandleImpl<FilePolicy>;
struct FindPolicy
{
using HandleT = HANDLE;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return INVALID_HANDLE_VALUE;
}
static bool Cleanup(HandleT handle)
{
return ::FindClose(handle) != 0;
}
};
using SmartFindHandle = SmartHandleImpl<FindPolicy>;
struct ComPolicy
{
using HandleT = IUnknown*;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
handle->Release();
return true;
}
};
using SmartComHandle = SmartHandleImpl<ComPolicy>;
struct GdiObjectPolicy
{
using HandleT = HGDIOBJ;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::DeleteObject(handle) != 0;
}
};
using SmartGdiObjectHandle = SmartHandleImpl<GdiObjectPolicy>;
struct DeleteDcPolicy
{
using HandleT = HDC;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::DeleteDC(handle) != 0;
}
};
using SmartDeleteDcHandle = SmartHandleImpl<DeleteDcPolicy>;
struct VectoredExceptionHandlerPolicy
{
using HandleT = PVOID;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::RemoveVectoredExceptionHandler(handle) != 0;
}
};
using SmartRemoveVectoredExceptionHandler =
SmartHandleImpl<VectoredExceptionHandlerPolicy>;
struct CryptContextPolicy
{
using HandleT = HCRYPTPROV;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return 0;
}
static bool Cleanup(HandleT handle)
{
return !!::CryptReleaseContext(handle, 0);
}
};
using SmartCryptContextHandle = SmartHandleImpl<CryptContextPolicy>;
struct DestroyHashPolicy
{
using HandleT = HCRYPTPROV;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return 0;
}
static bool Cleanup(HandleT handle)
{
return !!::CryptDestroyHash(handle);
}
};
using SmartCryptHashHandle = SmartHandleImpl<DestroyHashPolicy>;
struct UnmapViewOfFilePolicy
{
using HandleT = LPVOID;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return 0;
}
static bool Cleanup(HandleT handle)
{
return !!::UnmapViewOfFile(handle);
}
};
using SmartMappedFileHandle = SmartHandleImpl<UnmapViewOfFilePolicy>;
struct SetupDiDestroyDeviceInfoListPolicy
{
using HandleT = HDEVINFO;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return INVALID_HANDLE_VALUE;
}
static bool Cleanup(HandleT handle)
{
return !!::SetupDiDestroyDeviceInfoList(handle);
}
};
using SmartDeviceInfoListHandle =
SmartHandleImpl<SetupDiDestroyDeviceInfoListPolicy>;
struct RegKeyPolicy
{
using HandleT = HKEY;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::RegCloseKey(handle) == ERROR_SUCCESS;
}
};
using SmartRegKeyHandle = SmartHandleImpl<RegKeyPolicy>;
struct VirtualMemPolicy
{
using HandleT = PVOID;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return !!::VirtualFree(handle, 0, MEM_RELEASE);
}
};
using SmartVirtualMemHandle = SmartHandleImpl<VirtualMemPolicy>;
}
}
<commit_msg>[SmartHandle] Add event log handle type.<commit_after>// Copyright (C) 2010-2015 Joshua Boyce
// See the file COPYING for copying permission.
#pragma once
#include <windows.h>
#include <setupapi.h>
#include <wincrypt.h>
#include <hadesmem/config.hpp>
#include <hadesmem/detail/assert.hpp>
#include <hadesmem/detail/trace.hpp>
#include <hadesmem/error.hpp>
namespace hadesmem
{
namespace detail
{
template <typename Policy> class SmartHandleImpl
{
public:
using HandleT = typename Policy::HandleT;
HADESMEM_DETAIL_CONSTEXPR SmartHandleImpl() HADESMEM_DETAIL_NOEXCEPT
{
}
explicit HADESMEM_DETAIL_CONSTEXPR
SmartHandleImpl(HandleT handle) HADESMEM_DETAIL_NOEXCEPT : handle_{handle}
{
}
SmartHandleImpl(SmartHandleImpl const& other) = delete;
SmartHandleImpl& operator=(SmartHandleImpl const& other) = delete;
SmartHandleImpl& operator=(HandleT handle) HADESMEM_DETAIL_NOEXCEPT
{
CleanupUnchecked();
handle_ = handle;
return *this;
}
SmartHandleImpl(SmartHandleImpl&& other) HADESMEM_DETAIL_NOEXCEPT
: handle_{other.handle_}
{
other.handle_ = GetInvalid();
}
SmartHandleImpl& operator=(SmartHandleImpl&& other) HADESMEM_DETAIL_NOEXCEPT
{
CleanupUnchecked();
handle_ = other.handle_;
other.handle_ = other.GetInvalid();
return *this;
}
~SmartHandleImpl()
{
CleanupUnchecked();
}
HandleT GetHandle() const HADESMEM_DETAIL_NOEXCEPT
{
return handle_;
}
HandleT GetInvalid() const HADESMEM_DETAIL_NOEXCEPT
{
return Policy::GetInvalid();
}
bool IsValid() const HADESMEM_DETAIL_NOEXCEPT
{
return GetHandle() != GetInvalid();
}
void Cleanup()
{
if (handle_ == GetInvalid())
{
return;
}
if (!Policy::Cleanup(handle_))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(
Error{} << ErrorString{"SmartHandle cleanup failed."}
<< ErrorCodeWinLast{last_error});
}
handle_ = GetInvalid();
}
// WARNING: This detaches the handle from the smart handle. The
// caller is responsible for managing the lifetime of the handle
// after this point.
HandleT Detach()
{
HandleT const handle = handle_;
handle_ = GetInvalid();
return handle;
}
private:
void CleanupUnchecked() HADESMEM_DETAIL_NOEXCEPT
{
try
{
Cleanup();
}
catch (...)
{
// WARNING: Handle is leaked if 'Cleanup' fails.
HADESMEM_DETAIL_TRACE_A(
boost::current_exception_diagnostic_information().c_str());
HADESMEM_DETAIL_ASSERT(false);
handle_ = GetInvalid();
}
}
HandleT handle_{GetInvalid()};
};
struct HandlePolicy
{
using HandleT = HANDLE;
static HADESMEM_DETAIL_CONSTEXPR HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::CloseHandle(handle) != 0;
}
};
using SmartHandle = SmartHandleImpl<HandlePolicy>;
struct SnapPolicy
{
using HandleT = HANDLE;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return INVALID_HANDLE_VALUE;
}
static bool Cleanup(HandleT handle)
{
return ::CloseHandle(handle) != 0;
}
};
using SmartSnapHandle = SmartHandleImpl<SnapPolicy>;
struct LibraryPolicy
{
using HandleT = HMODULE;
static HADESMEM_DETAIL_CONSTEXPR HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::FreeLibrary(handle) != 0;
}
};
using SmartModuleHandle = SmartHandleImpl<LibraryPolicy>;
struct FilePolicy
{
using HandleT = HANDLE;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return INVALID_HANDLE_VALUE;
}
static bool Cleanup(HandleT handle)
{
return ::CloseHandle(handle) != 0;
}
};
using SmartFileHandle = SmartHandleImpl<FilePolicy>;
struct FindPolicy
{
using HandleT = HANDLE;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return INVALID_HANDLE_VALUE;
}
static bool Cleanup(HandleT handle)
{
return ::FindClose(handle) != 0;
}
};
using SmartFindHandle = SmartHandleImpl<FindPolicy>;
struct ComPolicy
{
using HandleT = IUnknown*;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
handle->Release();
return true;
}
};
using SmartComHandle = SmartHandleImpl<ComPolicy>;
struct GdiObjectPolicy
{
using HandleT = HGDIOBJ;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::DeleteObject(handle) != 0;
}
};
using SmartGdiObjectHandle = SmartHandleImpl<GdiObjectPolicy>;
struct DeleteDcPolicy
{
using HandleT = HDC;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::DeleteDC(handle) != 0;
}
};
using SmartDeleteDcHandle = SmartHandleImpl<DeleteDcPolicy>;
struct VectoredExceptionHandlerPolicy
{
using HandleT = PVOID;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::RemoveVectoredExceptionHandler(handle) != 0;
}
};
using SmartRemoveVectoredExceptionHandler =
SmartHandleImpl<VectoredExceptionHandlerPolicy>;
struct CryptContextPolicy
{
using HandleT = HCRYPTPROV;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return 0;
}
static bool Cleanup(HandleT handle)
{
return !!::CryptReleaseContext(handle, 0);
}
};
using SmartCryptContextHandle = SmartHandleImpl<CryptContextPolicy>;
struct DestroyHashPolicy
{
using HandleT = HCRYPTPROV;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return 0;
}
static bool Cleanup(HandleT handle)
{
return !!::CryptDestroyHash(handle);
}
};
using SmartCryptHashHandle = SmartHandleImpl<DestroyHashPolicy>;
struct UnmapViewOfFilePolicy
{
using HandleT = LPVOID;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return 0;
}
static bool Cleanup(HandleT handle)
{
return !!::UnmapViewOfFile(handle);
}
};
using SmartMappedFileHandle = SmartHandleImpl<UnmapViewOfFilePolicy>;
struct SetupDiDestroyDeviceInfoListPolicy
{
using HandleT = HDEVINFO;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return INVALID_HANDLE_VALUE;
}
static bool Cleanup(HandleT handle)
{
return !!::SetupDiDestroyDeviceInfoList(handle);
}
};
using SmartDeviceInfoListHandle =
SmartHandleImpl<SetupDiDestroyDeviceInfoListPolicy>;
struct RegKeyPolicy
{
using HandleT = HKEY;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return ::RegCloseKey(handle) == ERROR_SUCCESS;
}
};
using SmartRegKeyHandle = SmartHandleImpl<RegKeyPolicy>;
struct VirtualMemPolicy
{
using HandleT = PVOID;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return !!::VirtualFree(handle, 0, MEM_RELEASE);
}
};
using SmartVirtualMemHandle = SmartHandleImpl<VirtualMemPolicy>;
struct EventLogPolicy
{
using HandleT = HANDLE;
static HandleT GetInvalid() HADESMEM_DETAIL_NOEXCEPT
{
return nullptr;
}
static bool Cleanup(HandleT handle)
{
return !!::CloseEventLog(handle);
}
};
using SmartEventLogHandle = SmartHandleImpl<EventLogPolicy>;
}
}
<|endoftext|> |
<commit_before>
#include <Windows.h>
//#include "Game.h"
// --------------------------------------------------------
// Entry point for a graphical (non-console) Windows application
// --------------------------------------------------------
int WINAPI WinMain(
HINSTANCE hInstance, // The handle to this app's instance
HINSTANCE hPrevInstance, // A handle to the previous instance of the app (always NULL)
LPSTR lpCmdLine, // Command line params
int nCmdShow) // How the window should be shown (we ignore this)
{
#if defined(DEBUG) | defined(_DEBUG)
// Enable memory leak detection as a quick and dirty
// way of determining if we forgot to clean something up
// - You may want to use something more advanced, like Visual Leak Detector
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
return 0;
/*
// Create the Game object using
// the app handle we got from WinMain
Game dxGame(hInstance);
// Result variable for function calls below
HRESULT hr = S_OK;
// Attempt to create the window for our program, and
// exit early if something failed
hr = dxGame.InitWindow();
if(FAILED(hr)) return hr;
// Attempt to initialize DirectX, and exit
// early if something failed
hr = dxGame.InitDirectX();
if(FAILED(hr)) return hr;
// Begin the message and game loop, and then return
// whatever we get back once the game loop is over
return dxGame.Run();
*/
}
<commit_msg>Commmented out the rest of the code that were not in use.<commit_after>
#include <Windows.h>
//#include "Game.h"
// --------------------------------------------------------
// Entry point for a graphical (non-console) Windows application
// --------------------------------------------------------
int WINAPI WinMain(
HINSTANCE hInstance, // The handle to this app's instance
HINSTANCE hPrevInstance, // A handle to the previous instance of the app (always NULL)
LPSTR lpCmdLine, // Command line params
int nCmdShow) // How the window should be shown (we ignore this)
{
return 0;
/*
#if defined(DEBUG) | defined(_DEBUG)
// Enable memory leak detection as a quick and dirty
// way of determining if we forgot to clean something up
// - You may want to use something more advanced, like Visual Leak Detector
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
// Create the Game object using
// the app handle we got from WinMain
Game dxGame(hInstance);
// Result variable for function calls below
HRESULT hr = S_OK;
// Attempt to create the window for our program, and
// exit early if something failed
hr = dxGame.InitWindow();
if(FAILED(hr)) return hr;
// Attempt to initialize DirectX, and exit
// early if something failed
hr = dxGame.InitDirectX();
if(FAILED(hr)) return hr;
// Begin the message and game loop, and then return
// whatever we get back once the game loop is over
return dxGame.Run();
*/
}
<|endoftext|> |
<commit_before>//===-- ThreadPlanStepOverBreakpoint.cpp ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Stream.h"
using namespace lldb;
using namespace lldb_private;
//----------------------------------------------------------------------
// ThreadPlanStepOverBreakpoint: Single steps over a breakpoint bp_site_sp at
// the pc.
//----------------------------------------------------------------------
ThreadPlanStepOverBreakpoint::ThreadPlanStepOverBreakpoint(Thread &thread)
: ThreadPlan(
ThreadPlan::eKindStepOverBreakpoint, "Step over breakpoint trap",
thread, eVoteNo,
eVoteNoOpinion), // We need to report the run since this happens
// first in the thread plan stack when stepping over
// a breakpoint
m_breakpoint_addr(LLDB_INVALID_ADDRESS),
m_auto_continue(false), m_reenabled_breakpoint_site(false)
{
m_breakpoint_addr = m_thread.GetRegisterContext()->GetPC();
m_breakpoint_site_id =
m_thread.GetProcess()->GetBreakpointSiteList().FindIDByAddress(
m_breakpoint_addr);
}
ThreadPlanStepOverBreakpoint::~ThreadPlanStepOverBreakpoint() {}
void ThreadPlanStepOverBreakpoint::GetDescription(
Stream *s, lldb::DescriptionLevel level) {
s->Printf("Single stepping past breakpoint site %" PRIu64 " at 0x%" PRIx64,
m_breakpoint_site_id, (uint64_t)m_breakpoint_addr);
}
bool ThreadPlanStepOverBreakpoint::ValidatePlan(Stream *error) { return true; }
bool ThreadPlanStepOverBreakpoint::DoPlanExplainsStop(Event *event_ptr) {
StopInfoSP stop_info_sp = GetPrivateStopInfo();
if (stop_info_sp) {
// It's a little surprising that we stop here for a breakpoint hit.
// However, when you single step ONTO a breakpoint we still want to call
// that a breakpoint hit, and trigger the actions, etc. Otherwise you
// would see the
// PC at the breakpoint without having triggered the actions, then you'd
// continue, the PC wouldn't change,
// and you'd see the breakpoint hit, which would be odd. So the lower
// levels fake "step onto breakpoint address" and return that as a
// breakpoint. So our trace step COULD appear as a breakpoint hit if the
// next instruction also contained a breakpoint.
StopReason reason = stop_info_sp->GetStopReason();
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (log)
log->Printf("Step over breakpoint stopped for reason: %s.",
Thread::StopReasonAsCString(reason));
switch (reason) {
case eStopReasonTrace:
case eStopReasonNone:
return true;
case eStopReasonBreakpoint:
{
// It's a little surprising that we stop here for a breakpoint hit.
// However, when you single step ONTO a breakpoint we still want to call
// that a breakpoint hit, and trigger the actions, etc. Otherwise you
// would see the PC at the breakpoint without having triggered the
// actions, then you'd continue, the PC wouldn't change, and you'd see
// the breakpoint hit, which would be odd. So the lower levels fake
// "step onto breakpoint address" and return that as a breakpoint hit.
// So our trace step COULD appear as a breakpoint hit if the next
// instruction also contained a breakpoint. We don't want to handle
// that, since we really don't know what to do with breakpoint hits.
// But make sure we don't set ourselves to auto-continue or we'll wrench
// control away from the plans that can deal with this.
// Be careful, however, as we may have "seen a breakpoint under the PC
// because we stopped without changing the PC, in which case we do want
// to re-claim this stop so we'll try again.
lldb::addr_t pc_addr = m_thread.GetRegisterContext()->GetPC();
if (pc_addr == m_breakpoint_addr) {
if (log)
log->Printf("Got breakpoint stop reason but pc: %x" PRIx64
"hasn't changed.", pc_addr);
return true;
}
SetAutoContinue(false);
return false;
}
default:
return false;
}
}
return false;
}
bool ThreadPlanStepOverBreakpoint::ShouldStop(Event *event_ptr) {
return !ShouldAutoContinue(event_ptr);
}
bool ThreadPlanStepOverBreakpoint::StopOthers() { return true; }
StateType ThreadPlanStepOverBreakpoint::GetPlanRunState() {
return eStateStepping;
}
bool ThreadPlanStepOverBreakpoint::DoWillResume(StateType resume_state,
bool current_plan) {
if (current_plan) {
BreakpointSiteSP bp_site_sp(
m_thread.GetProcess()->GetBreakpointSiteList().FindByAddress(
m_breakpoint_addr));
if (bp_site_sp && bp_site_sp->IsEnabled()) {
m_thread.GetProcess()->DisableBreakpointSite(bp_site_sp.get());
m_reenabled_breakpoint_site = false;
}
}
return true;
}
bool ThreadPlanStepOverBreakpoint::WillStop() {
ReenableBreakpointSite();
return true;
}
void ThreadPlanStepOverBreakpoint::WillPop() {
ReenableBreakpointSite();
}
bool ThreadPlanStepOverBreakpoint::MischiefManaged() {
lldb::addr_t pc_addr = m_thread.GetRegisterContext()->GetPC();
if (pc_addr == m_breakpoint_addr) {
// If we are still at the PC of our breakpoint, then for some reason we
// didn't get a chance to run.
return false;
} else {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (log)
log->Printf("Completed step over breakpoint plan.");
// Otherwise, re-enable the breakpoint we were stepping over, and we're
// done.
ReenableBreakpointSite();
ThreadPlan::MischiefManaged();
return true;
}
}
void ThreadPlanStepOverBreakpoint::ReenableBreakpointSite() {
if (!m_reenabled_breakpoint_site) {
m_reenabled_breakpoint_site = true;
BreakpointSiteSP bp_site_sp(
m_thread.GetProcess()->GetBreakpointSiteList().FindByAddress(
m_breakpoint_addr));
if (bp_site_sp) {
m_thread.GetProcess()->EnableBreakpointSite(bp_site_sp.get());
}
}
}
void ThreadPlanStepOverBreakpoint::ThreadDestroyed() {
ReenableBreakpointSite();
}
void ThreadPlanStepOverBreakpoint::SetAutoContinue(bool do_it) {
m_auto_continue = do_it;
}
bool ThreadPlanStepOverBreakpoint::ShouldAutoContinue(Event *event_ptr) {
return m_auto_continue;
}
bool ThreadPlanStepOverBreakpoint::IsPlanStale() {
return m_thread.GetRegisterContext()->GetPC() != m_breakpoint_addr;
}
<commit_msg>Fix format string<commit_after>//===-- ThreadPlanStepOverBreakpoint.cpp ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Stream.h"
using namespace lldb;
using namespace lldb_private;
//----------------------------------------------------------------------
// ThreadPlanStepOverBreakpoint: Single steps over a breakpoint bp_site_sp at
// the pc.
//----------------------------------------------------------------------
ThreadPlanStepOverBreakpoint::ThreadPlanStepOverBreakpoint(Thread &thread)
: ThreadPlan(
ThreadPlan::eKindStepOverBreakpoint, "Step over breakpoint trap",
thread, eVoteNo,
eVoteNoOpinion), // We need to report the run since this happens
// first in the thread plan stack when stepping over
// a breakpoint
m_breakpoint_addr(LLDB_INVALID_ADDRESS),
m_auto_continue(false), m_reenabled_breakpoint_site(false)
{
m_breakpoint_addr = m_thread.GetRegisterContext()->GetPC();
m_breakpoint_site_id =
m_thread.GetProcess()->GetBreakpointSiteList().FindIDByAddress(
m_breakpoint_addr);
}
ThreadPlanStepOverBreakpoint::~ThreadPlanStepOverBreakpoint() {}
void ThreadPlanStepOverBreakpoint::GetDescription(
Stream *s, lldb::DescriptionLevel level) {
s->Printf("Single stepping past breakpoint site %" PRIu64 " at 0x%" PRIx64,
m_breakpoint_site_id, (uint64_t)m_breakpoint_addr);
}
bool ThreadPlanStepOverBreakpoint::ValidatePlan(Stream *error) { return true; }
bool ThreadPlanStepOverBreakpoint::DoPlanExplainsStop(Event *event_ptr) {
StopInfoSP stop_info_sp = GetPrivateStopInfo();
if (stop_info_sp) {
// It's a little surprising that we stop here for a breakpoint hit.
// However, when you single step ONTO a breakpoint we still want to call
// that a breakpoint hit, and trigger the actions, etc. Otherwise you
// would see the
// PC at the breakpoint without having triggered the actions, then you'd
// continue, the PC wouldn't change,
// and you'd see the breakpoint hit, which would be odd. So the lower
// levels fake "step onto breakpoint address" and return that as a
// breakpoint. So our trace step COULD appear as a breakpoint hit if the
// next instruction also contained a breakpoint.
StopReason reason = stop_info_sp->GetStopReason();
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (log)
log->Printf("Step over breakpoint stopped for reason: %s.",
Thread::StopReasonAsCString(reason));
switch (reason) {
case eStopReasonTrace:
case eStopReasonNone:
return true;
case eStopReasonBreakpoint:
{
// It's a little surprising that we stop here for a breakpoint hit.
// However, when you single step ONTO a breakpoint we still want to call
// that a breakpoint hit, and trigger the actions, etc. Otherwise you
// would see the PC at the breakpoint without having triggered the
// actions, then you'd continue, the PC wouldn't change, and you'd see
// the breakpoint hit, which would be odd. So the lower levels fake
// "step onto breakpoint address" and return that as a breakpoint hit.
// So our trace step COULD appear as a breakpoint hit if the next
// instruction also contained a breakpoint. We don't want to handle
// that, since we really don't know what to do with breakpoint hits.
// But make sure we don't set ourselves to auto-continue or we'll wrench
// control away from the plans that can deal with this.
// Be careful, however, as we may have "seen a breakpoint under the PC
// because we stopped without changing the PC, in which case we do want
// to re-claim this stop so we'll try again.
lldb::addr_t pc_addr = m_thread.GetRegisterContext()->GetPC();
if (pc_addr == m_breakpoint_addr) {
if (log)
log->Printf("Got breakpoint stop reason but pc: 0x%" PRIx64
"hasn't changed.", pc_addr);
return true;
}
SetAutoContinue(false);
return false;
}
default:
return false;
}
}
return false;
}
bool ThreadPlanStepOverBreakpoint::ShouldStop(Event *event_ptr) {
return !ShouldAutoContinue(event_ptr);
}
bool ThreadPlanStepOverBreakpoint::StopOthers() { return true; }
StateType ThreadPlanStepOverBreakpoint::GetPlanRunState() {
return eStateStepping;
}
bool ThreadPlanStepOverBreakpoint::DoWillResume(StateType resume_state,
bool current_plan) {
if (current_plan) {
BreakpointSiteSP bp_site_sp(
m_thread.GetProcess()->GetBreakpointSiteList().FindByAddress(
m_breakpoint_addr));
if (bp_site_sp && bp_site_sp->IsEnabled()) {
m_thread.GetProcess()->DisableBreakpointSite(bp_site_sp.get());
m_reenabled_breakpoint_site = false;
}
}
return true;
}
bool ThreadPlanStepOverBreakpoint::WillStop() {
ReenableBreakpointSite();
return true;
}
void ThreadPlanStepOverBreakpoint::WillPop() {
ReenableBreakpointSite();
}
bool ThreadPlanStepOverBreakpoint::MischiefManaged() {
lldb::addr_t pc_addr = m_thread.GetRegisterContext()->GetPC();
if (pc_addr == m_breakpoint_addr) {
// If we are still at the PC of our breakpoint, then for some reason we
// didn't get a chance to run.
return false;
} else {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (log)
log->Printf("Completed step over breakpoint plan.");
// Otherwise, re-enable the breakpoint we were stepping over, and we're
// done.
ReenableBreakpointSite();
ThreadPlan::MischiefManaged();
return true;
}
}
void ThreadPlanStepOverBreakpoint::ReenableBreakpointSite() {
if (!m_reenabled_breakpoint_site) {
m_reenabled_breakpoint_site = true;
BreakpointSiteSP bp_site_sp(
m_thread.GetProcess()->GetBreakpointSiteList().FindByAddress(
m_breakpoint_addr));
if (bp_site_sp) {
m_thread.GetProcess()->EnableBreakpointSite(bp_site_sp.get());
}
}
}
void ThreadPlanStepOverBreakpoint::ThreadDestroyed() {
ReenableBreakpointSite();
}
void ThreadPlanStepOverBreakpoint::SetAutoContinue(bool do_it) {
m_auto_continue = do_it;
}
bool ThreadPlanStepOverBreakpoint::ShouldAutoContinue(Event *event_ptr) {
return m_auto_continue;
}
bool ThreadPlanStepOverBreakpoint::IsPlanStale() {
return m_thread.GetRegisterContext()->GetPC() != m_breakpoint_addr;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013-2014, 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 John Haddon 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 "GafferScene/SceneWriter.h"
#include "GafferScene/SceneAlgo.h"
#include "Gaffer/Context.h"
#include "Gaffer/StringPlug.h"
#include "IECoreScene/SceneInterface.h"
#include "boost/filesystem.hpp"
#include "tbb/concurrent_unordered_map.h"
#include "tbb/mutex.h"
using namespace std;
using namespace IECore;
using namespace IECoreScene;
using namespace Gaffer;
using namespace GafferScene;
namespace
{
struct LocationWriter
{
LocationWriter(SceneInterfacePtr output, ConstCompoundDataPtr sets, float time, tbb::mutex& mutex) : m_output( output ), m_sets(sets), m_time( time ), m_mutex( mutex )
{
}
/// first half of this function can be lock free reading data from ScenePlug
/// once all the data has been read then we take a global lock and write
/// into the SceneInterface
bool operator()( const ScenePlug *scene, const ScenePlug::ScenePath &scenePath )
{
ConstCompoundObjectPtr attributes = scene->attributesPlug()->getValue();
ConstCompoundObjectPtr globals;
ConstObjectPtr object = scene->objectPlug()->getValue();
Imath::Box3f bound = scene->boundPlug()->getValue();
IECore::M44dDataPtr transformData;
if( scenePath.empty() )
{
globals = scene->globals();
}
else
{
Imath::M44f t = scene->transformPlug()->getValue();
transformData = new IECore::M44dData( Imath::M44d (
t[0][0], t[0][1], t[0][2], t[0][3],
t[1][0], t[1][1], t[1][2], t[1][3],
t[2][0], t[2][1], t[2][2], t[2][3],
t[3][0], t[3][1], t[3][2], t[3][3]
) );
}
SceneInterface::NameList locationSets;
const CompoundDataMap &setsMap = m_sets->readable();
locationSets.reserve( setsMap.size() );
for( CompoundDataMap::const_iterator it = setsMap.begin(); it != setsMap.end(); ++it)
{
ConstPathMatcherDataPtr pathMatcher = IECore::runTimeCast<PathMatcherData>( it->second );
if( pathMatcher->readable().match( scenePath ) & IECore::PathMatcher::ExactMatch )
{
locationSets.push_back( it->first );
}
}
tbb::mutex::scoped_lock scopedLock( m_mutex );
if( !scenePath.empty() )
{
m_output = m_output->child( scenePath.back(), SceneInterface::CreateIfMissing );
}
for( CompoundObject::ObjectMap::const_iterator it = attributes->members().begin(), eIt = attributes->members().end(); it != eIt; it++ )
{
m_output->writeAttribute( it->first, it->second.get(), m_time );
}
if( globals && !globals->members().empty() )
{
m_output->writeAttribute( "gaffer:globals", globals.get(), m_time );
}
if( object->typeId() != IECore::NullObjectTypeId && scenePath.size() > 0 )
{
m_output->writeObject( object.get(), m_time );
}
m_output->writeBound( Imath::Box3d( Imath::V3f( bound.min ), Imath::V3f( bound.max ) ), m_time );
if( transformData )
{
m_output->writeTransform( transformData.get(), m_time );
}
if( !locationSets.empty() )
{
m_output->writeTags( locationSets );
}
return true;
}
SceneInterfacePtr m_output;
ConstCompoundDataPtr m_sets;
float m_time;
tbb::mutex &m_mutex;
};
}
GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( SceneWriter );
size_t SceneWriter::g_firstPlugIndex = 0;
SceneWriter::SceneWriter( const std::string &name )
: TaskNode( name )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new ScenePlug( "in", Plug::In ) );
addChild( new StringPlug( "fileName" ) );
addChild( new ScenePlug( "out", Plug::Out, Plug::Default & ~Plug::Serialisable ) );
outPlug()->setInput( inPlug() );
}
SceneWriter::~SceneWriter()
{
}
ScenePlug *SceneWriter::inPlug()
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
const ScenePlug *SceneWriter::inPlug() const
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
StringPlug *SceneWriter::fileNamePlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 1 );
}
const StringPlug *SceneWriter::fileNamePlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 1 );
}
ScenePlug *SceneWriter::outPlug()
{
return getChild<ScenePlug>( g_firstPlugIndex + 2 );
}
const ScenePlug *SceneWriter::outPlug() const
{
return getChild<ScenePlug>( g_firstPlugIndex + 2 );
}
IECore::MurmurHash SceneWriter::hash( const Gaffer::Context *context ) const
{
Context::Scope scope( context );
const ScenePlug *scenePlug = inPlug()->source<ScenePlug>();
if ( ( fileNamePlug()->getValue() == "" ) || ( scenePlug == inPlug() ) )
{
return IECore::MurmurHash();
}
IECore::MurmurHash h = TaskNode::hash( context );
h.append( fileNamePlug()->hash() );
/// \todo hash the actual scene when we have a hierarchyHash
h.append( (uint64_t)scenePlug );
h.append( context->hash() );
return h;
}
void SceneWriter::execute() const
{
std::vector<float> frame( 1, Context::current()->getFrame() );
executeSequence( frame );
}
void SceneWriter::executeSequence( const std::vector<float> &frames ) const
{
const ScenePlug *scene = inPlug()->getInput<ScenePlug>();
if( !scene )
{
throw IECore::Exception( "No input scene" );
}
const std::string fileName = fileNamePlug()->getValue();
createDirectories( fileName );
SceneInterfacePtr output = SceneInterface::create( fileName, IndexedIO::Write );
tbb::mutex mutex;
ContextPtr context = new Context( *Context::current() );
Context::Scope scopedContext( context.get() );
for( std::vector<float>::const_iterator it = frames.begin(); it != frames.end(); ++it )
{
context->setFrame( *it );
ConstCompoundDataPtr sets = SceneAlgo::sets( scene );
LocationWriter locationWriter( output, sets, context->getTime(), mutex );
SceneAlgo::parallelProcessLocations( scene, locationWriter );
}
}
bool SceneWriter::requiresSequenceExecution() const
{
return true;
}
void SceneWriter::createDirectories( const std::string &fileName ) const
{
boost::filesystem::path filePath( fileName );
boost::filesystem::path directory = filePath.parent_path();
if( !directory.empty() )
{
boost::filesystem::create_directories( directory );
}
}
<commit_msg>SceneWriter : Remove redundant `Context::Scope`<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013-2014, 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 John Haddon 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 "GafferScene/SceneWriter.h"
#include "GafferScene/SceneAlgo.h"
#include "Gaffer/Context.h"
#include "Gaffer/StringPlug.h"
#include "IECoreScene/SceneInterface.h"
#include "boost/filesystem.hpp"
#include "tbb/concurrent_unordered_map.h"
#include "tbb/mutex.h"
using namespace std;
using namespace IECore;
using namespace IECoreScene;
using namespace Gaffer;
using namespace GafferScene;
namespace
{
struct LocationWriter
{
LocationWriter(SceneInterfacePtr output, ConstCompoundDataPtr sets, float time, tbb::mutex& mutex) : m_output( output ), m_sets(sets), m_time( time ), m_mutex( mutex )
{
}
/// first half of this function can be lock free reading data from ScenePlug
/// once all the data has been read then we take a global lock and write
/// into the SceneInterface
bool operator()( const ScenePlug *scene, const ScenePlug::ScenePath &scenePath )
{
ConstCompoundObjectPtr attributes = scene->attributesPlug()->getValue();
ConstCompoundObjectPtr globals;
ConstObjectPtr object = scene->objectPlug()->getValue();
Imath::Box3f bound = scene->boundPlug()->getValue();
IECore::M44dDataPtr transformData;
if( scenePath.empty() )
{
globals = scene->globals();
}
else
{
Imath::M44f t = scene->transformPlug()->getValue();
transformData = new IECore::M44dData( Imath::M44d (
t[0][0], t[0][1], t[0][2], t[0][3],
t[1][0], t[1][1], t[1][2], t[1][3],
t[2][0], t[2][1], t[2][2], t[2][3],
t[3][0], t[3][1], t[3][2], t[3][3]
) );
}
SceneInterface::NameList locationSets;
const CompoundDataMap &setsMap = m_sets->readable();
locationSets.reserve( setsMap.size() );
for( CompoundDataMap::const_iterator it = setsMap.begin(); it != setsMap.end(); ++it)
{
ConstPathMatcherDataPtr pathMatcher = IECore::runTimeCast<PathMatcherData>( it->second );
if( pathMatcher->readable().match( scenePath ) & IECore::PathMatcher::ExactMatch )
{
locationSets.push_back( it->first );
}
}
tbb::mutex::scoped_lock scopedLock( m_mutex );
if( !scenePath.empty() )
{
m_output = m_output->child( scenePath.back(), SceneInterface::CreateIfMissing );
}
for( CompoundObject::ObjectMap::const_iterator it = attributes->members().begin(), eIt = attributes->members().end(); it != eIt; it++ )
{
m_output->writeAttribute( it->first, it->second.get(), m_time );
}
if( globals && !globals->members().empty() )
{
m_output->writeAttribute( "gaffer:globals", globals.get(), m_time );
}
if( object->typeId() != IECore::NullObjectTypeId && scenePath.size() > 0 )
{
m_output->writeObject( object.get(), m_time );
}
m_output->writeBound( Imath::Box3d( Imath::V3f( bound.min ), Imath::V3f( bound.max ) ), m_time );
if( transformData )
{
m_output->writeTransform( transformData.get(), m_time );
}
if( !locationSets.empty() )
{
m_output->writeTags( locationSets );
}
return true;
}
SceneInterfacePtr m_output;
ConstCompoundDataPtr m_sets;
float m_time;
tbb::mutex &m_mutex;
};
}
GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( SceneWriter );
size_t SceneWriter::g_firstPlugIndex = 0;
SceneWriter::SceneWriter( const std::string &name )
: TaskNode( name )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new ScenePlug( "in", Plug::In ) );
addChild( new StringPlug( "fileName" ) );
addChild( new ScenePlug( "out", Plug::Out, Plug::Default & ~Plug::Serialisable ) );
outPlug()->setInput( inPlug() );
}
SceneWriter::~SceneWriter()
{
}
ScenePlug *SceneWriter::inPlug()
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
const ScenePlug *SceneWriter::inPlug() const
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
StringPlug *SceneWriter::fileNamePlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 1 );
}
const StringPlug *SceneWriter::fileNamePlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 1 );
}
ScenePlug *SceneWriter::outPlug()
{
return getChild<ScenePlug>( g_firstPlugIndex + 2 );
}
const ScenePlug *SceneWriter::outPlug() const
{
return getChild<ScenePlug>( g_firstPlugIndex + 2 );
}
IECore::MurmurHash SceneWriter::hash( const Gaffer::Context *context ) const
{
const ScenePlug *scenePlug = inPlug()->source<ScenePlug>();
if ( ( fileNamePlug()->getValue() == "" ) || ( scenePlug == inPlug() ) )
{
return IECore::MurmurHash();
}
IECore::MurmurHash h = TaskNode::hash( context );
h.append( fileNamePlug()->hash() );
/// \todo hash the actual scene when we have a hierarchyHash
h.append( (uint64_t)scenePlug );
h.append( context->hash() );
return h;
}
void SceneWriter::execute() const
{
std::vector<float> frame( 1, Context::current()->getFrame() );
executeSequence( frame );
}
void SceneWriter::executeSequence( const std::vector<float> &frames ) const
{
const ScenePlug *scene = inPlug()->getInput<ScenePlug>();
if( !scene )
{
throw IECore::Exception( "No input scene" );
}
const std::string fileName = fileNamePlug()->getValue();
createDirectories( fileName );
SceneInterfacePtr output = SceneInterface::create( fileName, IndexedIO::Write );
tbb::mutex mutex;
ContextPtr context = new Context( *Context::current() );
Context::Scope scopedContext( context.get() );
for( std::vector<float>::const_iterator it = frames.begin(); it != frames.end(); ++it )
{
context->setFrame( *it );
ConstCompoundDataPtr sets = SceneAlgo::sets( scene );
LocationWriter locationWriter( output, sets, context->getTime(), mutex );
SceneAlgo::parallelProcessLocations( scene, locationWriter );
}
}
bool SceneWriter::requiresSequenceExecution() const
{
return true;
}
void SceneWriter::createDirectories( const std::string &fileName ) const
{
boost::filesystem::path filePath( fileName );
boost::filesystem::path directory = filePath.parent_path();
if( !directory.empty() )
{
boost::filesystem::create_directories( directory );
}
}
<|endoftext|> |
<commit_before>/**
* @file constrained_ik.cpp
* @brief Basic low-level kinematics functions.
*
* Typically, just wrappers around the equivalent KDL calls.
*
* @author dsolomon
* @date Sep 15, 2013
* @version TODO
* @bug No known bugs
*
* @copyright Copyright (c) 2013, Southwest Research Institute
*
* @license Software License Agreement (Apache License)\n
* \n
* 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\n
* \n
* http://www.apache.org/licenses/LICENSE-2.0\n
* \n
* 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 "constrained_ik/constrained_ik.h"
#include "constrained_ik/constraint_group.h"
#include <ros/ros.h>
namespace constrained_ik
{
using Eigen::MatrixXd;
using Eigen::VectorXd;
using Eigen::Affine3d;
Constrained_IK::Constrained_IK()
{
initialized_ = false;
max_iter_ = 500; //default max_iter
joint_convergence_tol_ = 0.0001; //default convergence tolerance
debug_ = false;
kpp_ = 0.9;// default primary proportional gain
kpa_ = 0.5;// default auxillary proportional gain
}
Eigen::VectorXd Constrained_IK::calcConstraintError(constraint_types::ConstraintType constraint_type)
{
switch(constraint_type)
{
case constraint_types::primary:
return primary_constraints_.calcError();
case constraint_types::auxiliary:
return auxiliary_constraints_.calcError();
}
}
Eigen::MatrixXd Constrained_IK::calcConstraintJacobian(constraint_types::ConstraintType constraint_type)
{
switch(constraint_type)
{
case constraint_types::primary:
return primary_constraints_.calcJacobian();
case constraint_types::auxiliary:
return auxiliary_constraints_.calcJacobian();
}
}
Eigen::MatrixXd Constrained_IK::calcNullspaceProjection(const Eigen::MatrixXd &J) const
{
MatrixXd J_pinv = calcDampedPseudoinverse(J);
MatrixXd JplusJ = J_pinv * J;
int mn = JplusJ.rows();
MatrixXd P = MatrixXd::Identity(mn,mn)-JplusJ;
return (P);
}
Eigen::MatrixXd Constrained_IK::calcNullspaceProjectionTheRightWay(const Eigen::MatrixXd &A) const
{
Eigen::JacobiSVD<MatrixXd> svd(A, Eigen::ComputeFullV);
MatrixXd V(svd.matrixV());
int rnk = svd.rank();
// zero singular vectors in the range of A
for(int i=0; i<rnk; ++i)
{
for(int j=0; j<A.cols(); j++) V(j,i) = 0;
}
MatrixXd P = V * V.transpose();
return(P);
}
Eigen::MatrixXd Constrained_IK::calcDampedPseudoinverse(const Eigen::MatrixXd &J) const
{
MatrixXd J_pinv;
if (basic_kin::BasicKin::dampedPInv(J,J_pinv)){
return J_pinv;
}
else
{
ROS_ERROR_STREAM("Not able to calculate damped pseudoinverse!");
throw std::runtime_error("Not able to calculate damped pseudoinverse! IK solution may be invalid.");
}
}
void Constrained_IK::calcInvKin(const Eigen::Affine3d &goal, const Eigen::VectorXd &joint_seed, Eigen::VectorXd &joint_angles)
{
if (!checkInitialized(constraint_types::primary))
throw std::runtime_error("Must call init() before using Constrained_IK");
//TODO should goal be checked here instead of in reset()?
// initialize state
joint_angles = joint_seed; // initialize result to seed value
reset(goal, joint_seed); // reset state vars for this IK solve
update(joint_angles); // update current state
// iterate until solution converges (or aborted)
while (!checkStatus())
{
// calculate a Jacobian (relating joint-space updates/deltas to cartesian-space errors/deltas)
// and the associated cartesian-space error/delta vector
// Primary Constraints
MatrixXd J_p = calcConstraintJacobian(constraint_types::primary);
MatrixXd Ji_p = calcDampedPseudoinverse(J_p);
int rows = J_p.rows();
int cols = J_p.cols();
MatrixXd N_p = calcNullspaceProjectionTheRightWay(J_p);
VectorXd err_p = calcConstraintError(constraint_types::primary);
// solve for the resulting joint-space update
VectorXd dJoint_p;
VectorXd dJoint_a;
dJoint_p = kpp_*(Ji_p*err_p);
ROS_DEBUG("theta_p = %f ep = %f",dJoint_p.norm(), err_p.norm());
// Auxiliary Constraints
dJoint_a.setZero(dJoint_p.size());
if (checkInitialized(constraint_types::auxiliary)) {
MatrixXd J_a = calcConstraintJacobian(constraint_types::auxiliary);
VectorXd err_a = calcConstraintError(constraint_types::auxiliary);
MatrixXd Jnull_a = calcDampedPseudoinverse(J_a*N_p);
dJoint_a = kpa_*Jnull_a*(err_a-J_a*dJoint_p);
ROS_ERROR("theta_p = %f ep = %f ea = %f",dJoint_p.norm(), err_p.norm(), err_a.norm());
}
// update joint solution by the calculated update (or a partial fraction)
joint_angles += (dJoint_p + dJoint_a);
clipToJointLimits(joint_angles);
// re-update internal state variables
update(joint_angles);
}
ROS_INFO_STREAM("IK solution: " << joint_angles.transpose());
}
bool Constrained_IK::checkStatus() const
{
// check constraints for completion
if (primary_constraints_.checkStatus() && auxiliary_constraints_.checkStatus())
return true;
// check maximum iterations
if (state_.iter > max_iter_)
throw std::runtime_error("Maximum iterations reached. IK solution may be invalid.");
// check for joint convergence
// - this is an error: joints stabilize, but goal pose not reached
if (state_.joints_delta.cwiseAbs().maxCoeff() < joint_convergence_tol_)
{
// ROS_ERROR_STREAM("Reached " << state_.iter << " / " << max_iter_ << " iterations before convergence.");
// throw std::runtime_error("Iteration converged before goal reached. IK solution may be invalid");
ROS_WARN_STREAM("Reached " << state_.iter << " / " << max_iter_ << " iterations before convergence.");
return true;
}
return false;
}
void Constrained_IK::clearConstraintList()
{
primary_constraints_.clear();
auxiliary_constraints_.clear();
}
void Constrained_IK::clipToJointLimits(Eigen::VectorXd &joints)
{
const MatrixXd limits = kin_.getLimits();
const VectorXd orig_joints(joints);
if (joints.size() != limits.rows())
throw std::invalid_argument("clipToJointLimits: Unexpected number of joints");
for (size_t i=0; i<limits.rows(); ++i)
{
joints[i] = std::max(limits(i,0), std::min(limits(i,1), joints[i]));
}
if (debug_ && !joints.isApprox(orig_joints))
ROS_WARN("Joints have been clipped");
}
void Constrained_IK::init(const urdf::Model &robot, const std::string &base_name, const std::string &tip_name)
{
basic_kin::BasicKin kin;
if (! kin.init(robot, base_name, tip_name))
throw std::runtime_error("Failed to initialize BasicKin");
init(kin);
}
void Constrained_IK::init(const basic_kin::BasicKin &kin)
{
if (!kin.checkInitialized())
throw std::invalid_argument("Input argument 'BasicKin' must be initialized");
kin_ = kin;
initialized_ = true;
primary_constraints_.init(this);
auxiliary_constraints_.init(this);
}
double Constrained_IK::rangedAngle(double angle)
{
angle = copysign(fmod(fabs(angle),2.0*M_PI), angle);
if (angle < -M_PI) return angle+2.*M_PI;
if (angle > M_PI) return angle-2.*M_PI;
return angle;
}
void Constrained_IK::reset(const Eigen::Affine3d &goal, const Eigen::VectorXd &joint_seed)
{
if (!kin_.checkJoints(joint_seed))
throw std::invalid_argument("Seed doesn't match kinematic model");
if (!goal.matrix().block(0,0,3,3).isUnitary(1e-6))
throw std::invalid_argument("Goal pose not proper affine");
state_.reset(goal, joint_seed); // reset state
primary_constraints_.reset(); // reset primary constraints
auxiliary_constraints_.reset(); // reset auxiliary constraints
}
void Constrained_IK::update(const Eigen::VectorXd &joints)
{
// update maximum iterations
state_.iter++;
// update joint convergence
state_.joints_delta = joints - state_.joints;
state_.joints = joints;
kin_.calcFwdKin(joints, state_.pose_estimate);
if (debug_)
iteration_path_.push_back(joints);
primary_constraints_.update(state_);
auxiliary_constraints_.update(state_);
}
} // namespace constrained_ik
<commit_msg>replaced svd.rank() with equivalent code because Eigen3 is not yet a debian<commit_after>/**
* @file constrained_ik.cpp
* @brief Basic low-level kinematics functions.
*
* Typically, just wrappers around the equivalent KDL calls.
*
* @author dsolomon
* @date Sep 15, 2013
* @version TODO
* @bug No known bugs
*
* @copyright Copyright (c) 2013, Southwest Research Institute
*
* @license Software License Agreement (Apache License)\n
* \n
* 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\n
* \n
* http://www.apache.org/licenses/LICENSE-2.0\n
* \n
* 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 "constrained_ik/constrained_ik.h"
#include "constrained_ik/constraint_group.h"
#include <ros/ros.h>
namespace constrained_ik
{
using Eigen::MatrixXd;
using Eigen::VectorXd;
using Eigen::Affine3d;
Constrained_IK::Constrained_IK()
{
initialized_ = false;
max_iter_ = 500; //default max_iter
joint_convergence_tol_ = 0.0001; //default convergence tolerance
debug_ = false;
kpp_ = 0.9;// default primary proportional gain
kpa_ = 0.5;// default auxillary proportional gain
}
Eigen::VectorXd Constrained_IK::calcConstraintError(constraint_types::ConstraintType constraint_type)
{
switch(constraint_type)
{
case constraint_types::primary:
return primary_constraints_.calcError();
case constraint_types::auxiliary:
return auxiliary_constraints_.calcError();
}
}
Eigen::MatrixXd Constrained_IK::calcConstraintJacobian(constraint_types::ConstraintType constraint_type)
{
switch(constraint_type)
{
case constraint_types::primary:
return primary_constraints_.calcJacobian();
case constraint_types::auxiliary:
return auxiliary_constraints_.calcJacobian();
}
}
Eigen::MatrixXd Constrained_IK::calcNullspaceProjection(const Eigen::MatrixXd &J) const
{
MatrixXd J_pinv = calcDampedPseudoinverse(J);
MatrixXd JplusJ = J_pinv * J;
int mn = JplusJ.rows();
MatrixXd P = MatrixXd::Identity(mn,mn)-JplusJ;
return (P);
}
Eigen::MatrixXd Constrained_IK::calcNullspaceProjectionTheRightWay(const Eigen::MatrixXd &A) const
{
Eigen::JacobiSVD<MatrixXd> svd(A, Eigen::ComputeFullV);
MatrixXd V(svd.matrixV());
// determine rank using same algorithym as latest Eigen
// TODO replace next 10 lines of code with rnk = svd.rank(); once eigen3 is updated
int rnk = 0;
if(svd.singularValues().size()==0) {
rnk = 0;
}
else{
double premultiplied_threshold = svd.singularValues().coeff(0) * svd.threshold();
rnk = svd.nonzeroSingularValues()-1;
while(rnk>=0 && svd.singularValues().coeff(rnk) < premultiplied_threshold) --rnk;
rnk++;
}
// zero singular vectors in the range of A
for(int i=0; i<rnk; ++i)
{
for(int j=0; j<A.cols(); j++) V(j,i) = 0;
}
MatrixXd P = V * V.transpose();
return(P);
}
Eigen::MatrixXd Constrained_IK::calcDampedPseudoinverse(const Eigen::MatrixXd &J) const
{
MatrixXd J_pinv;
if (basic_kin::BasicKin::dampedPInv(J,J_pinv)){
return J_pinv;
}
else
{
ROS_ERROR_STREAM("Not able to calculate damped pseudoinverse!");
throw std::runtime_error("Not able to calculate damped pseudoinverse! IK solution may be invalid.");
}
}
void Constrained_IK::calcInvKin(const Eigen::Affine3d &goal, const Eigen::VectorXd &joint_seed, Eigen::VectorXd &joint_angles)
{
if (!checkInitialized(constraint_types::primary))
throw std::runtime_error("Must call init() before using Constrained_IK");
//TODO should goal be checked here instead of in reset()?
// initialize state
joint_angles = joint_seed; // initialize result to seed value
reset(goal, joint_seed); // reset state vars for this IK solve
update(joint_angles); // update current state
// iterate until solution converges (or aborted)
while (!checkStatus())
{
// calculate a Jacobian (relating joint-space updates/deltas to cartesian-space errors/deltas)
// and the associated cartesian-space error/delta vector
// Primary Constraints
MatrixXd J_p = calcConstraintJacobian(constraint_types::primary);
MatrixXd Ji_p = calcDampedPseudoinverse(J_p);
int rows = J_p.rows();
int cols = J_p.cols();
MatrixXd N_p = calcNullspaceProjectionTheRightWay(J_p);
VectorXd err_p = calcConstraintError(constraint_types::primary);
// solve for the resulting joint-space update
VectorXd dJoint_p;
VectorXd dJoint_a;
dJoint_p = kpp_*(Ji_p*err_p);
ROS_DEBUG("theta_p = %f ep = %f",dJoint_p.norm(), err_p.norm());
// Auxiliary Constraints
dJoint_a.setZero(dJoint_p.size());
if (checkInitialized(constraint_types::auxiliary)) {
MatrixXd J_a = calcConstraintJacobian(constraint_types::auxiliary);
VectorXd err_a = calcConstraintError(constraint_types::auxiliary);
MatrixXd Jnull_a = calcDampedPseudoinverse(J_a*N_p);
dJoint_a = kpa_*Jnull_a*(err_a-J_a*dJoint_p);
ROS_DEBUG("theta_p = %f ep = %f ea = %f",dJoint_p.norm(), err_p.norm(), err_a.norm());
}
// update joint solution by the calculated update (or a partial fraction)
joint_angles += (dJoint_p + dJoint_a);
clipToJointLimits(joint_angles);
// re-update internal state variables
update(joint_angles);
}
ROS_INFO_STREAM("IK solution: " << joint_angles.transpose());
}
bool Constrained_IK::checkStatus() const
{
// check constraints for completion
if (primary_constraints_.checkStatus() && auxiliary_constraints_.checkStatus())
return true;
// check maximum iterations
if (state_.iter > max_iter_)
throw std::runtime_error("Maximum iterations reached. IK solution may be invalid.");
// check for joint convergence
// - this is an error: joints stabilize, but goal pose not reached
if (state_.joints_delta.cwiseAbs().maxCoeff() < joint_convergence_tol_)
{
// ROS_ERROR_STREAM("Reached " << state_.iter << " / " << max_iter_ << " iterations before convergence.");
// throw std::runtime_error("Iteration converged before goal reached. IK solution may be invalid");
ROS_WARN_STREAM("Reached " << state_.iter << " / " << max_iter_ << " iterations before convergence.");
return true;
}
return false;
}
void Constrained_IK::clearConstraintList()
{
primary_constraints_.clear();
auxiliary_constraints_.clear();
}
void Constrained_IK::clipToJointLimits(Eigen::VectorXd &joints)
{
const MatrixXd limits = kin_.getLimits();
const VectorXd orig_joints(joints);
if (joints.size() != limits.rows())
throw std::invalid_argument("clipToJointLimits: Unexpected number of joints");
for (size_t i=0; i<limits.rows(); ++i)
{
joints[i] = std::max(limits(i,0), std::min(limits(i,1), joints[i]));
}
if (debug_ && !joints.isApprox(orig_joints))
ROS_WARN("Joints have been clipped");
}
void Constrained_IK::init(const urdf::Model &robot, const std::string &base_name, const std::string &tip_name)
{
basic_kin::BasicKin kin;
if (! kin.init(robot, base_name, tip_name))
throw std::runtime_error("Failed to initialize BasicKin");
init(kin);
}
void Constrained_IK::init(const basic_kin::BasicKin &kin)
{
if (!kin.checkInitialized())
throw std::invalid_argument("Input argument 'BasicKin' must be initialized");
kin_ = kin;
initialized_ = true;
primary_constraints_.init(this);
auxiliary_constraints_.init(this);
}
double Constrained_IK::rangedAngle(double angle)
{
angle = copysign(fmod(fabs(angle),2.0*M_PI), angle);
if (angle < -M_PI) return angle+2.*M_PI;
if (angle > M_PI) return angle-2.*M_PI;
return angle;
}
void Constrained_IK::reset(const Eigen::Affine3d &goal, const Eigen::VectorXd &joint_seed)
{
if (!kin_.checkJoints(joint_seed))
throw std::invalid_argument("Seed doesn't match kinematic model");
if (!goal.matrix().block(0,0,3,3).isUnitary(1e-6))
throw std::invalid_argument("Goal pose not proper affine");
state_.reset(goal, joint_seed); // reset state
primary_constraints_.reset(); // reset primary constraints
auxiliary_constraints_.reset(); // reset auxiliary constraints
}
void Constrained_IK::update(const Eigen::VectorXd &joints)
{
// update maximum iterations
state_.iter++;
// update joint convergence
state_.joints_delta = joints - state_.joints;
state_.joints = joints;
kin_.calcFwdKin(joints, state_.pose_estimate);
if (debug_)
iteration_path_.push_back(joints);
primary_constraints_.update(state_);
auxiliary_constraints_.update(state_);
}
} // namespace constrained_ik
<|endoftext|> |
<commit_before>#line 2 "quanta/core/object/object.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief Object interface.
@ingroup lib_core_object
*/
#pragma once
#include <quanta/core/config.hpp>
#include <quanta/core/types.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/memory/memory.hpp>
#include <togo/core/collection/array.hpp>
#include <togo/core/string/string.hpp>
#include <togo/core/hash/hash.hpp>
#include <quanta/core/string/unmanaged_string.hpp>
#include <quanta/core/object/types.hpp>
#include <quanta/core/object/object.gen_interface>
namespace quanta {
namespace object {
/**
@addtogroup lib_core_object
@{
*/
namespace {
static constexpr ObjectValueType const type_mask_numeric
= ObjectValueType::integer
| ObjectValueType::decimal
;
} // anonymous namespace
namespace internal {
inline unsigned get_property(Object const& obj, unsigned mask, unsigned shift) {
return (obj.properties & mask) >> shift;
}
inline void set_property(Object& obj, unsigned mask, unsigned shift, unsigned value) {
obj.properties = (obj.properties & ~mask) | (value << shift);
}
inline void clear_property(Object& obj, unsigned mask) {
obj.properties &= ~mask;
}
} // namespace internal
/// Calculate object name hash of string.
inline ObjectNameHash hash_name(StringRef const& name) {
return hash::calc_generic<ObjectNameHash>(name);
}
/// Value type.
inline ObjectValueType type(Object const& obj) {
return static_cast<ObjectValueType>(internal::get_property(obj, Object::M_TYPE, 0));
}
/// Whether type is type.
inline bool is_type(Object const& obj, ObjectValueType const type) {
return object::type(obj) == type;
}
/// Whether type is any in type.
inline bool is_type_any(Object const& obj, ObjectValueType const type) {
return enum_bool(object::type(obj) & type);
}
/// Whether type is ObjectValueType::null.
inline bool is_null(Object const& obj) { return object::is_type(obj, ObjectValueType::null); }
/// Whether type is ObjectValueType::boolean.
inline bool is_boolean(Object const& obj) { return object::is_type(obj, ObjectValueType::boolean); }
/// Whether type is ObjectValueType::integer.
inline bool is_integer(Object const& obj) { return object::is_type(obj, ObjectValueType::integer); }
/// Whether type is ObjectValueType::decimal.
inline bool is_decimal(Object const& obj) { return object::is_type(obj, ObjectValueType::decimal); }
/// Whether type is ObjectValueType::integer or ObjectValueType::decimal.
inline bool is_numeric(Object const& obj) {
return object::is_type_any(obj, type_mask_numeric);
}
/// Whether type is ObjectValueType::string.
inline bool is_string(Object const& obj) { return object::is_type(obj, ObjectValueType::string); }
/// Name.
inline StringRef name(Object const& obj) {
return obj.name;
}
/// Name hash.
inline ObjectNameHash name_hash(Object const& obj) {
return obj.name.hash;
}
/// Whether name is non-empty.
inline bool is_named(Object const& obj) {
return unmanaged_string::any(obj.name);
}
/// Set name.
inline void set_name(Object& obj, StringRef name) {
unmanaged_string::set(obj.name, name, memory::default_allocator());
}
/// Clear name.
inline void clear_name(Object& obj) {
unmanaged_string::clear(obj.name, memory::default_allocator());
}
/// Source.
inline unsigned source(Object const& obj) {
return obj.source;
}
/// Whether source uncertainty marker is set.
inline bool marker_source_uncertain(Object const& obj) {
return internal::get_property(obj, Object::M_SOURCE_UNCERTAIN, Object::S_SOURCE_UNCERTAIN);
}
/// Sub-source.
inline unsigned sub_source(Object const& obj) {
return obj.sub_source;
}
/// Whether sub-source uncertainty marker is set.
inline bool marker_sub_source_uncertain(Object const& obj) {
return internal::get_property(obj, Object::M_SUB_SOURCE_UNCERTAIN, Object::S_SUB_SOURCE_UNCERTAIN);
}
/// Whether a source is specified.
inline bool has_source(Object const& obj) {
return obj.source != 0;
}
/// Whether the source and sub-source are certain.
inline bool source_certain(Object const& obj) {
return object::has_source(obj) && !(obj.properties & Object::M_BOTH_SOURCE_UNCERTAIN);
}
/// Whether the source and sub-source are certain or unspecified.
inline bool source_certain_or_unspecified(Object const& obj) {
return !(obj.properties & Object::M_BOTH_SOURCE_UNCERTAIN);
}
/// Whether the value uncertain marker is set.
inline bool marker_value_uncertain(Object const& obj) {
return internal::get_property(obj, Object::M_VALUE_UNCERTAIN, Object::S_VALUE_UNCERTAIN);
}
/// Whether the value guess marker is set.
inline bool marker_value_guess(Object const& obj) {
return internal::get_property(obj, Object::M_VALUE_GUESS, Object::S_VALUE_GUESS);
}
/// Value approximation marker value.
inline signed value_approximation(Object const& obj) {
unsigned const value = internal::get_property(obj, Object::M_VALUE_APPROXIMATE, Object::S_VALUE_APPROXIMATE);
return (value & (1 << 2)) ? -(signed_cast(value) & 3) : signed_cast(value);
}
/// Whether value is certain.
///
/// If the value guess or uncertainty marker are set or the approximation marker
/// is non-zero, this returns false.
/// If the value is null, the value uncertainty and approximation markers can
/// still be set.
inline bool value_certain(Object const& obj) {
return !(obj.properties & Object::M_VALUE_MARKERS);
}
/// Boolean value.
inline bool boolean(Object const& obj) {
TOGO_ASSERTE(object::is_type(obj, ObjectValueType::boolean));
return obj.value.boolean;
}
/// Integer value.
inline s64 integer(Object const& obj) {
TOGO_ASSERTE(object::is_type(obj, ObjectValueType::integer));
return obj.value.numeric.integer;
}
/// Decimal value.
inline f64 decimal(Object const& obj) {
TOGO_ASSERTE(object::is_type(obj, ObjectValueType::decimal));
return obj.value.numeric.decimal;
}
/// Numeric value unit.
inline StringRef unit(Object const& obj) {
TOGO_ASSERTE(object::is_type_any(obj, type_mask_numeric));
return obj.value.numeric.unit;
}
/// Numeric value unit hash.
inline ObjectNumericUnitHash unit_hash(Object const& obj) {
TOGO_ASSERTE(object::is_type_any(obj, type_mask_numeric));
return obj.value.numeric.unit.hash;
}
/// Whether the numeric value has a unit.
inline bool has_unit(Object const& obj) {
return object::is_type_any(obj, type_mask_numeric) && unmanaged_string::any(obj.value.numeric.unit);
}
/// String value.
inline StringRef string(Object const& obj) {
TOGO_ASSERTE(object::is_type(obj, ObjectValueType::string));
return obj.value.string;
}
/// Clear source and sub-source uncertainty markers.
inline void clear_source_uncertainty(Object& obj) {
internal::clear_property(obj, Object::M_SOURCE_UNCERTAIN | Object::M_SUB_SOURCE_UNCERTAIN);
}
/// Set source certainty marker.
inline void set_source_certain(Object& obj, bool const certain) {
internal::set_property(obj, Object::M_SOURCE_UNCERTAIN, Object::S_SOURCE_UNCERTAIN, !certain);
}
/// Set source.
///
/// If source is 0, sub-source is also set to 0 (same effect as clear_source()).
/// This clears the source uncertainty marker.
inline void set_source(Object& obj, unsigned const source) {
if (source == 0) {
obj.source = 0;
obj.sub_source = 0;
object::clear_source_uncertainty(obj);
} else {
obj.source = static_cast<u16>(min(source, 0xFFFFu));
object::set_source_certain(obj, true);
}
}
/// Set sub-source certainty marker.
inline void set_sub_source_certain(Object& obj, bool const certain) {
internal::set_property(obj, Object::M_SUB_SOURCE_UNCERTAIN, Object::S_SUB_SOURCE_UNCERTAIN, !certain);
}
/// Set sub-source.
///
/// The source must be non-0 for the sub-source to take a non-0 value.
inline void set_sub_source(Object& obj, unsigned const sub_source) {
if (object::has_source(obj)) {
obj.sub_source = static_cast<u16>(min(sub_source, 0xFFFFu));
}
}
/// Clear source and sub-source and their uncertainty markers.
inline void clear_source(Object& obj) {
object::set_source(obj, 0);
object::clear_source_uncertainty(obj);
}
/// Set value certainty.
///
/// This clears the value guess marker.
inline void set_value_certain(Object& obj, bool const certain) {
internal::set_property(obj, Object::M_VALUE_UNCERTAIN_AND_GUESS, Object::S_VALUE_UNCERTAIN, !certain);
}
/// Set value guess marker.
///
/// If the value is null, this has no effect.
/// This clears the value uncertainty marker.
inline void set_value_guess(Object& obj, bool const guess) {
if (object::is_null(obj)) {
internal::set_property(obj, Object::M_VALUE_UNCERTAIN_AND_GUESS, Object::S_VALUE_GUESS, guess);
}
}
/// Set value approximation value.
///
/// value is bound to [-3, 3]. value of:
///
/// - <0 = approximately less than
/// - 0 = absolute
/// - >0 = approximately more than
inline void set_value_approximation(Object& obj, signed const value) {
unsigned property_value = value < 0;
property_value = unsigned_cast(min(property_value ? -value : value, 3)) | (property_value << 2);
internal::set_property(obj, Object::M_VALUE_APPROXIMATE, Object::S_VALUE_APPROXIMATE, property_value);
}
/// Clear value uncertainty, guess, and approximation markers.
inline void clear_value_markers(Object& obj) {
internal::clear_property(obj, Object::M_VALUE_MARKERS);
}
/// Set value to null.
inline void set_null(Object& obj) {
object::set_type(obj, ObjectValueType::null);
}
/// Set boolean value.
inline void set_boolean(Object& obj, bool const value) {
object::set_type(obj, ObjectValueType::boolean);
obj.value.boolean = value;
}
/// Set integer value.
inline void set_integer(Object& obj, s64 const value) {
object::set_type(obj, ObjectValueType::integer);
obj.value.numeric.integer = value;
}
/// Set decimal value.
inline void set_decimal(Object& obj, f64 const value) {
object::set_type(obj, ObjectValueType::decimal);
obj.value.numeric.decimal = value;
}
/// Set numeric value unit.
///
/// Type must be numeric.
inline void set_unit(Object& obj, StringRef const unit) {
TOGO_ASSERTE(object::is_type_any(obj, type_mask_numeric));
unmanaged_string::set(obj.value.numeric.unit, unit, memory::default_allocator());
}
/// Set integer value and unit.
inline void set_integer(Object& obj, s64 const value, StringRef const unit) {
object::set_type(obj, ObjectValueType::integer);
obj.value.numeric.integer = value;
object::set_unit(obj, unit);
}
/// Set decimal value and unit.
inline void set_decimal(Object& obj, f64 const value, StringRef const unit) {
object::set_type(obj, ObjectValueType::decimal);
obj.value.numeric.decimal = value;
object::set_unit(obj, unit);
}
/// Set string value.
inline void set_string(Object& obj, StringRef const value) {
object::set_type(obj, ObjectValueType::string);
unmanaged_string::set(obj.value.string, value, memory::default_allocator());
}
/// Children.
inline Array<Object>& children(Object& obj) { return obj.children; }
inline Array<Object> const& children(Object const& obj) { return obj.children; }
/// Tags.
inline Array<Object>& tags(Object& obj) { return obj.tags; }
inline Array<Object> const& tags(Object const& obj) { return obj.tags; }
/// Quantity.
inline Object* quantity(Object& obj) { return obj.quantity; }
inline Object const* quantity(Object const& obj) { return obj.quantity; }
/// Whether the object has tags.
inline bool has_tags(Object const& obj) {
return array::any(obj.tags);
}
/// Whether the object has children.
inline bool has_children(Object const& obj) {
return array::any(obj.children);
}
/// Whether the object has a quantity.
inline bool has_quantity(Object const& obj) {
return obj.quantity;
}
/// Clear tags.
inline void clear_tags(Object& obj) {
array::clear(obj.tags);
}
/// Clear children.
inline void clear_children(Object& obj) {
array::clear(obj.children);
}
/// Clear quantity.
inline void clear_quantity(Object& obj) {
if (object::has_quantity(obj)) {
object::clear(*obj.quantity);
}
}
/// Release quantity.
inline void release_quantity(Object& obj) {
TOGO_DESTROY(memory::default_allocator(), obj.quantity);
obj.quantity = nullptr;
}
/// Destruct.
inline Object::~Object() {
object::clear_name(*this);
object::set_null(*this);
object::release_quantity(*this);
}
/// Construct null.
inline Object::Object()
: properties(unsigned_cast(ObjectValueType::null))
, source(0)
, sub_source(0)
, name()
, value()
, tags(memory::default_allocator())
, children(memory::default_allocator())
, quantity(nullptr)
{}
/// Construct copy.
inline Object::Object(Object const& other)
: Object()
{
object::copy(*this, other);
}
inline Object& Object::operator=(Object const& other) {
object::copy(*this, other);
return *this;
}
/** @} */ // end of doc-group lib_core_object
} // namespace object
} // namespace quanta
<commit_msg>lib/core/object/object: added has_sub_source().<commit_after>#line 2 "quanta/core/object/object.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief Object interface.
@ingroup lib_core_object
*/
#pragma once
#include <quanta/core/config.hpp>
#include <quanta/core/types.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/memory/memory.hpp>
#include <togo/core/collection/array.hpp>
#include <togo/core/string/string.hpp>
#include <togo/core/hash/hash.hpp>
#include <quanta/core/string/unmanaged_string.hpp>
#include <quanta/core/object/types.hpp>
#include <quanta/core/object/object.gen_interface>
namespace quanta {
namespace object {
/**
@addtogroup lib_core_object
@{
*/
namespace {
static constexpr ObjectValueType const type_mask_numeric
= ObjectValueType::integer
| ObjectValueType::decimal
;
} // anonymous namespace
namespace internal {
inline unsigned get_property(Object const& obj, unsigned mask, unsigned shift) {
return (obj.properties & mask) >> shift;
}
inline void set_property(Object& obj, unsigned mask, unsigned shift, unsigned value) {
obj.properties = (obj.properties & ~mask) | (value << shift);
}
inline void clear_property(Object& obj, unsigned mask) {
obj.properties &= ~mask;
}
} // namespace internal
/// Calculate object name hash of string.
inline ObjectNameHash hash_name(StringRef const& name) {
return hash::calc_generic<ObjectNameHash>(name);
}
/// Value type.
inline ObjectValueType type(Object const& obj) {
return static_cast<ObjectValueType>(internal::get_property(obj, Object::M_TYPE, 0));
}
/// Whether type is type.
inline bool is_type(Object const& obj, ObjectValueType const type) {
return object::type(obj) == type;
}
/// Whether type is any in type.
inline bool is_type_any(Object const& obj, ObjectValueType const type) {
return enum_bool(object::type(obj) & type);
}
/// Whether type is ObjectValueType::null.
inline bool is_null(Object const& obj) { return object::is_type(obj, ObjectValueType::null); }
/// Whether type is ObjectValueType::boolean.
inline bool is_boolean(Object const& obj) { return object::is_type(obj, ObjectValueType::boolean); }
/// Whether type is ObjectValueType::integer.
inline bool is_integer(Object const& obj) { return object::is_type(obj, ObjectValueType::integer); }
/// Whether type is ObjectValueType::decimal.
inline bool is_decimal(Object const& obj) { return object::is_type(obj, ObjectValueType::decimal); }
/// Whether type is ObjectValueType::integer or ObjectValueType::decimal.
inline bool is_numeric(Object const& obj) {
return object::is_type_any(obj, type_mask_numeric);
}
/// Whether type is ObjectValueType::string.
inline bool is_string(Object const& obj) { return object::is_type(obj, ObjectValueType::string); }
/// Name.
inline StringRef name(Object const& obj) {
return obj.name;
}
/// Name hash.
inline ObjectNameHash name_hash(Object const& obj) {
return obj.name.hash;
}
/// Whether name is non-empty.
inline bool is_named(Object const& obj) {
return unmanaged_string::any(obj.name);
}
/// Set name.
inline void set_name(Object& obj, StringRef name) {
unmanaged_string::set(obj.name, name, memory::default_allocator());
}
/// Clear name.
inline void clear_name(Object& obj) {
unmanaged_string::clear(obj.name, memory::default_allocator());
}
/// Source.
inline unsigned source(Object const& obj) {
return obj.source;
}
/// Whether source uncertainty marker is set.
inline bool marker_source_uncertain(Object const& obj) {
return internal::get_property(obj, Object::M_SOURCE_UNCERTAIN, Object::S_SOURCE_UNCERTAIN);
}
/// Sub-source.
inline unsigned sub_source(Object const& obj) {
return obj.sub_source;
}
/// Whether sub-source uncertainty marker is set.
inline bool marker_sub_source_uncertain(Object const& obj) {
return internal::get_property(obj, Object::M_SUB_SOURCE_UNCERTAIN, Object::S_SUB_SOURCE_UNCERTAIN);
}
/// Whether a source is specified.
inline bool has_source(Object const& obj) {
return obj.source != 0;
}
/// Whether a sub-source is specified.
inline bool has_sub_source(Object const& obj) {
return obj.sub_source != 0;
}
/// Whether the source and sub-source are certain.
inline bool source_certain(Object const& obj) {
return object::has_source(obj) && !(obj.properties & Object::M_BOTH_SOURCE_UNCERTAIN);
}
/// Whether the source and sub-source are certain or unspecified.
inline bool source_certain_or_unspecified(Object const& obj) {
return !(obj.properties & Object::M_BOTH_SOURCE_UNCERTAIN);
}
/// Whether the value uncertain marker is set.
inline bool marker_value_uncertain(Object const& obj) {
return internal::get_property(obj, Object::M_VALUE_UNCERTAIN, Object::S_VALUE_UNCERTAIN);
}
/// Whether the value guess marker is set.
inline bool marker_value_guess(Object const& obj) {
return internal::get_property(obj, Object::M_VALUE_GUESS, Object::S_VALUE_GUESS);
}
/// Value approximation marker value.
inline signed value_approximation(Object const& obj) {
unsigned const value = internal::get_property(obj, Object::M_VALUE_APPROXIMATE, Object::S_VALUE_APPROXIMATE);
return (value & (1 << 2)) ? -(signed_cast(value) & 3) : signed_cast(value);
}
/// Whether value is certain.
///
/// If the value guess or uncertainty marker are set or the approximation marker
/// is non-zero, this returns false.
/// If the value is null, the value uncertainty and approximation markers can
/// still be set.
inline bool value_certain(Object const& obj) {
return !(obj.properties & Object::M_VALUE_MARKERS);
}
/// Boolean value.
inline bool boolean(Object const& obj) {
TOGO_ASSERTE(object::is_type(obj, ObjectValueType::boolean));
return obj.value.boolean;
}
/// Integer value.
inline s64 integer(Object const& obj) {
TOGO_ASSERTE(object::is_type(obj, ObjectValueType::integer));
return obj.value.numeric.integer;
}
/// Decimal value.
inline f64 decimal(Object const& obj) {
TOGO_ASSERTE(object::is_type(obj, ObjectValueType::decimal));
return obj.value.numeric.decimal;
}
/// Numeric value unit.
inline StringRef unit(Object const& obj) {
TOGO_ASSERTE(object::is_type_any(obj, type_mask_numeric));
return obj.value.numeric.unit;
}
/// Numeric value unit hash.
inline ObjectNumericUnitHash unit_hash(Object const& obj) {
TOGO_ASSERTE(object::is_type_any(obj, type_mask_numeric));
return obj.value.numeric.unit.hash;
}
/// Whether the numeric value has a unit.
inline bool has_unit(Object const& obj) {
return object::is_type_any(obj, type_mask_numeric) && unmanaged_string::any(obj.value.numeric.unit);
}
/// String value.
inline StringRef string(Object const& obj) {
TOGO_ASSERTE(object::is_type(obj, ObjectValueType::string));
return obj.value.string;
}
/// Clear source and sub-source uncertainty markers.
inline void clear_source_uncertainty(Object& obj) {
internal::clear_property(obj, Object::M_SOURCE_UNCERTAIN | Object::M_SUB_SOURCE_UNCERTAIN);
}
/// Set source certainty marker.
inline void set_source_certain(Object& obj, bool const certain) {
internal::set_property(obj, Object::M_SOURCE_UNCERTAIN, Object::S_SOURCE_UNCERTAIN, !certain);
}
/// Set source.
///
/// If source is 0, sub-source is also set to 0 (same effect as clear_source()).
/// This clears the source uncertainty marker.
inline void set_source(Object& obj, unsigned const source) {
if (source == 0) {
obj.source = 0;
obj.sub_source = 0;
object::clear_source_uncertainty(obj);
} else {
obj.source = static_cast<u16>(min(source, 0xFFFFu));
object::set_source_certain(obj, true);
}
}
/// Set sub-source certainty marker.
inline void set_sub_source_certain(Object& obj, bool const certain) {
internal::set_property(obj, Object::M_SUB_SOURCE_UNCERTAIN, Object::S_SUB_SOURCE_UNCERTAIN, !certain);
}
/// Set sub-source.
///
/// The source must be non-0 for the sub-source to take a non-0 value.
inline void set_sub_source(Object& obj, unsigned const sub_source) {
if (object::has_source(obj)) {
obj.sub_source = static_cast<u16>(min(sub_source, 0xFFFFu));
}
}
/// Clear source and sub-source and their uncertainty markers.
inline void clear_source(Object& obj) {
object::set_source(obj, 0);
object::clear_source_uncertainty(obj);
}
/// Set value certainty.
///
/// This clears the value guess marker.
inline void set_value_certain(Object& obj, bool const certain) {
internal::set_property(obj, Object::M_VALUE_UNCERTAIN_AND_GUESS, Object::S_VALUE_UNCERTAIN, !certain);
}
/// Set value guess marker.
///
/// If the value is null, this has no effect.
/// This clears the value uncertainty marker.
inline void set_value_guess(Object& obj, bool const guess) {
if (object::is_null(obj)) {
internal::set_property(obj, Object::M_VALUE_UNCERTAIN_AND_GUESS, Object::S_VALUE_GUESS, guess);
}
}
/// Set value approximation value.
///
/// value is bound to [-3, 3]. value of:
///
/// - <0 = approximately less than
/// - 0 = absolute
/// - >0 = approximately more than
inline void set_value_approximation(Object& obj, signed const value) {
unsigned property_value = value < 0;
property_value = unsigned_cast(min(property_value ? -value : value, 3)) | (property_value << 2);
internal::set_property(obj, Object::M_VALUE_APPROXIMATE, Object::S_VALUE_APPROXIMATE, property_value);
}
/// Clear value uncertainty, guess, and approximation markers.
inline void clear_value_markers(Object& obj) {
internal::clear_property(obj, Object::M_VALUE_MARKERS);
}
/// Set value to null.
inline void set_null(Object& obj) {
object::set_type(obj, ObjectValueType::null);
}
/// Set boolean value.
inline void set_boolean(Object& obj, bool const value) {
object::set_type(obj, ObjectValueType::boolean);
obj.value.boolean = value;
}
/// Set integer value.
inline void set_integer(Object& obj, s64 const value) {
object::set_type(obj, ObjectValueType::integer);
obj.value.numeric.integer = value;
}
/// Set decimal value.
inline void set_decimal(Object& obj, f64 const value) {
object::set_type(obj, ObjectValueType::decimal);
obj.value.numeric.decimal = value;
}
/// Set numeric value unit.
///
/// Type must be numeric.
inline void set_unit(Object& obj, StringRef const unit) {
TOGO_ASSERTE(object::is_type_any(obj, type_mask_numeric));
unmanaged_string::set(obj.value.numeric.unit, unit, memory::default_allocator());
}
/// Set integer value and unit.
inline void set_integer(Object& obj, s64 const value, StringRef const unit) {
object::set_type(obj, ObjectValueType::integer);
obj.value.numeric.integer = value;
object::set_unit(obj, unit);
}
/// Set decimal value and unit.
inline void set_decimal(Object& obj, f64 const value, StringRef const unit) {
object::set_type(obj, ObjectValueType::decimal);
obj.value.numeric.decimal = value;
object::set_unit(obj, unit);
}
/// Set string value.
inline void set_string(Object& obj, StringRef const value) {
object::set_type(obj, ObjectValueType::string);
unmanaged_string::set(obj.value.string, value, memory::default_allocator());
}
/// Children.
inline Array<Object>& children(Object& obj) { return obj.children; }
inline Array<Object> const& children(Object const& obj) { return obj.children; }
/// Tags.
inline Array<Object>& tags(Object& obj) { return obj.tags; }
inline Array<Object> const& tags(Object const& obj) { return obj.tags; }
/// Quantity.
inline Object* quantity(Object& obj) { return obj.quantity; }
inline Object const* quantity(Object const& obj) { return obj.quantity; }
/// Whether the object has tags.
inline bool has_tags(Object const& obj) {
return array::any(obj.tags);
}
/// Whether the object has children.
inline bool has_children(Object const& obj) {
return array::any(obj.children);
}
/// Whether the object has a quantity.
inline bool has_quantity(Object const& obj) {
return obj.quantity;
}
/// Clear tags.
inline void clear_tags(Object& obj) {
array::clear(obj.tags);
}
/// Clear children.
inline void clear_children(Object& obj) {
array::clear(obj.children);
}
/// Clear quantity.
inline void clear_quantity(Object& obj) {
if (object::has_quantity(obj)) {
object::clear(*obj.quantity);
}
}
/// Release quantity.
inline void release_quantity(Object& obj) {
TOGO_DESTROY(memory::default_allocator(), obj.quantity);
obj.quantity = nullptr;
}
/// Destruct.
inline Object::~Object() {
object::clear_name(*this);
object::set_null(*this);
object::release_quantity(*this);
}
/// Construct null.
inline Object::Object()
: properties(unsigned_cast(ObjectValueType::null))
, source(0)
, sub_source(0)
, name()
, value()
, tags(memory::default_allocator())
, children(memory::default_allocator())
, quantity(nullptr)
{}
/// Construct copy.
inline Object::Object(Object const& other)
: Object()
{
object::copy(*this, other);
}
inline Object& Object::operator=(Object const& other) {
object::copy(*this, other);
return *this;
}
/** @} */ // end of doc-group lib_core_object
} // namespace object
} // namespace quanta
<|endoftext|> |
<commit_before>#include <Interfaces/PacketSocket.h>
namespace nshdev
{
struct LinkAddr: public OriginInfo
{
struct sockaddr_ll addr;
socklen_t length;
};
void dump_ll(struct sockaddr_ll& addr, unsigned length)
{
printf("addr: len=%d %u/%u index %d hatype %u pkttype %u halen %u addr %02x:%02x:%02x:%02x:%02x:%02x\n",
length,
addr.sll_family,
addr.sll_protocol,
addr.sll_ifindex,
addr.sll_hatype,
addr.sll_pkttype,
addr.sll_halen,
addr.sll_addr[0],
addr.sll_addr[1],
addr.sll_addr[2],
addr.sll_addr[3],
addr.sll_addr[4],
addr.sll_addr[5]);
}
PacketSocket::PacketSocket(int ifIndex, uint16_t etherType)
{
// looking for specified Ethertype, with Ethernet header removed.
m_socket = socket(AF_PACKET, SOCK_DGRAM, htons(etherType));
if(m_socket < 0)
{
throw ErrMsg("Couldn't open socket", errno);
}
struct sockaddr_ll bind_addr;
memset(&bind_addr, 0, sizeof(bind_addr));
bind_addr.sll_family = AF_PACKET;
bind_addr.sll_ifindex = ifIndex;
bind_addr.sll_protocol = htons(etherType);
int const bind_result = bind(m_socket, reinterpret_cast<const struct sockaddr*>(&bind_addr), sizeof(bind_addr));
if(bind_result != 0)
{
close(m_socket);
throw ErrMsg("Unable to bind socket", errno);
}
}
PacketSocket::~PacketSocket()
{
close(m_socket);
}
int PacketSocket::GetWaitFD() const
{
return m_socket;
}
void PacketSocket::Run()
{
uint8_t data[2000];
LinkAddr from;
from.length = sizeof(from.addr);
ssize_t read = recvfrom(m_socket, data, sizeof(data),
/* flags */ 0,
reinterpret_cast<struct sockaddr*>(&from.addr),
&from.length);
if(read < 0)
{
throw ErrMsg("Error from recvfrom", errno);
}
printf("Send addr: ");
dump_ll(from.addr, from.length);
if( from.addr.sll_pkttype == PACKET_HOST ) // for us
{
PacketRef pref(data, read, &from);
Forward(pref);
}
}
void PacketSocket::ReturnToSender(PacketRef& packetRef)
{
const LinkAddr& from = static_cast<const LinkAddr&>(*packetRef.From());
struct sockaddr_ll to = from.addr;
printf("Return addr: ");
dump_ll(to, from.length);
// maybe we have to craft the ethernet header too
// REVISIT: prepend to packet
uint8_t new_packet[2000];
memcpy(new_packet, to.sll_addr, 6);
bzero(&new_packet[6], 6);
*reinterpret_cast<uint16_t*>(&new_packet[12]) = to.sll_protocol;
memcpy(&new_packet[14], packetRef.Data(), packetRef.Length());
ssize_t written = sendto(m_socket, new_packet, packetRef.Length()+14, MSG_DONTWAIT,
reinterpret_cast<struct sockaddr*>(&to), from.length);
if(written < 0)
{
fprintf(stderr, "Error %d from sendto (%s)\n", errno, strerror(errno));
}
}
}
<commit_msg>Got sentto() to work by fixing length of address<commit_after>#include <Interfaces/PacketSocket.h>
namespace nshdev
{
struct LinkAddr: public OriginInfo
{
struct sockaddr_ll addr;
socklen_t length;
};
void dump_ll(struct sockaddr_ll& addr, unsigned length)
{
printf("addr: len=%d %u/%u index %d hatype %u pkttype %u halen %u addr %02x:%02x:%02x:%02x:%02x:%02x\n",
length,
addr.sll_family,
addr.sll_protocol,
addr.sll_ifindex,
addr.sll_hatype,
addr.sll_pkttype,
addr.sll_halen,
addr.sll_addr[0],
addr.sll_addr[1],
addr.sll_addr[2],
addr.sll_addr[3],
addr.sll_addr[4],
addr.sll_addr[5]);
}
PacketSocket::PacketSocket(int ifIndex, uint16_t etherType)
{
// looking for specified Ethertype, with Ethernet header removed.
m_socket = socket(AF_PACKET, SOCK_DGRAM, htons(etherType));
if(m_socket < 0)
{
throw ErrMsg("Couldn't open socket", errno);
}
struct sockaddr_ll bind_addr;
memset(&bind_addr, 0, sizeof(bind_addr));
bind_addr.sll_family = AF_PACKET;
bind_addr.sll_ifindex = ifIndex;
bind_addr.sll_protocol = htons(etherType);
int const bind_result = bind(m_socket, reinterpret_cast<const struct sockaddr*>(&bind_addr), sizeof(bind_addr));
if(bind_result != 0)
{
close(m_socket);
throw ErrMsg("Unable to bind socket", errno);
}
}
PacketSocket::~PacketSocket()
{
close(m_socket);
}
int PacketSocket::GetWaitFD() const
{
return m_socket;
}
void PacketSocket::Run()
{
uint8_t data[2000];
LinkAddr from;
from.length = sizeof(from.addr);
ssize_t read = recvfrom(m_socket, data, sizeof(data),
/* flags */ 0,
reinterpret_cast<struct sockaddr*>(&from.addr),
&from.length);
if(read < 0)
{
throw ErrMsg("Error from recvfrom", errno);
}
printf("Send addr: ");
//dump_ll(from.addr, from.length);
if( from.addr.sll_pkttype == PACKET_HOST ) // for us
{
PacketRef pref(data, read, &from);
Forward(pref);
}
}
void PacketSocket::ReturnToSender(PacketRef& packetRef)
{
const LinkAddr& from = static_cast<const LinkAddr&>(*packetRef.From());
struct sockaddr_ll to = from.addr;
printf("Return addr: ");
//dump_ll(to, from.length);
ssize_t written = sendto(m_socket, packetRef.Data(), packetRef.Length(), MSG_DONTWAIT,
reinterpret_cast<struct sockaddr*>(&to), sizeof(to));
if(written < 0)
{
fprintf(stderr, "Error %d from sendto (%s)\n", errno, strerror(errno));
}
}
}
<|endoftext|> |
<commit_before>/*
* fetcher.cpp
*
* Created on: Nov 21, 2012
* Author: partio
*/
#include "fetcher.h"
#include "plugin_factory.h"
#include "logger_factory.h"
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "util.h"
#define HIMAN_AUXILIARY_INCLUDE
#include "grib.h"
#include "neons.h"
#include "param.h"
#include "cache.h"
#include "querydata.h"
#undef HIMAN_AUXILIARY_INCLUDE
using namespace himan::plugin;
using namespace std;
fetcher::fetcher()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("fetcher"));
}
shared_ptr<himan::info> fetcher::Fetch(shared_ptr<const configuration> config,
const forecast_time& requestedTime,
const level& requestedLevel,
const param& requestedParam)
{
const search_options opts { requestedTime, requestedParam, requestedLevel, config } ;
// 1. Fetch data from cache
// FromCache()
// 2. Fetch data from auxiliary files specified at command line
if (config->AuxiliaryFiles().size())
{
vector<shared_ptr<info>> auxInfos = FromFile(config->AuxiliaryFiles(), opts, true);
if (auxInfos.size())
{
itsLogger->Debug("Data found from auxiliary file(s)");
return auxInfos[0];
}
else
{
itsLogger->Warning("Data not found from auxiliary file(s)");
}
}
// 3. Fetch data from Neons
vector<string> files;
if (config->ReadDataFromDatabase())
{
shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons"));
files = n->Files(opts);
}
if (files.empty())
{
itsLogger->Debug("Could not find file(s) from Neons matching requested parameters");
}
vector<shared_ptr<info>> theInfos = FromFile(files, opts, true);
if (theInfos.size() == 0)
{
string optsStr = "producer: " + boost::lexical_cast<string> (config->SourceProducer());
optsStr = " origintime: " + requestedTime.OriginDateTime()->String() + ", step: " + boost::lexical_cast<string> (requestedTime.Step());
optsStr += " param: " + requestedParam.Name();
optsStr += " level: " + string(himan::HPLevelTypeToString.at(requestedLevel.Type())) + " " + boost::lexical_cast<string> (requestedLevel.Value());
itsLogger->Warning("No valid data found with given search options " + optsStr);
throw kFileDataNotFound;
}
/*
* Safeguard; later in the code we do not check whether the data requested
* was actually what was requested.
*/
// assert(theConfiguration->SourceProducer() == theInfos[0]->Producer());
assert((theInfos[0]->Level()) == requestedLevel);
assert((theInfos[0]->Time()) == requestedTime);
assert((theInfos[0]->Param()) == requestedParam);
return theInfos[0];
}
/*
* FromFile()
*
* Get data and metadata from a file. Returns a vector of infos, mainly because one grib file can
* contain many grib messages. If read file is querydata, the vector size is always one (or zero if the
* read fails).
*/
vector<shared_ptr<himan::info>> fetcher::FromFile(const vector<string>& files, const search_options& options, bool readContents)
{
vector<shared_ptr<himan::info>> allInfos ;
for (size_t i = 0; i < files.size(); i++)
{
string inputFile = files[i];
vector<shared_ptr<himan::info>> curInfos;
switch (util::FileType(inputFile))
{
case kGRIB:
case kGRIB1:
case kGRIB2:
{
curInfos = FromGrib(inputFile, options, readContents);
break;
}
case kQueryData:
{
curInfos = FromQueryData(inputFile, options, readContents);
break;
}
case kNetCDF:
cout << "File is NetCDF" << endl;
break;
default:
// Unknown file type, cannot proceed
throw runtime_error("Input file is neither GRID, NetCDF nor QueryData");
break;
}
allInfos.insert(allInfos.end(), curInfos.begin(), curInfos.end());
if (curInfos.size())
{
break; // We found what we were looking for
}
}
return allInfos;
}
vector<shared_ptr<himan::info> > fetcher::FromGrib(const string& inputFile, const search_options& options, bool readContents)
{
shared_ptr<grib> g = dynamic_pointer_cast<grib> (plugin_factory::Instance()->Plugin("grib"));
vector<shared_ptr<info>> infos = g->FromFile(inputFile, options, readContents);
return infos;
}
vector<shared_ptr<himan::info>> fetcher::FromQueryData(const string& inputFile, const search_options& options, bool readContents)
{
shared_ptr<querydata> q = dynamic_pointer_cast<querydata> (plugin_factory::Instance()->Plugin("querydata"));
shared_ptr<info> i = q->FromFile(inputFile, options, readContents);
vector<shared_ptr<info>> theInfos;
theInfos.push_back(i);
return theInfos;
}
<commit_msg>Check if file exists<commit_after>/*
* fetcher.cpp
*
* Created on: Nov 21, 2012
* Author: partio
*/
#include "fetcher.h"
#include "plugin_factory.h"
#include "logger_factory.h"
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem/operations.hpp>
#include "util.h"
#define HIMAN_AUXILIARY_INCLUDE
#include "grib.h"
#include "neons.h"
#include "param.h"
#include "cache.h"
#include "querydata.h"
#undef HIMAN_AUXILIARY_INCLUDE
using namespace himan::plugin;
using namespace std;
fetcher::fetcher()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("fetcher"));
}
shared_ptr<himan::info> fetcher::Fetch(shared_ptr<const configuration> config,
const forecast_time& requestedTime,
const level& requestedLevel,
const param& requestedParam)
{
const search_options opts { requestedTime, requestedParam, requestedLevel, config } ;
// 1. Fetch data from cache
// FromCache()
// 2. Fetch data from auxiliary files specified at command line
if (config->AuxiliaryFiles().size())
{
vector<shared_ptr<info>> auxInfos = FromFile(config->AuxiliaryFiles(), opts, true);
if (auxInfos.size())
{
itsLogger->Debug("Data found from auxiliary file(s)");
return auxInfos[0];
}
else
{
itsLogger->Warning("Data not found from auxiliary file(s)");
}
}
// 3. Fetch data from Neons
vector<string> files;
if (config->ReadDataFromDatabase())
{
shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons"));
files = n->Files(opts);
}
if (files.empty())
{
itsLogger->Debug("Could not find file(s) from Neons matching requested parameters");
}
vector<shared_ptr<info>> theInfos = FromFile(files, opts, true);
if (theInfos.size() == 0)
{
string optsStr = "producer: " + boost::lexical_cast<string> (config->SourceProducer());
optsStr += " origintime: " + requestedTime.OriginDateTime()->String() + ", step: " + boost::lexical_cast<string> (requestedTime.Step());
optsStr += " param: " + requestedParam.Name();
optsStr += " level: " + string(himan::HPLevelTypeToString.at(requestedLevel.Type())) + " " + boost::lexical_cast<string> (requestedLevel.Value());
itsLogger->Warning("No valid data found with given search options " + optsStr);
throw kFileDataNotFound;
}
/*
* Safeguard; later in the code we do not check whether the data requested
* was actually what was requested.
*/
// assert(theConfiguration->SourceProducer() == theInfos[0]->Producer());
assert((theInfos[0]->Level()) == requestedLevel);
assert((theInfos[0]->Time()) == requestedTime);
assert((theInfos[0]->Param()) == requestedParam);
return theInfos[0];
}
/*
* FromFile()
*
* Get data and metadata from a file. Returns a vector of infos, mainly because one grib file can
* contain many grib messages. If read file is querydata, the vector size is always one (or zero if the
* read fails).
*/
vector<shared_ptr<himan::info>> fetcher::FromFile(const vector<string>& files, const search_options& options, bool readContents)
{
vector<shared_ptr<himan::info>> allInfos ;
for (size_t i = 0; i < files.size(); i++)
{
string inputFile = files[i];
if (!boost::filesystem::exists(inputFile))
{
itsLogger->Error("Input file '" + inputFile + "' does not exist");
continue;
}
vector<shared_ptr<himan::info>> curInfos;
switch (util::FileType(inputFile))
{
case kGRIB:
case kGRIB1:
case kGRIB2:
{
curInfos = FromGrib(inputFile, options, readContents);
break;
}
case kQueryData:
{
curInfos = FromQueryData(inputFile, options, readContents);
break;
}
case kNetCDF:
cout << "File is NetCDF" << endl;
break;
default:
// Unknown file type, cannot proceed
throw runtime_error("Input file is neither GRID, NetCDF nor QueryData");
break;
}
allInfos.insert(allInfos.end(), curInfos.begin(), curInfos.end());
if (curInfos.size())
{
break; // We found what we were looking for
}
}
return allInfos;
}
vector<shared_ptr<himan::info> > fetcher::FromGrib(const string& inputFile, const search_options& options, bool readContents)
{
shared_ptr<grib> g = dynamic_pointer_cast<grib> (plugin_factory::Instance()->Plugin("grib"));
vector<shared_ptr<info>> infos = g->FromFile(inputFile, options, readContents);
return infos;
}
vector<shared_ptr<himan::info>> fetcher::FromQueryData(const string& inputFile, const search_options& options, bool readContents)
{
shared_ptr<querydata> q = dynamic_pointer_cast<querydata> (plugin_factory::Instance()->Plugin("querydata"));
shared_ptr<info> i = q->FromFile(inputFile, options, readContents);
vector<shared_ptr<info>> theInfos;
theInfos.push_back(i);
return theInfos;
}
<|endoftext|> |
<commit_before>//
// LutinLangInterperter
// ArgParser.cpp
//
// Created by H4115 on 19/03/2016.
// Copyright (c) 2016 H4115. All rights reserved.
//
#include "ArgParser.h"
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
using namespace std;
using namespace boost::filesystem;
namespace
{
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t SUCCESS = 0;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
} // namespace
ArgParser::ArgParser(int argc, char const *argv[]){
printFlag = false;
executionFlag = false;
staticAnalysisFlag = false;
optimizeFlag = false;
error = true;
filePath = "";
//DiscoverFlags
if(discoverFlags(argc, argv) == SUCCESS) {
//Lets continue
error = false;
}
}
int ArgParser::discoverFlags(const int argc, char const *argv[]) {
try
{
/** Define and parse the program options
*/
string sourceFile;
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Print help messages")
("print,p", "Print code")
("execute,e", "Execute program")
("optimize,o", "Optimize / Transform program")
("analyse,a", "Diagnostic static errors")
("input,i", po::value<std::string>()->required(), "Lutin program, default argument filename");
po::positional_options_description p;
p.add("input", -1);
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
/** --help option
*/
if ( vm.count("help") ) {
std::cout << "Lutin Interpreter App" << std::endl
<< desc << std::endl;
return SUCCESS;
}
if (argc == 1) {
std::cout << "Lutin Interpreter App" << std::endl
<< desc << std::endl;
return ERROR_IN_COMMAND_LINE;
}
if (vm.count("e")) executionFlag = true;
if (vm.count("a")) staticAnalysisFlag = true;
if (vm.count("o")) optimizeFlag = true;
if (vm.count("p")) printFlag = true;
if (vm.count("input")) {
sourceFile = vm["input"].as<std::string>();
path p(sourceFile);
if (exists(p)) {
if (is_regular_file(p))
{
if (p.has_extension() && p.extension() == ".lt") {
filePath = sourceFile;
return SUCCESS;
} else {
cout << "Filename has no extension or wrong one (" << p.extension() << "). Should have .lut extension" << endl;
}
} else {
cout << "Input argument is not a regular file" << endl;
}
} else {
cout << "Input path does not exist" << endl;
}
return ERROR_IN_COMMAND_LINE;
}
po::notify(vm); // throws on error, so do after help in case
// there are any problems
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return ERROR_IN_COMMAND_LINE;
}
// application code here //
}
catch(std::exception& e)
{
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
return ERROR_UNHANDLED_EXCEPTION;
}
bool ArgParser::getPrintFlag() {
return printFlag;
}
bool ArgParser::getExecutionFlag() {
return executionFlag;
}
bool ArgParser::getStaticAnalysisFlag() {
return staticAnalysisFlag;
}
bool ArgParser::getOptimizeFlag() {
return optimizeFlag;
}
bool ArgParser::getError() {
return error;
}
string ArgParser::getFilePath() {
return filePath;
}
ArgParser::~ArgParser() {
}
<commit_msg>fix arg paser<commit_after>//
// LutinLangInterperter
// ArgParser.cpp
//
// Created by H4115 on 19/03/2016.
// Copyright (c) 2016 H4115. All rights reserved.
//
#include "ArgParser.h"
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
using namespace std;
using namespace boost::filesystem;
namespace
{
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t SUCCESS = 0;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
} // namespace
ArgParser::ArgParser(int argc, char const *argv[]){
printFlag = false;
executionFlag = false;
staticAnalysisFlag = false;
optimizeFlag = false;
error = true;
filePath = "";
//DiscoverFlags
if(discoverFlags(argc, argv) == SUCCESS) {
//Lets continue
error = false;
}
}
int ArgParser::discoverFlags(const int argc, char const *argv[]) {
try
{
/** Define and parse the program options
*/
string sourceFile;
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Print help messages")
("print,p", "Print code")
("execute,e", "Execute program")
("optimize,o", "Optimize / Transform program")
("analyse,a", "Diagnostic static errors")
("input,i", po::value<std::string>()->required(), "Lutin program, default argument filename");
po::positional_options_description p;
p.add("input", -1);
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
/** --help option
*/
if ( vm.count("help") ) {
std::cout << "Lutin Interpreter App" << std::endl
<< desc << std::endl;
return SUCCESS;
}
if (argc == 1) {
std::cout << "Lutin Interpreter App" << std::endl
<< desc << std::endl;
return ERROR_IN_COMMAND_LINE;
}
if (vm.count("execute")) executionFlag = true;
if (vm.count("analyse")) staticAnalysisFlag = true;
if (vm.count("optimize")) optimizeFlag = true;
if (vm.count("print")) printFlag = true;
if (vm.count("input")) {
sourceFile = vm["input"].as<std::string>();
path p(sourceFile);
if (exists(p)) {
if (is_regular_file(p))
{
if (p.has_extension() && p.extension() == ".lt") {
filePath = sourceFile;
return SUCCESS;
} else {
cout << "Filename has no extension or wrong one (" << p.extension() << "). Should have .lut extension" << endl;
}
} else {
cout << "Input argument is not a regular file" << endl;
}
} else {
cout << "Input path does not exist" << endl;
}
return ERROR_IN_COMMAND_LINE;
}
po::notify(vm); // throws on error, so do after help in case
// there are any problems
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return ERROR_IN_COMMAND_LINE;
}
// application code here //
}
catch(std::exception& e)
{
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
return ERROR_UNHANDLED_EXCEPTION;
}
bool ArgParser::getPrintFlag() {
return printFlag;
}
bool ArgParser::getExecutionFlag() {
return executionFlag;
}
bool ArgParser::getStaticAnalysisFlag() {
return staticAnalysisFlag;
}
bool ArgParser::getOptimizeFlag() {
return optimizeFlag;
}
bool ArgParser::getError() {
return error;
}
string ArgParser::getFilePath() {
return filePath;
}
ArgParser::~ArgParser() {
}
<|endoftext|> |
<commit_before>#include <node.h>
#include <nan.h>
extern "C" {
#include "libkeccak/KeccakSponge.h"
}
class KeccakWrapper : public Nan::ObjectWrap {
public:
static v8::Local<v8::Function> GetConstructor () {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("KeccakWrapper").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "initialize", Initialize);
Nan::SetPrototypeMethod(tpl, "absorb", Absorb);
Nan::SetPrototypeMethod(tpl, "absorbLastFewBits", AbsorbLastFewBits);
Nan::SetPrototypeMethod(tpl, "squeeze", Squeeze);
Nan::SetPrototypeMethod(tpl, "copy", Copy);
return Nan::GetFunction(tpl).ToLocalChecked();
}
private:
KeccakWidth1600_SpongeInstance sponge;
static NAN_METHOD(New) {
KeccakWrapper* obj = new KeccakWrapper();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
static NAN_METHOD(Initialize) {
KeccakWrapper* obj = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info.Holder());
unsigned int rate = info[0]->IntegerValue();
unsigned int capacity = info[1]->IntegerValue();
// ignore return code, rate & capacity always will right because internal object
KeccakWidth1600_SpongeInitialize(&obj->sponge, rate, capacity);
}
static NAN_METHOD(Absorb) {
KeccakWrapper* obj = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info.Holder());
v8::Local<v8::Object> buffer = info[0].As<v8::Object>();
const unsigned char* data = (const unsigned char*) node::Buffer::Data(buffer);
size_t length = node::Buffer::Length(buffer);
// ignore return code, bcause internal object
KeccakWidth1600_SpongeAbsorb(&obj->sponge, data, length);
}
static NAN_METHOD(AbsorbLastFewBits) {
KeccakWrapper* obj = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info.Holder());
unsigned char bits = info[0]->IntegerValue();
// ignore return code, bcause internal object
KeccakWidth1600_SpongeAbsorbLastFewBits(&obj->sponge, bits);
}
static NAN_METHOD(Squeeze) {
KeccakWrapper* obj = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info.Holder());
size_t length = info[0]->IntegerValue();
v8::Local<v8::Object> buffer = Nan::NewBuffer(length).ToLocalChecked();
unsigned char* data = (unsigned char*) node::Buffer::Data(buffer);
KeccakWidth1600_SpongeSqueeze(&obj->sponge, data, length);
info.GetReturnValue().Set(buffer);
}
static NAN_METHOD(Copy) {
KeccakWrapper* from = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info.Holder());
KeccakWrapper* to = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info[0].As<v8::Object>());
memcpy(&to->sponge, &from->sponge, sizeof(KeccakWidth1600_SpongeInstance));
}
};
NAN_MODULE_INIT(Init) {
// I wish to use pure functions, but we need wrapper around state
v8::Local<v8::Function> KeccakConstructor = KeccakWrapper::GetConstructor();
Nan::Set(target, Nan::New("Keccak").ToLocalChecked(), KeccakConstructor);
}
NODE_MODULE(keccak, Init)
<commit_msg>Small improvements in addon code<commit_after>#include <node.h>
#include <nan.h>
extern "C" {
#include "libkeccak/KeccakSponge.h"
}
class KeccakWrapper : public Nan::ObjectWrap {
public:
static v8::Local<v8::Function> Init () {
Nan::EscapableHandleScope scope;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("KeccakWrapper").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "initialize", Initialize);
Nan::SetPrototypeMethod(tpl, "absorb", Absorb);
Nan::SetPrototypeMethod(tpl, "absorbLastFewBits", AbsorbLastFewBits);
Nan::SetPrototypeMethod(tpl, "squeeze", Squeeze);
Nan::SetPrototypeMethod(tpl, "copy", Copy);
return scope.Escape(Nan::GetFunction(tpl).ToLocalChecked());
}
private:
KeccakWidth1600_SpongeInstance sponge;
static NAN_METHOD(New) {
KeccakWrapper* obj = new KeccakWrapper();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
static NAN_METHOD(Initialize) {
KeccakWrapper* obj = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info.Holder());
unsigned int rate = info[0]->IntegerValue();
unsigned int capacity = info[1]->IntegerValue();
// ignore return code, rate & capacity always will right because internal object
KeccakWidth1600_SpongeInitialize(&obj->sponge, rate, capacity);
}
static NAN_METHOD(Absorb) {
KeccakWrapper* obj = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info.Holder());
v8::Local<v8::Object> buffer = info[0].As<v8::Object>();
const unsigned char* data = (const unsigned char*) node::Buffer::Data(buffer);
size_t length = node::Buffer::Length(buffer);
// ignore return code, bcause internal object
KeccakWidth1600_SpongeAbsorb(&obj->sponge, data, length);
}
static NAN_METHOD(AbsorbLastFewBits) {
KeccakWrapper* obj = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info.Holder());
unsigned char bits = info[0]->IntegerValue();
// ignore return code, bcause internal object
KeccakWidth1600_SpongeAbsorbLastFewBits(&obj->sponge, bits);
}
static NAN_METHOD(Squeeze) {
KeccakWrapper* obj = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info.Holder());
size_t length = info[0]->IntegerValue();
v8::Local<v8::Object> buffer = Nan::NewBuffer(length).ToLocalChecked();
unsigned char* data = (unsigned char*) node::Buffer::Data(buffer);
KeccakWidth1600_SpongeSqueeze(&obj->sponge, data, length);
info.GetReturnValue().Set(buffer);
}
static NAN_METHOD(Copy) {
KeccakWrapper* from = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info.Holder());
KeccakWrapper* to = Nan::ObjectWrap::Unwrap<KeccakWrapper>(info[0]->ToObject());
memcpy(&to->sponge, &from->sponge, sizeof(KeccakWidth1600_SpongeInstance));
}
};
NAN_MODULE_INIT(Init) {
// I wish to use pure functions, but we need wrapper around state
Nan::Set(target, Nan::New("Keccak").ToLocalChecked(), KeccakWrapper::Init());
}
NODE_MODULE(keccak, Init)
<|endoftext|> |
<commit_before>#include<iostream<
using namespace std;
int main(){
cout<<"Hello world"<<endl;
}
<commit_msg>Fix: 2021-10-28<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: launcher.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2007-05-09 13:24:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#define UNICODE
#include "launcher.hxx"
#ifndef _WINDOWS_
# define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
# include <windows.h>
# include <shellapi.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif
#include <stdlib.h>
#include <malloc.h>
extern "C" int APIENTRY _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int )
{
// Retreive startup info
STARTUPINFO aStartupInfo;
ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) );
aStartupInfo.cb = sizeof( aStartupInfo );
GetStartupInfo( &aStartupInfo );
// Retrieve command line
LPTSTR lpCommandLine = GetCommandLine();
LPTSTR *ppArguments = NULL;
int nArguments = 0;
ppArguments = GetArgv( &nArguments );
// if ( 1 == nArguments )
{
lpCommandLine = (LPTSTR)_alloca( sizeof(_TCHAR) * (_tcslen(lpCommandLine) + _tcslen(APPLICATION_SWITCH) + 2) );
_tcscpy( lpCommandLine, GetCommandLine() );
_tcscat( lpCommandLine, _T(" ") );
_tcscat( lpCommandLine, APPLICATION_SWITCH );
}
// Calculate application name
TCHAR szApplicationName[MAX_PATH];
TCHAR szDrive[MAX_PATH];
TCHAR szDir[MAX_PATH];
TCHAR szFileName[MAX_PATH];
TCHAR szExt[MAX_PATH];
GetModuleFileName( NULL, szApplicationName, MAX_PATH );
_tsplitpath( szApplicationName, szDrive, szDir, szFileName, szExt );
_tmakepath( szApplicationName, szDrive, szDir, OFFICE_IMAGE_NAME, _T(".exe") );
PROCESS_INFORMATION aProcessInfo;
BOOL fSuccess = CreateProcess(
szApplicationName,
lpCommandLine,
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&aStartupInfo,
&aProcessInfo );
if ( fSuccess )
{
CloseHandle( aProcessInfo.hProcess );
CloseHandle( aProcessInfo.hThread );
return 0;
}
DWORD dwError = GetLastError();
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR)&lpMsgBuf,
0,
NULL
);
// Display the string.
MessageBox( NULL, (LPCTSTR)lpMsgBuf, NULL, MB_OK | MB_ICONERROR );
// Free the buffer.
LocalFree( lpMsgBuf );
return GetLastError();
}
<commit_msg>INTEGRATION: CWS ause079 (1.6.4); FILE MERGED 2007/06/11 15:11:43 hjs 1.6.4.1: #i77339# move UNICODE define from source to makefile<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: launcher.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-06-27 17:55:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "launcher.hxx"
#ifndef _WINDOWS_
# define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
# include <windows.h>
# include <shellapi.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif
#include <stdlib.h>
#include <malloc.h>
extern "C" int APIENTRY _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int )
{
// Retreive startup info
STARTUPINFO aStartupInfo;
ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) );
aStartupInfo.cb = sizeof( aStartupInfo );
GetStartupInfo( &aStartupInfo );
// Retrieve command line
LPTSTR lpCommandLine = GetCommandLine();
LPTSTR *ppArguments = NULL;
int nArguments = 0;
ppArguments = GetArgv( &nArguments );
// if ( 1 == nArguments )
{
lpCommandLine = (LPTSTR)_alloca( sizeof(_TCHAR) * (_tcslen(lpCommandLine) + _tcslen(APPLICATION_SWITCH) + 2) );
_tcscpy( lpCommandLine, GetCommandLine() );
_tcscat( lpCommandLine, _T(" ") );
_tcscat( lpCommandLine, APPLICATION_SWITCH );
}
// Calculate application name
TCHAR szApplicationName[MAX_PATH];
TCHAR szDrive[MAX_PATH];
TCHAR szDir[MAX_PATH];
TCHAR szFileName[MAX_PATH];
TCHAR szExt[MAX_PATH];
GetModuleFileName( NULL, szApplicationName, MAX_PATH );
_tsplitpath( szApplicationName, szDrive, szDir, szFileName, szExt );
_tmakepath( szApplicationName, szDrive, szDir, OFFICE_IMAGE_NAME, _T(".exe") );
PROCESS_INFORMATION aProcessInfo;
BOOL fSuccess = CreateProcess(
szApplicationName,
lpCommandLine,
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&aStartupInfo,
&aProcessInfo );
if ( fSuccess )
{
CloseHandle( aProcessInfo.hProcess );
CloseHandle( aProcessInfo.hThread );
return 0;
}
DWORD dwError = GetLastError();
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR)&lpMsgBuf,
0,
NULL
);
// Display the string.
MessageBox( NULL, (LPCTSTR)lpMsgBuf, NULL, MB_OK | MB_ICONERROR );
// Free the buffer.
LocalFree( lpMsgBuf );
return GetLastError();
}
<|endoftext|> |
<commit_before>#include <regex>
#include <map>
#include <cstdint>
#include <cstdio>
#include <bitset>
#include "Assembler.hpp"
#include "Assembly.hpp"
using namespace std;
const int Assembler::RS = 0;
const int Assembler::RT = 1;
const int Assembler::RD = 2;
Assembler::Assembler() {
}
Assembler::Assembler(const vector<string> &instOriginal) {
this->instOriginal = instOriginal;
const static regex rTypeExp ("(addu|add|subu|sub|and|or|xor|nor|sltu|slt|sllv|srlv|srav|sll|srl|sra|jr)\\b");
const static regex iTypeExp ("(addiu|addi|andi|ori|xori|lui|lw|sw|beq|bne|sltiu|slti)\\b");
const static regex jTypeExp ("(jal|j)\\b");
const static regex operandExp ("\\$(\\w+),\\s*\\$(\\w+),\\s*\\$(\\w+)");
const static map<string, int> funcMap = {
{"addu", 0b100001},
{"add", 0b100000},
{"sub", 0b100010},
{"subu", 0b100011},
{"and", 0b100100},
{"or", 0b100101},
{"xor", 0b100110},
{"nor", 0b100111},
{"slt", 0b101010},
{"sltu", 0b101011},
{"sll", 0b000000},
{"srl", 0b000010},
{"sra", 0b000011},
{"sllv", 0b000100},
{"srlv", 0b000110},
{"srav", 0b000111},
{"jr", 0b001000}
};
for (auto inst: this->instOriginal) {
uint32_t opcode, rs, rt, rd, shamt, func;
smatch match;
if (regex_search(inst, match, rTypeExp)) {
opcode = 0b000000;
string funcName = match[0];
string rsName, rtName, rdName;
smatch operands;
if (regex_search(inst, operands, operandExp)) {
rsName = operands[1];
rtName = operands[2];
rdName = operands[3];
rs = getOperand(rsName);
rt = getOperand(rtName);
rd = getOperand(rdName);
func = funcMap.at(funcName);
shamt = 0;
uint32_t instruction = opcode;
instruction = (instruction << 5) | rs;
instruction = (instruction << 5) | rt;
instruction = (instruction << 5) | rd;
instruction = (instruction << 5) | shamt;
instruction = (instruction << 6) | func;
instAssembled.push_back(Assembly(instruction));
} else {
cout << "Syntax error with statement:" << endl;
cout << inst << endl;
}
}
}
}
vector<Assembly> Assembler::getInstAssembled() {
return instAssembled;
}
uint32_t Assembler::getOperand(string &operandName) {
const static string regNames[] = {
"zero", "at",
"v0", "v1", "a0", "a1", "a2", "a3",
"t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7",
"s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
"t8", "t9",
"k0", "k1",
"gp", "sp", "fp", "ra"
};
for (int i = 0; i < 32; ++i) {
if (regNames[i] == operandName) return i;
}
cout << "Unrecongnized reg:" << operandName << endl;
return -1;
}
ostream &operator<< (ostream &os, const Assembler &assembler) {
for (auto inst: assembler.instAssembled) {
os << inst << endl;
}
return os;
}
<commit_msg>Add Shift type assembly && fix rtype assembly<commit_after>#include <regex>
#include <map>
#include <cstdint>
#include <cstdio>
#include <bitset>
#include <string>
#include "Assembler.hpp"
#include "Assembly.hpp"
using namespace std;
const int Assembler::RS = 0;
const int Assembler::RT = 1;
const int Assembler::RD = 2;
Assembler::Assembler() {
}
Assembler::Assembler(const vector<string> &instOriginal) {
this->instOriginal = instOriginal;
const static regex rTypeExp ("(addu|add|subu|sub|and|or|xor|nor|sltu|slt|sllv|srlv|srav|jr)\\b");
const static regex shiftTypeExp ("(sll|srl|sra)\\b");
const static regex iTypeExp ("(addiu|addi|andi|ori|xori|lui|lw|sw|beq|bne|sltiu|slti)\\b");
const static regex jTypeExp ("(jal|j)\\b");
const static regex operandExp ("\\$(\\w+),\\s*\\$(\\w+),\\s*\\$(\\w+)");
const static regex operandWithImmExp ("\\$(\\w+),\\s*\\$(\\w+),\\s*(\\d+)");
const static map<string, int> funcMap = {
{"addu", 0b100001},
{"add", 0b100000},
{"sub", 0b100010},
{"subu", 0b100011},
{"and", 0b100100},
{"or", 0b100101},
{"xor", 0b100110},
{"nor", 0b100111},
{"slt", 0b101010},
{"sltu", 0b101011},
{"sll", 0b000000},
{"srl", 0b000010},
{"sra", 0b000011},
{"sllv", 0b000100},
{"srlv", 0b000110},
{"srav", 0b000111},
{"jr", 0b001000}
};
for (auto inst: this->instOriginal) {
uint32_t opcode, rs, rt, rd, shamt, func;
smatch match;
if (regex_search(inst, match, rTypeExp)) {
opcode = 0b000000;
string funcName = match[0];
string rsName, rtName, rdName;
smatch operands;
if (regex_search(inst, operands, operandExp)) {
rsName = operands[2];
rtName = operands[3];
rdName = operands[1];
rs = getOperand(rsName);
rt = getOperand(rtName);
rd = getOperand(rdName);
shamt = 0;
func = funcMap.at(funcName);
} else {
cout << "Syntax error with statement:" << endl;
cout << inst << endl;
}
} else if (regex_search(inst, match, shiftTypeExp)) {
opcode = 0b000000;
string funcName = match[0];
string rtName, rdName, immName;
smatch operandWithImm;
if (regex_search(inst, operandWithImm, operandWithImmExp)) {
rdName = operandWithImm[2];
rtName = operandWithImm[1];
immName = operandWithImm[3];
rs = 0b00000;
rd = getOperand(rdName);
rt = getOperand(rtName);
shamt = stoul(immName);
func = funcMap.at(funcName);
} else {
cout << "Syntax error with statement:" << endl;
cout << inst << endl;
}
}
uint32_t instruction = opcode;
instruction = (instruction << 5) | rs;
instruction = (instruction << 5) | rt;
instruction = (instruction << 5) | rd;
instruction = (instruction << 5) | shamt;
instruction = (instruction << 6) | func;
instAssembled.push_back(Assembly(instruction));
}
}
vector<Assembly> Assembler::getInstAssembled() {
return instAssembled;
}
uint32_t Assembler::getOperand(string &operandName) {
const static string regNames[] = {
"zero", "at",
"v0", "v1", "a0", "a1", "a2", "a3",
"t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7",
"s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
"t8", "t9",
"k0", "k1",
"gp", "sp", "fp", "ra"
};
for (int i = 0; i < 32; ++i) {
if (regNames[i] == operandName) return i;
}
cout << "Unrecongnized reg:" << operandName << endl;
return -1;
}
ostream &operator<< (ostream &os, const Assembler &assembler) {
for (auto inst: assembler.instAssembled) {
os << inst << endl;
}
return os;
}
<|endoftext|> |
<commit_before>//
// NSolver::apply_laplacian_continuation.cpp
//
// Created by Lei Qiao on 15/11/5.
// A work based on deal.II tutorial step-33.
//
#include <NSolver/solver/NSolver.h>
namespace NSFEMSolver
{
using namespace dealii;
template <int dim>
void
NSolver<dim>::apply_laplacian_continuation()
{
typedef Sacado::Fad::DFad<double> DFADD;
// Apply the laplacian operator
const unsigned int dofs_per_cell = dof_handler.get_fe().dofs_per_cell;
const unsigned int n_q_points = quadrature.size();
std::vector<types::global_dof_index> dof_indices (dofs_per_cell);
const UpdateFlags update_flags = update_values
| update_gradients
| update_quadrature_points
| update_JxW_values;
FEValues<dim> fe_v (*mapping_ptr, fe, quadrature, update_flags);
std::vector<std::vector<Tensor<1,dim> > > grad_W (n_q_points,
std::vector<Tensor<1,dim> > (EquationComponents<dim>::n_components));
unsigned int n_laplacian = 0;
typename DoFHandler<dim>::active_cell_iterator
cell = dof_handler.begin_active(),
endc = dof_handler.end();
for (; cell!=endc; ++cell)
if (cell->is_locally_owned())
{
const bool use_laplacian =
n_time_step == 0 ||
laplacian_indicator[cell->active_cell_index()] >= laplacian_threshold;
n_laplacian += use_laplacian;
const double factor = use_laplacian
? 1.0
: 0.01;
fe_v.reinit (cell);
cell->get_dof_indices (dof_indices);
fe_v.get_function_gradients (current_solution, grad_W);
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
double residual = 0.0;
const unsigned int c = fe_v.get_fe().system_to_component_index (i).first;
for (unsigned int q=0; q<n_q_points; ++q)
{
residual += laplacian_coefficient * factor *
(grad_W[q][c] *
fe_v.shape_grad_component (i, q, c)) *
fe_v.JxW (q);
}
std::vector<double> matrix_row (dofs_per_cell, 0.0);
for (unsigned int j=0; j<dofs_per_cell; ++j)
{
if (c == fe_v.get_fe().system_to_component_index (j).first)
{
for (unsigned int q=0; q<n_q_points; ++q)
{
matrix_row[j] += laplacian_coefficient * factor *
(fe_v.shape_grad_component (j, q, c)
* fe_v.shape_grad_component (i, q, c)) *
fe_v.JxW (q);
}
}
}
system_matrix.add (dof_indices[i], dof_indices.size(),
& (dof_indices[0]), & (matrix_row[0]));
right_hand_side (dof_indices[i]) -= residual;
}
}
pcout << "n_laplacian = "
<< Utilities::MPI::sum (n_laplacian, mpi_communicator)
<< std::endl;
return;
}
#include "NSolver.inst"
}
<commit_msg>change laplacian ratio factor in smooth region to 0.1<commit_after>//
// NSolver::apply_laplacian_continuation.cpp
//
// Created by Lei Qiao on 15/11/5.
// A work based on deal.II tutorial step-33.
//
#include <NSolver/solver/NSolver.h>
namespace NSFEMSolver
{
using namespace dealii;
template <int dim>
void
NSolver<dim>::apply_laplacian_continuation()
{
typedef Sacado::Fad::DFad<double> DFADD;
// Apply the laplacian operator
const unsigned int dofs_per_cell = dof_handler.get_fe().dofs_per_cell;
const unsigned int n_q_points = quadrature.size();
std::vector<types::global_dof_index> dof_indices (dofs_per_cell);
const UpdateFlags update_flags = update_values
| update_gradients
| update_quadrature_points
| update_JxW_values;
FEValues<dim> fe_v (*mapping_ptr, fe, quadrature, update_flags);
std::vector<std::vector<Tensor<1,dim> > > grad_W (n_q_points,
std::vector<Tensor<1,dim> > (EquationComponents<dim>::n_components));
unsigned int n_laplacian = 0;
typename DoFHandler<dim>::active_cell_iterator
cell = dof_handler.begin_active(),
endc = dof_handler.end();
for (; cell!=endc; ++cell)
if (cell->is_locally_owned())
{
const bool use_laplacian =
n_time_step == 0 ||
laplacian_indicator[cell->active_cell_index()] >= laplacian_threshold;
n_laplacian += use_laplacian;
const double factor = use_laplacian
? 1.0
: 0.1;
fe_v.reinit (cell);
cell->get_dof_indices (dof_indices);
fe_v.get_function_gradients (current_solution, grad_W);
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
double residual = 0.0;
const unsigned int c = fe_v.get_fe().system_to_component_index (i).first;
for (unsigned int q=0; q<n_q_points; ++q)
{
residual += laplacian_coefficient * factor *
(grad_W[q][c] *
fe_v.shape_grad_component (i, q, c)) *
fe_v.JxW (q);
}
std::vector<double> matrix_row (dofs_per_cell, 0.0);
for (unsigned int j=0; j<dofs_per_cell; ++j)
{
if (c == fe_v.get_fe().system_to_component_index (j).first)
{
for (unsigned int q=0; q<n_q_points; ++q)
{
matrix_row[j] += laplacian_coefficient * factor *
(fe_v.shape_grad_component (j, q, c)
* fe_v.shape_grad_component (i, q, c)) *
fe_v.JxW (q);
}
}
}
system_matrix.add (dof_indices[i], dof_indices.size(),
& (dof_indices[0]), & (matrix_row[0]));
right_hand_side (dof_indices[i]) -= residual;
}
}
pcout << "n_laplacian = "
<< Utilities::MPI::sum (n_laplacian, mpi_communicator)
<< std::endl;
return;
}
#include "NSolver.inst"
}
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetScopeLoader.cpp
* @brief Module for oscilloscope data
* Reads oscilloscope ASCII data and procudes JPetRecoSignal structures.
*/
#include "./JPetScopeLoader.h"
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#include <TSystem.h>
#include "JPetCommonTools/JPetCommonTools.h"
#include "JPetScopeConfigParser/JPetScopeConfigParser.h"
#include "JPetOptionsGenerator/JPetOptionsGeneratorTools.h"
#include "JPetScopeData/JPetScopeData.h"
using namespace std;
using namespace boost::filesystem;
using boost::property_tree::ptree;
JPetScopeLoader::JPetScopeLoader(std::unique_ptr<JPetScopeTask> task): JPetTaskIO("ScopeTask", "", "reco.sig")
{
addSubTask(std::move(task));
gSystem->Load("libTree");
}
JPetScopeLoader::~JPetScopeLoader()
{
if (fWriter != nullptr) {
delete fWriter;
fWriter = nullptr;
}
}
void JPetScopeLoader::addSubTask(std::unique_ptr<JPetTaskInterface> subTask)
{
if (dynamic_cast<JPetScopeTask*>(subTask.get()) == nullptr)
ERROR("JPetScopeLoader currently allows only JPetScopeTask as subtask");
if (fSubTasks.size() > 0)
ERROR("JPetScopeLoader currently allows only one subtask");
fSubTasks.push_back(std::move(subTask));
}
bool JPetScopeLoader::createInputObjects(const char*)
{
using namespace jpet_options_tools;
auto opts = fParams.getOptions();
for (auto fSubTask = fSubTasks.begin(); fSubTask != fSubTasks.end(); fSubTask++) {
auto task = dynamic_cast<JPetScopeTask*>((*fSubTask).get());
std::unique_ptr<JPetStatistics> tmp(new JPetStatistics());
fStatistics = std::move(tmp);
assert(fStatistics);
fHeader = new JPetTreeHeader(getRunNumber(opts));
assert(fHeader);
fHeader->setBaseFileName(getInputFile(opts));
fHeader->addStageInfo(task->getName(), "", 0, JPetCommonTools::getTimeString());
}
return true;
}
std::map<std::string, int> JPetScopeLoader::getPMPrefixToPMIdMap()
{
std::map< std::string, int> prefixToId;
for (const auto& pm : getParamBank().getPMs()) {
prefixToId[pm.second->getDescription()] = pm.first;
}
return prefixToId;
}
/// Returns a map of list of scope input files. The value is the corresponding
/// index of the photomultiplier in the param bank.
std::map<std::string, int> JPetScopeLoader::createInputScopeFileNames(
const std::string& inputPathToScopeFiles,
std::map<std::string, int> pmPref2Id
) const
{
std::map<std::string, int> scopeFiles;
path current_dir(inputPathToScopeFiles);
if (exists(current_dir)) {
for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) {
std::string filename = iter->path().leaf().string();
if (isCorrectScopeFileName(filename)) {
auto prefix = getFilePrefix(filename);
if ( pmPref2Id.find(prefix) != pmPref2Id.end()) {
int id = pmPref2Id.find(prefix)->second;
scopeFiles[iter->path().parent_path().string() + "/" + filename] = id;
} else {
WARNING("The filename does not contain the accepted prefix:" + filename);
}
}
}
} else {
string msg = "Directory: \"";
msg += current_dir.string();
msg += "\" does not exist.";
ERROR(msg.c_str());
}
return scopeFiles;
}
std::string JPetScopeLoader::getFilePrefix(const std::string& filename) const
{
auto pos = filename.find("_");
if (pos != string::npos) {
return filename.substr(0, pos);
}
return "";
}
/// not very effective, but at least we can test it
bool JPetScopeLoader::isCorrectScopeFileName(const std::string& filename) const
{
boost::regex pattern("^[A-Za-z0-9]+_\\d*.txt");
return regex_match(filename, pattern);
}
bool JPetScopeLoader::init(const JPetParamsInterface& paramsI)
{
using namespace jpet_options_tools;
INFO( "Initialize Scope Loader Module." );
JPetTaskIO::init(paramsI);
DEBUG( "After initialization of the JPetTaskIO in Scope Loader init." );
return true;
}
bool JPetScopeLoader::run(const JPetDataInterface& inData)
{
assert(!fSubTasks.empty());
if (fSubTasks.size() != 1) {
ERROR("number of subtasks !=1");
return false;
}
auto subTask = fSubTasks.begin()->get();
subTask->init(fParams);
using namespace jpet_options_tools;
JPetScopeConfigParser confParser;
auto opts = fParams.getOptions();
auto config = confParser.getConfig(getScopeConfigFile(opts));
auto prefix2PM = getPMPrefixToPMIdMap();
auto inputScopeFiles = createInputScopeFileNames(getScopeInputDirectory(opts), prefix2PM);
auto events = JPetScopeLoader::groupScopeFileNamesByTimeWindowIndex(inputScopeFiles);
for (auto& ev : events) {
auto pOutputEvent = (dynamic_cast<JPetUserTask*>(subTask))->getOutputEvents();
if (pOutputEvent != nullptr) {
pOutputEvent->Clear();
} else {
WARNING("No proper timeWindow object returned to clear events");
}
JPetScopeData data(ev);
subTask->run(data);
pOutputEvent = (dynamic_cast<JPetUserTask*>(subTask))->getOutputEvents();
if (pOutputEvent != nullptr) {
fWriter->write(*pOutputEvent);
} else {
ERROR("No proper timeWindow object returned to save to file, returning from subtask " + subTask->getName());
return false;
}
}
subTask->terminate(fParams);
return true;
}
bool JPetScopeLoader::terminate(JPetParamsInterface& output_params)
{
auto& params = dynamic_cast<JPetParams&>(output_params);
OptsStrAny new_opts;
jpet_options_generator_tools::setOutputFile(new_opts, fOutFileFullPath);
params = JPetParams(new_opts, params.getParamManagerAsShared());
assert(fWriter);
assert(fHeader);
assert(fStatistics);
fWriter->writeHeader(fHeader);
fWriter->writeCollection(fStatistics->getStatsTable(), "Stats");
//store the parametric objects in the ouptut ROOT file
getParamManager().saveParametersToFile(fWriter);
getParamManager().clearParameters();
fWriter->closeFile();
return true;
}
bool JPetScopeLoader::createOutputObjects(const char* outputFilename)
{
fWriter = new JPetWriter( outputFilename );
assert(fWriter);
if (!fSubTasks.empty()) {
for (auto fSubTask = fSubTasks.begin(); fSubTask != fSubTasks.end(); fSubTask++) {
auto task = dynamic_cast<JPetScopeTask*>((*fSubTask).get());
task->setStatistics(fStatistics.get());
}
} else {
WARNING("the subTask does not exist, so JPetWriter and JPetStatistics not passed to it");
return false;
}
return true;
}
std::tuple<bool, std::string, std::string, bool> JPetScopeLoader::setInputAndOutputFile(const jpet_options_tools::OptsStrAny opts) const
{
using namespace jpet_options_tools;
bool resetOutputPath = fResetOutputPath;
std::string inputFilename = getInputFile(opts);
/// this argument is not really used by the ScopeLoader since inputFiles are generated
/// based on json content
inputFilename = inputFilename + "." + fOutFileType + ".root";
auto outFileFullPath = inputFilename;
if (isOptionSet(opts, "outputPath_std::string")) {
std::string outputPath(getOutputPath(opts));
if (!outputPath.empty()) {
outFileFullPath = outputPath + JPetCommonTools::extractFileNameFromFullPath(inputFilename);
resetOutputPath = true;
}
}
return std::make_tuple(true, inputFilename, outFileFullPath, resetOutputPath);
}
int JPetScopeLoader::getTimeWindowIndex(const std::string& pathAndFileName)
{
int time_window_index = -1;
if (!boost::filesystem::exists(pathAndFileName)) {
ERROR("File does not exist ");
}
int res = sscanf(JPetCommonTools::extractFileNameFromFullPath(pathAndFileName).c_str(), "%*3s %d", &time_window_index);
if (res <= 0) {
ERROR("scanf failed");
return -1;
} else {
return time_window_index;
}
}
std::map<int, std::map<std::string, int>> JPetScopeLoader::groupScopeFileNamesByTimeWindowIndex(const std::map<std::string, int>& scopeFileNames)
{
std::map<int, std::map<std::string, int>> res;
for (auto& el : scopeFileNames) {
auto index = JPetScopeLoader::getTimeWindowIndex(el.first);
auto it = res.find(index);
if (it == res.end() ) {
res[index] = {{el.first, el.second}};
} else {
it->second.insert(el);
}
}
return res;
}
<commit_msg>Remove unused parameter from JPetScopeLoader to get rid of the warning<commit_after>/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetScopeLoader.cpp
* @brief Module for oscilloscope data
* Reads oscilloscope ASCII data and procudes JPetRecoSignal structures.
*/
#include "./JPetScopeLoader.h"
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#include <TSystem.h>
#include "JPetCommonTools/JPetCommonTools.h"
#include "JPetScopeConfigParser/JPetScopeConfigParser.h"
#include "JPetOptionsGenerator/JPetOptionsGeneratorTools.h"
#include "JPetScopeData/JPetScopeData.h"
using namespace std;
using namespace boost::filesystem;
using boost::property_tree::ptree;
JPetScopeLoader::JPetScopeLoader(std::unique_ptr<JPetScopeTask> task): JPetTaskIO("ScopeTask", "", "reco.sig")
{
addSubTask(std::move(task));
gSystem->Load("libTree");
}
JPetScopeLoader::~JPetScopeLoader()
{
if (fWriter != nullptr) {
delete fWriter;
fWriter = nullptr;
}
}
void JPetScopeLoader::addSubTask(std::unique_ptr<JPetTaskInterface> subTask)
{
if (dynamic_cast<JPetScopeTask*>(subTask.get()) == nullptr)
ERROR("JPetScopeLoader currently allows only JPetScopeTask as subtask");
if (fSubTasks.size() > 0)
ERROR("JPetScopeLoader currently allows only one subtask");
fSubTasks.push_back(std::move(subTask));
}
bool JPetScopeLoader::createInputObjects(const char*)
{
using namespace jpet_options_tools;
auto opts = fParams.getOptions();
for (auto fSubTask = fSubTasks.begin(); fSubTask != fSubTasks.end(); fSubTask++) {
auto task = dynamic_cast<JPetScopeTask*>((*fSubTask).get());
std::unique_ptr<JPetStatistics> tmp(new JPetStatistics());
fStatistics = std::move(tmp);
assert(fStatistics);
fHeader = new JPetTreeHeader(getRunNumber(opts));
assert(fHeader);
fHeader->setBaseFileName(getInputFile(opts));
fHeader->addStageInfo(task->getName(), "", 0, JPetCommonTools::getTimeString());
}
return true;
}
std::map<std::string, int> JPetScopeLoader::getPMPrefixToPMIdMap()
{
std::map< std::string, int> prefixToId;
for (const auto& pm : getParamBank().getPMs()) {
prefixToId[pm.second->getDescription()] = pm.first;
}
return prefixToId;
}
/// Returns a map of list of scope input files. The value is the corresponding
/// index of the photomultiplier in the param bank.
std::map<std::string, int> JPetScopeLoader::createInputScopeFileNames(
const std::string& inputPathToScopeFiles,
std::map<std::string, int> pmPref2Id
) const
{
std::map<std::string, int> scopeFiles;
path current_dir(inputPathToScopeFiles);
if (exists(current_dir)) {
for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) {
std::string filename = iter->path().leaf().string();
if (isCorrectScopeFileName(filename)) {
auto prefix = getFilePrefix(filename);
if ( pmPref2Id.find(prefix) != pmPref2Id.end()) {
int id = pmPref2Id.find(prefix)->second;
scopeFiles[iter->path().parent_path().string() + "/" + filename] = id;
} else {
WARNING("The filename does not contain the accepted prefix:" + filename);
}
}
}
} else {
string msg = "Directory: \"";
msg += current_dir.string();
msg += "\" does not exist.";
ERROR(msg.c_str());
}
return scopeFiles;
}
std::string JPetScopeLoader::getFilePrefix(const std::string& filename) const
{
auto pos = filename.find("_");
if (pos != string::npos) {
return filename.substr(0, pos);
}
return "";
}
/// not very effective, but at least we can test it
bool JPetScopeLoader::isCorrectScopeFileName(const std::string& filename) const
{
boost::regex pattern("^[A-Za-z0-9]+_\\d*.txt");
return regex_match(filename, pattern);
}
bool JPetScopeLoader::init(const JPetParamsInterface& paramsI)
{
using namespace jpet_options_tools;
INFO( "Initialize Scope Loader Module." );
JPetTaskIO::init(paramsI);
DEBUG( "After initialization of the JPetTaskIO in Scope Loader init." );
return true;
}
bool JPetScopeLoader::run(const JPetDataInterface&)
{
assert(!fSubTasks.empty());
if (fSubTasks.size() != 1) {
ERROR("number of subtasks !=1");
return false;
}
auto subTask = fSubTasks.begin()->get();
subTask->init(fParams);
using namespace jpet_options_tools;
JPetScopeConfigParser confParser;
auto opts = fParams.getOptions();
auto config = confParser.getConfig(getScopeConfigFile(opts));
auto prefix2PM = getPMPrefixToPMIdMap();
auto inputScopeFiles = createInputScopeFileNames(getScopeInputDirectory(opts), prefix2PM);
auto events = JPetScopeLoader::groupScopeFileNamesByTimeWindowIndex(inputScopeFiles);
for (auto& ev : events) {
auto pOutputEvent = (dynamic_cast<JPetUserTask*>(subTask))->getOutputEvents();
if (pOutputEvent != nullptr) {
pOutputEvent->Clear();
} else {
WARNING("No proper timeWindow object returned to clear events");
}
JPetScopeData data(ev);
subTask->run(data);
pOutputEvent = (dynamic_cast<JPetUserTask*>(subTask))->getOutputEvents();
if (pOutputEvent != nullptr) {
fWriter->write(*pOutputEvent);
} else {
ERROR("No proper timeWindow object returned to save to file, returning from subtask " + subTask->getName());
return false;
}
}
subTask->terminate(fParams);
return true;
}
bool JPetScopeLoader::terminate(JPetParamsInterface& output_params)
{
auto& params = dynamic_cast<JPetParams&>(output_params);
OptsStrAny new_opts;
jpet_options_generator_tools::setOutputFile(new_opts, fOutFileFullPath);
params = JPetParams(new_opts, params.getParamManagerAsShared());
assert(fWriter);
assert(fHeader);
assert(fStatistics);
fWriter->writeHeader(fHeader);
fWriter->writeCollection(fStatistics->getStatsTable(), "Stats");
//store the parametric objects in the ouptut ROOT file
getParamManager().saveParametersToFile(fWriter);
getParamManager().clearParameters();
fWriter->closeFile();
return true;
}
bool JPetScopeLoader::createOutputObjects(const char* outputFilename)
{
fWriter = new JPetWriter( outputFilename );
assert(fWriter);
if (!fSubTasks.empty()) {
for (auto fSubTask = fSubTasks.begin(); fSubTask != fSubTasks.end(); fSubTask++) {
auto task = dynamic_cast<JPetScopeTask*>((*fSubTask).get());
task->setStatistics(fStatistics.get());
}
} else {
WARNING("the subTask does not exist, so JPetWriter and JPetStatistics not passed to it");
return false;
}
return true;
}
std::tuple<bool, std::string, std::string, bool> JPetScopeLoader::setInputAndOutputFile(const jpet_options_tools::OptsStrAny opts) const
{
using namespace jpet_options_tools;
bool resetOutputPath = fResetOutputPath;
std::string inputFilename = getInputFile(opts);
/// this argument is not really used by the ScopeLoader since inputFiles are generated
/// based on json content
inputFilename = inputFilename + "." + fOutFileType + ".root";
auto outFileFullPath = inputFilename;
if (isOptionSet(opts, "outputPath_std::string")) {
std::string outputPath(getOutputPath(opts));
if (!outputPath.empty()) {
outFileFullPath = outputPath + JPetCommonTools::extractFileNameFromFullPath(inputFilename);
resetOutputPath = true;
}
}
return std::make_tuple(true, inputFilename, outFileFullPath, resetOutputPath);
}
int JPetScopeLoader::getTimeWindowIndex(const std::string& pathAndFileName)
{
int time_window_index = -1;
if (!boost::filesystem::exists(pathAndFileName)) {
ERROR("File does not exist ");
}
int res = sscanf(JPetCommonTools::extractFileNameFromFullPath(pathAndFileName).c_str(), "%*3s %d", &time_window_index);
if (res <= 0) {
ERROR("scanf failed");
return -1;
} else {
return time_window_index;
}
}
std::map<int, std::map<std::string, int>> JPetScopeLoader::groupScopeFileNamesByTimeWindowIndex(const std::map<std::string, int>& scopeFileNames)
{
std::map<int, std::map<std::string, int>> res;
for (auto& el : scopeFileNames) {
auto index = JPetScopeLoader::getTimeWindowIndex(el.first);
auto it = res.find(index);
if (it == res.end() ) {
res[index] = {{el.first, el.second}};
} else {
it->second.insert(el);
}
}
return res;
}
<|endoftext|> |
<commit_before><commit_msg>rendercontext: Fix border window's painting to work well with rendercontext.<commit_after><|endoftext|> |
<commit_before>#include "taskqueuer.h"
WARNINGS_DISABLE
#include <QCoreApplication>
#include <QEventLoop>
#include <QVariant>
WARNINGS_ENABLE
#include "cmdlinetask.h"
/*! Track info about tasks. */
struct TaskMeta
{
/*! Actual task. */
CmdlineTask *task;
/*! Does this task need to be the only one happening? */
bool isExclusive;
/*! This is a "create archive" task? */
bool isBackup;
};
TaskQueuer::TaskQueuer() : _threadPool(QThreadPool::globalInstance())
{
#ifdef QT_TESTLIB_LIB
_fakeNextTask = false;
#endif
}
TaskQueuer::~TaskQueuer()
{
// Wait up to 1 second to finish any background tasks
_threadPool->waitForDone(1000);
// Wait up to 1 second to delete objects scheduled with ->deleteLater()
QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);
}
void TaskQueuer::stopTasks(bool interrupt, bool running, bool queued)
{
// Clear the queue first, to avoid starting a queued task
// after already clearing the running task(s).
if(queued)
{
while(!_taskQueue.isEmpty())
{
TaskMeta * tm = _taskQueue.dequeue();
CmdlineTask *task = tm->task;
if(task)
{
task->emitCanceled();
task->deleteLater();
}
}
emit message("Cleared queued tasks.");
}
// Deal with a running backup.
if(interrupt)
{
// Sending a SIGQUIT will cause the tarsnap binary to
// create a checkpoint. Non-tarsnap binaries should be
// receive a CmdlineTask::stop() instead of a SIGQUIT.
if(!_runningTasks.isEmpty())
_runningTasks.first()->task->sigquit();
emit message("Interrupting current backup.");
}
// Stop running tasks.
if(running)
{
for(TaskMeta *tm : _runningTasks)
{
CmdlineTask *task = tm->task;
if(task)
task->stop();
}
emit message("Stopped running tasks.");
}
}
void TaskQueuer::queueTask(CmdlineTask *task, bool exclusive, bool isBackup)
{
// Sanity check.
Q_ASSERT(task != nullptr);
// Create & initialize the TaskMeta object.
TaskMeta *tm = new TaskMeta;
tm->task = task;
tm->isExclusive = exclusive;
tm->isBackup = isBackup;
// Add to the queue and trigger starting a new task.
_taskQueue.enqueue(tm);
startTasks();
}
void TaskQueuer::startTasks()
{
while(!_taskQueue.isEmpty() && !isExclusiveTaskRunning())
{
// Bail from loop if the next task requires exclusive running.
if(!_runningTasks.isEmpty() && _taskQueue.head()->isExclusive)
break;
// Bail from loop if we've reached the maximum number of threads.
if(_runningTasks.count() >= _threadPool->maxThreadCount())
break;
startTask();
}
// Send the updated task numbers.
updateTaskNumbers();
}
void TaskQueuer::startTask()
{
// Bail if there's nothing to do.
if(_taskQueue.isEmpty())
return;
// Check for exclusive.
if(isExclusiveTaskRunning())
return;
// Get a new task.
TaskMeta *tm = _taskQueue.dequeue();
// Set up the task ending.
CmdlineTask *task = tm->task;
connect(task, &CmdlineTask::dequeue, this, &TaskQueuer::dequeueTask);
task->setAutoDelete(false);
// Record this thread as "running", even though it hasn't actually
// started yet. QThreadPool::start() is non-blocking, and in fact
// explicitly states that a QRunnable can be added to an internal
// run queue if it's exceeded QThreadPoll::maxThreadCount().
//
// However, for the purpose of this TaskQueuer, the task should not
// be recorded in our _taskQueue (because we've just dequeued()'d it).
// The "strictly correct" solution would be to add a
// _waitingForStart queue, and move items out of that queue when the
// relevant CmdlineTask::started signal was emitted. At the moment,
// I don't think that step is necessary, but I might need to revisit
// that decision later.
_runningTasks.append(tm);
// Start the task.
#ifdef QT_TESTLIB_LIB
if(_fakeNextTask)
task->fake();
#endif
_threadPool->start(task);
}
void TaskQueuer::dequeueTask()
{
// Get the task.
CmdlineTask *task = qobject_cast<CmdlineTask *>(sender());
// Sanity check.
if(task == nullptr)
return;
// Clean up task.
for(TaskMeta *tm : _runningTasks)
{
if(tm->task == task)
{
_runningTasks.removeOne(tm);
delete tm;
break;
}
}
task->deleteLater();
// Start another task(s) if applicable.
startTasks();
}
bool TaskQueuer::isExclusiveTaskRunning()
{
for(TaskMeta *tm : _runningTasks)
{
if(tm->isExclusive)
return true;
}
return false;
}
bool TaskQueuer::isBackupTaskRunning()
{
for(TaskMeta *tm : _runningTasks)
{
if(tm->isBackup)
return true;
}
return false;
}
void TaskQueuer::updateTaskNumbers()
{
bool backupTaskRunning = isBackupTaskRunning();
emit numTasks(backupTaskRunning, _runningTasks.count(), _taskQueue.count());
}
#ifdef QT_TESTLIB_LIB
void TaskQueuer::fakeNextTask()
{
_fakeNextTask = true;
}
void TaskQueuer::waitUntilIdle()
{
while(!(_taskQueue.isEmpty() && _runningTasks.isEmpty()))
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
#endif
<commit_msg>TaskQueuer: expand, sanity check for backupTask->sigquit()<commit_after>#include "taskqueuer.h"
WARNINGS_DISABLE
#include <QCoreApplication>
#include <QEventLoop>
#include <QVariant>
WARNINGS_ENABLE
#include "cmdlinetask.h"
/*! Track info about tasks. */
struct TaskMeta
{
/*! Actual task. */
CmdlineTask *task;
/*! Does this task need to be the only one happening? */
bool isExclusive;
/*! This is a "create archive" task? */
bool isBackup;
};
TaskQueuer::TaskQueuer() : _threadPool(QThreadPool::globalInstance())
{
#ifdef QT_TESTLIB_LIB
_fakeNextTask = false;
#endif
}
TaskQueuer::~TaskQueuer()
{
// Wait up to 1 second to finish any background tasks
_threadPool->waitForDone(1000);
// Wait up to 1 second to delete objects scheduled with ->deleteLater()
QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);
}
void TaskQueuer::stopTasks(bool interrupt, bool running, bool queued)
{
// Clear the queue first, to avoid starting a queued task
// after already clearing the running task(s).
if(queued)
{
while(!_taskQueue.isEmpty())
{
TaskMeta * tm = _taskQueue.dequeue();
CmdlineTask *task = tm->task;
if(task)
{
task->emitCanceled();
task->deleteLater();
}
}
emit message("Cleared queued tasks.");
}
// Deal with a running backup.
if(interrupt)
{
// Sending a SIGQUIT will cause the tarsnap binary to
// create a checkpoint. Non-tarsnap binaries should be
// receive a CmdlineTask::stop() instead of a SIGQUIT.
if(!_runningTasks.isEmpty())
{
TaskMeta *tm = _runningTasks.first();
Q_ASSERT(tm->isBackup == true);
CmdlineTask *backupTask = tm->task;
backupTask->sigquit();
}
emit message("Interrupting current backup.");
}
// Stop running tasks.
if(running)
{
for(TaskMeta *tm : _runningTasks)
{
CmdlineTask *task = tm->task;
if(task)
task->stop();
}
emit message("Stopped running tasks.");
}
}
void TaskQueuer::queueTask(CmdlineTask *task, bool exclusive, bool isBackup)
{
// Sanity check.
Q_ASSERT(task != nullptr);
// Create & initialize the TaskMeta object.
TaskMeta *tm = new TaskMeta;
tm->task = task;
tm->isExclusive = exclusive;
tm->isBackup = isBackup;
// Add to the queue and trigger starting a new task.
_taskQueue.enqueue(tm);
startTasks();
}
void TaskQueuer::startTasks()
{
while(!_taskQueue.isEmpty() && !isExclusiveTaskRunning())
{
// Bail from loop if the next task requires exclusive running.
if(!_runningTasks.isEmpty() && _taskQueue.head()->isExclusive)
break;
// Bail from loop if we've reached the maximum number of threads.
if(_runningTasks.count() >= _threadPool->maxThreadCount())
break;
startTask();
}
// Send the updated task numbers.
updateTaskNumbers();
}
void TaskQueuer::startTask()
{
// Bail if there's nothing to do.
if(_taskQueue.isEmpty())
return;
// Check for exclusive.
if(isExclusiveTaskRunning())
return;
// Get a new task.
TaskMeta *tm = _taskQueue.dequeue();
// Set up the task ending.
CmdlineTask *task = tm->task;
connect(task, &CmdlineTask::dequeue, this, &TaskQueuer::dequeueTask);
task->setAutoDelete(false);
// Record this thread as "running", even though it hasn't actually
// started yet. QThreadPool::start() is non-blocking, and in fact
// explicitly states that a QRunnable can be added to an internal
// run queue if it's exceeded QThreadPoll::maxThreadCount().
//
// However, for the purpose of this TaskQueuer, the task should not
// be recorded in our _taskQueue (because we've just dequeued()'d it).
// The "strictly correct" solution would be to add a
// _waitingForStart queue, and move items out of that queue when the
// relevant CmdlineTask::started signal was emitted. At the moment,
// I don't think that step is necessary, but I might need to revisit
// that decision later.
_runningTasks.append(tm);
// Start the task.
#ifdef QT_TESTLIB_LIB
if(_fakeNextTask)
task->fake();
#endif
_threadPool->start(task);
}
void TaskQueuer::dequeueTask()
{
// Get the task.
CmdlineTask *task = qobject_cast<CmdlineTask *>(sender());
// Sanity check.
if(task == nullptr)
return;
// Clean up task.
for(TaskMeta *tm : _runningTasks)
{
if(tm->task == task)
{
_runningTasks.removeOne(tm);
delete tm;
break;
}
}
task->deleteLater();
// Start another task(s) if applicable.
startTasks();
}
bool TaskQueuer::isExclusiveTaskRunning()
{
for(TaskMeta *tm : _runningTasks)
{
if(tm->isExclusive)
return true;
}
return false;
}
bool TaskQueuer::isBackupTaskRunning()
{
for(TaskMeta *tm : _runningTasks)
{
if(tm->isBackup)
return true;
}
return false;
}
void TaskQueuer::updateTaskNumbers()
{
bool backupTaskRunning = isBackupTaskRunning();
emit numTasks(backupTaskRunning, _runningTasks.count(), _taskQueue.count());
}
#ifdef QT_TESTLIB_LIB
void TaskQueuer::fakeNextTask()
{
_fakeNextTask = true;
}
void TaskQueuer::waitUntilIdle()
{
while(!(_taskQueue.isEmpty() && _runningTasks.isEmpty()))
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
#endif
<|endoftext|> |
<commit_before>
#pragma once
#include "quantities/parser.hpp"
#include <array>
#include <string>
#include "quantities/astronomy.hpp"
#include "quantities/bipm.hpp"
#include "quantities/dimensions.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/si.hpp"
namespace principia {
namespace quantities {
namespace internal_parser {
using internal_dimensions::Dimensions;
using RuntimeDimensions = std::array<std::int64_t, 8>;
template<typename Q>
struct ExtractDimensions {};
template<>
struct ExtractDimensions<double> {
static constexpr RuntimeDimensions dimensions() {
return {{0, 0, 0, 0, 0, 0, 0, 0}};
}
};
template<std::int64_t LengthExponent,
std::int64_t MassExponent,
std::int64_t TimeExponent,
std::int64_t CurrentExponent,
std::int64_t TemperatureExponent,
std::int64_t AmountExponent,
std::int64_t LuminousIntensityExponent,
std::int64_t AngleExponent>
struct ExtractDimensions<Quantity<Dimensions<LengthExponent,
MassExponent,
TimeExponent,
CurrentExponent,
TemperatureExponent,
AmountExponent,
LuminousIntensityExponent,
AngleExponent>>> {
static constexpr RuntimeDimensions dimensions() {
return {{LengthExponent,
MassExponent,
TimeExponent,
CurrentExponent,
TemperatureExponent,
AmountExponent,
LuminousIntensityExponent,
AngleExponent}};
}
};
struct Unit {
template<typename Q>
explicit Unit(Q const& quantity);
Unit(RuntimeDimensions&& dimensions, double scale);
RuntimeDimensions dimensions;
double scale;
};
template<typename Q>
Unit::Unit(Q const& quantity)
: dimensions(ExtractDimensions<Q>::dimensions()),
scale(quantity / si::Unit<Q>) {}
inline Unit::Unit(RuntimeDimensions&& dimensions, double const scale)
: dimensions(dimensions),
scale(scale) {}
inline Unit operator*(Unit const& left, Unit const& right) {
RuntimeDimensions dimensions;
for (std::int64_t i = 0; i < dimensions.size(); ++i) {
dimensions[i] = left.dimensions[i] + right.dimensions[i];
}
return {std::move(dimensions), left.scale * right.scale};
}
inline Unit operator/(Unit const& left, Unit const& right) {
RuntimeDimensions dimensions;
for (std::int64_t i = 0; i < dimensions.size(); ++i) {
dimensions[i] = left.dimensions[i] - right.dimensions[i];
}
return {std::move(dimensions), left.scale / right.scale};
}
inline Unit operator^(Unit const& left, int const exponent) {
RuntimeDimensions dimensions;
for (std::int64_t i = 0; i < dimensions.size(); ++i) {
dimensions[i] = left.dimensions[i] * exponent;
}
return {std::move(dimensions), std::pow(left.scale, exponent)};
}
inline Unit ParseUnit(std::string const& s) {
// Unitless quantities.
if (s == "") {
return Unit(1.0);
// Units of length.
} else if (s == u8"Å") {
return Unit(bipm::Ångström);
} else if (s == u8"μm") {
return Unit(si::Micro(si::Metre));
} else if (s == "mm") {
return Unit(si::Milli(si::Metre));
} else if (s == "cm") {
return Unit(si::Centi(si::Metre));
} else if (s == "m") {
return Unit(si::Metre);
} else if (s == "km") {
return Unit(si::Kilo(si::Metre));
} else if (s == u8"R🜨") {
return Unit(astronomy::TerrestrialEquatorialRadius);
} else if (s == u8"R☉") {
return Unit(astronomy::SolarRadius);
} else if (s == "au") {
return Unit(astronomy::AstronomicalUnit);
// Units of mass.
} else if (s == "kg") {
return Unit(si::Kilogram);
// Units of time.
} else if (s == "ms") {
return Unit(si::Milli(si::Second));
} else if (s == "s") {
return Unit(si::Second);
} else if (s == "min") {
return Unit(si::Minute);
} else if (s == "h") {
return Unit(si::Hour);
} else if (s == "d") {
return Unit(si::Day);
// Units of gravitational parameter.
} else if (s == u8"GM🜨") {
return Unit(astronomy::TerrestrialGravitationalParameter);
} else if (s == u8"GM☉") {
return Unit(astronomy::SolarGravitationalParameter);
// Units of power.
} else if (s == "W") {
return Unit(si::Watt);
// Units of angle.
} else if (s == "deg" || s == u8"°") {
return Unit(si::Degree);
} else if (s == "rad") {
return Unit(si::Radian);
// Units of solid angle.
} else if (s == "sr") {
return Unit(si::Steradian);
} else {
LOG(FATAL) << "Unsupported unit " << s;
base::noreturn();
}
}
inline int ParseExponent(std::string const& s) {
// Parse an int.
char* interpreted_end;
char const* const c_string = s.c_str();
int const exponent = std::strtol(c_string, &interpreted_end, /*base=*/10);
int const interpreted = interpreted_end - c_string;
CHECK_LT(0, interpreted) << "invalid integer number " << s;
return exponent;
}
inline Unit ParseExponentiationUnit(std::string const& s) {
int const first_caret = s.find('^');
if (first_caret == std::string::npos) {
return ParseUnit(s);
} else {
int const first_nonblank = s.find_first_not_of(' ', first_caret + 1);
CHECK_NE(std::string::npos, first_nonblank);
int const last_nonblank = s.find_last_not_of(' ', first_caret - 1);
CHECK_NE(std::string::npos, last_nonblank);
auto const left = ParseUnit(s.substr(0, last_nonblank + 1));
auto const right = ParseExponent(s.substr(first_nonblank));
return left ^ right;
}
}
inline Unit ParseProductUnit(std::string const& s) {
// For a product we are looking for a blank character that is not next to a
// carret.
int first_blank;
int first_nonblank;
int last_nonblank;
for (int start = 0;; start = first_blank + 1) {
first_blank = s.find(' ', start);
if (first_blank == std::string::npos) {
return ParseExponentiationUnit(s);
} else {
first_nonblank = s.find_first_not_of(' ', first_blank + 1);
last_nonblank = s.find_last_not_of(' ', first_blank - 1);
if ((first_nonblank == std::string::npos || s[first_nonblank] != '^') &&
(last_nonblank == std::string::npos || s[last_nonblank] != '^')) {
break;
}
}
}
auto const left = ParseExponentiationUnit(s.substr(0, last_nonblank + 1));
auto const right = ParseProductUnit(s.substr(first_nonblank));
return left * right;
}
inline Unit ParseQuotientUnit(std::string const& s) {
// Look for the slash from the back to achieve proper associativity.
int const last_slash = s.rfind('/');
if (last_slash == std::string::npos) {
// Not a quotient.
return ParseProductUnit(s);
} else {
// A quotient. Parse each half. Note that there may not be a left half for
// input like 1.23 / s.
int const first_nonblank = s.find_first_not_of(' ', last_slash + 1);
CHECK_NE(std::string::npos, first_nonblank);
size_t const last_nonblank = last_slash == 0
? std::string::npos
: s.find_last_not_of(' ', last_slash - 1);
auto const left = last_nonblank == std::string::npos
? Unit(1.0)
: ParseQuotientUnit(s.substr(0, last_nonblank + 1));
auto const right = ParseExponentiationUnit(s.substr(first_nonblank));
return left / right;
}
}
template<typename Q>
Q ParseQuantity(std::string const& s) {
// Parse a double.
char* interpreted_end;
char const* const c_string = s.c_str();
double const magnitude = std::strtod(c_string, &interpreted_end);
int const interpreted = interpreted_end - c_string;
CHECK_LT(0, interpreted) << "invalid floating-point number " << s;
// Locate the unit. It may be empty for a double.
int const first_nonblank = s.find_first_not_of(' ', interpreted);
int const last_nonblank = s.find_last_not_of(' ');
std::string unit_string;
if (first_nonblank != std::string::npos) {
unit_string = s.substr(first_nonblank, last_nonblank - first_nonblank + 1);
}
Unit const unit = ParseQuotientUnit(unit_string);
CHECK(ExtractDimensions<Q>::dimensions() == unit.dimensions) << unit_string;
return magnitude * unit.scale * si::Unit<Q>;
}
} // namespace internal_parser
} // namespace quantities
} // namespace principia
<commit_msg>After egg's review.<commit_after>
#pragma once
#include "quantities/parser.hpp"
#include <array>
#include <string>
#include "quantities/astronomy.hpp"
#include "quantities/bipm.hpp"
#include "quantities/dimensions.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/si.hpp"
namespace principia {
namespace quantities {
namespace internal_parser {
using internal_dimensions::Dimensions;
using RuntimeDimensions = std::array<std::int64_t, 8>;
template<typename Q>
struct ExtractDimensions {};
template<>
struct ExtractDimensions<double> {
static constexpr RuntimeDimensions dimensions() {
return {{0, 0, 0, 0, 0, 0, 0, 0}};
}
};
template<std::int64_t LengthExponent,
std::int64_t MassExponent,
std::int64_t TimeExponent,
std::int64_t CurrentExponent,
std::int64_t TemperatureExponent,
std::int64_t AmountExponent,
std::int64_t LuminousIntensityExponent,
std::int64_t AngleExponent>
struct ExtractDimensions<Quantity<Dimensions<LengthExponent,
MassExponent,
TimeExponent,
CurrentExponent,
TemperatureExponent,
AmountExponent,
LuminousIntensityExponent,
AngleExponent>>> {
static constexpr RuntimeDimensions dimensions() {
return {{LengthExponent,
MassExponent,
TimeExponent,
CurrentExponent,
TemperatureExponent,
AmountExponent,
LuminousIntensityExponent,
AngleExponent}};
}
};
struct Unit {
template<typename Q>
explicit Unit(Q const& quantity);
Unit(RuntimeDimensions&& dimensions, double scale);
RuntimeDimensions dimensions;
double scale;
};
template<typename Q>
Unit::Unit(Q const& quantity)
: dimensions(ExtractDimensions<Q>::dimensions()),
scale(quantity / si::Unit<Q>) {}
inline Unit::Unit(RuntimeDimensions&& dimensions, double const scale)
: dimensions(dimensions),
scale(scale) {}
inline Unit operator*(Unit const& left, Unit const& right) {
RuntimeDimensions dimensions;
for (std::int64_t i = 0; i < dimensions.size(); ++i) {
dimensions[i] = left.dimensions[i] + right.dimensions[i];
}
return {std::move(dimensions), left.scale * right.scale};
}
inline Unit operator/(Unit const& left, Unit const& right) {
RuntimeDimensions dimensions;
for (std::int64_t i = 0; i < dimensions.size(); ++i) {
dimensions[i] = left.dimensions[i] - right.dimensions[i];
}
return {std::move(dimensions), left.scale / right.scale};
}
inline Unit operator^(Unit const& left, int const exponent) {
RuntimeDimensions dimensions;
for (std::int64_t i = 0; i < dimensions.size(); ++i) {
dimensions[i] = left.dimensions[i] * exponent;
}
return {std::move(dimensions), std::pow(left.scale, exponent)};
}
inline Unit ParseUnit(std::string const& s) {
// Unitless quantities.
if (s == "") {
return Unit(1.0);
// Units of length.
} else if (s == u8"Å") {
return Unit(bipm::Ångström);
} else if (s == u8"μm") {
return Unit(si::Micro(si::Metre));
} else if (s == "mm") {
return Unit(si::Milli(si::Metre));
} else if (s == "cm") {
return Unit(si::Centi(si::Metre));
} else if (s == "m") {
return Unit(si::Metre);
} else if (s == "km") {
return Unit(si::Kilo(si::Metre));
} else if (s == u8"R🜨") {
return Unit(astronomy::TerrestrialEquatorialRadius);
} else if (s == u8"R☉") {
return Unit(astronomy::SolarRadius);
} else if (s == "au") {
return Unit(astronomy::AstronomicalUnit);
// Units of mass.
} else if (s == "kg") {
return Unit(si::Kilogram);
// Units of time.
} else if (s == "ms") {
return Unit(si::Milli(si::Second));
} else if (s == "s") {
return Unit(si::Second);
} else if (s == "min") {
return Unit(si::Minute);
} else if (s == "h") {
return Unit(si::Hour);
} else if (s == "d") {
return Unit(si::Day);
// Units of gravitational parameter.
} else if (s == u8"GM🜨") {
return Unit(astronomy::TerrestrialGravitationalParameter);
} else if (s == u8"GM☉") {
return Unit(astronomy::SolarGravitationalParameter);
// Units of power.
} else if (s == "W") {
return Unit(si::Watt);
// Units of angle.
} else if (s == "deg" || s == u8"°") {
return Unit(si::Degree);
} else if (s == "rad") {
return Unit(si::Radian);
// Units of solid angle.
} else if (s == "sr") {
return Unit(si::Steradian);
} else {
LOG(FATAL) << "Unsupported unit " << s;
base::noreturn();
}
}
inline int ParseExponent(std::string const& s) {
// Parse an int.
char* interpreted_end;
char const* const c_string = s.c_str();
int const exponent = std::strtol(c_string, &interpreted_end, /*base=*/10);
int const interpreted = interpreted_end - c_string;
CHECK_LT(0, interpreted) << "invalid integer number " << s;
return exponent;
}
inline Unit ParseExponentiationUnit(std::string const& s) {
int const first_caret = s.find('^');
if (first_caret == std::string::npos) {
return ParseUnit(s);
} else {
int const first_nonblank = s.find_first_not_of(' ', first_caret + 1);
CHECK_NE(std::string::npos, first_nonblank);
int const last_nonblank = s.find_last_not_of(' ', first_caret - 1);
CHECK_NE(std::string::npos, last_nonblank);
auto const left = ParseUnit(s.substr(0, last_nonblank + 1));
auto const right = ParseExponent(s.substr(first_nonblank));
return left ^ right;
}
}
inline Unit ParseProductUnit(std::string const& s) {
// For a product we are looking for a blank character that is not next to a
// carret.
int first_blank;
int first_nonblank;
int last_nonblank;
for (int start = 0;; start = first_blank + 1) {
first_blank = s.find(' ', start);
if (first_blank == std::string::npos) {
return ParseExponentiationUnit(s);
} else {
first_nonblank = s.find_first_not_of(' ', first_blank + 1);
last_nonblank = s.find_last_not_of(' ', first_blank - 1);
if ((first_nonblank == std::string::npos || s[first_nonblank] != '^') &&
(last_nonblank == std::string::npos || s[last_nonblank] != '^')) {
break;
}
}
}
auto const left = ParseExponentiationUnit(s.substr(0, last_nonblank + 1));
auto const right = ParseProductUnit(s.substr(first_nonblank));
return left * right;
}
inline Unit ParseQuotientUnit(std::string const& s) {
// Look for the slash from the back to achieve proper associativity.
int const last_slash = s.rfind('/');
if (last_slash == std::string::npos) {
// Not a quotient.
return ParseProductUnit(s);
} else {
// A quotient. Parse each half. Note that there may not be a left half for
// input like 1.23 / s.
int const first_nonblank = s.find_first_not_of(' ', last_slash + 1);
CHECK_NE(std::string::npos, first_nonblank);
std::size_t const last_nonblank =
last_slash == 0 ? std::string::npos
: s.find_last_not_of(' ', last_slash - 1);
auto const left = last_nonblank == std::string::npos
? Unit(1.0)
: ParseQuotientUnit(s.substr(0, last_nonblank + 1));
auto const right = ParseExponentiationUnit(s.substr(first_nonblank));
return left / right;
}
}
template<typename Q>
Q ParseQuantity(std::string const& s) {
// Parse a double.
char* interpreted_end;
char const* const c_string = s.c_str();
double const magnitude = std::strtod(c_string, &interpreted_end);
int const interpreted = interpreted_end - c_string;
CHECK_LT(0, interpreted) << "invalid floating-point number " << s;
// Locate the unit. It may be empty for a double.
int const first_nonblank = s.find_first_not_of(' ', interpreted);
int const last_nonblank = s.find_last_not_of(' ');
std::string unit_string;
if (first_nonblank != std::string::npos) {
unit_string = s.substr(first_nonblank, last_nonblank - first_nonblank + 1);
}
Unit const unit = ParseQuotientUnit(unit_string);
CHECK(ExtractDimensions<Q>::dimensions() == unit.dimensions) << unit_string;
return magnitude * unit.scale * si::Unit<Q>;
}
} // namespace internal_parser
} // namespace quantities
} // namespace principia
<|endoftext|> |
<commit_before><commit_msg>disable off-screen drawing of statusbar items (for now)<commit_after><|endoftext|> |
<commit_before>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#ifndef _WIN32
#include <cstdlib>
#endif
#include "Pickup.h"
#include "ClientHandle.h"
#include "Inventory.h"
#include "World.h"
#include "Simulator/FluidSimulator.h"
#include "Server.h"
#include "Player.h"
#include "PluginManager.h"
#include "Item.h"
#include "Root.h"
#include "Tracer.h"
#include "Chunk.h"
#include "Vector3d.h"
#include "Vector3f.h"
cPickup::cPickup(int a_MicroPosX, int a_MicroPosY, int a_MicroPosZ, const cItem & a_Item, float a_SpeedX /* = 0.f */, float a_SpeedY /* = 0.f */, float a_SpeedZ /* = 0.f */)
: cEntity(etPickup, ((double)(a_MicroPosX)) / 32, ((double)(a_MicroPosY)) / 32, ((double)(a_MicroPosZ)) / 32)
, m_Health(5)
, m_Timer( 0.f )
, m_Item(a_Item)
, m_bCollected( false )
{
SetSpeed(a_SpeedX, a_SpeedY, a_SpeedZ);
m_Gravity = -3.0;
}
void cPickup::Initialize(cWorld * a_World)
{
super::Initialize(a_World);
a_World->BroadcastSpawn(*this);
}
void cPickup::SpawnOn(cClientHandle & a_Client)
{
a_Client.SendPickupSpawn(*this);
}
void cPickup::Tick(float a_Dt, cChunk & a_Chunk)
{
super::Tick(a_Dt, a_Chunk);
BroadcastMovementUpdate(); //Notify clients of position
m_Timer += a_Dt;
if (!m_bCollected)
{
int BlockY = (int) floor(GetPosY());
if (BlockY < cChunkDef::Height) // Don't do anything except for falling when above the world
{
int BlockX = (int) floor(GetPosX());
int BlockZ = (int) floor(GetPosZ());
//Position might have changed due to physics. So we have to make sure we have the correct chunk.
cChunk * CurrentChunk = a_Chunk.GetNeighborChunk(BlockX, BlockZ);
if (CurrentChunk != NULL) // Make sure the chunk is loaded
{
int RelBlockX = BlockX - (CurrentChunk->GetPosX() * cChunkDef::Width);
int RelBlockZ = BlockZ - (CurrentChunk->GetPosZ() * cChunkDef::Width);
BLOCKTYPE BlockBelow = CurrentChunk->GetBlock(RelBlockX, BlockY - 1, RelBlockZ);
BLOCKTYPE BlockIn = CurrentChunk->GetBlock(RelBlockX, BlockY, RelBlockZ);
if (
IsBlockLava(BlockBelow) || (BlockBelow == E_BLOCK_FIRE) ||
IsBlockLava(BlockIn) || (BlockIn == E_BLOCK_FIRE)
)
{
m_bCollected = true;
m_Timer = 0; // We have to reset the timer.
m_Timer += a_Dt; // In case we have to destroy the pickup in the same tick.
if (m_Timer > 500.f)
{
Destroy();
return;
}
}
}
}
}
else
{
if (m_Timer > 500.f) // 0.5 second
{
Destroy();
return;
}
}
if (m_Timer > 1000 * 60 * 5) // 5 minutes
{
Destroy();
return;
}
if (GetPosY() < -8) // Out of this world and no more visible!
{
Destroy();
return;
}
}
bool cPickup::CollectedBy(cPlayer * a_Dest)
{
ASSERT(a_Dest != NULL);
if (m_bCollected)
{
LOG("Pickup %d cannot be collected by \"%s\", because it has already been collected.", a_Dest->GetName().c_str(), m_UniqueID);
return false; // It's already collected!
}
// 800 is to long
if (m_Timer < 500.f)
{
LOG("Pickup %d cannot be collected by \"%s\", because it is not old enough.", a_Dest->GetName().c_str(), m_UniqueID);
return false; // Not old enough
}
if (cRoot::Get()->GetPluginManager()->CallHookCollectingPickup(a_Dest, *this))
{
LOG("Pickup %d cannot be collected by \"%s\", because a plugin has said no.", a_Dest->GetName().c_str(), m_UniqueID);
return false;
}
if (a_Dest->GetInventory().AddItemAnyAmount(m_Item))
{
m_World->BroadcastCollectPickup(*this, *a_Dest);
m_bCollected = true;
m_Timer = 0;
if (m_Item.m_ItemCount != 0)
{
cItems Pickup;
Pickup.push_back(cItem(m_Item));
m_World->SpawnItemPickups(Pickup, GetPosX(), GetPosY(), GetPosZ());
}
return true;
}
LOG("Pickup %d cannot be collected by \"%s\", because there's no space in the inventory.", a_Dest->GetName().c_str(), m_UniqueID);
return false;
}
<commit_msg>Pickup: fixed logging parameters causing a crash.<commit_after>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#ifndef _WIN32
#include <cstdlib>
#endif
#include "Pickup.h"
#include "ClientHandle.h"
#include "Inventory.h"
#include "World.h"
#include "Simulator/FluidSimulator.h"
#include "Server.h"
#include "Player.h"
#include "PluginManager.h"
#include "Item.h"
#include "Root.h"
#include "Tracer.h"
#include "Chunk.h"
#include "Vector3d.h"
#include "Vector3f.h"
cPickup::cPickup(int a_MicroPosX, int a_MicroPosY, int a_MicroPosZ, const cItem & a_Item, float a_SpeedX /* = 0.f */, float a_SpeedY /* = 0.f */, float a_SpeedZ /* = 0.f */)
: cEntity(etPickup, ((double)(a_MicroPosX)) / 32, ((double)(a_MicroPosY)) / 32, ((double)(a_MicroPosZ)) / 32)
, m_Health(5)
, m_Timer( 0.f )
, m_Item(a_Item)
, m_bCollected( false )
{
SetSpeed(a_SpeedX, a_SpeedY, a_SpeedZ);
m_Gravity = -3.0;
}
void cPickup::Initialize(cWorld * a_World)
{
super::Initialize(a_World);
a_World->BroadcastSpawn(*this);
}
void cPickup::SpawnOn(cClientHandle & a_Client)
{
a_Client.SendPickupSpawn(*this);
}
void cPickup::Tick(float a_Dt, cChunk & a_Chunk)
{
super::Tick(a_Dt, a_Chunk);
BroadcastMovementUpdate(); //Notify clients of position
m_Timer += a_Dt;
if (!m_bCollected)
{
int BlockY = (int) floor(GetPosY());
if (BlockY < cChunkDef::Height) // Don't do anything except for falling when above the world
{
int BlockX = (int) floor(GetPosX());
int BlockZ = (int) floor(GetPosZ());
//Position might have changed due to physics. So we have to make sure we have the correct chunk.
cChunk * CurrentChunk = a_Chunk.GetNeighborChunk(BlockX, BlockZ);
if (CurrentChunk != NULL) // Make sure the chunk is loaded
{
int RelBlockX = BlockX - (CurrentChunk->GetPosX() * cChunkDef::Width);
int RelBlockZ = BlockZ - (CurrentChunk->GetPosZ() * cChunkDef::Width);
BLOCKTYPE BlockBelow = CurrentChunk->GetBlock(RelBlockX, BlockY - 1, RelBlockZ);
BLOCKTYPE BlockIn = CurrentChunk->GetBlock(RelBlockX, BlockY, RelBlockZ);
if (
IsBlockLava(BlockBelow) || (BlockBelow == E_BLOCK_FIRE) ||
IsBlockLava(BlockIn) || (BlockIn == E_BLOCK_FIRE)
)
{
m_bCollected = true;
m_Timer = 0; // We have to reset the timer.
m_Timer += a_Dt; // In case we have to destroy the pickup in the same tick.
if (m_Timer > 500.f)
{
Destroy();
return;
}
}
}
}
}
else
{
if (m_Timer > 500.f) // 0.5 second
{
Destroy();
return;
}
}
if (m_Timer > 1000 * 60 * 5) // 5 minutes
{
Destroy();
return;
}
if (GetPosY() < -8) // Out of this world and no more visible!
{
Destroy();
return;
}
}
bool cPickup::CollectedBy(cPlayer * a_Dest)
{
ASSERT(a_Dest != NULL);
if (m_bCollected)
{
LOG("Pickup %d cannot be collected by \"%s\", because it has already been collected.", m_UniqueID, a_Dest->GetName().c_str());
return false; // It's already collected!
}
// 800 is to long
if (m_Timer < 500.f)
{
LOG("Pickup %d cannot be collected by \"%s\", because it is not old enough.", m_UniqueID, a_Dest->GetName().c_str());
return false; // Not old enough
}
if (cRoot::Get()->GetPluginManager()->CallHookCollectingPickup(a_Dest, *this))
{
LOG("Pickup %d cannot be collected by \"%s\", because a plugin has said no.", m_UniqueID, a_Dest->GetName().c_str());
return false;
}
if (a_Dest->GetInventory().AddItemAnyAmount(m_Item))
{
m_World->BroadcastCollectPickup(*this, *a_Dest);
m_bCollected = true;
m_Timer = 0;
if (m_Item.m_ItemCount != 0)
{
cItems Pickup;
Pickup.push_back(cItem(m_Item));
m_World->SpawnItemPickups(Pickup, GetPosX(), GetPosY(), GetPosZ());
}
return true;
}
LOG("Pickup %d cannot be collected by \"%s\", because there's no space in the inventory.", a_Dest->GetName().c_str(), m_UniqueID);
return false;
}
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2006-2015 ARM Limited
*
* 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 "equip/Router.h"
#include "cborg/Cbor.h"
#include "equip/Equip.h"
using namespace Equip;
#include <stdio.h>
#include <stdarg.h>
#if 1
#warning debug enabled
#define DEBUGOUT(...) { printf(__VA_ARGS__); }
#else
#define DEBUGOUT(...) /* nothing */
#endif // DEBUGOUT
/*****************************************************************************/
/* Router::Next */
/*****************************************************************************/
/**
* Create a callback functor that will dvance the state in the routing stack.
**/
Router::Next::Next(Router::RoutingStack* _stack)
: stack(_stack)
{}
/**
* Advances the state of the routing stack, triggering the next middleware
* in the chain to get exectuted (if it exists).
**/
void Router::Next::operator () (uint32_t status)
{
if (stack)
{
stack->next(status);
}
}
/*****************************************************************************/
/* RoutingStack */
/*****************************************************************************/
/**
* Initialises the state of the routing stack by creating an iterator on the routes
* held by the router.
**/
Router::RoutingStack::RoutingStack(Request& _req, Response& _res, std::vector<route_t>& _routes)
: req(_req), res(_res), iter(), routes(_routes)
{
iter = routes.begin();
}
/**
* Advances the iterator state if the status is not set (i.e. status == 0).
* If a status is set (i.e. status != 0) moves the iterator to the end and
* signals the response to end with the given status code.
**/
void Router::RoutingStack::next(uint32_t status)
{
if ((iter >= routes.end()) || status != 0)
{
iter = routes.end();
res.end(status ? status : 500);
} else {
route_t route = *iter;
iter++;
Next callback(this);
route(req, res, callback);
}
}
/*****************************************************************************/
/* Router */
/*****************************************************************************/
/**
* Bridging function between object function calls and non-object ones.
**/
static Router* bridge;
static void RouterInternalOnFinished(const Response& res)
{
bridge->internalOnFinished(res);
}
Router::Router(const char * _name, Response::ended_callback_t _onResponseFinished)
: name(_name),
stateMask(0xFFFFFFFF),
intentVector(),
getRoutes(),
postRoutes(),
stack(NULL),
onResponseFinished(_onResponseFinished)
{
// save object to global variable
bridge = this;
}
Router::~Router()
{
delete stack;
}
void Router::setStateMask(uint32_t _stateMask)
{
stateMask = _stateMask;
}
uint32_t Router::getStateMask() const
{
return stateMask;
}
void Router::registerIntent(intent_construction_delegate_t constructionCallback,
uint32_t intentState)
{
intent_t intentStruct = { .constructionCallback = constructionCallback,
.state = intentState };
intentVector.push_back(intentStruct);
}
void Router::get(const char* endpoint, route_t route, ...)
{
DEBUGOUT("configured route: GET %s ", endpoint);
/**
* Process the variadic arguments until a NULL entry is reached.
* Each callback found is added a list of middleware for that path.
* todo: the variadic arguments used here lead to a bad API (i.e. it
* requres a NULL termination and isn't type safe). Ideally we'd use
* an initializer list or templated function call here.
**/
std::vector<route_t> routes;
va_list va;
va_start(va, endpoint);
for (route_t i = route; i; i = va_arg(va, route_t))
{
if (i) routes.push_back(i);
}
va_end(va);
routes.push_back(route);
DEBUGOUT(" - %u middlewares regsitered\r\n", routes.size());
std::string endpointString = endpoint;
std::pair<std::string, std::vector<route_t> > pair(endpointString, routes);
getRoutes.insert(pair);
}
void Router::post(const char* endpoint, route_t route, ...)
{
DEBUGOUT("configured route: POST %s ", endpoint);
/**
* Process the variadic arguments until a NULL entry is reached.
* Each callback found is added a list of middleware for that path.
* todo: the variadic arguments used here lead to a bad API (i.e. it
* requres a NULL termination and isn't type safe). Ideally we'd use
* an initializer list or templated function call here.
**/
std::vector<route_t> routes;
va_list va;
va_start(va, endpoint);
for (route_t i = route; i; i = va_arg(va, route_t))
{
if (i) routes.push_back(i);
}
va_end(va);
DEBUGOUT(" - %u middlewares regsitered\r\n", routes.size());
std::string endpointString = endpoint;
std::pair<std::string, std::vector<route_t> > pair(endpointString, routes);
postRoutes.insert(pair);
}
void Router::homeResource(Request& req, Response& res) const
{
DEBUGOUT("home resource fetched\r\n");
/* find size of intent array
*/
uint32_t size = 0;
for(IntentVectorType::const_iterator iter = intentVector.begin();
iter != intentVector.end();
++iter)
{
if (iter->state & stateMask)
{
size++;
}
}
/* home resource consists of 2 fields:
name: of device
intents: the list of intents currently offered
*/
res.map(2)
.key(ShortKeyName).value(name, strlen(name)) // todo: remove this strlen
.key(ShortKeyIntents).array(size);
if (size > 0)
{
/* Iterate over all intents in vector, but only add those which
bitmap matches the current stateMask.
*/
for(IntentVectorType::const_iterator iter = intentVector.begin();
iter != intentVector.end();
++iter)
{
if (iter->state & stateMask)
{
// callback function is responsible for adding objects to encode
iter->constructionCallback(req, res);
}
}
}
res.end(200);
}
void Router::route(RouteMapType& routes, Request& req, Response& res)
{
DEBUGOUT("%s %s\r\n", req.getMethod() == Request::GET ? "GET" : "POST", req.getURL().c_str());
// the path to the requested resource
std::string url = req.getURL();
// the root resource is special and lists the available intents
if ((req.getMethod() == Request::GET) && (url.compare("/") == 0))
{
homeResource(req, res);
// root resource always found
return;
}
/* Resource requested is not the root.
Search the resource map for a matching callback function.
*/
RouteMapType::iterator iter = routes.find(url);
if (iter != routes.end())
{
/* The callback is also responsible for checking whether
the hub is in the correct state for this resource.
*/
DEBUGOUT(" -> route found\r\n");
stack = new RoutingStack(req, res, iter->second);
// kick off middleware chain
// a status code of 0 isn't a valid HTTP status code, so we use this
// to signal that execution should continue.
// any non-zero status code here would end execution of the middleware.
stack->next(0);
} else {
res.end(404);
}
}
void Router::processCBOR(BlockStatic* input, BlockStatic* output)
{
/* Decode CBOR array into CBOR objects
*/
Cborg decoder(input->getData(), input->getLength());
/* The output length is non-zero when the CBOR processing generated a response.
*/
output->setLength(0);
if (decoder.getType() == Cbor::TypeMap)
{
switch (decoder.getTag())
{
case Request::TAG:
{
DEBUGOUT("hub: received Request:\r\n");
#if VERBOSE_DEBUG_OUT
decoder.print();
DEBUGOUT("\r\n");
#endif
// provide request object
Request req = Request(decoder);
// construct a response object with pointers to the output buffer
// also forward the response-finished callback to be executed by the response itself
// once the end method is called.
// todo: pass the output biffer as a Block object rather than pointer + length
Response res = Response(req, output, RouterInternalOnFinished);
// route the request
switch (req.getMethod())
{
case Request::GET: {
this->route(getRoutes, req, res);
break;
}
case Request::POST: {
this->route(postRoutes, req, res);
break;
}
default: {
DEBUGOUT("hub: received unknown method in request: %04lX\r\n", req.getMethod());
DEBUGOUT("\r\n");
res.end(405);
break;
}
}
}
break;
default:
DEBUGOUT("hub: received unknown tag: %04lX\r\n", decoder.getTag());
#if VERBOSE_DEBUG_OUT
decoder.print();
DEBUGOUT("\r\n");
#endif
break;
}
}
}
void Router::internalOnFinished(const Response& res)
{
// clean up stack
delete stack;
stack = NULL;
// call user function
onResponseFinished(res);
}
<commit_msg>Disable debug output by default.<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2006-2015 ARM Limited
*
* 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 "equip/Router.h"
#include "cborg/Cbor.h"
#include "equip/Equip.h"
using namespace Equip;
#include <stdio.h>
#include <stdarg.h>
#if 0
#warning debug enabled
#define DEBUGOUT(...) { printf(__VA_ARGS__); }
#else
#define DEBUGOUT(...) /* nothing */
#endif // DEBUGOUT
/*****************************************************************************/
/* Router::Next */
/*****************************************************************************/
/**
* Create a callback functor that will dvance the state in the routing stack.
**/
Router::Next::Next(Router::RoutingStack* _stack)
: stack(_stack)
{}
/**
* Advances the state of the routing stack, triggering the next middleware
* in the chain to get exectuted (if it exists).
**/
void Router::Next::operator () (uint32_t status)
{
if (stack)
{
stack->next(status);
}
}
/*****************************************************************************/
/* RoutingStack */
/*****************************************************************************/
/**
* Initialises the state of the routing stack by creating an iterator on the routes
* held by the router.
**/
Router::RoutingStack::RoutingStack(Request& _req, Response& _res, std::vector<route_t>& _routes)
: req(_req), res(_res), iter(), routes(_routes)
{
iter = routes.begin();
}
/**
* Advances the iterator state if the status is not set (i.e. status == 0).
* If a status is set (i.e. status != 0) moves the iterator to the end and
* signals the response to end with the given status code.
**/
void Router::RoutingStack::next(uint32_t status)
{
if ((iter >= routes.end()) || status != 0)
{
iter = routes.end();
res.end(status ? status : 500);
} else {
route_t route = *iter;
iter++;
Next callback(this);
route(req, res, callback);
}
}
/*****************************************************************************/
/* Router */
/*****************************************************************************/
/**
* Bridging function between object function calls and non-object ones.
**/
static Router* bridge;
static void RouterInternalOnFinished(const Response& res)
{
bridge->internalOnFinished(res);
}
Router::Router(const char * _name, Response::ended_callback_t _onResponseFinished)
: name(_name),
stateMask(0xFFFFFFFF),
intentVector(),
getRoutes(),
postRoutes(),
stack(NULL),
onResponseFinished(_onResponseFinished)
{
// save object to global variable
bridge = this;
}
Router::~Router()
{
delete stack;
}
void Router::setStateMask(uint32_t _stateMask)
{
stateMask = _stateMask;
}
uint32_t Router::getStateMask() const
{
return stateMask;
}
void Router::registerIntent(intent_construction_delegate_t constructionCallback,
uint32_t intentState)
{
intent_t intentStruct = { .constructionCallback = constructionCallback,
.state = intentState };
intentVector.push_back(intentStruct);
}
void Router::get(const char* endpoint, route_t route, ...)
{
DEBUGOUT("configured route: GET %s ", endpoint);
/**
* Process the variadic arguments until a NULL entry is reached.
* Each callback found is added a list of middleware for that path.
* todo: the variadic arguments used here lead to a bad API (i.e. it
* requres a NULL termination and isn't type safe). Ideally we'd use
* an initializer list or templated function call here.
**/
std::vector<route_t> routes;
va_list va;
va_start(va, endpoint);
for (route_t i = route; i; i = va_arg(va, route_t))
{
if (i) routes.push_back(i);
}
va_end(va);
routes.push_back(route);
DEBUGOUT(" - %u middlewares regsitered\r\n", routes.size());
std::string endpointString = endpoint;
std::pair<std::string, std::vector<route_t> > pair(endpointString, routes);
getRoutes.insert(pair);
}
void Router::post(const char* endpoint, route_t route, ...)
{
DEBUGOUT("configured route: POST %s ", endpoint);
/**
* Process the variadic arguments until a NULL entry is reached.
* Each callback found is added a list of middleware for that path.
* todo: the variadic arguments used here lead to a bad API (i.e. it
* requres a NULL termination and isn't type safe). Ideally we'd use
* an initializer list or templated function call here.
**/
std::vector<route_t> routes;
va_list va;
va_start(va, endpoint);
for (route_t i = route; i; i = va_arg(va, route_t))
{
if (i) routes.push_back(i);
}
va_end(va);
DEBUGOUT(" - %u middlewares regsitered\r\n", routes.size());
std::string endpointString = endpoint;
std::pair<std::string, std::vector<route_t> > pair(endpointString, routes);
postRoutes.insert(pair);
}
void Router::homeResource(Request& req, Response& res) const
{
DEBUGOUT("home resource fetched\r\n");
/* find size of intent array
*/
uint32_t size = 0;
for(IntentVectorType::const_iterator iter = intentVector.begin();
iter != intentVector.end();
++iter)
{
if (iter->state & stateMask)
{
size++;
}
}
/* home resource consists of 2 fields:
name: of device
intents: the list of intents currently offered
*/
res.map(2)
.key(ShortKeyName).value(name, strlen(name)) // todo: remove this strlen
.key(ShortKeyIntents).array(size);
if (size > 0)
{
/* Iterate over all intents in vector, but only add those which
bitmap matches the current stateMask.
*/
for(IntentVectorType::const_iterator iter = intentVector.begin();
iter != intentVector.end();
++iter)
{
if (iter->state & stateMask)
{
// callback function is responsible for adding objects to encode
iter->constructionCallback(req, res);
}
}
}
res.end(200);
}
void Router::route(RouteMapType& routes, Request& req, Response& res)
{
DEBUGOUT("%s %s\r\n", req.getMethod() == Request::GET ? "GET" : "POST", req.getURL().c_str());
// the path to the requested resource
std::string url = req.getURL();
// the root resource is special and lists the available intents
if ((req.getMethod() == Request::GET) && (url.compare("/") == 0))
{
homeResource(req, res);
// root resource always found
return;
}
/* Resource requested is not the root.
Search the resource map for a matching callback function.
*/
RouteMapType::iterator iter = routes.find(url);
if (iter != routes.end())
{
/* The callback is also responsible for checking whether
the hub is in the correct state for this resource.
*/
DEBUGOUT(" -> route found\r\n");
stack = new RoutingStack(req, res, iter->second);
// kick off middleware chain
// a status code of 0 isn't a valid HTTP status code, so we use this
// to signal that execution should continue.
// any non-zero status code here would end execution of the middleware.
stack->next(0);
} else {
res.end(404);
}
}
void Router::processCBOR(BlockStatic* input, BlockStatic* output)
{
/* Decode CBOR array into CBOR objects
*/
Cborg decoder(input->getData(), input->getLength());
/* The output length is non-zero when the CBOR processing generated a response.
*/
output->setLength(0);
if (decoder.getType() == Cbor::TypeMap)
{
switch (decoder.getTag())
{
case Request::TAG:
{
DEBUGOUT("hub: received Request:\r\n");
#if VERBOSE_DEBUG_OUT
decoder.print();
DEBUGOUT("\r\n");
#endif
// provide request object
Request req = Request(decoder);
// construct a response object with pointers to the output buffer
// also forward the response-finished callback to be executed by the response itself
// once the end method is called.
// todo: pass the output biffer as a Block object rather than pointer + length
Response res = Response(req, output, RouterInternalOnFinished);
// route the request
switch (req.getMethod())
{
case Request::GET: {
this->route(getRoutes, req, res);
break;
}
case Request::POST: {
this->route(postRoutes, req, res);
break;
}
default: {
DEBUGOUT("hub: received unknown method in request: %04lX\r\n", req.getMethod());
DEBUGOUT("\r\n");
res.end(405);
break;
}
}
}
break;
default:
DEBUGOUT("hub: received unknown tag: %04lX\r\n", decoder.getTag());
#if VERBOSE_DEBUG_OUT
decoder.print();
DEBUGOUT("\r\n");
#endif
break;
}
}
}
void Router::internalOnFinished(const Response& res)
{
// clean up stack
delete stack;
stack = NULL;
// call user function
onResponseFinished(res);
}
<|endoftext|> |
<commit_before>/* main.cpp
* localcall main file - locally loads a shared library, instantiates a module and calls a function from that module
*/
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <getopt.h>
#include <boost/shared_ptr.hpp>
#include <qi/os.hpp>
#include <qi/path.hpp>
#include <qi/log.hpp>
#include <alcommon/almodule.h>
#include <alcommon/alproxy.h>
#include <alcommon/albroker.h>
#include <alcommon/albrokermanager.h>
// Turn bold text on
std::ostream& bold_on(std::ostream& os)
{
return os << "\e[1m";
}
// Turn bold text off
std::ostream& bold_off(std::ostream& os)
{
return os << "\e[0m";
}
// Wrong number of arguments
void argErr(void)
{
// Standard usage message
std::string usage = "Usage: localcall [--pip robot_ip] [--pport port] [--lib library] [--mod module] [--fun function]";
std::cerr << "Wrong number of arguments!" << std::endl;
std::cerr << usage << std::endl;
exit(2);
}
int main(int argc, char* argv[])
{
// Default name of desired library
std::string libName = "libmoduletest.so";
// Default name of desired module in library
std::string moduleName = "ModuleTest";
// Default name of void(void) function to call in module
std::string funcName = "printHello";
// Set broker name, ip and port, finding first available port from 54000
const std::string brokerName = "localCallBroker";
int brokerPort = qi::os::findAvailablePort(54000);
const std::string brokerIp = "0.0.0.0";
// Default parent port and ip
int pport = 9559;
std::string pip = "127.0.0.1";
// Check for odd number of command line arguments (in this case)
if (argc % 2 != 1)
{
argErr();
}
// Get any arguments
while (true)
{
static int index = 0;
// Struct of options
static const struct option longopts[] =
{
{"pip", 1, 0, 'p'},
{"pport", 1, 0, 'o'},
{"lib", 1, 0, 'l'},
{"mod", 1, 0, 'm'},
{"fun", 1, 0, 'f'},
{0, 0, 0, 0 }
};
switch(index = getopt_long(argc, argv, "", longopts, &index))
{
case 'p':
if (optarg)
pip = std::string(optarg);
else
argErr();
break;
case 'o':
if (optarg)
pport = atoi(optarg);
else
argErr();
break;
case 'l':
if (optarg)
libName = std::string(optarg);
else
argErr();
break;
case 'm':
if (optarg)
moduleName = std::string(optarg);
else
argErr();
break;
case 'f':
if (optarg)
funcName = std::string(optarg);
else
argErr();
break;
}
if (index == -1)
break;
}
// Need this for SOAP serialisation of floats to work
setlocale(LC_NUMERIC, "C");
// Create a broker
boost::shared_ptr<AL::ALBroker> broker;
try
{
broker = AL::ALBroker::createBroker(
brokerName,
brokerIp,
brokerPort,
pip,
pport,
0);
}
// Throw error and quit if a broker could not be created
catch(...)
{
std::cerr << "Failed to connect broker to: "
<< pip
<< ":"
<< pport
<< std::endl;
AL::ALBrokerManager::getInstance()->killAllBroker();
AL::ALBrokerManager::kill();
return 1;
}
// Add the broker to NAOqi
AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
AL::ALBrokerManager::getInstance()->addBroker(broker);
// Find the desired library
std::cout << bold_on << "Finding " << libName << "..." << bold_off << std::endl;
std::string library = qi::path::findLib(libName.c_str());
// Open the library
std::cout << bold_on << "Loading " << library << "..." << bold_off << std::endl;
void* handle = qi::os::dlopen(library.c_str());
if (!handle)
{
qiLogWarning(moduleName.c_str()) << "Could not load library:"
<< qi::os::dlerror()
<< std::endl;
return -1;
}
// Load the create symbol
std::cout << bold_on << "Loading _createModule symbol..." << bold_off << std::endl;
int(*createModule)(boost::shared_ptr<AL::ALBroker>) = (int(*)(boost::shared_ptr<AL::ALBroker>))(qi::os::dlsym(handle, "_createModule"));
if (!createModule)
{
qiLogWarning(moduleName.c_str()) << "Could not load symbol _createModule: "
<< qi::os::dlerror()
<< std::endl;
return -1;
}
// Check if module is already present
std::cout << bold_on << "Module " << moduleName << " is ";
if (!(broker->isModulePresent(moduleName)))
{
std::cout << "not ";
}
std::cout << "present" << bold_off << std::endl;
// Create an instance of the desired module
std::cout << bold_on << "Creating " << moduleName << " instance..." << bold_off << std::endl;
createModule(broker);
// Check for module creation
std::cout << bold_on << "Module " << moduleName.c_str() << " is ";
if (!(broker->isModulePresent(moduleName)))
{
std::cout << "not ";
}
std::cout << "present" << bold_off << std::endl;
// Create a proxy to the module
std::cout << bold_on << "Creating proxy to module..." << bold_off << std::endl;
AL::ALProxy testProxy(moduleName, pip, pport);
// Call a generic function from the module with no arguments
std::cout << bold_on << "Calling function " << funcName << "..." << bold_off << std::endl;
testProxy.callVoid(funcName);
// Get a handle to the module and close it
{
boost::shared_ptr<AL::ALModuleCore> module = broker->getModuleByName(moduleName);
std::cout << bold_on << "Closing module " << moduleName << "..." << bold_off << std::endl;
module->exit();
}
// Check module has closed
std::cout << bold_on << "Module " << moduleName << " is ";
if (!(broker->isModulePresent(moduleName)))
{
std::cout << "not ";
}
std::cout << "present" << bold_off << std::endl;
// Close the broker
std::cout << bold_on << "Closing broker..." << bold_off << std::endl;
broker->shutdown();
// Exit program
std::cout << bold_on << "Exiting..." << bold_off << std::endl;
return 0;
}
<commit_msg>Added extra localcall options<commit_after>/* main.cpp
* localcall main file - locally loads a shared library, instantiates a module and calls a function from that module
*/
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <getopt.h>
#include <boost/shared_ptr.hpp>
#include <qi/os.hpp>
#include <qi/path.hpp>
#include <qi/log.hpp>
#include <alcommon/almodule.h>
#include <alcommon/alproxy.h>
#include <alcommon/albroker.h>
#include <alcommon/albrokermanager.h>
// Turn bold text on
std::ostream& bold_on(std::ostream& os)
{
return os << "\e[1m";
}
// Turn bold text off
std::ostream& bold_off(std::ostream& os)
{
return os << "\e[0m";
}
// Wrong number of arguments
void argErr(void)
{
// Standard usage message
std::string usage = "Usage: localcall [--pip robot_ip] [--pport port] [--lib library] [--mod module] [--fun function]";
std::cerr << usage << std::endl;
exit(2);
}
int main(int argc, char* argv[])
{
// Whether to print verbose output - default off
bool verb = false;
// Default name of desired library
std::string libName = "libmoduletest.so";
// Default name of desired module in library
std::string moduleName = "ModuleTest";
// Default name of void(void) function to call in module
std::string funcName = "printHello";
// Set broker name, ip and port, finding first available port from 54000
const std::string brokerName = "localCallBroker";
int brokerPort = qi::os::findAvailablePort(54000);
const std::string brokerIp = "0.0.0.0";
// Default parent port and ip
int pport = 9559;
std::string pip = "127.0.0.1";
// Check for odd number of command line arguments (in this case)
/* if (argc % 2 != 1)
{
argErr();
}
*/
// Get any arguments
while (true)
{
static int index = 0;
// Struct of options
// Columns are:
// {Option name, Option required?, flag(not needed here), return value/character}
static const struct option longopts[] =
{
{"pip", 1, 0, 'p'},
{"pport", 1, 0, 'o'},
{"lib", 1, 0, 'l'},
{"mod", 1, 0, 'm'},
{"fun", 1, 0, 'f'},
{"verb", 0, 0, 'v'},
{"help", 0, 0, 'h'},
{0, 0, 0, 0 }
};
// Get next option, and check return value
// p:o:l:m:f:vh allow short option specification
switch(index = getopt_long(argc, argv, "p:o:l:m:f:vh", longopts, &index))
{
// Print usage and quit
case 'h':
argErr();
break;
// Set parent IP
case 'p':
if (optarg)
pip = std::string(optarg);
else
argErr();
break;
// Set parent port
case 'o':
if (optarg)
pport = atoi(optarg);
else
argErr();
break;
// Set library name
case 'l':
if (optarg)
libName = std::string(optarg);
else
argErr();
break;
// Set module name
case 'm':
if (optarg)
moduleName = std::string(optarg);
else
argErr();
break;
// Set function name
case 'f':
if (optarg)
funcName = std::string(optarg);
else
argErr();
break;
case 'v':
verb = true;
}
if (index == -1)
break;
}
// Need this for SOAP serialisation of floats to work
setlocale(LC_NUMERIC, "C");
// Create a broker
if(verb)
std::cout << bold_on << "Creating broker..." << bold_off << std::endl;
boost::shared_ptr<AL::ALBroker> broker;
try
{
broker = AL::ALBroker::createBroker(
brokerName,
brokerIp,
brokerPort,
pip,
pport,
0);
}
// Throw error and quit if a broker could not be created
catch(...)
{
std::cerr << "Failed to connect broker to: "
<< pip
<< ":"
<< pport
<< std::endl;
AL::ALBrokerManager::getInstance()->killAllBroker();
AL::ALBrokerManager::kill();
return 1;
}
// Add the broker to NAOqi
AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
AL::ALBrokerManager::getInstance()->addBroker(broker);
// Find the desired library
if(verb)
std::cout << bold_on << "Finding " << libName << "..." << bold_off << std::endl;
std::string library = qi::path::findLib(libName.c_str());
// Open the library
if(verb)
std::cout << bold_on << "Loading " << library << "..." << bold_off << std::endl;
void* handle = qi::os::dlopen(library.c_str());
if (!handle)
{
qiLogWarning(moduleName.c_str()) << "Could not load library:"
<< qi::os::dlerror()
<< std::endl;
return -1;
}
// Load the create symbol
if(verb)
std::cout << bold_on << "Loading _createModule symbol..." << bold_off << std::endl;
int(*createModule)(boost::shared_ptr<AL::ALBroker>) = (int(*)(boost::shared_ptr<AL::ALBroker>))(qi::os::dlsym(handle, "_createModule"));
if (!createModule)
{
qiLogWarning(moduleName.c_str()) << "Could not load symbol _createModule: "
<< qi::os::dlerror()
<< std::endl;
return -1;
}
// Check if module is already present
if(verb)
{
std::cout << bold_on << "Module " << moduleName << " is ";
if (!(broker->isModulePresent(moduleName)))
{
std::cout << "not ";
}
std::cout << "present" << bold_off << std::endl;
}
// Create an instance of the desired module
if(verb)
std::cout << bold_on << "Creating " << moduleName << " instance..." << bold_off << std::endl;
createModule(broker);
// Check for module creation
if(verb)
{
std::cout << bold_on << "Module " << moduleName.c_str() << " is ";
if (!(broker->isModulePresent(moduleName)))
{
std::cout << "not ";
}
std::cout << "present" << bold_off << std::endl;
}
// Create a proxy to the module
if(verb)
std::cout << bold_on << "Creating proxy to module..." << bold_off << std::endl;
AL::ALProxy testProxy(moduleName, pip, pport);
// Call a generic function from the module with no arguments
if(verb)
std::cout << bold_on << "Calling function " << funcName << "..." << bold_off << std::endl;
testProxy.callVoid(funcName);
// Get a handle to the module and close it
{
boost::shared_ptr<AL::ALModuleCore> module = broker->getModuleByName(moduleName);
std::cout << bold_on << "Closing module " << moduleName << "..." << bold_off << std::endl;
module->exit();
}
// Check module has closed
if(verb)
{
std::cout << bold_on << "Module " << moduleName << " is ";
if (!(broker->isModulePresent(moduleName)))
{
std::cout << "not ";
}
std::cout << "present" << bold_off << std::endl;
}
// Close the broker
if(verb)
std::cout << bold_on << "Closing broker..." << bold_off << std::endl;
broker->shutdown();
// Exit program
if(verb)
std::cout << bold_on << "Exiting..." << bold_off << std::endl;
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>More minor improvements<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/File.h>
#include <fstream>
#include <random>
#include <boost/filesystem.hpp>
#include <fmt/core.h>
#include <glog/logging.h>
#include <folly/String.h>
#include <folly/portability/Fcntl.h>
#include <folly/portability/GTest.h>
using namespace folly;
namespace fs = boost::filesystem;
namespace {
void expectWouldBlock(ssize_t r) {
int savedErrno = errno;
EXPECT_EQ(-1, r);
EXPECT_EQ(EAGAIN, savedErrno) << errnoStr(savedErrno);
}
void expectOK(ssize_t r) {
int savedErrno = errno;
EXPECT_LE(0, r) << ": errno=" << errnoStr(savedErrno);
}
class TempDir {
public:
static fs::path make_path() {
std::random_device rng;
std::uniform_int_distribution<uint64_t> dist;
auto basename = "folly-unit-test-" + fmt::format("{:016x}", dist(rng));
return fs::canonical(fs::temp_directory_path()) / basename;
}
fs::path const path{make_path()};
TempDir() { fs::create_directory(path); }
~TempDir() { fs::remove_all(path); }
};
} // namespace
TEST(File, Simple) {
TempDir tmpd;
auto tmpf = tmpd.path / "foobar.txt";
std::ofstream{tmpf.native()} << "hello world" << std::endl;
// Open a file, ensure it's indeed open for reading
char buf = 'x';
{
File f(tmpf.string());
EXPECT_NE(-1, f.fd());
EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
f.close();
EXPECT_EQ(-1, f.fd());
}
}
TEST(File, SimpleStringPiece) {
TempDir tmpd;
auto tmpf = tmpd.path / "foobar.txt";
std::ofstream{tmpf.native()} << "hello world" << std::endl;
char buf = 'x';
File f(StringPiece(tmpf.string()));
EXPECT_NE(-1, f.fd());
EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
f.close();
EXPECT_EQ(-1, f.fd());
}
TEST(File, OwnsFd) {
// Wrap a file descriptor, make sure that ownsFd works
// We'll test that the file descriptor is closed by closing the writing
// end of a pipe and making sure that a non-blocking read from the reading
// end returns 0.
char buf = 'x';
int p[2];
expectOK(::pipe(p));
int flags = ::fcntl(p[0], F_GETFL);
expectOK(flags);
expectOK(::fcntl(p[0], F_SETFL, flags | O_NONBLOCK));
expectWouldBlock(::read(p[0], &buf, 1));
{
File f(p[1]);
EXPECT_EQ(p[1], f.fd());
}
// Ensure that moving the file doesn't close it
{
File f(p[1]);
EXPECT_EQ(p[1], f.fd());
File f1(std::move(f));
EXPECT_EQ(-1, f.fd());
EXPECT_EQ(p[1], f1.fd());
}
expectWouldBlock(::read(p[0], &buf, 1)); // not closed
{
File f(p[1], true);
EXPECT_EQ(p[1], f.fd());
}
ssize_t r = ::read(p[0], &buf, 1); // eof
expectOK(r);
EXPECT_EQ(0, r);
::close(p[0]);
}
TEST(File, Release) {
File in(STDOUT_FILENO, false);
CHECK_EQ(STDOUT_FILENO, in.release());
CHECK_EQ(-1, in.release());
}
#define EXPECT_CONTAINS(haystack, needle) \
EXPECT_NE(::std::string::npos, ::folly::StringPiece(haystack).find(needle)) \
<< "Haystack: '" << haystack << "'\nNeedle: '" << needle << "'";
TEST(File, UsefulError) {
try {
File("does_not_exist.txt", 0, 0666);
} catch (const std::runtime_error& e) {
EXPECT_CONTAINS(e.what(), "does_not_exist.txt");
EXPECT_CONTAINS(e.what(), "0666");
}
}
TEST(File, Truthy) {
File temp = File::temporary();
EXPECT_TRUE(bool(temp));
if (temp) {
;
} else {
ADD_FAILURE();
}
if (File file = File::temporary()) {
;
} else {
ADD_FAILURE();
}
EXPECT_FALSE(bool(File()));
if (File()) {
ADD_FAILURE();
}
if (File notOpened = File()) {
ADD_FAILURE();
}
}
TEST(File, HelperCtor) {
TempDir tmpd;
auto tmpf = tmpd.path / "foobar.txt";
File::makeFile(StringPiece(tmpf.string())).then([](File&& f) {
char buf = 'x';
EXPECT_NE(-1, f.fd());
EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
f.close();
EXPECT_EQ(-1, f.fd());
});
}
<commit_msg>use std::filesystem in File tests<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/File.h>
#include <fstream>
#include <random>
#include <fmt/core.h>
#include <glog/logging.h>
#include <folly/String.h>
#include <folly/portability/Fcntl.h>
#include <folly/portability/Filesystem.h>
#include <folly/portability/GTest.h>
using namespace folly;
namespace {
void expectWouldBlock(ssize_t r) {
int savedErrno = errno;
EXPECT_EQ(-1, r);
EXPECT_EQ(EAGAIN, savedErrno) << errnoStr(savedErrno);
}
void expectOK(ssize_t r) {
int savedErrno = errno;
EXPECT_LE(0, r) << ": errno=" << errnoStr(savedErrno);
}
class TempDir {
public:
static fs::path make_path() {
std::random_device rng;
std::uniform_int_distribution<uint64_t> dist;
auto basename = "folly-unit-test-" + fmt::format("{:016x}", dist(rng));
return fs::canonical(fs::temp_directory_path()) / basename;
}
fs::path const path{make_path()};
TempDir() { fs::create_directory(path); }
~TempDir() { fs::remove_all(path); }
};
} // namespace
TEST(File, Simple) {
TempDir tmpd;
auto tmpf = tmpd.path / "foobar.txt";
std::ofstream{tmpf.native()} << "hello world" << std::endl;
// Open a file, ensure it's indeed open for reading
char buf = 'x';
{
File f(tmpf.string());
EXPECT_NE(-1, f.fd());
EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
f.close();
EXPECT_EQ(-1, f.fd());
}
}
TEST(File, SimpleStringPiece) {
TempDir tmpd;
auto tmpf = tmpd.path / "foobar.txt";
std::ofstream{tmpf.native()} << "hello world" << std::endl;
char buf = 'x';
File f(StringPiece(tmpf.string()));
EXPECT_NE(-1, f.fd());
EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
f.close();
EXPECT_EQ(-1, f.fd());
}
TEST(File, OwnsFd) {
// Wrap a file descriptor, make sure that ownsFd works
// We'll test that the file descriptor is closed by closing the writing
// end of a pipe and making sure that a non-blocking read from the reading
// end returns 0.
char buf = 'x';
int p[2];
expectOK(::pipe(p));
int flags = ::fcntl(p[0], F_GETFL);
expectOK(flags);
expectOK(::fcntl(p[0], F_SETFL, flags | O_NONBLOCK));
expectWouldBlock(::read(p[0], &buf, 1));
{
File f(p[1]);
EXPECT_EQ(p[1], f.fd());
}
// Ensure that moving the file doesn't close it
{
File f(p[1]);
EXPECT_EQ(p[1], f.fd());
File f1(std::move(f));
EXPECT_EQ(-1, f.fd());
EXPECT_EQ(p[1], f1.fd());
}
expectWouldBlock(::read(p[0], &buf, 1)); // not closed
{
File f(p[1], true);
EXPECT_EQ(p[1], f.fd());
}
ssize_t r = ::read(p[0], &buf, 1); // eof
expectOK(r);
EXPECT_EQ(0, r);
::close(p[0]);
}
TEST(File, Release) {
File in(STDOUT_FILENO, false);
CHECK_EQ(STDOUT_FILENO, in.release());
CHECK_EQ(-1, in.release());
}
#define EXPECT_CONTAINS(haystack, needle) \
EXPECT_NE(::std::string::npos, ::folly::StringPiece(haystack).find(needle)) \
<< "Haystack: '" << haystack << "'\nNeedle: '" << needle << "'";
TEST(File, UsefulError) {
try {
File("does_not_exist.txt", 0, 0666);
} catch (const std::runtime_error& e) {
EXPECT_CONTAINS(e.what(), "does_not_exist.txt");
EXPECT_CONTAINS(e.what(), "0666");
}
}
TEST(File, Truthy) {
File temp = File::temporary();
EXPECT_TRUE(bool(temp));
if (temp) {
;
} else {
ADD_FAILURE();
}
if (File file = File::temporary()) {
;
} else {
ADD_FAILURE();
}
EXPECT_FALSE(bool(File()));
if (File()) {
ADD_FAILURE();
}
if (File notOpened = File()) {
ADD_FAILURE();
}
}
TEST(File, HelperCtor) {
TempDir tmpd;
auto tmpf = tmpd.path / "foobar.txt";
File::makeFile(StringPiece(tmpf.string())).then([](File&& f) {
char buf = 'x';
EXPECT_NE(-1, f.fd());
EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
f.close();
EXPECT_EQ(-1, f.fd());
});
}
<|endoftext|> |
<commit_before>/*=============================================================================
Library: CppMicroServices
Copyright (c) The CppMicroServices developers. See the COPYRIGHT
file at the top-level directory of this distribution and at
https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .
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 "CCActiveState.hpp"
#include "../ComponentConfigurationImpl.hpp"
#include "CCUnsatisfiedReferenceState.hpp"
#include "cppmicroservices/detail/ScopeGuard.h"
#include "cppmicroservices/SharedLibraryException.h"
namespace cppmicroservices {
namespace scrimpl {
CCActiveState::CCActiveState() = default;
std::shared_ptr<ComponentInstance> CCActiveState::Activate(
ComponentConfigurationImpl& mgr,
const cppmicroservices::Bundle& clientBundle)
{
std::shared_ptr<ComponentInstance> instance;
auto logger = mgr.GetLogger();
if (latch.CountUp()) {
{
detail::ScopeGuard sg([this, logger]() {
// By using try/catch here, we ensure that this lambda function doesn't
// throw inside LatchScopeGuard's dtor.
try {
latch.CountDown();
} catch (...) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"latch.CountDown() threw an exception during "
"LatchScopeGuard cleanup.",
std::current_exception());
}
});
std::lock_guard<std::mutex> lock(oneAtATimeMutex);
// Make sure the state didn't change while we were waiting
auto currentState = mgr.GetState();
if (currentState->GetValue() !=
service::component::runtime::dto::ComponentState::ACTIVE) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_WARNING,
"Activate failed. Component no longer in Active State.");
return nullptr;
}
// no state change, already in active state. create and return a ComponentInstance object
// This could throw; a scope guard is put in place to call latch.CountDown().
instance = mgr.CreateAndActivateComponentInstance(clientBundle);
// Just in case the configuration properties changed between Registration and
// Construction of the component, update the properties in the service registration object.
// An example of when this could happen is when immediate=false and configuration-policy
// = optional. The component could be registered before all the configuration objects are
// available but it won't be constructed until someone gets the service. In between those
// two activities the configuration objects could change and the service registration properties
// would be out of date.
if (instance) {
mgr.SetRegistrationProperties();
}
}
if (!instance) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"Component configuration activation failed");
}
return instance;
}
// do not allow any new component instances to be created if Deactivate was called
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_DEBUG,
"Component configuration activation failed because component is "
"not in active state");
return nullptr;
}
void CCActiveState::Deactivate(ComponentConfigurationImpl& mgr)
{
auto currentState = shared_from_this();
std::promise<void> transitionAction;
auto fut = transitionAction.get_future();
auto unsatisfiedState =
std::make_shared<CCUnsatisfiedReferenceState>(std::move(fut));
while (
currentState->GetValue() !=
service::component::runtime::dto::ComponentState::UNSATISFIED_REFERENCE) {
if (mgr.CompareAndSetState(¤tState, unsatisfiedState)) {
// The currentState is CCActiveState so the WaitForTransitionTask is the version
// that waits for the latch. The Deactivate function won't continue until
// the latch counts down to 0, thereby allowing all Activate, Rebind and Modified
// activities to complete.
currentState->WaitForTransitionTask(); // wait for the previous transition to finish
mgr.UnregisterService();
mgr.DestroyComponentInstances();
transitionAction.set_value();
}
}
}
bool CCActiveState::Modified(ComponentConfigurationImpl& mgr)
{
auto logger = mgr.GetLogger();
if (latch.CountUp()) {
detail::ScopeGuard sg([this, logger]() {
// By using try/catch here, we ensure that this lambda function doesn't
// throw inside LatchScopeGuard's dtor.
try {
latch.CountDown();
} catch (...) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"latch.CountDown() threw an exception during "
"LatchScopeGuard cleanup in CCActiveState::Modified.",
std::current_exception());
}
});
std::lock_guard<std::mutex> lock(oneAtATimeMutex);
// Make sure the state didn't change while we were waiting
auto currentState = mgr.GetState();
if (currentState->GetValue() !=
service::component::runtime::dto::ComponentState::ACTIVE) {
auto logger = mgr.GetLogger();
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_WARNING,
"Modified failed. Component no longer in Active State.");
return false;
}
bool result = mgr.ModifyComponentInstanceProperties();
if (result) {
// Update service registration properties
mgr.SetRegistrationProperties();
return true;
}
} // count down the latch and release the lock
Deactivate(mgr);
// Service registration properties will be updated when the service is
// registered. Don't need to do it here.
return false;
};
void CCActiveState::Rebind(ComponentConfigurationImpl & mgr,
const std::string& refName,
const ServiceReference<void>& svcRefToBind,
const ServiceReference<void>& svcRefToUnbind)
{
auto logger = mgr.GetLogger();
if (latch.CountUp()) {
detail::ScopeGuard sg([this, logger]() {
// By using try/catch here, we ensure that this lambda function doesn't
// throw inside LatchScopeGuard's dtor.
try {
latch.CountDown();
} catch (...) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"latch.CountDown() threw an exception during "
"LatchScopeGuard cleanup in CCActiveState::Modified.",
std::current_exception());
}
});
std::lock_guard<std::mutex> lock(oneAtATimeMutex);
// Make sure the state didn't change while we were waiting
auto currentState = mgr.GetState();
if (currentState->GetValue() !=
service::component::runtime::dto::ComponentState::ACTIVE) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_WARNING,
"Rebind failed. Component no longer in Active State.");
return;
}
if (svcRefToBind) {
try {
mgr.BindReference(refName, svcRefToBind);
} catch (const std::exception&) {
mgr.GetLogger()->Log(
cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"Exception while dynamically binding a reference. ",
std::current_exception());
}
}
if (svcRefToUnbind) {
try {
mgr.UnbindReference(refName, svcRefToUnbind);
} catch (const std::exception&) {
mgr.GetLogger()->Log(
cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"Exception while dynamically unbinding a reference. ",
std::current_exception());
}
}
}
}
}
}
<commit_msg>Cppms patch (#637)<commit_after>/*=============================================================================
Library: CppMicroServices
Copyright (c) The CppMicroServices developers. See the COPYRIGHT
file at the top-level directory of this distribution and at
https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .
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 "CCActiveState.hpp"
#include "../ComponentConfigurationImpl.hpp"
#include "CCUnsatisfiedReferenceState.hpp"
#include "cppmicroservices/detail/ScopeGuard.h"
#include "cppmicroservices/SharedLibraryException.h"
namespace cppmicroservices {
namespace scrimpl {
CCActiveState::CCActiveState() = default;
std::shared_ptr<ComponentInstance> CCActiveState::Activate(
ComponentConfigurationImpl& mgr,
const cppmicroservices::Bundle& clientBundle)
{
std::shared_ptr<ComponentInstance> instance;
auto logger = mgr.GetLogger();
if (latch.CountUp()) {
{
detail::ScopeGuard sg([this, logger]() {
// By using try/catch here, we ensure that this lambda function doesn't
// throw inside LatchScopeGuard's dtor.
try {
latch.CountDown();
} catch (...) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"latch.CountDown() threw an exception during "
"LatchScopeGuard cleanup.",
std::current_exception());
}
});
std::lock_guard<std::mutex> lock(oneAtATimeMutex);
// Make sure the state didn't change while we were waiting
auto currentState = mgr.GetState();
if (currentState->GetValue() !=
service::component::runtime::dto::ComponentState::ACTIVE) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_WARNING,
"Activate failed. Component no longer in Active State.");
return nullptr;
}
// no state change, already in active state. create and return a ComponentInstance object
// This could throw; a scope guard is put in place to call latch.CountDown().
instance = mgr.CreateAndActivateComponentInstance(clientBundle);
// Just in case the configuration properties changed between Registration and
// Construction of the component, update the properties in the service registration object.
// An example of when this could happen is when immediate=false and configuration-policy
// = optional. The component could be registered before all the configuration objects are
// available but it won't be constructed until someone gets the service. In between those
// two activities the configuration objects could change and the service registration properties
// would be out of date.
if (instance) {
mgr.SetRegistrationProperties();
}
}
if (!instance) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"Component configuration activation failed");
}
return instance;
}
// do not allow any new component instances to be created if Deactivate was called
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_DEBUG,
"Component configuration activation failed because component is "
"not in active state");
return nullptr;
}
void CCActiveState::Deactivate(ComponentConfigurationImpl& mgr)
{
auto currentState = shared_from_this();
std::promise<void> transitionAction;
auto fut = transitionAction.get_future();
auto unsatisfiedState =
std::make_shared<CCUnsatisfiedReferenceState>(std::move(fut));
while (
currentState->GetValue() !=
service::component::runtime::dto::ComponentState::UNSATISFIED_REFERENCE) {
if (mgr.CompareAndSetState(¤tState, unsatisfiedState)) {
// The currentState is CCActiveState so the WaitForTransitionTask is the version
// that waits for the latch. The Deactivate function won't continue until
// the latch counts down to 0, thereby allowing all Activate, Rebind and Modified
// activities to complete.
currentState->WaitForTransitionTask(); // wait for the previous transition to finish
mgr.UnregisterService();
mgr.DestroyComponentInstances();
transitionAction.set_value();
}
}
}
bool CCActiveState::Modified(ComponentConfigurationImpl& mgr)
{
auto logger = mgr.GetLogger();
if (latch.CountUp()) {
detail::ScopeGuard sg([this, logger]() {
// By using try/catch here, we ensure that this lambda function doesn't
// throw inside LatchScopeGuard's dtor.
try {
latch.CountDown();
} catch (...) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"latch.CountDown() threw an exception during "
"LatchScopeGuard cleanup in CCActiveState::Modified.",
std::current_exception());
}
});
std::lock_guard<std::mutex> lock(oneAtATimeMutex);
// Make sure the state didn't change while we were waiting
auto currentState = mgr.GetState();
if (currentState->GetValue() !=
service::component::runtime::dto::ComponentState::ACTIVE) {
auto logger = mgr.GetLogger();
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_WARNING,
"Modified failed. Component no longer in Active State.");
return false;
}
bool result = mgr.ModifyComponentInstanceProperties();
if (result) {
// Update service registration properties
mgr.SetRegistrationProperties();
return true;
}
} // count down the latch and release the lock
Deactivate(mgr);
// Service registration properties will be updated when the service is
// registered. Don't need to do it here.
return false;
};
void CCActiveState::Rebind(ComponentConfigurationImpl & mgr,
const std::string& refName,
const ServiceReference<void>& svcRefToBind,
const ServiceReference<void>& svcRefToUnbind)
{
auto logger = mgr.GetLogger();
if (latch.CountUp()) {
detail::ScopeGuard sg([this, logger]() {
// By using try/catch here, we ensure that this lambda function doesn't
// throw inside LatchScopeGuard's dtor.
try {
latch.CountDown();
} catch (...) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"latch.CountDown() threw an exception during "
"LatchScopeGuard cleanup in CCActiveState::Rebind.",
std::current_exception());
}
});
std::lock_guard<std::mutex> lock(oneAtATimeMutex);
// Make sure the state didn't change while we were waiting
auto currentState = mgr.GetState();
if (currentState->GetValue() !=
service::component::runtime::dto::ComponentState::ACTIVE) {
logger->Log(cppmicroservices::logservice::SeverityLevel::LOG_WARNING,
"Rebind failed. Component no longer in Active State.");
return;
}
if (svcRefToBind) {
try {
mgr.BindReference(refName, svcRefToBind);
} catch (const std::exception&) {
mgr.GetLogger()->Log(
cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"Exception while dynamically binding a reference. ",
std::current_exception());
}
}
if (svcRefToUnbind) {
try {
mgr.UnbindReference(refName, svcRefToUnbind);
} catch (const std::exception&) {
mgr.GetLogger()->Log(
cppmicroservices::logservice::SeverityLevel::LOG_ERROR,
"Exception while dynamically unbinding a reference. ",
std::current_exception());
}
}
}
}
}
}
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Andrew Manson <g.real.ate@gmail.com>
//
#include "KmlTagWriter.h"
#include "GeoWriter.h"
#include "KmlElementDictionary.h"
namespace Marble
{
static GeoTagWriterRegistrar s_writerKml( GeoTagWriter::QualifiedName( "",
kml::kmlTag_nameSpace22),
new KmlTagWriter() );
bool KmlTagWriter::write( const GeoNode *node, GeoWriter& writer ) const
{
Q_UNUSED(node);
writer.writeStartElement( "kml" );
writer.writeAttribute( "xmlns", kml::kmlTag_nameSpace22 );
writer.writeAttribute( "xmlns:gx", kml::kmlTag_nameSpaceGx22 );
// Do not write an end element for document handlers
return true;
}
}
<commit_msg>Write namespaces using the respective methods, not via attributes.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Andrew Manson <g.real.ate@gmail.com>
//
#include "KmlTagWriter.h"
#include "GeoWriter.h"
#include "KmlElementDictionary.h"
namespace Marble
{
static GeoTagWriterRegistrar s_writerKml( GeoTagWriter::QualifiedName( "",
kml::kmlTag_nameSpace22),
new KmlTagWriter() );
bool KmlTagWriter::write( const GeoNode *node, GeoWriter& writer ) const
{
Q_UNUSED(node);
writer.writeDefaultNamespace( kml::kmlTag_nameSpace22 );
writer.writeNamespace( kml::kmlTag_nameSpaceGx22, "gx" );
writer.writeStartElement( "kml" );
// Do not write an end element for document handlers
return true;
}
}
<|endoftext|> |
<commit_before>// Copyright 2022 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Codegen/PassDetail.h"
#include "iree/compiler/Codegen/Passes.h"
#include "iree/compiler/Codegen/Utils/Utils.h"
#include "iree/compiler/Dialect/Util/IR/UtilOps.h"
#include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
#include "mlir/Dialect/GPU/IR/GPUDialect.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/Vector/Transforms/VectorDistribution.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/Passes.h"
namespace mlir {
namespace iree_compiler {
/// Emit shared local memory allocation in case it is needed when lowering the
/// warp operations.
static Value allocateGlobalSharedMemory(Location loc, OpBuilder &builder,
vector::WarpExecuteOnLane0Op warpOp,
Type type) {
builder.setInsertionPoint(warpOp);
MemRefType memrefType;
if (auto vectorType = type.dyn_cast<VectorType>()) {
memrefType =
MemRefType::get(vectorType.getShape(), vectorType.getElementType(), {},
gpu::GPUDialect::getWorkgroupAddressSpace());
} else {
memrefType = MemRefType::get({1}, type, {},
gpu::GPUDialect::getWorkgroupAddressSpace());
}
return builder.create<memref::AllocOp>(loc, memrefType);
}
/// Emit warp reduction code sequence for a given input.
static Value warpReduction(Location loc, OpBuilder &builder, Value input,
vector::CombiningKind kind, uint32_t size) {
Value laneVal = input;
// Parallel reduction using butterfly shuffles.
for (uint64_t i = 1; i < size; i <<= 1) {
Value shuffled = builder
.create<gpu::ShuffleOp>(loc, laneVal, i,
/*width=*/size,
/*mode=*/gpu::ShuffleMode::XOR)
.result();
laneVal = makeArithReduction(builder, loc, kind, laneVal, shuffled);
}
return laneVal;
}
/// Special case to hoist hal operations that have side effect but are safe to
/// move out of the warp single lane region.
static void hoistHalBindingOps(vector::WarpExecuteOnLane0Op warpOp) {
Block *body = warpOp.getBody();
// Keep track of the ops we want to hoist.
llvm::SmallSetVector<Operation *, 8> opsToMove;
// Do not use walk here, as we do not want to go into nested regions and hoist
// operations from there.
for (auto &op : body->without_terminator()) {
if (!isa<IREE::HAL::InterfaceBindingSubspanOp>(&op)) continue;
if (llvm::any_of(op.getOperands(), [&](Value operand) {
return !warpOp.isDefinedOutsideOfRegion(operand);
}))
continue;
opsToMove.insert(&op);
}
// Move all the ops marked as uniform outside of the region.
for (Operation *op : opsToMove) op->moveBefore(warpOp);
}
namespace {
/// Pattern to convert InsertElement to broadcast, this is a workaround until
/// MultiDimReduction distribution is supported.
class InsertElementToBroadcast final
: public OpRewritePattern<vector::InsertElementOp> {
public:
using OpRewritePattern<vector::InsertElementOp>::OpRewritePattern;
LogicalResult matchAndRewrite(vector::InsertElementOp insertOp,
PatternRewriter &rewriter) const override {
if (insertOp.getDestVectorType().getNumElements() != 1) return failure();
rewriter.replaceOpWithNewOp<vector::BroadcastOp>(
insertOp, insertOp.getDestVectorType(), insertOp.getSource());
return success();
}
};
struct LLVMGPUReduceToGPUPass
: public LLVMGPUReduceToGPUBase<LLVMGPUReduceToGPUPass> {
void runOnOperation() override {
func::FuncOp funcOp = getOperation();
MLIRContext *ctx = &getContext();
// 1. Pre-process multiDimReductions.
// TODO: Remove once MultiDimReduce is supported by distribute patterns.
{
RewritePatternSet patterns(ctx);
vector::populateVectorMultiReductionLoweringPatterns(
patterns, vector::VectorMultiReductionLowering::InnerReduction);
patterns.add<InsertElementToBroadcast>(ctx);
(void)applyPatternsAndFoldGreedily(getOperation(), std::move(patterns));
}
// 2. Create the warp op and move the function body into it.
const int warpSize = 32;
Location loc = funcOp.getLoc();
OpBuilder builder(funcOp);
auto threadX = builder.create<gpu::ThreadIdOp>(loc, builder.getIndexType(),
gpu::Dimension::x);
auto cstWarpSize = builder.create<arith::ConstantIndexOp>(loc, warpSize);
auto laneId =
builder.create<arith::RemUIOp>(loc, threadX.getResult(), cstWarpSize);
auto warpOp = builder.create<vector::WarpExecuteOnLane0Op>(
loc, TypeRange(), laneId, warpSize);
warpOp.getWarpRegion().takeBody(funcOp.getBody());
Block &newBlock = funcOp.getBody().emplaceBlock();
threadX->moveBefore(&newBlock, newBlock.end());
cstWarpSize->moveBefore(&newBlock, newBlock.end());
laneId->moveBefore(&newBlock, newBlock.end());
warpOp->moveBefore(&newBlock, newBlock.end());
warpOp.getWarpRegion().getBlocks().back().back().moveBefore(&newBlock,
newBlock.end());
builder.setInsertionPointToEnd(&warpOp.getWarpRegion().getBlocks().back());
builder.create<vector::YieldOp>(loc);
// 3. Hoist the scalar code outside of the warp region.
vector::moveScalarUniformCode(warpOp);
hoistHalBindingOps(warpOp);
vector::moveScalarUniformCode(warpOp);
// 4. Distribute transfer write operations.
{
auto distributionFn = [](vector::TransferWriteOp writeOp) {
// Create a map (d0, d1) -> (d1) to distribute along the inner
// dimension. Once we support n-d distribution we can add more
// complex cases.
int64_t vecRank = writeOp.getVectorType().getRank();
OpBuilder builder(writeOp.getContext());
auto map =
AffineMap::get(vecRank, 0, builder.getAffineDimExpr(vecRank - 1));
return map;
};
RewritePatternSet patterns(ctx);
vector::populateDistributeTransferWriteOpPatterns(patterns,
distributionFn);
(void)applyPatternsAndFoldGreedily(getOperation(), std::move(patterns));
}
// 4. Propagate vector distribution.
{
RewritePatternSet patterns(ctx);
vector::populatePropagateWarpVectorDistributionPatterns(patterns);
vector::populateDistributeReduction(patterns, warpReduction);
(void)applyPatternsAndFoldGreedily(getOperation(), std::move(patterns));
}
// 4. Lower the remaining WarpExecuteOnLane0 ops.
{
RewritePatternSet patterns(ctx);
vector::WarpExecuteOnLane0LoweringOptions options;
options.warpAllocationFn = allocateGlobalSharedMemory;
options.warpSyncronizationFn = [](Location loc, OpBuilder &builder,
vector::WarpExecuteOnLane0Op warpOp) {};
vector::populateWarpExecuteOnLane0OpToScfForPattern(patterns, options);
(void)applyPatternsAndFoldGreedily(getOperation(), std::move(patterns));
}
}
};
} // anonymous namespace
std::unique_ptr<OperationPass<func::FuncOp>>
createConvertVectorReductionToGPUPass() {
return std::make_unique<LLVMGPUReduceToGPUPass>();
}
} // namespace iree_compiler
} // namespace mlir<commit_msg>[LLVMGPU] Remove wrong setInsertPoint in vector distribution (#9613)<commit_after>// Copyright 2022 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Codegen/PassDetail.h"
#include "iree/compiler/Codegen/Passes.h"
#include "iree/compiler/Codegen/Utils/Utils.h"
#include "iree/compiler/Dialect/Util/IR/UtilOps.h"
#include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
#include "mlir/Dialect/GPU/IR/GPUDialect.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/Vector/Transforms/VectorDistribution.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/Passes.h"
namespace mlir {
namespace iree_compiler {
/// Emit shared local memory allocation in case it is needed when lowering the
/// warp operations.
static Value allocateGlobalSharedMemory(Location loc, OpBuilder &builder,
vector::WarpExecuteOnLane0Op warpOp,
Type type) {
MemRefType memrefType;
if (auto vectorType = type.dyn_cast<VectorType>()) {
memrefType =
MemRefType::get(vectorType.getShape(), vectorType.getElementType(), {},
gpu::GPUDialect::getWorkgroupAddressSpace());
} else {
memrefType = MemRefType::get({1}, type, {},
gpu::GPUDialect::getWorkgroupAddressSpace());
}
return builder.create<memref::AllocOp>(loc, memrefType);
}
/// Emit warp reduction code sequence for a given input.
static Value warpReduction(Location loc, OpBuilder &builder, Value input,
vector::CombiningKind kind, uint32_t size) {
Value laneVal = input;
// Parallel reduction using butterfly shuffles.
for (uint64_t i = 1; i < size; i <<= 1) {
Value shuffled = builder
.create<gpu::ShuffleOp>(loc, laneVal, i,
/*width=*/size,
/*mode=*/gpu::ShuffleMode::XOR)
.result();
laneVal = makeArithReduction(builder, loc, kind, laneVal, shuffled);
}
return laneVal;
}
/// Special case to hoist hal operations that have side effect but are safe to
/// move out of the warp single lane region.
static void hoistHalBindingOps(vector::WarpExecuteOnLane0Op warpOp) {
Block *body = warpOp.getBody();
// Keep track of the ops we want to hoist.
llvm::SmallSetVector<Operation *, 8> opsToMove;
// Do not use walk here, as we do not want to go into nested regions and hoist
// operations from there.
for (auto &op : body->without_terminator()) {
if (!isa<IREE::HAL::InterfaceBindingSubspanOp>(&op)) continue;
if (llvm::any_of(op.getOperands(), [&](Value operand) {
return !warpOp.isDefinedOutsideOfRegion(operand);
}))
continue;
opsToMove.insert(&op);
}
// Move all the ops marked as uniform outside of the region.
for (Operation *op : opsToMove) op->moveBefore(warpOp);
}
namespace {
/// Pattern to convert InsertElement to broadcast, this is a workaround until
/// MultiDimReduction distribution is supported.
class InsertElementToBroadcast final
: public OpRewritePattern<vector::InsertElementOp> {
public:
using OpRewritePattern<vector::InsertElementOp>::OpRewritePattern;
LogicalResult matchAndRewrite(vector::InsertElementOp insertOp,
PatternRewriter &rewriter) const override {
if (insertOp.getDestVectorType().getNumElements() != 1) return failure();
rewriter.replaceOpWithNewOp<vector::BroadcastOp>(
insertOp, insertOp.getDestVectorType(), insertOp.getSource());
return success();
}
};
struct LLVMGPUReduceToGPUPass
: public LLVMGPUReduceToGPUBase<LLVMGPUReduceToGPUPass> {
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<scf::SCFDialect>();
}
void runOnOperation() override {
func::FuncOp funcOp = getOperation();
MLIRContext *ctx = &getContext();
// 1. Pre-process multiDimReductions.
// TODO: Remove once MultiDimReduce is supported by distribute patterns.
{
RewritePatternSet patterns(ctx);
vector::populateVectorMultiReductionLoweringPatterns(
patterns, vector::VectorMultiReductionLowering::InnerReduction);
patterns.add<InsertElementToBroadcast>(ctx);
(void)applyPatternsAndFoldGreedily(getOperation(), std::move(patterns));
}
// 2. Create the warp op and move the function body into it.
const int warpSize = 32;
Location loc = funcOp.getLoc();
OpBuilder builder(funcOp);
auto threadX = builder.create<gpu::ThreadIdOp>(loc, builder.getIndexType(),
gpu::Dimension::x);
auto cstWarpSize = builder.create<arith::ConstantIndexOp>(loc, warpSize);
auto laneId =
builder.create<arith::RemUIOp>(loc, threadX.getResult(), cstWarpSize);
auto warpOp = builder.create<vector::WarpExecuteOnLane0Op>(
loc, TypeRange(), laneId, warpSize);
warpOp.getWarpRegion().takeBody(funcOp.getBody());
Block &newBlock = funcOp.getBody().emplaceBlock();
threadX->moveBefore(&newBlock, newBlock.end());
cstWarpSize->moveBefore(&newBlock, newBlock.end());
laneId->moveBefore(&newBlock, newBlock.end());
warpOp->moveBefore(&newBlock, newBlock.end());
warpOp.getWarpRegion().getBlocks().back().back().moveBefore(&newBlock,
newBlock.end());
builder.setInsertionPointToEnd(&warpOp.getWarpRegion().getBlocks().back());
builder.create<vector::YieldOp>(loc);
// 3. Hoist the scalar code outside of the warp region.
vector::moveScalarUniformCode(warpOp);
hoistHalBindingOps(warpOp);
vector::moveScalarUniformCode(warpOp);
// 4. Distribute transfer write operations.
{
auto distributionFn = [](vector::TransferWriteOp writeOp) {
// Create a map (d0, d1) -> (d1) to distribute along the inner
// dimension. Once we support n-d distribution we can add more
// complex cases.
int64_t vecRank = writeOp.getVectorType().getRank();
OpBuilder builder(writeOp.getContext());
auto map =
AffineMap::get(vecRank, 0, builder.getAffineDimExpr(vecRank - 1));
return map;
};
RewritePatternSet patterns(ctx);
vector::populateDistributeTransferWriteOpPatterns(patterns,
distributionFn);
(void)applyPatternsAndFoldGreedily(getOperation(), std::move(patterns));
}
// 4. Propagate vector distribution.
{
RewritePatternSet patterns(ctx);
vector::populatePropagateWarpVectorDistributionPatterns(patterns);
vector::populateDistributeReduction(patterns, warpReduction);
(void)applyPatternsAndFoldGreedily(getOperation(), std::move(patterns));
}
// 4. Lower the remaining WarpExecuteOnLane0 ops.
{
RewritePatternSet patterns(ctx);
vector::WarpExecuteOnLane0LoweringOptions options;
options.warpAllocationFn = allocateGlobalSharedMemory;
options.warpSyncronizationFn = [](Location loc, OpBuilder &builder,
vector::WarpExecuteOnLane0Op warpOp) {};
vector::populateWarpExecuteOnLane0OpToScfForPattern(patterns, options);
(void)applyPatternsAndFoldGreedily(getOperation(), std::move(patterns));
}
}
};
} // anonymous namespace
std::unique_ptr<OperationPass<func::FuncOp>>
createConvertVectorReductionToGPUPass() {
return std::make_unique<LLVMGPUReduceToGPUPass>();
}
} // namespace iree_compiler
} // namespace mlir<|endoftext|> |
<commit_before>//
// File: gmxtrajectoryreader.cc
// Author: ruehle
//
// Created on April 5, 2007, 2:42 PM
//
#include <iostream>
#include "topology.h"
#include "gmxtrajectoryreader.h"
using namespace std;
bool GMXTrajectoryReader::Open(const string &file)
{
_filename = file;
return true;
}
void GMXTrajectoryReader::Close()
{
gmx::close_trx(_gmx_status);
}
bool GMXTrajectoryReader::FirstFrame(Topology &conf)
{
if(!gmx::read_first_frame(&_gmx_status,(char*)_filename.c_str(),&_gmx_frame,TRX_READ_X | TRX_READ_F))
return false;
matrix m;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
m[i][j] = _gmx_frame.box[j][i];
conf.setBox(m);
conf.setTime(_gmx_frame.time);
conf.setStep(_gmx_frame.step);
cout << endl;
//conf.HasPos(true);
//conf.HasF(_gmx_frame.bF);
for(int i=0; i<_gmx_frame.natoms; i++) {
double r[3] = { _gmx_frame.x[i][XX], _gmx_frame.x[i][YY], _gmx_frame.x[i][ZZ] };
conf.getBead(i)->setPos(r);
if(_gmx_frame.bF) {
double f[3] = { _gmx_frame.f[i][XX], _gmx_frame.f[i][YY], _gmx_frame.f[i][ZZ] };
conf.getBead(i)->setPos(f);
}
}
return true;
}
bool GMXTrajectoryReader::NextFrame(Topology &conf)
{
if(!gmx::read_next_frame(_gmx_status,&_gmx_frame))
return false;
matrix m;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
m[i][j] = _gmx_frame.box[j][i];
conf.setTime(_gmx_frame.time);
conf.setStep(_gmx_frame.step);
conf.setBox(m);
//conf.HasF(_gmx_frame.bF);
for(int i=0; i<_gmx_frame.natoms; i++) {
double r[3] = { _gmx_frame.x[i][XX], _gmx_frame.x[i][YY], _gmx_frame.x[i][ZZ] };
conf.getBead(i)->setPos(r);
if(_gmx_frame.bF) {
double f[3] = { _gmx_frame.f[i][XX], _gmx_frame.f[i][YY], _gmx_frame.f[i][ZZ] };
conf.getBead(i)->setF(f);
}
}
return true;
}
<commit_msg>bug in gmxtrajectoryreader.cc fixed<commit_after>//
// File: gmxtrajectoryreader.cc
// Author: ruehle
//
// Created on April 5, 2007, 2:42 PM
//
#include <iostream>
#include "topology.h"
#include "gmxtrajectoryreader.h"
using namespace std;
bool GMXTrajectoryReader::Open(const string &file)
{
_filename = file;
return true;
}
void GMXTrajectoryReader::Close()
{
gmx::close_trx(_gmx_status);
}
bool GMXTrajectoryReader::FirstFrame(Topology &conf)
{
if(!gmx::read_first_frame(&_gmx_status,(char*)_filename.c_str(),&_gmx_frame,TRX_READ_X | TRX_READ_F))
return false;
matrix m;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
m[i][j] = _gmx_frame.box[j][i];
conf.setBox(m);
conf.setTime(_gmx_frame.time);
conf.setStep(_gmx_frame.step);
cout << endl;
//conf.HasPos(true);
//conf.HasF(_gmx_frame.bF);
for(int i=0; i<_gmx_frame.natoms; i++) {
double r[3] = { _gmx_frame.x[i][XX], _gmx_frame.x[i][YY], _gmx_frame.x[i][ZZ] };
conf.getBead(i)->setPos(r);
if(_gmx_frame.bF) {
double f[3] = { _gmx_frame.f[i][XX], _gmx_frame.f[i][YY], _gmx_frame.f[i][ZZ] };
conf.getBead(i)->setF(f);
}
}
return true;
}
bool GMXTrajectoryReader::NextFrame(Topology &conf)
{
if(!gmx::read_next_frame(_gmx_status,&_gmx_frame))
return false;
matrix m;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
m[i][j] = _gmx_frame.box[j][i];
conf.setTime(_gmx_frame.time);
conf.setStep(_gmx_frame.step);
conf.setBox(m);
//conf.HasF(_gmx_frame.bF);
for(int i=0; i<_gmx_frame.natoms; i++) {
double r[3] = { _gmx_frame.x[i][XX], _gmx_frame.x[i][YY], _gmx_frame.x[i][ZZ] };
conf.getBead(i)->setPos(r);
if(_gmx_frame.bF) {
double f[3] = { _gmx_frame.f[i][XX], _gmx_frame.f[i][YY], _gmx_frame.f[i][ZZ] };
conf.getBead(i)->setF(f);
}
}
return true;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlprofilertraceclient.h"
#include "qmlenginecontrolclient.h"
namespace QmlDebug {
class QmlProfilerTraceClientPrivate {
public:
QmlProfilerTraceClientPrivate(QmlProfilerTraceClient *_q, QmlDebugConnection *client)
: q(_q)
, engineControl(client)
, inProgressRanges(0)
, maximumTime(0)
, recording(false)
, requestedFeatures(0)
, recordedFeatures(0)
{
::memset(rangeCount, 0, MaximumRangeType * sizeof(int));
}
void sendRecordingStatus(int engineId);
bool updateFeatures(QmlDebug::ProfileFeature feature);
QmlProfilerTraceClient *q;
QmlEngineControlClient engineControl;
qint64 inProgressRanges;
QStack<qint64> rangeStartTimes[MaximumRangeType];
QStack<QString> rangeDatas[MaximumRangeType];
QStack<QmlEventLocation> rangeLocations[MaximumRangeType];
QStack<BindingType> bindingTypes;
int rangeCount[MaximumRangeType];
qint64 maximumTime;
bool recording;
quint64 requestedFeatures;
quint64 recordedFeatures;
};
} // namespace QmlDebug
using namespace QmlDebug;
static const int GAP_TIME = 150;
void QmlProfilerTraceClientPrivate::sendRecordingStatus(int engineId)
{
QByteArray ba;
QDataStream stream(&ba, QIODevice::WriteOnly);
stream << recording << engineId; // engineId -1 is OK. It means "all of them"
if (recording)
stream << requestedFeatures;
q->sendMessage(ba);
}
QmlProfilerTraceClient::QmlProfilerTraceClient(QmlDebugConnection *client, quint64 features)
: QmlDebugClient(QLatin1String("CanvasFrameRate"), client)
, d(new QmlProfilerTraceClientPrivate(this, client))
{
d->requestedFeatures = features;
connect(&d->engineControl, SIGNAL(engineAboutToBeAdded(int,QString)),
this, SLOT(sendRecordingStatus(int)));
}
QmlProfilerTraceClient::~QmlProfilerTraceClient()
{
//Disable profiling if started by client
//Profiling data will be lost!!
if (isRecording())
setRecording(false);
delete d;
}
void QmlProfilerTraceClient::clearData()
{
::memset(d->rangeCount, 0, MaximumRangeType * sizeof(int));
for (int eventType = 0; eventType < MaximumRangeType; eventType++) {
d->rangeDatas[eventType].clear();
d->rangeLocations[eventType].clear();
d->rangeStartTimes[eventType].clear();
}
d->bindingTypes.clear();
if (d->recordedFeatures != 0) {
d->recordedFeatures = 0;
emit recordedFeaturesChanged(0);
}
emit cleared();
}
void QmlProfilerTraceClient::sendRecordingStatus(int engineId)
{
d->sendRecordingStatus(engineId);
}
bool QmlProfilerTraceClient::isEnabled() const
{
return state() == Enabled;
}
bool QmlProfilerTraceClient::isRecording() const
{
return d->recording;
}
void QmlProfilerTraceClient::setRecording(bool v)
{
if (v == d->recording)
return;
d->recording = v;
if (state() == Enabled)
sendRecordingStatus();
emit recordingChanged(v);
}
quint64 QmlProfilerTraceClient::recordedFeatures() const
{
return d->recordedFeatures;
}
void QmlProfilerTraceClient::setRequestedFeatures(quint64 features)
{
d->requestedFeatures = features;
}
void QmlProfilerTraceClient::setRecordingFromServer(bool v)
{
if (v == d->recording)
return;
d->recording = v;
emit recordingChanged(v);
}
bool QmlProfilerTraceClientPrivate::updateFeatures(ProfileFeature feature)
{
quint64 flag = 1ULL << feature;
if (!(requestedFeatures & flag))
return false;
if (!(recordedFeatures & flag)) {
recordedFeatures |= flag;
emit q->recordedFeaturesChanged(recordedFeatures);
}
return true;
}
void QmlProfilerTraceClient::stateChanged(State /*status*/)
{
emit enabledChanged();
}
void QmlProfilerTraceClient::messageReceived(const QByteArray &data)
{
QByteArray rwData = data;
QDataStream stream(&rwData, QIODevice::ReadOnly);
qint64 time;
int messageType;
int subtype;
stream >> time >> messageType;
if (!stream.atEnd())
stream >> subtype;
else
subtype = -1;
if (time > (d->maximumTime + GAP_TIME) && 0 == d->inProgressRanges)
emit gap(time);
switch (messageType) {
case Event: {
switch (subtype) {
case StartTrace: {
if (!d->recording)
setRecordingFromServer(true);
QList<int> engineIds;
while (!stream.atEnd()) {
int id;
stream >> id;
engineIds << id;
}
emit this->traceStarted(time, engineIds);
d->maximumTime = time;
break;
}
case EndTrace: {
QList<int> engineIds;
while (!stream.atEnd()) {
int id;
stream >> id;
engineIds << id;
}
emit this->traceFinished(time, engineIds);
d->maximumTime = time;
d->maximumTime = qMax(time, d->maximumTime);
break;
}
case AnimationFrame: {
if (!d->updateFeatures(ProfileAnimations))
break;
int frameRate, animationCount;
int threadId;
stream >> frameRate >> animationCount;
if (!stream.atEnd())
stream >> threadId;
else
threadId = 0;
emit rangedEvent(Event, MaximumRangeType, AnimationFrame, time, 0, QString(),
QmlEventLocation(), frameRate, animationCount, threadId,
0, 0);
d->maximumTime = qMax(time, d->maximumTime);
break;
}
case Key:
case Mouse:
if (!d->updateFeatures(ProfileInputEvents))
break;
emit this->rangedEvent(Event, MaximumRangeType, subtype, time, 0, QString(),
QmlEventLocation(), 0, 0, 0, 0, 0);
d->maximumTime = qMax(time, d->maximumTime);
break;
}
break;
}
case Complete:
emit complete(d->maximumTime);
break;
case SceneGraphFrame: {
if (!d->updateFeatures(ProfileSceneGraph))
break;
int count = 0;
qint64 params[5];
while (!stream.atEnd()) {
stream >> params[count++];
}
while (count<5)
params[count++] = 0;
emit rangedEvent(SceneGraphFrame, MaximumRangeType, subtype,time, 0,
QString(), QmlEventLocation(), params[0], params[1],
params[2], params[3], params[4]);
break;
}
case PixmapCacheEvent: {
if (!d->updateFeatures(ProfilePixmapCache))
break;
int width = 0, height = 0, refcount = 0;
QString pixUrl;
stream >> pixUrl;
if (subtype == (int)PixmapReferenceCountChanged || subtype == (int)PixmapCacheCountChanged) {
stream >> refcount;
} else if (subtype == (int)PixmapSizeKnown) {
stream >> width >> height;
refcount = 1;
}
emit rangedEvent(PixmapCacheEvent, MaximumRangeType, subtype, time, 0,
QString(), QmlEventLocation(pixUrl,0,0), width, height,
refcount, 0, 0);
d->maximumTime = qMax(time, d->maximumTime);
break;
}
case MemoryAllocation: {
if (!d->updateFeatures(ProfileMemory))
break;
qint64 delta;
stream >> delta;
emit rangedEvent(MemoryAllocation, MaximumRangeType, subtype, time, 0,
QString(), QmlEventLocation(), delta, 0, 0, 0, 0);
d->maximumTime = qMax(time, d->maximumTime);
break;
}
case RangeStart: {
if (!d->updateFeatures(featureFromRangeType(static_cast<RangeType>(subtype))))
break;
d->rangeStartTimes[subtype].push(time);
d->inProgressRanges |= (static_cast<qint64>(1) << subtype);
++d->rangeCount[subtype];
// read binding type
if ((RangeType)subtype == Binding) {
int bindingType = (int)QmlBinding;
if (!stream.atEnd())
stream >> bindingType;
d->bindingTypes.push((BindingType)bindingType);
}
break;
}
case RangeData: {
if (!d->updateFeatures(featureFromRangeType(static_cast<RangeType>(subtype))))
break;
QString data;
stream >> data;
int count = d->rangeCount[subtype];
if (count > 0) {
while (d->rangeDatas[subtype].count() < count)
d->rangeDatas[subtype].push(QString());
d->rangeDatas[subtype][count-1] = data;
}
break;
}
case RangeLocation: {
if (!d->updateFeatures(featureFromRangeType(static_cast<RangeType>(subtype))))
break;
QString fileName;
int line;
int column = -1;
stream >> fileName >> line;
if (!stream.atEnd())
stream >> column;
if (d->rangeCount[subtype] > 0)
d->rangeLocations[subtype].push(QmlEventLocation(fileName, line, column));
break;
}
case RangeEnd: {
if (!d->updateFeatures(featureFromRangeType(static_cast<RangeType>(subtype))))
break;
if (d->rangeCount[subtype] == 0)
break;
--d->rangeCount[subtype];
if (d->inProgressRanges & (static_cast<qint64>(1) << subtype))
d->inProgressRanges &= ~(static_cast<qint64>(1) << subtype);
d->maximumTime = qMax(time, d->maximumTime);
QString data = d->rangeDatas[subtype].count() ? d->rangeDatas[subtype].pop() : QString();
QmlEventLocation location = d->rangeLocations[subtype].count() ? d->rangeLocations[subtype].pop() : QmlEventLocation();
qint64 startTime = d->rangeStartTimes[subtype].pop();
BindingType bindingType = QmlBinding;
if ((RangeType)subtype == Binding)
bindingType = d->bindingTypes.pop();
if ((RangeType)subtype == Painting)
bindingType = QPainterEvent;
emit rangedEvent(MaximumMessage, (RangeType)subtype, bindingType, startTime,
time - startTime, data, location, 0, 0, 0, 0, 0);
if (d->rangeCount[subtype] == 0) {
int count = d->rangeDatas[subtype].count() +
d->rangeStartTimes[subtype].count() +
d->rangeLocations[subtype].count();
if (count != 0)
qWarning() << "incorrectly nested data";
}
break;
}
default:
break;
}
// stop with the first data
if (messageType != Event || subtype != StartTrace)
setRecordingFromServer(false);
}
<commit_msg>QmlProfiler: Switch recording button only on "Complete"<commit_after>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlprofilertraceclient.h"
#include "qmlenginecontrolclient.h"
namespace QmlDebug {
class QmlProfilerTraceClientPrivate {
public:
QmlProfilerTraceClientPrivate(QmlProfilerTraceClient *_q, QmlDebugConnection *client)
: q(_q)
, engineControl(client)
, inProgressRanges(0)
, maximumTime(0)
, recording(false)
, requestedFeatures(0)
, recordedFeatures(0)
{
::memset(rangeCount, 0, MaximumRangeType * sizeof(int));
}
void sendRecordingStatus(int engineId);
bool updateFeatures(QmlDebug::ProfileFeature feature);
QmlProfilerTraceClient *q;
QmlEngineControlClient engineControl;
qint64 inProgressRanges;
QStack<qint64> rangeStartTimes[MaximumRangeType];
QStack<QString> rangeDatas[MaximumRangeType];
QStack<QmlEventLocation> rangeLocations[MaximumRangeType];
QStack<BindingType> bindingTypes;
int rangeCount[MaximumRangeType];
qint64 maximumTime;
bool recording;
quint64 requestedFeatures;
quint64 recordedFeatures;
};
} // namespace QmlDebug
using namespace QmlDebug;
static const int GAP_TIME = 150;
void QmlProfilerTraceClientPrivate::sendRecordingStatus(int engineId)
{
QByteArray ba;
QDataStream stream(&ba, QIODevice::WriteOnly);
stream << recording << engineId; // engineId -1 is OK. It means "all of them"
if (recording)
stream << requestedFeatures;
q->sendMessage(ba);
}
QmlProfilerTraceClient::QmlProfilerTraceClient(QmlDebugConnection *client, quint64 features)
: QmlDebugClient(QLatin1String("CanvasFrameRate"), client)
, d(new QmlProfilerTraceClientPrivate(this, client))
{
d->requestedFeatures = features;
connect(&d->engineControl, SIGNAL(engineAboutToBeAdded(int,QString)),
this, SLOT(sendRecordingStatus(int)));
}
QmlProfilerTraceClient::~QmlProfilerTraceClient()
{
//Disable profiling if started by client
//Profiling data will be lost!!
if (isRecording())
setRecording(false);
delete d;
}
void QmlProfilerTraceClient::clearData()
{
::memset(d->rangeCount, 0, MaximumRangeType * sizeof(int));
for (int eventType = 0; eventType < MaximumRangeType; eventType++) {
d->rangeDatas[eventType].clear();
d->rangeLocations[eventType].clear();
d->rangeStartTimes[eventType].clear();
}
d->bindingTypes.clear();
if (d->recordedFeatures != 0) {
d->recordedFeatures = 0;
emit recordedFeaturesChanged(0);
}
emit cleared();
}
void QmlProfilerTraceClient::sendRecordingStatus(int engineId)
{
d->sendRecordingStatus(engineId);
}
bool QmlProfilerTraceClient::isEnabled() const
{
return state() == Enabled;
}
bool QmlProfilerTraceClient::isRecording() const
{
return d->recording;
}
void QmlProfilerTraceClient::setRecording(bool v)
{
if (v == d->recording)
return;
d->recording = v;
if (state() == Enabled)
sendRecordingStatus();
emit recordingChanged(v);
}
quint64 QmlProfilerTraceClient::recordedFeatures() const
{
return d->recordedFeatures;
}
void QmlProfilerTraceClient::setRequestedFeatures(quint64 features)
{
d->requestedFeatures = features;
}
void QmlProfilerTraceClient::setRecordingFromServer(bool v)
{
if (v == d->recording)
return;
d->recording = v;
emit recordingChanged(v);
}
bool QmlProfilerTraceClientPrivate::updateFeatures(ProfileFeature feature)
{
quint64 flag = 1ULL << feature;
if (!(requestedFeatures & flag))
return false;
if (!(recordedFeatures & flag)) {
recordedFeatures |= flag;
emit q->recordedFeaturesChanged(recordedFeatures);
}
return true;
}
void QmlProfilerTraceClient::stateChanged(State /*status*/)
{
emit enabledChanged();
}
void QmlProfilerTraceClient::messageReceived(const QByteArray &data)
{
QByteArray rwData = data;
QDataStream stream(&rwData, QIODevice::ReadOnly);
qint64 time;
int messageType;
int subtype;
stream >> time >> messageType;
if (!stream.atEnd())
stream >> subtype;
else
subtype = -1;
if (time > (d->maximumTime + GAP_TIME) && 0 == d->inProgressRanges)
emit gap(time);
switch (messageType) {
case Event: {
switch (subtype) {
case StartTrace: {
if (!d->recording)
setRecordingFromServer(true);
QList<int> engineIds;
while (!stream.atEnd()) {
int id;
stream >> id;
engineIds << id;
}
emit this->traceStarted(time, engineIds);
d->maximumTime = time;
break;
}
case EndTrace: {
QList<int> engineIds;
while (!stream.atEnd()) {
int id;
stream >> id;
engineIds << id;
}
emit this->traceFinished(time, engineIds);
d->maximumTime = time;
d->maximumTime = qMax(time, d->maximumTime);
break;
}
case AnimationFrame: {
if (!d->updateFeatures(ProfileAnimations))
break;
int frameRate, animationCount;
int threadId;
stream >> frameRate >> animationCount;
if (!stream.atEnd())
stream >> threadId;
else
threadId = 0;
emit rangedEvent(Event, MaximumRangeType, AnimationFrame, time, 0, QString(),
QmlEventLocation(), frameRate, animationCount, threadId,
0, 0);
d->maximumTime = qMax(time, d->maximumTime);
break;
}
case Key:
case Mouse:
if (!d->updateFeatures(ProfileInputEvents))
break;
emit this->rangedEvent(Event, MaximumRangeType, subtype, time, 0, QString(),
QmlEventLocation(), 0, 0, 0, 0, 0);
d->maximumTime = qMax(time, d->maximumTime);
break;
}
break;
}
case Complete:
emit complete(d->maximumTime);
setRecordingFromServer(false);
break;
case SceneGraphFrame: {
if (!d->updateFeatures(ProfileSceneGraph))
break;
int count = 0;
qint64 params[5];
while (!stream.atEnd()) {
stream >> params[count++];
}
while (count<5)
params[count++] = 0;
emit rangedEvent(SceneGraphFrame, MaximumRangeType, subtype,time, 0,
QString(), QmlEventLocation(), params[0], params[1],
params[2], params[3], params[4]);
break;
}
case PixmapCacheEvent: {
if (!d->updateFeatures(ProfilePixmapCache))
break;
int width = 0, height = 0, refcount = 0;
QString pixUrl;
stream >> pixUrl;
if (subtype == (int)PixmapReferenceCountChanged || subtype == (int)PixmapCacheCountChanged) {
stream >> refcount;
} else if (subtype == (int)PixmapSizeKnown) {
stream >> width >> height;
refcount = 1;
}
emit rangedEvent(PixmapCacheEvent, MaximumRangeType, subtype, time, 0,
QString(), QmlEventLocation(pixUrl,0,0), width, height,
refcount, 0, 0);
d->maximumTime = qMax(time, d->maximumTime);
break;
}
case MemoryAllocation: {
if (!d->updateFeatures(ProfileMemory))
break;
qint64 delta;
stream >> delta;
emit rangedEvent(MemoryAllocation, MaximumRangeType, subtype, time, 0,
QString(), QmlEventLocation(), delta, 0, 0, 0, 0);
d->maximumTime = qMax(time, d->maximumTime);
break;
}
case RangeStart: {
if (!d->updateFeatures(featureFromRangeType(static_cast<RangeType>(subtype))))
break;
d->rangeStartTimes[subtype].push(time);
d->inProgressRanges |= (static_cast<qint64>(1) << subtype);
++d->rangeCount[subtype];
// read binding type
if ((RangeType)subtype == Binding) {
int bindingType = (int)QmlBinding;
if (!stream.atEnd())
stream >> bindingType;
d->bindingTypes.push((BindingType)bindingType);
}
break;
}
case RangeData: {
if (!d->updateFeatures(featureFromRangeType(static_cast<RangeType>(subtype))))
break;
QString data;
stream >> data;
int count = d->rangeCount[subtype];
if (count > 0) {
while (d->rangeDatas[subtype].count() < count)
d->rangeDatas[subtype].push(QString());
d->rangeDatas[subtype][count-1] = data;
}
break;
}
case RangeLocation: {
if (!d->updateFeatures(featureFromRangeType(static_cast<RangeType>(subtype))))
break;
QString fileName;
int line;
int column = -1;
stream >> fileName >> line;
if (!stream.atEnd())
stream >> column;
if (d->rangeCount[subtype] > 0)
d->rangeLocations[subtype].push(QmlEventLocation(fileName, line, column));
break;
}
case RangeEnd: {
if (!d->updateFeatures(featureFromRangeType(static_cast<RangeType>(subtype))))
break;
if (d->rangeCount[subtype] == 0)
break;
--d->rangeCount[subtype];
if (d->inProgressRanges & (static_cast<qint64>(1) << subtype))
d->inProgressRanges &= ~(static_cast<qint64>(1) << subtype);
d->maximumTime = qMax(time, d->maximumTime);
QString data = d->rangeDatas[subtype].count() ? d->rangeDatas[subtype].pop() : QString();
QmlEventLocation location = d->rangeLocations[subtype].count() ? d->rangeLocations[subtype].pop() : QmlEventLocation();
qint64 startTime = d->rangeStartTimes[subtype].pop();
BindingType bindingType = QmlBinding;
if ((RangeType)subtype == Binding)
bindingType = d->bindingTypes.pop();
if ((RangeType)subtype == Painting)
bindingType = QPainterEvent;
emit rangedEvent(MaximumMessage, (RangeType)subtype, bindingType, startTime,
time - startTime, data, location, 0, 0, 0, 0, 0);
if (d->rangeCount[subtype] == 0) {
int count = d->rangeDatas[subtype].count() +
d->rangeStartTimes[subtype].count() +
d->rangeLocations[subtype].count();
if (count != 0)
qWarning() << "incorrectly nested data";
}
break;
}
default:
break;
}
}
<|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 "printing/page_setup.h"
#include <algorithm>
#include "base/logging.h"
namespace printing {
PageMargins::PageMargins()
: header(0),
footer(0),
left(0),
right(0),
top(0),
bottom(0) {
}
void PageMargins::Clear() {
header = 0;
footer = 0;
left = 0;
right = 0;
top = 0;
bottom = 0;
}
bool PageMargins::Equals(const PageMargins& rhs) const {
return header == rhs.header &&
footer == rhs.footer &&
left == rhs.left &&
top == rhs.top &&
right == rhs.right &&
bottom == rhs.bottom;
}
PageSetup::PageSetup() : text_height_(0) {
}
PageSetup::~PageSetup() {}
void PageSetup::Clear() {
physical_size_.SetSize(0, 0);
printable_area_.SetRect(0, 0, 0, 0);
overlay_area_.SetRect(0, 0, 0, 0);
content_area_.SetRect(0, 0, 0, 0);
effective_margins_.Clear();
text_height_ = 0;
}
bool PageSetup::Equals(const PageSetup& rhs) const {
return physical_size_ == rhs.physical_size_ &&
printable_area_ == rhs.printable_area_ &&
overlay_area_ == rhs.overlay_area_ &&
content_area_ == rhs.content_area_ &&
effective_margins_.Equals(rhs.effective_margins_) &&
requested_margins_.Equals(rhs.requested_margins_) &&
text_height_ == rhs.text_height_;
}
void PageSetup::Init(const gfx::Size& physical_size,
const gfx::Rect& printable_area,
int text_height) {
DCHECK_LE(printable_area.right(), physical_size.width());
// I've seen this assert triggers on Canon GP160PF PCL 5e and HP LaserJet 5.
// Since we don't know the dpi here, just disable the check.
// DCHECK_LE(printable_area.bottom(), physical_size.height());
DCHECK_GE(printable_area.x(), 0);
DCHECK_GE(printable_area.y(), 0);
DCHECK_GE(text_height, 0);
physical_size_ = physical_size;
printable_area_ = printable_area;
text_height_ = text_height;
// Calculate the effective margins. The tricky part.
effective_margins_.header = std::max(requested_margins_.header,
printable_area_.y());
effective_margins_.footer = std::max(requested_margins_.footer,
physical_size.height() -
printable_area_.bottom());
effective_margins_.left = std::max(requested_margins_.left,
printable_area_.x());
effective_margins_.top = std::max(std::max(requested_margins_.top,
printable_area_.y()),
effective_margins_.header + text_height);
effective_margins_.right = std::max(requested_margins_.right,
physical_size.width() -
printable_area_.right());
effective_margins_.bottom = std::max(std::max(requested_margins_.bottom,
physical_size.height() -
printable_area_.bottom()),
effective_margins_.footer + text_height);
// Calculate the overlay area. If the margins are excessive, the overlay_area
// size will be (0, 0).
overlay_area_.set_x(effective_margins_.left);
overlay_area_.set_y(effective_margins_.header);
overlay_area_.set_width(std::max(0,
physical_size.width() -
effective_margins_.right -
overlay_area_.x()));
overlay_area_.set_height(std::max(0,
physical_size.height() -
effective_margins_.footer -
overlay_area_.y()));
// Calculate the content area. If the margins are excessive, the content_area
// size will be (0, 0).
content_area_.set_x(effective_margins_.left);
content_area_.set_y(effective_margins_.top);
content_area_.set_width(std::max(0,
physical_size.width() -
effective_margins_.right -
content_area_.x()));
content_area_.set_height(std::max(0,
physical_size.height() -
effective_margins_.bottom -
content_area_.y()));
}
void PageSetup::SetRequestedMargins(const PageMargins& requested_margins) {
requested_margins_ = requested_margins;
if (physical_size_.width() && physical_size_.height())
Init(physical_size_, printable_area_, text_height_);
}
void PageSetup::FlipOrientation() {
if (physical_size_.width() && physical_size_.height()) {
gfx::Size new_size(physical_size_.height(), physical_size_.width());
int new_y = physical_size_.width() -
(printable_area_.width() + printable_area_.x());
gfx::Rect new_printable_area(printable_area_.y(),
new_y,
printable_area_.height(),
printable_area_.width());
Init(new_size, new_printable_area, text_height_);
}
}
} // namespace printing
<commit_msg>Add check to debug issue 96063<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 "printing/page_setup.h"
#include <algorithm>
#include "base/logging.h"
namespace printing {
PageMargins::PageMargins()
: header(0),
footer(0),
left(0),
right(0),
top(0),
bottom(0) {
}
void PageMargins::Clear() {
header = 0;
footer = 0;
left = 0;
right = 0;
top = 0;
bottom = 0;
}
bool PageMargins::Equals(const PageMargins& rhs) const {
return header == rhs.header &&
footer == rhs.footer &&
left == rhs.left &&
top == rhs.top &&
right == rhs.right &&
bottom == rhs.bottom;
}
PageSetup::PageSetup() : text_height_(0) {
}
PageSetup::~PageSetup() {}
void PageSetup::Clear() {
physical_size_.SetSize(0, 0);
printable_area_.SetRect(0, 0, 0, 0);
overlay_area_.SetRect(0, 0, 0, 0);
content_area_.SetRect(0, 0, 0, 0);
effective_margins_.Clear();
text_height_ = 0;
}
bool PageSetup::Equals(const PageSetup& rhs) const {
return physical_size_ == rhs.physical_size_ &&
printable_area_ == rhs.printable_area_ &&
overlay_area_ == rhs.overlay_area_ &&
content_area_ == rhs.content_area_ &&
effective_margins_.Equals(rhs.effective_margins_) &&
requested_margins_.Equals(rhs.requested_margins_) &&
text_height_ == rhs.text_height_;
}
void PageSetup::Init(const gfx::Size& physical_size,
const gfx::Rect& printable_area,
int text_height) {
DCHECK_LE(printable_area.right(), physical_size.width());
// I've seen this assert triggers on Canon GP160PF PCL 5e and HP LaserJet 5.
// Since we don't know the dpi here, just disable the check.
// DCHECK_LE(printable_area.bottom(), physical_size.height());
DCHECK_GE(printable_area.x(), 0);
DCHECK_GE(printable_area.y(), 0);
DCHECK_GE(text_height, 0);
physical_size_ = physical_size;
printable_area_ = printable_area;
text_height_ = text_height;
// Calculate the effective margins. The tricky part.
effective_margins_.header = std::max(requested_margins_.header,
printable_area_.y());
effective_margins_.footer = std::max(requested_margins_.footer,
physical_size.height() -
printable_area_.bottom());
effective_margins_.left = std::max(requested_margins_.left,
printable_area_.x());
effective_margins_.top = std::max(std::max(requested_margins_.top,
printable_area_.y()),
effective_margins_.header + text_height);
effective_margins_.right = std::max(requested_margins_.right,
physical_size.width() -
printable_area_.right());
effective_margins_.bottom = std::max(std::max(requested_margins_.bottom,
physical_size.height() -
printable_area_.bottom()),
effective_margins_.footer + text_height);
// Calculate the overlay area. If the margins are excessive, the overlay_area
// size will be (0, 0).
overlay_area_.set_x(effective_margins_.left);
overlay_area_.set_y(effective_margins_.header);
overlay_area_.set_width(std::max(0,
physical_size.width() -
effective_margins_.right -
overlay_area_.x()));
overlay_area_.set_height(std::max(0,
physical_size.height() -
effective_margins_.footer -
overlay_area_.y()));
// Calculate the content area. If the margins are excessive, the content_area
// size will be (0, 0).
content_area_.set_x(effective_margins_.left);
content_area_.set_y(effective_margins_.top);
content_area_.set_width(std::max(0,
physical_size.width() -
effective_margins_.right -
content_area_.x()));
content_area_.set_height(std::max(0,
physical_size.height() -
effective_margins_.bottom -
content_area_.y()));
// TODO(vandebo) Remove once bug 96063 is resolved.
CHECK(content_area_.width() > 0 && content_area_.height() > 0);
}
void PageSetup::SetRequestedMargins(const PageMargins& requested_margins) {
requested_margins_ = requested_margins;
if (physical_size_.width() && physical_size_.height())
Init(physical_size_, printable_area_, text_height_);
}
void PageSetup::FlipOrientation() {
if (physical_size_.width() && physical_size_.height()) {
gfx::Size new_size(physical_size_.height(), physical_size_.width());
int new_y = physical_size_.width() -
(printable_area_.width() + printable_area_.x());
gfx::Rect new_printable_area(printable_area_.y(),
new_y,
printable_area_.height(),
printable_area_.width());
Init(new_size, new_printable_area, text_height_);
}
}
} // namespace printing
<|endoftext|> |
<commit_before>#include "query_saver.hpp"
#include "platform/settings.hpp"
#include "coding/base64.hpp"
#include "coding/reader.hpp"
#include "coding/writer.hpp"
#include "coding/write_to_sink.hpp"
#include "base/logging.hpp"
namespace
{
char constexpr kSettingsKey[] = "UserQueries";
using TLength = uint16_t;
TLength constexpr kMaxSuggestCount = 10;
size_t constexpr kLengthTypeSize = sizeof(TLength);
bool ReadLength(ReaderSource<MemReader> & reader, TLength & length)
{
if (reader.Size() < kLengthTypeSize)
return false;
length = ReadPrimitiveFromSource<TLength>(reader);
return true;
}
} // namespace
namespace search
{
QuerySaver::QuerySaver()
{
Load();
}
void QuerySaver::Add(string const & query)
{
if (query.empty())
return;
// Remove items if needed.
auto const it = find(m_topQueries.begin(), m_topQueries.end(), query);
if (it != m_topQueries.end())
m_topQueries.erase(it);
else if (m_topQueries.size() >= kMaxSuggestCount)
m_topQueries.pop_back();
// Add new query and save it to drive.
m_topQueries.push_front(query);
Save();
}
void QuerySaver::Clear()
{
m_topQueries.clear();
Settings::Delete(kSettingsKey);
}
void QuerySaver::Serialize(string & data) const
{
vector<uint8_t> rawData;
MemWriter<vector<uint8_t>> writer(rawData);
TLength size = m_topQueries.size();
WriteToSink(writer, size);
for (auto const & query : m_topQueries)
{
size = query.size();
WriteToSink(writer, size);
writer.Write(query.c_str(), size);
}
data = base64::Encode(string(rawData.begin(), rawData.end()));
}
void QuerySaver::EmergencyReset()
{
Clear();
LOG(LWARNING, ("Search history data corrupted! Creating new one."));
}
void QuerySaver::Deserialize(string const & data)
{
string decodedData;
decodedData = base64::Decode(data);
MemReader rawReader(decodedData.c_str(), decodedData.size());
ReaderSource<MemReader> reader(rawReader);
TLength queriesCount;
if (!ReadLength(reader, queriesCount))
{
EmergencyReset();
return;
}
queriesCount = min(queriesCount, kMaxSuggestCount);
for (TLength i = 0; i < queriesCount; ++i)
{
TLength stringLength;
if (!ReadLength(reader, stringLength))
{
EmergencyReset();
return;
}
if (reader.Size() < stringLength)
{
EmergencyReset();
return;
}
vector<char> str(stringLength);
reader.Read(&str[0], stringLength);
m_topQueries.emplace_back(&str[0], stringLength);
}
}
void QuerySaver::Save()
{
string data;
Serialize(data);
Settings::Set(kSettingsKey, data);
}
void QuerySaver::Load()
{
string hexData;
Settings::Get(kSettingsKey, hexData);
if (hexData.empty())
return;
Deserialize(hexData);
}
} // namesapce search
<commit_msg>PR fixes.<commit_after>#include "query_saver.hpp"
#include "platform/settings.hpp"
#include "coding/base64.hpp"
#include "coding/reader.hpp"
#include "coding/writer.hpp"
#include "coding/write_to_sink.hpp"
#include "base/logging.hpp"
namespace
{
char constexpr kSettingsKey[] = "UserQueries";
using TLength = uint16_t;
TLength constexpr kMaxSuggestCount = 10;
size_t constexpr kLengthTypeSize = sizeof(TLength);
bool ReadLength(ReaderSource<MemReader> & reader, TLength & length)
{
if (reader.Size() < kLengthTypeSize)
return false;
length = ReadPrimitiveFromSource<TLength>(reader);
return true;
}
} // namespace
namespace search
{
QuerySaver::QuerySaver()
{
Load();
}
void QuerySaver::Add(string const & query)
{
if (query.empty())
return;
// Remove items if needed.
auto const it = find(m_topQueries.begin(), m_topQueries.end(), query);
if (it != m_topQueries.end())
m_topQueries.erase(it);
else if (m_topQueries.size() >= kMaxSuggestCount)
m_topQueries.pop_back();
// Add new query and save it to drive.
m_topQueries.push_front(query);
Save();
}
void QuerySaver::Clear()
{
m_topQueries.clear();
Settings::Delete(kSettingsKey);
}
void QuerySaver::Serialize(string & data) const
{
vector<uint8_t> rawData;
MemWriter<vector<uint8_t>> writer(rawData);
TLength size = m_topQueries.size();
WriteToSink(writer, size);
for (auto const & query : m_topQueries)
{
size = query.size();
WriteToSink(writer, size);
writer.Write(query.c_str(), size);
}
data = base64::Encode(string(rawData.begin(), rawData.end()));
}
void QuerySaver::EmergencyReset()
{
Clear();
LOG(LWARNING, ("Search history data corrupted! Creating new one."));
}
void QuerySaver::Deserialize(string const & data)
{
string decodedData = base64::Decode(data);
MemReader rawReader(decodedData.c_str(), decodedData.size());
ReaderSource<MemReader> reader(rawReader);
TLength queriesCount;
if (!ReadLength(reader, queriesCount))
{
EmergencyReset();
return;
}
queriesCount = min(queriesCount, kMaxSuggestCount);
for (TLength i = 0; i < queriesCount; ++i)
{
TLength stringLength;
if (!ReadLength(reader, stringLength))
{
EmergencyReset();
return;
}
if (reader.Size() < stringLength)
{
EmergencyReset();
return;
}
vector<char> str(stringLength);
reader.Read(&str[0], stringLength);
m_topQueries.emplace_back(&str[0], stringLength);
}
}
void QuerySaver::Save()
{
string data;
Serialize(data);
Settings::Set(kSettingsKey, data);
}
void QuerySaver::Load()
{
string hexData;
Settings::Get(kSettingsKey, hexData);
if (hexData.empty())
return;
Deserialize(hexData);
}
} // namesapce search
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "bssrdf.h"
// appleseed.renderer headers.
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/project/project.h"
// appleseed.foundation headers.
#include "foundation/image/colorspace.h"
using namespace foundation;
/*
Quick ref:
----------
sigma_a absorption coeff.
sigma_s scattering coeff.
g anisotropy
sigma_t extinction coeff. -> sigma_a + sigma_s
sigma_s_prime reduced scattering coeff. -> sigma_s * (1 - g)
sigma_t_prime reduced extinction coeff. -> sigma_a + sigma_s_prime
sigma_tr effective extinction coeff. -> sqrt( 3 * sigma_a * sigma_t_prime)
Texture mapping:
----------------
alpha_prime -> sigma_s_prime / sigma_t_prime
ld mean free path -> 1 / sigma_tr
sigma_t_prime = sigma_tr / sqrt( 3 * (1 - alpha_prime))
sigma_s_prime = alpha_prime * sigma_t_prime
sigma_a = sigma_t_prime - sigma_s_prime
*/
namespace renderer
{
//
// BSSRDF class implementation.
//
namespace
{
const UniqueID g_class_uid = new_guid();
}
UniqueID BSSRDF::get_class_uid()
{
return g_class_uid;
}
BSSRDF::BSSRDF(
const char* name,
const ParamArray& params)
: ConnectableEntity(g_class_uid, params)
, m_lighting_conditions(0)
{
set_name(name);
}
bool BSSRDF::on_frame_begin(
const Project& project,
const Assembly& assembly,
IAbortSwitch* abort_switch)
{
m_lighting_conditions = &project.get_frame()->get_lighting_conditions();
return true;
}
void BSSRDF::on_frame_end(
const Project& project,
const Assembly& assembly)
{
m_lighting_conditions = 0;
}
size_t BSSRDF::compute_input_data_size(
const Assembly& assembly) const
{
return get_inputs().compute_data_size();
}
void BSSRDF::evaluate_inputs(
const ShadingContext& shading_context,
InputEvaluator& input_evaluator,
const ShadingPoint& shading_point,
const size_t offset) const
{
input_evaluator.evaluate(get_inputs(), shading_point.get_uv(0), offset);
}
bool BSSRDF::sample(
const void* data,
BSSRDFSample& sample) const
{
sample.get_sampling_context().split_in_place(1, 1);
const double r = sample.get_sampling_context().next_double2();
const Basis3d& shading_basis = sample.get_shading_point().get_shading_basis();
if (r <= 0.5)
{
sample.set_sample_basis(shading_basis);
sample.set_use_offset_origin(true);
}
else if (r <= 0.75)
{
sample.set_sample_basis(
Basis3d(
shading_basis.get_tangent_u(),
shading_basis.get_tangent_v(),
shading_basis.get_normal()));
}
else
{
sample.set_sample_basis(
Basis3d(
shading_basis.get_tangent_v(),
shading_basis.get_normal(),
shading_basis.get_tangent_u()));
}
Vector2d d;
if (do_sample(data, sample, d))
{
sample.set_origin(
sample.get_shading_point().get_point() +
sample.get_sample_basis().get_tangent_u() * d.x +
sample.get_sample_basis().get_tangent_v() * d.y);
return true;
}
return false;
}
double BSSRDF::pdf(
const void* data,
const ShadingPoint& outgoing_point,
const ShadingPoint& incoming_point,
const Basis3d& basis,
const size_t channel) const
{
// From PBRT 3.
const Vector3d d = outgoing_point.get_point() - incoming_point.get_point();
const Vector3d dlocal(
dot(basis.get_tangent_u(), d),
dot(basis.get_tangent_v(), d),
dot(basis.get_normal() , d));
const Vector3d& n = incoming_point.get_shading_normal();
const Vector3d nlocal(
dot(basis.get_tangent_u(), n),
dot(basis.get_tangent_v(), n),
dot(basis.get_normal() , n));
const double axis_prob[3] = {.25f, .25f, .5f};
const double dist_sqr[3] = {
square(dlocal.y) + square(dlocal.z),
square(dlocal.z) + square(dlocal.x),
square(dlocal.x) + square(dlocal.y)};
double result = 0.0;
for (size_t i = 0; i < 3; ++i)
result += 0.5 * pdf(data, channel, std::sqrt(dist_sqr[i])) * axis_prob[i] * std::abs(nlocal[i]);
return result;
}
//
// Reference:
//
// A better dipole, Eugene d’Eon
// http://www.eugenedeon.com/papers/betterdipole.pdf
//
double BSSRDF::fresnel_moment_1(const double eta)
{
return
eta >= 1.0
? (-9.23372 + eta * (22.2272 + eta * (-20.9292 + eta * (10.2291 + eta * (-2.54396 + 0.254913 * eta))))) * 0.5
: (0.919317 + eta * (-3.4793 + eta * (6.75335 + eta * (-7.80989 + eta *(4.98554 - 1.36881 * eta))))) * 0.5;
}
double BSSRDF::fresnel_moment_2(const double eta)
{
double r = -1641.1 + eta * (1213.67 + eta * (-568.556 + eta * (164.798 + eta * (-27.0181 + 1.91826 * eta))));
r += (((135.926 / eta) - 656.175) / eta + 1376.53) / eta;
return r * 0.33333333;
}
} // namespace renderer
<commit_msg>simplified renderer::BSSRDF::pdf() implementation.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "bssrdf.h"
// appleseed.renderer headers.
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/project/project.h"
// appleseed.foundation headers.
#include "foundation/image/colorspace.h"
using namespace foundation;
/*
Quick ref:
----------
sigma_a absorption coeff.
sigma_s scattering coeff.
g anisotropy
sigma_t extinction coeff. -> sigma_a + sigma_s
sigma_s_prime reduced scattering coeff. -> sigma_s * (1 - g)
sigma_t_prime reduced extinction coeff. -> sigma_a + sigma_s_prime
sigma_tr effective extinction coeff. -> sqrt( 3 * sigma_a * sigma_t_prime)
Texture mapping:
----------------
alpha_prime -> sigma_s_prime / sigma_t_prime
ld mean free path -> 1 / sigma_tr
sigma_t_prime = sigma_tr / sqrt( 3 * (1 - alpha_prime))
sigma_s_prime = alpha_prime * sigma_t_prime
sigma_a = sigma_t_prime - sigma_s_prime
*/
namespace renderer
{
//
// BSSRDF class implementation.
//
namespace
{
const UniqueID g_class_uid = new_guid();
}
UniqueID BSSRDF::get_class_uid()
{
return g_class_uid;
}
BSSRDF::BSSRDF(
const char* name,
const ParamArray& params)
: ConnectableEntity(g_class_uid, params)
, m_lighting_conditions(0)
{
set_name(name);
}
bool BSSRDF::on_frame_begin(
const Project& project,
const Assembly& assembly,
IAbortSwitch* abort_switch)
{
m_lighting_conditions = &project.get_frame()->get_lighting_conditions();
return true;
}
void BSSRDF::on_frame_end(
const Project& project,
const Assembly& assembly)
{
m_lighting_conditions = 0;
}
size_t BSSRDF::compute_input_data_size(
const Assembly& assembly) const
{
return get_inputs().compute_data_size();
}
void BSSRDF::evaluate_inputs(
const ShadingContext& shading_context,
InputEvaluator& input_evaluator,
const ShadingPoint& shading_point,
const size_t offset) const
{
input_evaluator.evaluate(get_inputs(), shading_point.get_uv(0), offset);
}
bool BSSRDF::sample(
const void* data,
BSSRDFSample& sample) const
{
sample.get_sampling_context().split_in_place(1, 1);
const double r = sample.get_sampling_context().next_double2();
const Basis3d& shading_basis = sample.get_shading_point().get_shading_basis();
if (r <= 0.5)
{
sample.set_sample_basis(shading_basis);
sample.set_use_offset_origin(true);
}
else if (r <= 0.75)
{
sample.set_sample_basis(
Basis3d(
shading_basis.get_tangent_u(),
shading_basis.get_tangent_v(),
shading_basis.get_normal()));
}
else
{
sample.set_sample_basis(
Basis3d(
shading_basis.get_tangent_v(),
shading_basis.get_normal(),
shading_basis.get_tangent_u()));
}
Vector2d d;
if (do_sample(data, sample, d))
{
sample.set_origin(
sample.get_shading_point().get_point() +
sample.get_sample_basis().get_tangent_u() * d.x +
sample.get_sample_basis().get_tangent_v() * d.y);
return true;
}
return false;
}
double BSSRDF::pdf(
const void* data,
const ShadingPoint& outgoing_point,
const ShadingPoint& incoming_point,
const Basis3d& basis,
const size_t channel) const
{
// From PBRT 3.
const Vector3d d = outgoing_point.get_point() - incoming_point.get_point();
const Vector3d dlocal(
dot(basis.get_tangent_u(), d),
dot(basis.get_tangent_v(), d),
dot(basis.get_normal() , d));
const Vector3d& n = incoming_point.get_shading_normal();
const Vector3d nlocal(
dot(basis.get_tangent_u(), n),
dot(basis.get_tangent_v(), n),
dot(basis.get_normal() , n));
return
pdf(data, channel, std::sqrt(square(dlocal.y) + square(dlocal.z))) * 0.125 * std::abs(nlocal[0]) +
pdf(data, channel, std::sqrt(square(dlocal.z) + square(dlocal.x))) * 0.125 * std::abs(nlocal[1]) +
pdf(data, channel, std::sqrt(square(dlocal.x) + square(dlocal.y))) * 0.250 * std::abs(nlocal[2]);
}
//
// Reference:
//
// A better dipole, Eugene d’Eon
// http://www.eugenedeon.com/papers/betterdipole.pdf
//
double BSSRDF::fresnel_moment_1(const double eta)
{
return
eta >= 1.0
? (-9.23372 + eta * (22.2272 + eta * (-20.9292 + eta * (10.2291 + eta * (-2.54396 + 0.254913 * eta))))) * 0.5
: (0.919317 + eta * (-3.4793 + eta * (6.75335 + eta * (-7.80989 + eta *(4.98554 - 1.36881 * eta))))) * 0.5;
}
double BSSRDF::fresnel_moment_2(const double eta)
{
double r = -1641.1 + eta * (1213.67 + eta * (-568.556 + eta * (164.798 + eta * (-27.0181 + 1.91826 * eta))));
r += (((135.926 / eta) - 656.175) / eta + 1376.53) / eta;
return r * 0.33333333;
}
} // namespace renderer
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <utility>
#include <string>
#include <vector>
#include <cmath>
#include <set>
#include <stack>
#include <queue>
#include <map>
#include <sstream>
#include <ctime>
#include <numeric>
#include <cstring>
#include <functional>
using namespace std;
typedef vector<int> VI;
typedef pair<int, int> PII;
typedef vector<PII> VPII;
typedef vector<string> VS;
typedef map<string, int> MSI;
typedef long long int LL;
typedef unsigned long long int ULL;
#define REP(i, n) for (int i = 0; i < n; ++i)
#define FOR(i, a, b) for (int i = a; i < b; ++i)
#define FORD(i, a, b) for (int i = a-1; i >= b; --i)
#define ALL(x) x.begin(), x.end()
#define SIZE(x) (int)x.size()
#define FOREACH(it, c) for (__typeof(c.begin()) it = c.begin(); it != c.end(); ++it)
#define INF 1023456789
#define PB push_back
#define MP make_pair
#define DEBUG(x) cerr<<#x<<": "<<x<<endl;
#define ERR(...) fprintf(stderr, __VA_ARGS__);
#define EPS 1e-9
int main(void) {
srand(time(NULL));
cout << rand()%2134 << endl;
double first = 1.4;
DEBUG(first);
return 0;
}
----------Extended GCD algorithm----------
struct ans {
int x, y, gcd;
};
//To find an inverse of a mod n, a must be coprime with n and we sould run
//extGcd(a, n) and take the x value of the result - this is the inverse
//a * x + b * y = gcd(a,b)
ans extGcd(int a, int b) {
//PRE: a > b ??? seems to work without it
ans res;
if (b == 0) {res.x=1; res.y=0; res.gcd=a;}
else {
ans prev = extGcd(b, a % b);
res.x = prev.y; res.y = prev.x - (a / b) * prev.y; res.gcd = prev.gcd;
}
return res;
}
----------Union Find algorithm with the heuristics(path compression and joining
according to rank) O(m alpha(n))----------
#define MAX_N 10001
int rank[MAX_N];//upper bound on the length of the path from the root to a leaf
int rep[MAX_N];
void makeSet(int x) {
rank[x] = 0;
rep[x] = x;
}
int findSet(int x) {
if (x != rep[x]) rep[x] = findSet(rep[x]); //path compression
return rep[x];
}
void link(int x, int y) {
if (rank[x] > rank[y]) rep[y] = x;//join according to rang
else {
if (rank[x] == rank[y]) rank[y]++;
rep[x] = y;
}
}
void unionSet(int x, int y) {
link(findSet(x), findSet(y));
}
----------Online LCA O(n log n)----------
#include <vector>
#include <algorithm>
using namespace std;
#define MAX_N 1001
#define MAX_LOG 10
struct interval {
int in, out;
};
vector<int> graph[MAX_N];
int pred[MAX_N][MAX_LOG];
int depth[MAX_N];
interval processTimes[MAX_N];
int n; //number of vertices in the tree
int dfs(int v, int time) {
processTimes[v].in = ++time;
for (int i=0; i<graph[v].size(); i++) {
int cand = graph[v][i];
if (depth[cand] == -1) {
depth[cand] = depth[v] + 1;
pred[cand][0] = v;
time = dfs(cand, time);
}
}
processTimes[v].out = ++time;
return time;
}
void calcPredTable(void) {
int maxDepth = 0;
for (int i=1; i<=n; i++) maxDepth = max(depth[i], maxDepth);
for (int dist=2, j=1; dist <= maxDepth; j++, dist*=2) {
for (int i=1; i<=n; i++) pred[i][j] = pred[pred[i][j-1]][j-1];
}
}
void preprocess(int root) {
for (int i=1; i<=n; i++) depth[i] = -1;
depth[root] = 0; pred[root][0] = 0;
dfs(root, 0);
calcPredTable();
}
bool contains(interval a, interval b) {
return (a.in < b.in && a.out > b.out);
}
int reachDepth(int v, int d) {
if (depth[v] == d) return v;
int i=0;
while (depth[pred[v][i+1]] >= d) i++;
return reachDepth(pred[v][i], d);
}
int lca(int va, int vb) {
if (va == vb || contains(processTimes[va], processTimes[vb])) return va;
if (contains(processTimes[vb], processTimes[va])) return vb;
if (depth[va] > depth[vb]) va = reachDepth(va, depth[vb]);
if (depth[va] < depth[vb]) vb = reachDepth(vb, depth[va]);
while(va != vb) {
int i=0;
for (; pred[va][i+1] != pred[vb][i+1]; i++)
;
va = pred[va][i]; vb = pred[vb][i];
}
return va;
}
----------Maximum Flow in a directed graph (derivation of the Dinic's method)
O(n^4) with a VERY small const----------
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define MAX_N 5001
const int inf = 2000000000;
int begin[MAX_N];
int dist[MAX_N];
vector<int> graph[MAX_N];
int c[MAX_N][MAX_N];
bool vis[MAX_N];
queue<int> q;
void bfsIn(int v) {
for (int i=0; i<graph[v].size(); i++) {
int cand = graph[v][i];
if (!vis[cand] && c[v][cand] > 0) {
vis[cand] = true; dist[cand] = dist[v] + 1;
q.push(cand);
}
}
}
bool bfs(int s, int t) {
for (int i=s+1; i<=t; i++) {
dist[i] = 0; vis[i] = false;
}
vis[s]=true; dist[s]=0; q.push(s);
while(!q.empty()) {
int v = q.front(); q.pop();
bfsIn(v);
}
return vis[t];
}
int dfs(int v, int t, int min_cap) {
int res = 0;
if (v == t || min_cap == 0) return min_cap;
for (int& i=begin[v]; i<graph[v].size(); i++) {
int cand = graph[v][i];
if (dist[cand] == dist[v]+1 && c[v][cand] > 0) {
int newFlow = dfs(cand, t, min(min_cap, c[v][cand]));
c[v][cand] -= newFlow;
c[cand][v] += newFlow;
min_cap -= newFlow;
res += newFlow;
if (min_cap == 0) break;
}
}
return res;
}
int maxFlow(int s, int t) {
long long result = 0;
while (bfs(s,t)) {
for (int i=s; i<=t; i++) begin[i] = 0;
int init_cap = inf;
result += dfs(s,t,init_cap);
}
return result;
}
----------Maximum matching in the bipartite graph O(n^2.5)----------
#include <algorithm>
using namespace std;
#define MAX_X 201
#define MAX_Y 401
vector<int> graph[MAX_X];
bool vis[MAX_X];
int matchX[MAX_X];
int matchY[MAX_Y];
int sizeX, sizeY;
int dfs(int x) {
vis[x] = true;
for (int i=0; i<graph[x].size(); i++) {
int y = graph[x][i];
if (matchY[y] == -1 || (!vis[matchY[y]] && dfs(matchY[y]))) {
matchY[y] = x;
matchX[x] = y;
return 1;
}
}
return 0;
}
int maxMatching(void) {
for (int i=1; i<=sizeX; i++) random_shuffle(graph[i].begin(), graph[i].end());
for (int i=1; i<=sizeX; i++) matchX[i] = -1;
for (int i=1; i<=sizeY; i++) matchY[i] = -1;
int res = 0; bool change = true;
while(change) {
change = false;
for (int i=1; i<=sizeX; i++) vis[i] = false;
for (int i=1; i<=sizeX; i++) {
if (matchX[i] == -1 && !vis[i] && dfs(i)) {
res++; change = true;
}
}
}
return res;
}
<commit_msg>Algorithm finding the shortest distance between all pairs of points added.<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <utility>
#include <string>
#include <vector>
#include <cmath>
#include <set>
#include <stack>
#include <queue>
#include <map>
#include <sstream>
#include <ctime>
#include <numeric>
#include <cstring>
#include <functional>
using namespace std;
typedef vector<int> VI;
typedef pair<int, int> PII;
typedef vector<PII> VPII;
typedef vector<string> VS;
typedef map<string, int> MSI;
typedef long long int LL;
typedef unsigned long long int ULL;
#define REP(i, n) for (int i = 0; i < n; ++i)
#define FOR(i, a, b) for (int i = a; i < b; ++i)
#define FORD(i, a, b) for (int i = a-1; i >= b; --i)
#define ALL(x) x.begin(), x.end()
#define SIZE(x) (int)x.size()
#define FOREACH(it, c) for (__typeof(c.begin()) it = c.begin(); it != c.end(); ++it)
#define INF 1023456789
#define PB push_back
#define MP make_pair
#define DEBUG(x) cerr<<#x<<": "<<x<<endl;
#define ERR(...) fprintf(stderr, __VA_ARGS__);
#define EPS 1e-9
int main(void) {
srand(time(NULL));
cout << rand()%2134 << endl;
double first = 1.4;
DEBUG(first);
return 0;
}
----------Extended GCD algorithm----------
struct ans {
int x, y, gcd;
};
//To find an inverse of a mod n, a must be coprime with n and we sould run
//extGcd(a, n) and take the x value of the result - this is the inverse
//a * x + b * y = gcd(a,b)
ans extGcd(int a, int b) {
//PRE: a > b ??? seems to work without it
ans res;
if (b == 0) {res.x=1; res.y=0; res.gcd=a;}
else {
ans prev = extGcd(b, a % b);
res.x = prev.y; res.y = prev.x - (a / b) * prev.y; res.gcd = prev.gcd;
}
return res;
}
----------Union Find algorithm with the heuristics(path compression and joining
according to rank) O(m alpha(n))----------
#define MAX_N 10001
int rank[MAX_N];//upper bound on the length of the path from the root to a leaf
int rep[MAX_N];
void makeSet(int x) {
rank[x] = 0;
rep[x] = x;
}
int findSet(int x) {
if (x != rep[x]) rep[x] = findSet(rep[x]); //path compression
return rep[x];
}
void link(int x, int y) {
if (rank[x] > rank[y]) rep[y] = x;//join according to rang
else {
if (rank[x] == rank[y]) rank[y]++;
rep[x] = y;
}
}
void unionSet(int x, int y) {
link(findSet(x), findSet(y));
}
----------Online LCA O(n log n)----------
#include <vector>
#include <algorithm>
using namespace std;
#define MAX_N 1001
#define MAX_LOG 10
struct interval {
int in, out;
};
vector<int> graph[MAX_N];
int pred[MAX_N][MAX_LOG];
int depth[MAX_N];
interval processTimes[MAX_N];
int n; //number of vertices in the tree
int dfs(int v, int time) {
processTimes[v].in = ++time;
for (int i=0; i<graph[v].size(); i++) {
int cand = graph[v][i];
if (depth[cand] == -1) {
depth[cand] = depth[v] + 1;
pred[cand][0] = v;
time = dfs(cand, time);
}
}
processTimes[v].out = ++time;
return time;
}
void calcPredTable(void) {
int maxDepth = 0;
for (int i=1; i<=n; i++) maxDepth = max(depth[i], maxDepth);
for (int dist=2, j=1; dist <= maxDepth; j++, dist*=2) {
for (int i=1; i<=n; i++) pred[i][j] = pred[pred[i][j-1]][j-1];
}
}
void preprocess(int root) {
for (int i=1; i<=n; i++) depth[i] = -1;
depth[root] = 0; pred[root][0] = 0;
dfs(root, 0);
calcPredTable();
}
bool contains(interval a, interval b) {
return (a.in < b.in && a.out > b.out);
}
int reachDepth(int v, int d) {
if (depth[v] == d) return v;
int i=0;
while (depth[pred[v][i+1]] >= d) i++;
return reachDepth(pred[v][i], d);
}
int lca(int va, int vb) {
if (va == vb || contains(processTimes[va], processTimes[vb])) return va;
if (contains(processTimes[vb], processTimes[va])) return vb;
if (depth[va] > depth[vb]) va = reachDepth(va, depth[vb]);
if (depth[va] < depth[vb]) vb = reachDepth(vb, depth[va]);
while(va != vb) {
int i=0;
for (; pred[va][i+1] != pred[vb][i+1]; i++)
;
va = pred[va][i]; vb = pred[vb][i];
}
return va;
}
----------Maximum Flow in a directed graph (derivation of the Dinic's method)
O(n^4) with a VERY small const----------
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define MAX_N 5001
const int inf = 2000000000;
int begin[MAX_N];
int dist[MAX_N];
vector<int> graph[MAX_N];
int c[MAX_N][MAX_N];
bool vis[MAX_N];
queue<int> q;
void bfsIn(int v) {
for (int i=0; i<graph[v].size(); i++) {
int cand = graph[v][i];
if (!vis[cand] && c[v][cand] > 0) {
vis[cand] = true; dist[cand] = dist[v] + 1;
q.push(cand);
}
}
}
bool bfs(int s, int t) {
for (int i=s+1; i<=t; i++) {
dist[i] = 0; vis[i] = false;
}
vis[s]=true; dist[s]=0; q.push(s);
while(!q.empty()) {
int v = q.front(); q.pop();
bfsIn(v);
}
return vis[t];
}
int dfs(int v, int t, int min_cap) {
int res = 0;
if (v == t || min_cap == 0) return min_cap;
for (int& i=begin[v]; i<graph[v].size(); i++) {
int cand = graph[v][i];
if (dist[cand] == dist[v]+1 && c[v][cand] > 0) {
int newFlow = dfs(cand, t, min(min_cap, c[v][cand]));
c[v][cand] -= newFlow;
c[cand][v] += newFlow;
min_cap -= newFlow;
res += newFlow;
if (min_cap == 0) break;
}
}
return res;
}
int maxFlow(int s, int t) {
long long result = 0;
while (bfs(s,t)) {
for (int i=s; i<=t; i++) begin[i] = 0;
int init_cap = inf;
result += dfs(s,t,init_cap);
}
return result;
}
----------Maximum matching in the bipartite graph O(n^2.5)----------
#include <algorithm>
using namespace std;
#define MAX_X 201
#define MAX_Y 401
vector<int> graph[MAX_X];
bool vis[MAX_X];
int matchX[MAX_X];
int matchY[MAX_Y];
int sizeX, sizeY;
int dfs(int x) {
vis[x] = true;
for (int i=0; i<graph[x].size(); i++) {
int y = graph[x][i];
if (matchY[y] == -1 || (!vis[matchY[y]] && dfs(matchY[y]))) {
matchY[y] = x;
matchX[x] = y;
return 1;
}
}
return 0;
}
int maxMatching(void) {
for (int i=1; i<=sizeX; i++) random_shuffle(graph[i].begin(), graph[i].end());
for (int i=1; i<=sizeX; i++) matchX[i] = -1;
for (int i=1; i<=sizeY; i++) matchY[i] = -1;
int res = 0; bool change = true;
while(change) {
change = false;
for (int i=1; i<=sizeX; i++) vis[i] = false;
for (int i=1; i<=sizeX; i++) {
if (matchX[i] == -1 && !vis[i] && dfs(i)) {
res++; change = true;
}
}
}
return res;
}
----------Shortest distance between all pairs of points O(n log n)----------
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
#define MAX_N 50000
#define MIN(a,b) ((a)<(b)) ? a : b
#define MAX(a,b) ((a)>(b)) ? a : b
struct point {
int x, y, nr;
};
struct ans {
long long dist;
int index1, index2;
void operator=(const ans& val) {
dist = val.dist;
index1 = val.index1;
index2 = val.index2;
}
bool operator<(const ans& val) const {
return dist < val.dist;
}
};
bool compX(const point pA, const point pB) {
return pA.x < pB.x;
}
bool compY(const point pA, const point pB) {
return pA.y < pB.y;
}
inline long long dist(const point pA, const point pB) {
long long aX = static_cast<long long>(pA.x);
long long bX = static_cast<long long>(pB.x);
long long aY = static_cast<long long>(pA.y);
long long bY = static_cast<long long>(pB.y);
return ((aX - bX) * (aX - bX) + (aY - bY) * (aY - bY));
}
ans minDist(point *tab, int n) {
if (n >= 2) {
ans res = {dist(tab[0], tab[1]), tab[0].nr, tab[1].nr};
if (n == 3) {
ans cand1 = {dist(tab[0], tab[2]), tab[0].nr, tab[2].nr};
res = MIN(res, cand1);
ans cand2 = {dist(tab[1], tab[2]), tab[1].nr, tab[2].nr};
res = MIN(res, cand2);
}
return res;
}
}
ans closestPair(point *tabX, point *tabY, int n) {
if (n <= 3) {
return minDist(tabX, n);
}
int m = n/2;
ans ansL = closestPair(tabX, tabY, m);
ans ansR = closestPair(tabX + m, tabY + m, n - m);
ans res = MIN(ansL, ansR);
long long distMin = res.dist;
vector<point> temp;
for (int i=0; i<n; i++) {
if (abs(tabY[m].x - tabY[i].x) < distMin) {
temp.push_back(tabY[i]);
}
}
for (int i=0; i<temp.size(); i++) {
for (int k=i+1; k<temp.size() && dist(temp[i],temp[k])<distMin; k++) {
ans candRes = { dist(temp[i],temp[k]), temp[i].nr, temp[k].nr};
res = MIN(res, candRes);
}
}
return res;
}
ans calcRes(point *tabX, point *tabY, int n) {
sort(tabX, tabX + n, compX);
sort(tabY, tabY + n, compY);
return closestPair(tabX, tabY, n);
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "protein/RMSF.h"
#include <cmath>
#include "vislib/sys/Log.h"
#include "vislib/Array.h"
#include "vislib/math/ShallowVector.h"
#include <fstream>
using namespace megamol;
using namespace megamol::protein;
using namespace megamol::protein_calls;
PROTEIN_API bool megamol::protein::computeRMSF(protein_calls::MolecularDataCall *mol) {
if (mol == NULL) return false;
// store current frame and calltime
float currentCallTime = mol->Calltime();
unsigned int currentFrame = mol->FrameID();
// load first frame
mol->SetFrameID(0, true);
if (!(*mol)(MolecularDataCall::CallForGetData)) return false;
// check if atom count is zero
if (mol->AtomCount() < 1) return false;
// no frames available -> false
if (mol->FrameCount() < 2) return false;
// allocate mem
vislib::Array<float> meanPos;
meanPos.SetCount(mol->AtomCount() * 3);
float *rmsf;
rmsf = new float[mol->AtomCount()];
// initialize rmsf to zero
for (unsigned int i = 0; i < mol->AtomCount(); i++) {
rmsf[i] = 0;
}
// get atom pos of first frame
for (unsigned int atomIdx = 0; atomIdx < mol->AtomCount(); atomIdx++) {
meanPos[atomIdx * 3 + 0] = mol->AtomPositions()[atomIdx * 3 + 0];
meanPos[atomIdx * 3 + 1] = mol->AtomPositions()[atomIdx * 3 + 1];
meanPos[atomIdx * 3 + 2] = mol->AtomPositions()[atomIdx * 3 + 2];
}
// sum up all atom positions
for (unsigned int i = 1; i < mol->FrameCount(); i++) {
// load frame
mol->SetFrameID(i, true);
if (!(*mol)(MolecularDataCall::CallForGetData)) return false;
// add atom pos
for (unsigned int atomIdx = 0; atomIdx < mol->AtomCount(); atomIdx++) {
meanPos[atomIdx*3+0] += mol->AtomPositions()[atomIdx*3+0];
meanPos[atomIdx*3+1] += mol->AtomPositions()[atomIdx*3+1];
meanPos[atomIdx*3+2] += mol->AtomPositions()[atomIdx*3+2];
}
}
// compute average pos
for (unsigned int i = 0; i < meanPos.Count(); i++) {
meanPos[i] /= static_cast<float>(mol->FrameCount());
}
// compute RMSF
vislib::math::Vector<float, 3> tmpVec;
float len;
for (unsigned int i = 0; i < mol->FrameCount(); i++) {
// load frame
mol->SetFrameID(i, true);
if (!(*mol)(MolecularDataCall::CallForGetData)) return false;
// get deviation from mean pos for current atom pos
for (unsigned int atomIdx = 0; atomIdx < mol->AtomCount(); atomIdx++) {
tmpVec.SetX( mol->AtomPositions()[atomIdx * 3 + 0] - meanPos[atomIdx * 3 + 0]);
tmpVec.SetY( mol->AtomPositions()[atomIdx * 3 + 1] - meanPos[atomIdx * 3 + 1]);
tmpVec.SetZ( mol->AtomPositions()[atomIdx * 3 + 2] - meanPos[atomIdx * 3 + 2]);
len = tmpVec.Length();
rmsf[atomIdx] += len * len;
}
}
// compute average pos
float minRMSF = FLT_MAX, maxRMSF = 0.0f;
for (unsigned int i = 0; i < mol->AtomCount(); i++) {
rmsf[i] = sqrtf( rmsf[i] / static_cast<float>(mol->FrameCount()));
minRMSF = rmsf[i] < minRMSF ? rmsf[i] : minRMSF;
maxRMSF = rmsf[i] > maxRMSF ? rmsf[i] : maxRMSF;
}
// restore current frame
mol->SetCalltime(currentCallTime);
mol->SetFrameID(currentFrame);
if (!(*mol)(MolecularDataCall::CallForGetData)) return false;
// write RMSF to B-Factor
mol->SetAtomBFactors(rmsf, true);
mol->SetBFactorRange(minRMSF, maxRMSF);
return true;
}
<commit_msg>compile fix gcc<commit_after>#include "stdafx.h"
#include "protein/RMSF.h"
#include <cmath>
#include "vislib/sys/Log.h"
#include "vislib/Array.h"
#include "vislib/math/ShallowVector.h"
#include <fstream>
#include <cfloat>
using namespace megamol;
using namespace megamol::protein;
using namespace megamol::protein_calls;
PROTEIN_API bool megamol::protein::computeRMSF(protein_calls::MolecularDataCall *mol) {
if (mol == NULL) return false;
// store current frame and calltime
float currentCallTime = mol->Calltime();
unsigned int currentFrame = mol->FrameID();
// load first frame
mol->SetFrameID(0, true);
if (!(*mol)(MolecularDataCall::CallForGetData)) return false;
// check if atom count is zero
if (mol->AtomCount() < 1) return false;
// no frames available -> false
if (mol->FrameCount() < 2) return false;
// allocate mem
vislib::Array<float> meanPos;
meanPos.SetCount(mol->AtomCount() * 3);
float *rmsf;
rmsf = new float[mol->AtomCount()];
// initialize rmsf to zero
for (unsigned int i = 0; i < mol->AtomCount(); i++) {
rmsf[i] = 0;
}
// get atom pos of first frame
for (unsigned int atomIdx = 0; atomIdx < mol->AtomCount(); atomIdx++) {
meanPos[atomIdx * 3 + 0] = mol->AtomPositions()[atomIdx * 3 + 0];
meanPos[atomIdx * 3 + 1] = mol->AtomPositions()[atomIdx * 3 + 1];
meanPos[atomIdx * 3 + 2] = mol->AtomPositions()[atomIdx * 3 + 2];
}
// sum up all atom positions
for (unsigned int i = 1; i < mol->FrameCount(); i++) {
// load frame
mol->SetFrameID(i, true);
if (!(*mol)(MolecularDataCall::CallForGetData)) return false;
// add atom pos
for (unsigned int atomIdx = 0; atomIdx < mol->AtomCount(); atomIdx++) {
meanPos[atomIdx*3+0] += mol->AtomPositions()[atomIdx*3+0];
meanPos[atomIdx*3+1] += mol->AtomPositions()[atomIdx*3+1];
meanPos[atomIdx*3+2] += mol->AtomPositions()[atomIdx*3+2];
}
}
// compute average pos
for (unsigned int i = 0; i < meanPos.Count(); i++) {
meanPos[i] /= static_cast<float>(mol->FrameCount());
}
// compute RMSF
vislib::math::Vector<float, 3> tmpVec;
float len;
for (unsigned int i = 0; i < mol->FrameCount(); i++) {
// load frame
mol->SetFrameID(i, true);
if (!(*mol)(MolecularDataCall::CallForGetData)) return false;
// get deviation from mean pos for current atom pos
for (unsigned int atomIdx = 0; atomIdx < mol->AtomCount(); atomIdx++) {
tmpVec.SetX( mol->AtomPositions()[atomIdx * 3 + 0] - meanPos[atomIdx * 3 + 0]);
tmpVec.SetY( mol->AtomPositions()[atomIdx * 3 + 1] - meanPos[atomIdx * 3 + 1]);
tmpVec.SetZ( mol->AtomPositions()[atomIdx * 3 + 2] - meanPos[atomIdx * 3 + 2]);
len = tmpVec.Length();
rmsf[atomIdx] += len * len;
}
}
// compute average pos
float minRMSF = FLT_MAX, maxRMSF = 0.0f;
for (unsigned int i = 0; i < mol->AtomCount(); i++) {
rmsf[i] = sqrtf( rmsf[i] / static_cast<float>(mol->FrameCount()));
minRMSF = rmsf[i] < minRMSF ? rmsf[i] : minRMSF;
maxRMSF = rmsf[i] > maxRMSF ? rmsf[i] : maxRMSF;
}
// restore current frame
mol->SetCalltime(currentCallTime);
mol->SetFrameID(currentFrame);
if (!(*mol)(MolecularDataCall::CallForGetData)) return false;
// write RMSF to B-Factor
mol->SetAtomBFactors(rmsf, true);
mol->SetBFactorRange(minRMSF, maxRMSF);
return true;
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief イグナイター・プロジェクト設定クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <array>
#include "core/glcore.hpp"
#include "utils/director.hpp"
#include "widgets/widget_dialog.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_image.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/widget_text.hpp"
#include "widgets/widget_label.hpp"
#include "widgets/widget_spinbox.hpp"
#include "widgets/widget_check.hpp"
#include "widgets/widget_filer.hpp"
#include "utils/input.hpp"
#include "utils/format.hpp"
#include "utils/preference.hpp"
#include "img_io/img_files.hpp"
namespace app {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief イグナイター・プロジェクト設定クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class project {
utils::director<core>& director_;
gui::widget_dialog* dialog_;
gui::widget_label* csv_name_;
gui::widget_label* pbase_;
gui::widget_label* pext_;
gui::widget_label* pname_[50];
gui::widget_text* help_;
std::string get_path_(uint32_t no) const {
if(pname_[no]->get_text().empty()) return "";
std::string s = pbase_->get_text();
s += pname_[no]->get_text();
s += pext_->get_text();
if(!s.empty()) {
auto& core = gl::core::get_instance();
std::string path = core.get_current_path();
path += '/';
path += s;
return path;
}
return s;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
project(utils::director<core>& d) : director_(d),
dialog_(nullptr),
csv_name_(nullptr),
pbase_(nullptr), pext_(nullptr),
pname_{ nullptr }, help_(nullptr)
{ }
//-----------------------------------------------------------------//
/*!
@brief ダイアログの取得
@return ダイアログ
*/
//-----------------------------------------------------------------//
gui::widget_dialog* get_dialog() { return dialog_; }
//-----------------------------------------------------------------//
/*!
@brief テスト名の取得
@param[in] no テスト番号(0~49)
@return テスト名
*/
//-----------------------------------------------------------------//
std::string get_test_name(uint32_t no) const {
if(no >= 50) return "";
return get_path_(no);
}
//-----------------------------------------------------------------//
/*!
@brief 初期化(リソースの構築)
*/
//-----------------------------------------------------------------//
void initialize()
{
using namespace gui;
widget_director& wd = director_.at().widget_director_;
int w = 1020;
int h = 720;
{ // 単体試験設定ダイアログ
widget::param wp(vtx::irect(120, 120, w, h));
widget_dialog::param wp_;
wp_.style_ = widget_dialog::style::OK;
dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
dialog_->enable(false);
int yy = 20;
{ // CSV 名設定
{
widget::param wp(vtx::irect(20, yy, 60, 40), dialog_);
widget_text::param wp_("CSV:");
wp_.text_param_.placement_
= vtx::placement(vtx::placement::holizontal::LEFT,
vtx::placement::vertical::CENTER);
wd.add_widget<widget_text>(wp, wp_);
}
widget::param wp(vtx::irect(20 + 60 + 10, yy, 150, 40), dialog_);
widget_label::param wp_("", false);
csv_name_ = wd.add_widget<widget_label>(wp, wp_);
}
yy += 50;
{ // 単体試験ベース名設定
{
widget::param wp(vtx::irect(20, yy, 100, 40), dialog_);
widget_text::param wp_("ベース名:");
wp_.text_param_.placement_
= vtx::placement(vtx::placement::holizontal::LEFT,
vtx::placement::vertical::CENTER);
wd.add_widget<widget_text>(wp, wp_);
}
widget::param wp(vtx::irect(20 + 100 + 10, yy, 150, 40), dialog_);
widget_label::param wp_("", false);
pbase_ = wd.add_widget<widget_label>(wp, wp_);
}
{ // 単体試験拡張子設定
{
widget::param wp(vtx::irect(320, yy, 90, 40), dialog_);
widget_text::param wp_("拡張子:");
wp_.text_param_.placement_
= vtx::placement(vtx::placement::holizontal::LEFT,
vtx::placement::vertical::CENTER);
wd.add_widget<widget_text>(wp, wp_);
}
widget::param wp(vtx::irect(320 + 90 + 10, yy, 150, 40), dialog_);
widget_label::param wp_(".unt", false);
pext_ = wd.add_widget<widget_label>(wp, wp_);
}
for(int i = 0; i < 50; ++i) {
int x = (i / 10) * 200;
int y = 40 + 10 + (i % 10) * 50;
{
widget::param wp(vtx::irect(x + 20, y + yy, 50, 40), dialog_);
std::string no = (boost::format("%d:") % (i + 1)).str();
widget_text::param wp_(no);
wp_.text_param_.placement_
= vtx::placement(vtx::placement::holizontal::LEFT,
vtx::placement::vertical::CENTER);
wd.add_widget<widget_text>(wp, wp_);
}
widget::param wp(vtx::irect(x + 60, y + yy, 130, 40), dialog_);
widget_label::param wp_("", false);
pname_[i] = wd.add_widget<widget_label>(wp, wp_);
}
{
widget::param wp(vtx::irect(20, h - 100, w - 20 * 2, 40), dialog_);
widget_text::param wp_;
wp_.text_param_.placement_
= vtx::placement(vtx::placement::holizontal::LEFT,
vtx::placement::vertical::CENTER);
help_ = wd.add_widget<widget_text>(wp, wp_);
}
}
}
//-----------------------------------------------------------------//
/*!
@brief 更新
*/
//-----------------------------------------------------------------//
void update()
{
if(dialog_->get_state(gui::widget::state::ENABLE)) {
std::string s;
for(int i = 0; i < 50; ++i) {
if(pname_[i]->get_focus()) {
if(pname_[i]->get_text().empty()) continue;
s = get_path_(i);
if(utils::probe_file(s)) {
s += " (find !)";
} else {
s += " (can't find)";
}
break;
}
}
help_->set_text(s);
}
}
//-----------------------------------------------------------------//
/*!
@brief セーブ
@param[in] pre プリファレンス(参照)
@return 正常なら「true」
*/
//-----------------------------------------------------------------//
bool save(sys::preference& pre)
{
if(dialog_ == nullptr) return false;
if(pbase_ == nullptr) return false;
if(pext_ == nullptr) return false;
dialog_->save(pre);
pbase_->save(pre);
pext_->save(pre);
for(int i = 0; i < 50; ++i) {
if(pname_[i] == nullptr) return false;
pname_[i]->save(pre);
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief セーブ
@param[in] pre プリファレンス(参照)
@return 正常なら「true」
*/
//-----------------------------------------------------------------//
bool load(sys::preference& pre)
{
if(dialog_ == nullptr) return false;
if(pbase_ == nullptr) return false;
if(pext_ == nullptr) return false;
dialog_->load(pre);
pbase_->load(pre);
pext_->load(pre);
for(int i = 0; i < 50; ++i) {
if(pname_[i] == nullptr) return false;
pname_[i]->load(pre);
}
return true;
}
};
}
<commit_msg>update: project start manage<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief イグナイター・プロジェクト設定クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <array>
#include "core/glcore.hpp"
#include "utils/director.hpp"
#include "widgets/widget_dialog.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_image.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/widget_text.hpp"
#include "widgets/widget_label.hpp"
#include "widgets/widget_spinbox.hpp"
#include "widgets/widget_check.hpp"
#include "widgets/widget_filer.hpp"
#include "utils/input.hpp"
#include "utils/format.hpp"
#include "utils/preference.hpp"
#include "img_io/img_files.hpp"
namespace app {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief イグナイター・プロジェクト設定クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class project {
utils::director<core>& director_;
gui::widget_dialog* name_dialog_;
gui::widget_label* proj_name_;
gui::widget_label* proj_dir_;
gui::widget_dialog* dialog_;
gui::widget_label* csv_name_;
gui::widget_list* image_ext_;
gui::widget_label* pbase_;
gui::widget_label* pext_;
gui::widget_label* pname_[50];
gui::widget_text* help_;
gui::widget_dialog* msg_dialog_;
std::string proj_title_;
std::string root_path_;
std::string get_path_(uint32_t no) const {
if(pname_[no]->get_text().empty()) return "";
std::string s = pbase_->get_text();
s += pname_[no]->get_text();
s += pext_->get_text();
if(!s.empty()) {
auto& core = gl::core::get_instance();
std::string path = core.get_current_path();
path += '/';
path += s;
return path;
}
return s;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
project(utils::director<core>& d) : director_(d),
name_dialog_(nullptr), proj_name_(nullptr), proj_dir_(nullptr),
dialog_(nullptr),
csv_name_(nullptr),
pbase_(nullptr), pext_(nullptr),
pname_{ nullptr }, help_(nullptr),
msg_dialog_(nullptr), proj_title_(), root_path_()
{ }
//-----------------------------------------------------------------//
/*!
@brief プロジェクト名ダイアログの取得
@return プロジェクト名ダイアログ
*/
//-----------------------------------------------------------------//
gui::widget_dialog* get_name_dialog() { return name_dialog_; }
//-----------------------------------------------------------------//
/*!
@brief プロジェクト・タイトルの取得
@return プロジェクト・タイトル
*/
//-----------------------------------------------------------------//
const std::string& get_project_title() const { return proj_title_; }
//-----------------------------------------------------------------//
/*!
@brief ルート・パスの取得
@return ルート・パス
*/
//-----------------------------------------------------------------//
const std::string& get_root_path() const { return root_path_; }
//-----------------------------------------------------------------//
/*!
@brief プロジェクト・ダイアログの取得
@return プロジェクト・ダイアログ
*/
//-----------------------------------------------------------------//
gui::widget_dialog* get_dialog() { return dialog_; }
//-----------------------------------------------------------------//
/*!
@brief テスト名の取得
@param[in] no テスト番号(0~49)
@return テスト名
*/
//-----------------------------------------------------------------//
std::string get_test_name(uint32_t no) const {
if(no >= 50) return "";
return get_path_(no);
}
//-----------------------------------------------------------------//
/*!
@brief 初期化(リソースの構築)
*/
//-----------------------------------------------------------------//
void initialize()
{
using namespace gui;
widget_director& wd = director_.at().widget_director_;
{ // プロジェクト名入力ダイアログ
int w = 300;
int h = 260;
widget::param wp(vtx::irect(100, 100, w, h));
widget_dialog::param wp_;
wp_.style_ = widget_dialog::style::CANCEL_OK;
name_dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
name_dialog_->enable(false);
name_dialog_->at_local_param().select_func_ = [=](bool ok) {
proj_title_.clear();
root_path_.clear();
if(ok) {
auto s = proj_name_->get_text();
if(s.empty()) {
msg_dialog_->set_text(
"プロジェクトのタイトル\nが指定されていません。");
msg_dialog_->enable();
return;
}
s = proj_dir_->get_text();
if(s.empty()) {
msg_dialog_->set_text(
"プロジェクトのルートフォルダ\nが指定されていません。");
msg_dialog_->enable();
return;
} else {
auto path = proj_dir_->get_text();
if(!utils::is_directory(path)) {
msg_dialog_->set_text((boost::format(
"プロジェクトのルートフォルダ\n"
"%s\n"
"がありません。") % path).str());
msg_dialog_->enable();
return;
}
}
proj_title_ = proj_name_->get_text();
root_path_ = proj_dir_->get_text();
}
};
{
widget::param wp(vtx::irect(10, 10, w - 10 * 2, 40), name_dialog_);
widget_text::param wp_("プロジェクト名:");
wd.add_widget<widget_text>(wp, wp_);
}
{
widget::param wp(vtx::irect(10, 50, w - 10 * 2, 40), name_dialog_);
widget_label::param wp_("", false);
proj_name_ = wd.add_widget<widget_label>(wp, wp_);
}
{
widget::param wp(vtx::irect(10, 100, w - 10 * 2, 40), name_dialog_);
widget_text::param wp_("ルートフォルダ:");
wd.add_widget<widget_text>(wp, wp_);
}
{
widget::param wp(vtx::irect(10, 140, w - 10 * 2, 40), name_dialog_);
widget_label::param wp_("", false);
proj_dir_ = wd.add_widget<widget_label>(wp, wp_);
}
}
{ // 単体試験設定ダイアログ
int w = 1020;
int h = 720;
widget::param wp(vtx::irect(120, 120, w, h));
widget_dialog::param wp_;
wp_.style_ = widget_dialog::style::OK;
dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
dialog_->enable(false);
int yy = 20;
{ // CSV 名設定
{
widget::param wp(vtx::irect(20, yy, 60, 40), dialog_);
widget_text::param wp_("CSV:");
wp_.text_param_.placement_
= vtx::placement(vtx::placement::holizontal::LEFT,
vtx::placement::vertical::CENTER);
wd.add_widget<widget_text>(wp, wp_);
}
widget::param wp(vtx::irect(20 + 60 + 10, yy, 150, 40), dialog_);
widget_label::param wp_("", false);
csv_name_ = wd.add_widget<widget_label>(wp, wp_);
}
{
widget::param wp(vtx::irect(20 + 70 + 170, yy, 100, 40), dialog_);
widget_list::param wp_;
wp_.init_list_.push_back("JPEG");
wp_.init_list_.push_back("PNG");
wp_.init_list_.push_back("BMP");
image_ext_ = wd.add_widget<widget_list>(wp, wp_);
}
yy += 50;
{ // 単体試験ベース名設定
{
widget::param wp(vtx::irect(20, yy, 100, 40), dialog_);
widget_text::param wp_("ベース名:");
wp_.text_param_.placement_
= vtx::placement(vtx::placement::holizontal::LEFT,
vtx::placement::vertical::CENTER);
wd.add_widget<widget_text>(wp, wp_);
}
widget::param wp(vtx::irect(20 + 100 + 10, yy, 150, 40), dialog_);
widget_label::param wp_("", false);
pbase_ = wd.add_widget<widget_label>(wp, wp_);
}
{ // 単体試験拡張子設定
{
widget::param wp(vtx::irect(320, yy, 90, 40), dialog_);
widget_text::param wp_("拡張子:");
wp_.text_param_.placement_
= vtx::placement(vtx::placement::holizontal::LEFT,
vtx::placement::vertical::CENTER);
wd.add_widget<widget_text>(wp, wp_);
}
widget::param wp(vtx::irect(320 + 90 + 10, yy, 150, 40), dialog_);
widget_label::param wp_(".unt", false);
pext_ = wd.add_widget<widget_label>(wp, wp_);
}
for(int i = 0; i < 50; ++i) {
int x = (i / 10) * 200;
int y = 40 + 10 + (i % 10) * 50;
{
widget::param wp(vtx::irect(x + 20, y + yy, 50, 40), dialog_);
std::string no = (boost::format("%d:") % (i + 1)).str();
widget_text::param wp_(no);
wp_.text_param_.placement_
= vtx::placement(vtx::placement::holizontal::LEFT,
vtx::placement::vertical::CENTER);
wd.add_widget<widget_text>(wp, wp_);
}
widget::param wp(vtx::irect(x + 60, y + yy, 130, 40), dialog_);
widget_label::param wp_("", false);
pname_[i] = wd.add_widget<widget_label>(wp, wp_);
}
{
widget::param wp(vtx::irect(20, h - 100, w - 20 * 2, 40), dialog_);
widget_text::param wp_;
wp_.text_param_.placement_
= vtx::placement(vtx::placement::holizontal::LEFT,
vtx::placement::vertical::CENTER);
help_ = wd.add_widget<widget_text>(wp, wp_);
}
}
{ // メッセージ・ダイアログ
int w = 400;
int h = 200;
widget::param wp(vtx::irect(100, 100, w, h));
widget_dialog::param wp_;
wp_.style_ = widget_dialog::style::OK;
msg_dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
msg_dialog_->enable(false);
}
}
//-----------------------------------------------------------------//
/*!
@brief 更新
*/
//-----------------------------------------------------------------//
void update()
{
if(dialog_->get_state(gui::widget::state::ENABLE)) {
std::string s;
for(int i = 0; i < 50; ++i) {
if(pname_[i]->get_focus()) {
if(pname_[i]->get_text().empty()) continue;
s = get_path_(i);
if(utils::probe_file(s)) {
s += " (find !)";
} else {
s += " (can't find)";
}
break;
}
}
help_->set_text(s);
}
}
//-----------------------------------------------------------------//
/*!
@brief セーブ
@param[in] pre プリファレンス(参照)
@return 正常なら「true」
*/
//-----------------------------------------------------------------//
bool save(sys::preference& pre)
{
if(dialog_ == nullptr) return false;
if(pbase_ == nullptr) return false;
if(pext_ == nullptr) return false;
if(csv_name_ == nullptr) return false;
if(image_ext_ == nullptr) return false;
dialog_->save(pre);
csv_name_->save(pre);
image_ext_->save(pre);
pbase_->save(pre);
pext_->save(pre);
for(int i = 0; i < 50; ++i) {
if(pname_[i] == nullptr) return false;
pname_[i]->save(pre);
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief セーブ
@param[in] pre プリファレンス(参照)
@return 正常なら「true」
*/
//-----------------------------------------------------------------//
bool load(sys::preference& pre)
{
if(dialog_ == nullptr) return false;
if(pbase_ == nullptr) return false;
if(pext_ == nullptr) return false;
if(csv_name_ == nullptr) return false;
if(image_ext_ == nullptr) return false;
dialog_->load(pre);
csv_name_->load(pre);
image_ext_->load(pre);
pbase_->load(pre);
pext_->load(pre);
for(int i = 0; i < 50; ++i) {
if(pname_[i] == nullptr) return false;
pname_[i]->load(pre);
}
return true;
}
};
}
<|endoftext|> |
<commit_before>/* ___ _ ___ __ _ ___ _
/ _ \_ __ ___ ___ ___ ___ ___ __ _ _ __ ___ ___ _ __ | |_ ___ / _ \_ __ __ _ / _(_) ___ ___ / _ \ /_\
/ /_)/ '__/ _ \ / __/ _ \/ __/ __|/ _` | '_ ` _ \ / _ \ '_ \| __/ _ \ / /_\/ '__/ _` | |_| |/ __/ _ \ _____ / /_\///_\\
/ ___/| | | (_) | (_| __/\__ \__ \ (_| | | | | | | __/ | | | || (_) | / /_\\| | | (_| | _| | (_| (_) | |_____| / /_\\/ _ \
\/ |_| \___/ \___\___||___/___/\__,_|_| |_| |_|\___|_| |_|\__\___/ \____/|_| \__,_|_| |_|\___\___/ \____/\_/ \_/
Unisinos 2016 - Vinicius Pegorini Arnhold e Reni Steffenon
*/
#include "Image.h"
#pragma warning( disable : 4244)
Image::Image(int largura, int altura) {
width = largura;
height = altura;
pixels = new unsigned int[width*height];
}
Image::Image() {
width = 0;
height = 0;
}
void Image::setWidth(int w) {
width = w;
}
void Image::setHeight(int h) {
height = h;
}
void Image::calcular() {
pixels = new unsigned int[width*height];
}
void Image::setPixel(int rgb, int x, int y) {
pixels[x + y*width] = rgb;
}
int Image::getPixel(int x, int y) {
return pixels[x + y*width];
}
void Image::setPixel(int a, int r, int g, int b, int x, int y) {
pixels[x + y*width] = (a << 24) | (r << 16) | (g << 8) | (b);
}
unsigned int* Image::getPixels() {
return pixels;
}
int Image::getWidth() {
return width;
}
int Image::getHeight() {
return height;
}
Image Image::clone() {
Image aux(getWidth(), getHeight());
for (int x = 0; x < getWidth(); x++) {
for (int y = 0; y < getHeight(); y++) {
aux.setPixel(getPixel(x, y), x, y);
}
}
return aux;
}
void Image::subImage(Image *src, int startx, int starty) {
int memoryStartY = starty;
for (int x = 0; x < src->getWidth(); x++) {
for (int y = 0; y < src->getHeight(); y++) {
src->setPixel(getPixel(startx, starty), x, y);
starty++;
}
startx++;
starty = memoryStartY;
}
}
void Image::plotInto(Image* sobreposta, int posicaoX, int posicaoY, char* zBuffer, char z)
{
int xRef = 0;
int yRef = 0;
for (int x = posicaoX;x < sobreposta->getWidth() && x< this->width; x++) {
for (int y = posicaoY; y < sobreposta->getHeight() && y< this->height; y++) {
int alfa = (getPixel(x, y) >> 24) & 0xff;
if (alfa != 0) {
if (!alfa == 255) {
sobreposta->setPixel(calcularPixels(getPixel(x, y), sobreposta->getPixel(xRef, yRef)), xRef, yRef);
}
else {
sobreposta->setPixel(getPixel(x, y), xRef, yRef);
}
}
yRef++;
}
yRef = 0;
xRef++;
}
}
void Image::plot(Image sobreposta, int posicaoX, int posicaoY) {
int xSobreposta = 0;
int ySobreposta = 0;
for (int x = posicaoX; x < sobreposta.width + posicaoX; x++) {
for (int y = posicaoY; y < posicaoY + sobreposta.height; y++) {
int pixelSobreposta = sobreposta.getPixel(xSobreposta, ySobreposta);
int alfa = (pixelSobreposta >> 24) & 0xff;
if (alfa == 0) {
}
else {
if (alfa == 255) {
setPixel(pixelSobreposta, x, y);
}
else {
setPixel(calcularPixels(pixelSobreposta, getPixel(x, y)), x, y);
}
}
ySobreposta++;
}
ySobreposta = 0;
xSobreposta++;
}
}
int Image::calcularPixels(int sobreposta, int fundo) {
int aSobreposta = (sobreposta >> 24) & 0xff;
int rSobreposta = (sobreposta >> 16) & 0xff;
int gSobreposta = (sobreposta >> 8) & 0xff;
int bSobreposta = sobreposta & 0xff;
int aFundo = (fundo >> 24) & 0xff;
int rFundo = (fundo >> 16) & 0xff;
int gFundo = (fundo >> 8) & 0xff;
int bFundo = fundo & 0xff;
double alfa = aSobreposta / 255;
int r = 0;
int g = 0;
int b = 0;
r = rFundo*(1 - alfa) + rSobreposta*alfa;
g = gFundo*(1 - alfa) + gSobreposta*alfa;
b = bFundo*(1 - alfa) + bSobreposta*alfa;
int resultado = (255 << 24) | (r << 16) | (g << 8) | (b);
return resultado;
}<commit_msg>Re-fix scroll<commit_after>/* ___ _ ___ __ _ ___ _
/ _ \_ __ ___ ___ ___ ___ ___ __ _ _ __ ___ ___ _ __ | |_ ___ / _ \_ __ __ _ / _(_) ___ ___ / _ \ /_\
/ /_)/ '__/ _ \ / __/ _ \/ __/ __|/ _` | '_ ` _ \ / _ \ '_ \| __/ _ \ / /_\/ '__/ _` | |_| |/ __/ _ \ _____ / /_\///_\\
/ ___/| | | (_) | (_| __/\__ \__ \ (_| | | | | | | __/ | | | || (_) | / /_\\| | | (_| | _| | (_| (_) | |_____| / /_\\/ _ \
\/ |_| \___/ \___\___||___/___/\__,_|_| |_| |_|\___|_| |_|\__\___/ \____/|_| \__,_|_| |_|\___\___/ \____/\_/ \_/
Unisinos 2016 - Vinicius Pegorini Arnhold e Reni Steffenon
*/
#include "Image.h"
#pragma warning( disable : 4244)
Image::Image(int largura, int altura) {
width = largura;
height = altura;
pixels = new unsigned int[width*height];
}
Image::Image() {
width = 0;
height = 0;
}
void Image::setWidth(int w) {
width = w;
}
void Image::setHeight(int h) {
height = h;
}
void Image::calcular() {
pixels = new unsigned int[width*height];
}
void Image::setPixel(int rgb, int x, int y) {
pixels[x + y*width] = rgb;
}
int Image::getPixel(int x, int y) {
return pixels[x + y*width];
}
void Image::setPixel(int a, int r, int g, int b, int x, int y) {
pixels[x + y*width] = (a << 24) | (r << 16) | (g << 8) | (b);
}
unsigned int* Image::getPixels() {
return pixels;
}
int Image::getWidth() {
return width;
}
int Image::getHeight() {
return height;
}
Image Image::clone() {
Image aux(getWidth(), getHeight());
for (int x = 0; x < getWidth(); x++) {
for (int y = 0; y < getHeight(); y++) {
aux.setPixel(getPixel(x, y), x, y);
}
}
return aux;
}
void Image::subImage(Image *src, int startx, int starty) {
int memoryStartY = starty;
for (int x = 0; x < src->getWidth(); x++) {
for (int y = 0; y < src->getHeight(); y++) {
src->setPixel(getPixel(startx, starty), x, y);
starty++;
}
startx++;
starty = memoryStartY;
}
}
void Image::plotInto(Image* ref, int posicaoX, int posicaoY, char* zBuffer, char z)
{
int xRef = 0;
int yRef = 0;
for (int x = posicaoX; x < ref->getWidth() && x < this->width; x++) {
for (int y = posicaoY; y < ref->getHeight() && y < this->height; y++) {
int alfa = (getPixel(x, y) >> 24) & 0xff;
if (alfa != 0) {
if (alfa != 255) {
ref->setPixel(calcularPixels(getPixel(x, y), ref->getPixel(xRef, yRef)), xRef, yRef);
}
else {
ref->setPixel(getPixel(x, y), xRef, yRef);
}
}
yRef++;
}
yRef = 0;
xRef++;
}
}
void Image::plot(Image sobreposta, int posicaoX, int posicaoY) {
int xSobreposta = 0;
int ySobreposta = 0;
for (int x = posicaoX; x < sobreposta.width + posicaoX; x++) {
for (int y = posicaoY; y < posicaoY + sobreposta.height; y++) {
int pixelSobreposta = sobreposta.getPixel(xSobreposta, ySobreposta);
int alfa = (pixelSobreposta >> 24) & 0xff;
if (alfa == 0) {
}
else {
if (alfa == 255) {
setPixel(pixelSobreposta, x, y);
}
else {
setPixel(calcularPixels(pixelSobreposta, getPixel(x, y)), x, y);
}
}
ySobreposta++;
}
ySobreposta = 0;
xSobreposta++;
}
}
int Image::calcularPixels(int sobreposta, int fundo) {
int aSobreposta = (sobreposta >> 24) & 0xff;
int rSobreposta = (sobreposta >> 16) & 0xff;
int gSobreposta = (sobreposta >> 8) & 0xff;
int bSobreposta = sobreposta & 0xff;
int aFundo = (fundo >> 24) & 0xff;
int rFundo = (fundo >> 16) & 0xff;
int gFundo = (fundo >> 8) & 0xff;
int bFundo = fundo & 0xff;
double alfa = aSobreposta / 255;
int r = 0;
int g = 0;
int b = 0;
r = rFundo*(1 - alfa) + rSobreposta*alfa;
g = gFundo*(1 - alfa) + gSobreposta*alfa;
b = bFundo*(1 - alfa) + bSobreposta*alfa;
int resultado = (255 << 24) | (r << 16) | (g << 8) | (b);
return resultado;
}<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetScopeLoader.cpp
* @brief Module for oscilloscope data
* Reads oscilloscope ASCII data and procudes JPetRecoSignal structures.
*/
#include "./JPetScopeLoader.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <utility>
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <TSystem.h>
#include <TApplication.h>
#include "../JPetBarrelSlot/JPetBarrelSlot.h"
#include "../JPetManager/JPetManager.h"
#include "../JPetParamBank/JPetParamBank.h"
#include "../JPetPhysSignal/JPetPhysSignal.h"
#include "../JPetPM/JPetPM.h"
#include "../JPetRecoSignal/JPetRecoSignal.h"
#include "../JPetScin/JPetScin.h"
#include "../JPetScopeLoader/JPetScopeLoader.h"
#include "../JPetTreeHeader/JPetTreeHeader.h"
#include "../JPetWriter/JPetWriter.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../JPetScopeConfigParser/JPetScopeConfigParser.h"
#include <iostream>
using namespace std;
using namespace boost::filesystem;
using boost::property_tree::ptree;
JPetScopeLoader::JPetScopeLoader(JPetScopeTask* task): JPetTaskLoader("", "reco.sig", task)
{
gSystem->Load("libTree");
/**/
}
JPetScopeLoader::~JPetScopeLoader()
{
if (fWriter != nullptr) {
delete fWriter;
fWriter = nullptr;
}
}
void JPetScopeLoader::createInputObjects(const char*)
{
JPetScopeConfigParser confParser;
auto config = confParser.getConfig(fOptions.getScopeConfigFile());
auto prefix2PM = getPMPrefixToPMIdMap(config);
std::map<std::string, int> inputScopeFiles = createInputScopeFileNames(fOptions.getScopeInputDirectory(), prefix2PM);
auto task = dynamic_cast<JPetScopeTask*>(fTask);
task->setInputFiles(inputScopeFiles);
// create an object for storing histograms and counters during processing
fStatistics = new JPetStatistics();
assert(fStatistics);
fHeader = new JPetTreeHeader(fOptions.getRunNumber());
assert(fHeader);
fHeader->setBaseFileName(fOptions.getInputFile());
fHeader->addStageInfo(task->GetName(), task->GetTitle(), 0, JPetCommonTools::getTimeString());
//fHeader->setSourcePosition((*fIter).pCollPosition);
}
std::map<std::string, int> JPetScopeLoader::getPMPrefixToPMIdMap(const scope_config::Config& config) const
{
std::map< std::string, int> prefixToId;
for (const auto & pm : config.fPMs) {
prefixToId[pm.fPrefix] = pm.fId;
}
return prefixToId;
}
/// Returns a map of list of scope input files. The key is the corresponding
/// index of the photomultiplier in the param bank.
std::map<std::string, int> JPetScopeLoader::createInputScopeFileNames(
const std::string& inputPathToScopeFiles,
std::map<std::string, int> pmPref2Id
) const
{
for (auto el : pmPref2Id) {
}
std::map<std::string, int> scopeFiles;
path current_dir(inputPathToScopeFiles);
if (exists(current_dir)) {
for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) {
std::string filename = iter->path().leaf().string();
if (isCorrectScopeFileName(filename)) {
auto prefix = getFilePrefix(filename);
if ( pmPref2Id.find(prefix) != pmPref2Id.end()) {
int id = pmPref2Id.find(prefix)->second;
scopeFiles[iter->path().parent_path().string() + "/" + filename] = id;
} else {
WARNING("The filename does not contain the accepted prefix:" + filename);
}
}
}
} else {
string msg = "Directory: \"";
msg += current_dir.string();
msg += "\" does not exist.";
ERROR(msg.c_str());
}
return scopeFiles;
}
std::string JPetScopeLoader::getFilePrefix(const std::string& filename) const
{
auto pos = filename.find("_");
if (pos != string::npos) {
return filename.substr(0, pos);
}
return "";
}
/// not very effective, but at least we can test it
bool JPetScopeLoader::isCorrectScopeFileName(const std::string& filename) const
{
boost::regex pattern("^[A-Za-z0-9]+_\\d*.txt");
return regex_match(filename, pattern);
}
void JPetScopeLoader::init(const JPetOptions::Options& opts)
{
INFO( "Initialize Scope Loader Module." );
JPetTaskLoader::init(opts);
}
void JPetScopeLoader::exec()
{
assert(fTask);
fTask->setParamManager(fParamManager);
JPetTaskInterface::Options emptyOpts;
fTask->init(emptyOpts);
fTask->exec();
fTask->terminate();
}
void JPetScopeLoader::terminate()
{
assert(fWriter);
assert(fHeader);
assert(fStatistics);
fWriter->writeHeader(fHeader);
fWriter->writeObject(fStatistics->getHistogramsTable(), "Stats");
//store the parametric objects in the ouptut ROOT file
getParamManager().saveParametersToFile(fWriter);
getParamManager().clearParameters();
fWriter->closeFile();
}
<commit_msg>Refactor method name also in JPetScopeLoader<commit_after>/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetScopeLoader.cpp
* @brief Module for oscilloscope data
* Reads oscilloscope ASCII data and procudes JPetRecoSignal structures.
*/
#include "./JPetScopeLoader.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <utility>
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <TSystem.h>
#include <TApplication.h>
#include "../JPetBarrelSlot/JPetBarrelSlot.h"
#include "../JPetManager/JPetManager.h"
#include "../JPetParamBank/JPetParamBank.h"
#include "../JPetPhysSignal/JPetPhysSignal.h"
#include "../JPetPM/JPetPM.h"
#include "../JPetRecoSignal/JPetRecoSignal.h"
#include "../JPetScin/JPetScin.h"
#include "../JPetScopeLoader/JPetScopeLoader.h"
#include "../JPetTreeHeader/JPetTreeHeader.h"
#include "../JPetWriter/JPetWriter.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../JPetScopeConfigParser/JPetScopeConfigParser.h"
#include <iostream>
using namespace std;
using namespace boost::filesystem;
using boost::property_tree::ptree;
JPetScopeLoader::JPetScopeLoader(JPetScopeTask* task): JPetTaskLoader("", "reco.sig", task)
{
gSystem->Load("libTree");
/**/
}
JPetScopeLoader::~JPetScopeLoader()
{
if (fWriter != nullptr) {
delete fWriter;
fWriter = nullptr;
}
}
void JPetScopeLoader::createInputObjects(const char*)
{
JPetScopeConfigParser confParser;
auto config = confParser.getConfig(fOptions.getScopeConfigFile());
auto prefix2PM = getPMPrefixToPMIdMap(config);
std::map<std::string, int> inputScopeFiles = createInputScopeFileNames(fOptions.getScopeInputDirectory(), prefix2PM);
auto task = dynamic_cast<JPetScopeTask*>(fTask);
task->setInputFiles(inputScopeFiles);
// create an object for storing histograms and counters during processing
fStatistics = new JPetStatistics();
assert(fStatistics);
fHeader = new JPetTreeHeader(fOptions.getRunNumber());
assert(fHeader);
fHeader->setBaseFileName(fOptions.getInputFile());
fHeader->addStageInfo(task->GetName(), task->GetTitle(), 0, JPetCommonTools::getTimeString());
//fHeader->setSourcePosition((*fIter).pCollPosition);
}
std::map<std::string, int> JPetScopeLoader::getPMPrefixToPMIdMap(const scope_config::Config& config) const
{
std::map< std::string, int> prefixToId;
for (const auto & pm : config.fPMs) {
prefixToId[pm.fPrefix] = pm.fId;
}
return prefixToId;
}
/// Returns a map of list of scope input files. The key is the corresponding
/// index of the photomultiplier in the param bank.
std::map<std::string, int> JPetScopeLoader::createInputScopeFileNames(
const std::string& inputPathToScopeFiles,
std::map<std::string, int> pmPref2Id
) const
{
for (auto el : pmPref2Id) {
}
std::map<std::string, int> scopeFiles;
path current_dir(inputPathToScopeFiles);
if (exists(current_dir)) {
for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) {
std::string filename = iter->path().leaf().string();
if (isCorrectScopeFileName(filename)) {
auto prefix = getFilePrefix(filename);
if ( pmPref2Id.find(prefix) != pmPref2Id.end()) {
int id = pmPref2Id.find(prefix)->second;
scopeFiles[iter->path().parent_path().string() + "/" + filename] = id;
} else {
WARNING("The filename does not contain the accepted prefix:" + filename);
}
}
}
} else {
string msg = "Directory: \"";
msg += current_dir.string();
msg += "\" does not exist.";
ERROR(msg.c_str());
}
return scopeFiles;
}
std::string JPetScopeLoader::getFilePrefix(const std::string& filename) const
{
auto pos = filename.find("_");
if (pos != string::npos) {
return filename.substr(0, pos);
}
return "";
}
/// not very effective, but at least we can test it
bool JPetScopeLoader::isCorrectScopeFileName(const std::string& filename) const
{
boost::regex pattern("^[A-Za-z0-9]+_\\d*.txt");
return regex_match(filename, pattern);
}
void JPetScopeLoader::init(const JPetOptions::Options& opts)
{
INFO( "Initialize Scope Loader Module." );
JPetTaskLoader::init(opts);
}
void JPetScopeLoader::exec()
{
assert(fTask);
fTask->setParamManager(fParamManager);
JPetTaskInterface::Options emptyOpts;
fTask->init(emptyOpts);
fTask->exec();
fTask->terminate();
}
void JPetScopeLoader::terminate()
{
assert(fWriter);
assert(fHeader);
assert(fStatistics);
fWriter->writeHeader(fHeader);
fWriter->writeCollection(fStatistics->getStatsTable(), "Stats");
//store the parametric objects in the ouptut ROOT file
getParamManager().saveParametersToFile(fWriter);
getParamManager().clearParameters();
fWriter->closeFile();
}
<|endoftext|> |
<commit_before>#include "./JPetScopeReader.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <utility>
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <TSystem.h>
#include <TApplication.h>
#include "../JPetBarrelSlot/JPetBarrelSlot.h"
#include "../JPetManager/JPetManager.h"
#include "../JPetParamBank/JPetParamBank.h"
#include "../JPetPhysSignal/JPetPhysSignal.h"
#include "../JPetPM/JPetPM.h"
#include "../JPetRecoSignal/JPetRecoSignal.h"
#include "../JPetScin/JPetScin.h"
#include "../JPetScopeReader/JPetScopeReader.h"
#include "../JPetTreeHeader/JPetTreeHeader.h"
#include "../JPetWriter/JPetWriter.h"
#include "../CommonTools/CommonTools.h"
#include <iostream>
using namespace std;
using namespace boost::filesystem;
using boost::property_tree::ptree;
JPetScopeReader::JPetScopeReader(JPetScopeTask * task): JPetTaskLoader(), fEventNb(0), fWriter(nullptr) {
gSystem->Load("libTree");
addSubTask(task);
}
JPetScopeReader::~JPetScopeReader() {
if (fWriter != nullptr) {
delete fWriter;
fWriter = nullptr;
}
}
JPetParamBank const& JPetScopeReader::createParamBank(ptree const& conf_data) {
// Read Data from config tree
int bslotid1, bslotid2;
bool bslotactive1, bslotactive2;
string bslotname1, bslotname2;
float bslottheta1, bslottheta2;
int bslotframe1, bslotframe2;
bslotid1 = conf_data.get("bslot1.id", -1);
bslotid2 = conf_data.get("bslot2.id", -1);
bslotactive1 = conf_data.get("bslot1.active", false);
bslotactive2 = conf_data.get("bslot2.active", false);
bslotname1 = conf_data.get("bslot1.name", string(""));
bslotname2 = conf_data.get("bslot2.name", string(""));
bslottheta1 = conf_data.get("bslot1.theta", -1.f);
bslottheta2 = conf_data.get("bslot2.theta", -1.f);
bslotframe1 = conf_data.get("bslot1.frame", -1);
bslotframe2 = conf_data.get("bslot2.frame", -1);
int pmid1, pmid2, pmid3, pmid4;
pmid1 = conf_data.get("pm1.id", 0);
pmid2 = conf_data.get("pm2.id", 0);
pmid3 = conf_data.get("pm3.id", 0);
pmid4 = conf_data.get("pm4.id", 0);
int scinid1, scinid2;
scinid1 = conf_data.get("scin1.id", 0);
scinid2 = conf_data.get("scin2.id", 0);
// Create Parametric objects
JPetBarrelSlot bslot1 (bslotid1, bslotactive1, bslotname1, bslottheta1, bslotframe1);
JPetBarrelSlot bslot2 (bslotid2, bslotactive2, bslotname2, bslottheta2, bslotframe2);
JPetPM pm1(pmid1);
JPetPM pm2(pmid2);
JPetPM pm3(pmid3);
JPetPM pm4(pmid4);
JPetScin scin1(scinid1);
JPetScin scin2(scinid2);
JPetParamBank* param_bank = new JPetParamBank();
param_bank->addBarrelSlot(bslot1);
param_bank->addBarrelSlot(bslot2);
param_bank->addPM(pm1);
param_bank->addPM(pm2);
param_bank->addPM(pm3);
param_bank->addPM(pm4);
param_bank->addScintillator(scin1);
param_bank->addScintillator(scin2);
(param_bank->getPM(0)).setScin(param_bank->getScintillator(0));
(param_bank->getPM(1)).setScin(param_bank->getScintillator(0));
(param_bank->getPM(2)).setScin(param_bank->getScintillator(1));
(param_bank->getPM(3)).setScin(param_bank->getScintillator(1));
(param_bank->getPM(0)).setBarrelSlot(param_bank->getBarrelSlot(0));
(param_bank->getPM(1)).setBarrelSlot(param_bank->getBarrelSlot(0));
(param_bank->getPM(2)).setBarrelSlot(param_bank->getBarrelSlot(1));
(param_bank->getPM(3)).setBarrelSlot(param_bank->getBarrelSlot(1));
(param_bank->getScintillator(0)).setBarrelSlot(param_bank->getBarrelSlot(0));
(param_bank->getScintillator(1)).setBarrelSlot(param_bank->getBarrelSlot(1));
return *param_bank;
}
void JPetScopeReader::createInputObjects(const char* inputFilename) {
// Create property tree
ptree prop_tree;
// Check file type
string ext = path((const char*)fInFilename).extension().string();
// Read configuration data to property tree
if (ext.compare(".ini") == 0) {
read_ini(fInFilename.Data(), prop_tree);
} else if (ext.compare(".info") == 0) {
read_info(fInFilename.Data(), prop_tree);
} else if (ext.compare(".json") == 0) {
read_json(fInFilename.Data(), prop_tree);
} else if (ext.compare(".xml") == 0) {
read_xml(fInFilename.Data(), prop_tree);
} else {
ERROR("Cannot open config file. Exiting");
exit(-1);
}
// Fill fConfigs
for (ptree::const_iterator it = prop_tree.begin(); it != prop_tree.end(); ++it) {
string files_location;
const ptree& conf_data = it->second;
files_location = conf_data.get<string>("location");
JPetParamBank const& param_bank = createParamBank (conf_data);
// Fill Configs
string collimator_function;
int a, b, c, n;
BOOST_FOREACH(const ptree::value_type& v, conf_data.get_child("collimator")) {
if (ext.compare(".json") == 0) collimator_function = v.second.get<string>("positions");
else collimator_function = v.second.data();
n = sscanf(collimator_function.c_str(), "%d %d %d", &a, &b, &c);
if (n > 0) {
if (n == 1) {b = a; c = 1;}
if (n == 2) {c = 1;}
for (int j = a; j <=b; j+= c) {
fConfigs.push_back(ScopeConfig());
vector <ScopeConfig> :: iterator current_config = fConfigs.end() - 1;
// Add config name
(*current_config).pName = it->first;
// Add collimator position
(*current_config).pCollPosition = j;
// Add param bank
(*current_config).pParamBank = ¶m_bank;
// Add PMs
(*current_config).pPM1 = &(param_bank.getPM(0));
(*current_config).pPM2 = &(param_bank.getPM(1));
(*current_config).pPM3 = &(param_bank.getPM(2));
(*current_config).pPM4 = &(param_bank.getPM(3));
// Add Scintillators
(*current_config).pScin1 = &(param_bank.getScintillator(0));
(*current_config).pScin2 = &(param_bank.getScintillator(1));
// Add filename prefixes
(*current_config).pPrefix1 = conf_data.get<string>("pm1.prefix");
(*current_config).pPrefix2 = conf_data.get<string>("pm2.prefix");
(*current_config).pPrefix3 = conf_data.get<string>("pm3.prefix");
(*current_config).pPrefix4 = conf_data.get<string>("pm4.prefix");
// Add oscilloscope files
string starting_loc = path((const char*)fInFilename).parent_path().string();
starting_loc += "/";
starting_loc += files_location;
starting_loc += "/";
starting_loc += to_string (j);
path current_dir(starting_loc);
boost::regex pattern(Form("%s_\\d*.txt", (*current_config).pPrefix1.c_str()));
if (exists(current_dir))
for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) {
string name = iter->path().leaf().string();
string dir;
if (regex_match(name, pattern)) {
name[1] = ((*current_config).pPrefix1)[1];
dir = iter->path().parent_path().string();
dir += "/";
dir += name;
(*current_config).pFiles.insert(dir);
}
}
else {
string msg = "Directory: \"";
msg += current_dir.string();
msg += "\" does not exist.";
ERROR(msg.c_str());
}
// Set Iterator to begining
(*current_config).pIter = (*current_config).pFiles.begin();
}
}
}
}
fWriter = nullptr;
fEventNb = 0;
for (vector <ScopeConfig> :: iterator it = fConfigs.begin(); it != fConfigs.end(); ++it) {
fEventNb += (*it).pFiles.size();
}
}
void JPetScopeReader::createOutputObjects(const char* outputFilename) {
fIter = fConfigs.begin();
}
void JPetScopeReader::createNewWriter(const char* outputFilename) {
if (fConfigs.empty()) {
ERROR("No files for processing.");
}
else {
terminate();
INFO (Form("Creating root file for configuration %s and position %d", ((*fIter).pName).c_str(), (*fIter).pCollPosition));
string out_fn(fOutFilename.Data());
int last_dot = out_fn.find_last_of(".");
string out_fn2 = out_fn.substr(0,last_dot );
out_fn2 += "_";
out_fn2 += (*fIter).pName;
out_fn2 += "_";
out_fn2 += to_string((*fIter).pCollPosition);
out_fn2 += ".reco.sig";
out_fn2 += out_fn.substr(last_dot);
fWriter = new JPetWriter(out_fn2.c_str());
auto optionContainer = JPetManager::getManager().getOptions();
assert(optionContainer.size() ==1);
auto options = optionContainer.front();
fHeader = new JPetTreeHeader(options.getRunNumber());
fHeader->setBaseFileName(options.getInputFile());
fHeader->addStageInfo(fTask->GetName(), fTask->GetTitle(), 0, CommonTools::getTimeString());
fHeader->setSourcePosition((*fIter).pCollPosition);
fWriter->writeHeader(fHeader);
}
}
void JPetScopeReader::init() {
INFO( "Starting Scope Reader Module." );
createInputObjects();
createOutputObjects();
}
void JPetScopeReader::exec() {
assert(fTask);
JPetTaskInterface::Options emptyOpts;
fTask->init(emptyOpts);
for(fIter = fConfigs.begin();fIter != fConfigs.end();fIter++){
createNewWriter();
fTask->setWriter(fWriter);
for((*fIter).pIter = (*fIter).pFiles.begin();(*fIter).pIter != (*fIter).pFiles.end(); (*fIter).pIter++){
dynamic_cast<JPetScopeTask*>(fTask)->setScopeConfig(&(*fIter));
fTask->exec();
}
fWriter->writeObject((*fIter).pParamBank, "ParamBank");
}
}
void JPetScopeReader::terminate() {
if(fWriter)
if(fWriter->isOpen()) {
fWriter->closeFile();
delete fWriter;
fWriter = nullptr;
}
}
void JPetScopeReader::setFileName(const char* name)
{
fInFilename = TString(name);
fOutFilename = TString(name);
fOutFilename.ReplaceAll(".ini", "");
fOutFilename.ReplaceAll(".info", "");
fOutFilename.ReplaceAll(".json", "");
fOutFilename.ReplaceAll(".xml", "");
fOutFilename.Append(".root");
}
<commit_msg>693 Set sides for JPetPMs in JPetScopeReader.<commit_after>#include "./JPetScopeReader.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <utility>
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <TSystem.h>
#include <TApplication.h>
#include "../JPetBarrelSlot/JPetBarrelSlot.h"
#include "../JPetManager/JPetManager.h"
#include "../JPetParamBank/JPetParamBank.h"
#include "../JPetPhysSignal/JPetPhysSignal.h"
#include "../JPetPM/JPetPM.h"
#include "../JPetRecoSignal/JPetRecoSignal.h"
#include "../JPetScin/JPetScin.h"
#include "../JPetScopeReader/JPetScopeReader.h"
#include "../JPetTreeHeader/JPetTreeHeader.h"
#include "../JPetWriter/JPetWriter.h"
#include "../CommonTools/CommonTools.h"
#include <iostream>
using namespace std;
using namespace boost::filesystem;
using boost::property_tree::ptree;
JPetScopeReader::JPetScopeReader(JPetScopeTask * task): JPetTaskLoader(), fEventNb(0), fWriter(nullptr) {
gSystem->Load("libTree");
addSubTask(task);
}
JPetScopeReader::~JPetScopeReader() {
if (fWriter != nullptr) {
delete fWriter;
fWriter = nullptr;
}
}
JPetParamBank const& JPetScopeReader::createParamBank(ptree const& conf_data) {
// Read Data from config tree
int bslotid1, bslotid2;
bool bslotactive1, bslotactive2;
string bslotname1, bslotname2;
float bslottheta1, bslottheta2;
int bslotframe1, bslotframe2;
bslotid1 = conf_data.get("bslot1.id", -1);
bslotid2 = conf_data.get("bslot2.id", -1);
bslotactive1 = conf_data.get("bslot1.active", false);
bslotactive2 = conf_data.get("bslot2.active", false);
bslotname1 = conf_data.get("bslot1.name", string(""));
bslotname2 = conf_data.get("bslot2.name", string(""));
bslottheta1 = conf_data.get("bslot1.theta", -1.f);
bslottheta2 = conf_data.get("bslot2.theta", -1.f);
bslotframe1 = conf_data.get("bslot1.frame", -1);
bslotframe2 = conf_data.get("bslot2.frame", -1);
int pmid1, pmid2, pmid3, pmid4;
pmid1 = conf_data.get("pm1.id", 0);
pmid2 = conf_data.get("pm2.id", 0);
pmid3 = conf_data.get("pm3.id", 0);
pmid4 = conf_data.get("pm4.id", 0);
int scinid1, scinid2;
scinid1 = conf_data.get("scin1.id", 0);
scinid2 = conf_data.get("scin2.id", 0);
// Create Parametric objects
JPetBarrelSlot bslot1 (bslotid1, bslotactive1, bslotname1, bslottheta1, bslotframe1);
JPetBarrelSlot bslot2 (bslotid2, bslotactive2, bslotname2, bslottheta2, bslotframe2);
JPetPM pm1(pmid1);
JPetPM pm2(pmid2);
JPetPM pm3(pmid3);
JPetPM pm4(pmid4);
/**
* A B
* PM1 PM2
* PM3 PM4
*/
pm1.setSide(JPetPM::SideA);
pm2.setSide(JPetPM::SideB);
pm3.setSide(JPetPM::SideA);
pm4.setSide(JPetPM::SideB);
JPetScin scin1(scinid1);
JPetScin scin2(scinid2);
JPetParamBank* param_bank = new JPetParamBank();
param_bank->addBarrelSlot(bslot1);
param_bank->addBarrelSlot(bslot2);
param_bank->addPM(pm1);
param_bank->addPM(pm2);
param_bank->addPM(pm3);
param_bank->addPM(pm4);
param_bank->addScintillator(scin1);
param_bank->addScintillator(scin2);
(param_bank->getPM(0)).setScin(param_bank->getScintillator(0));
(param_bank->getPM(1)).setScin(param_bank->getScintillator(0));
(param_bank->getPM(2)).setScin(param_bank->getScintillator(1));
(param_bank->getPM(3)).setScin(param_bank->getScintillator(1));
(param_bank->getPM(0)).setBarrelSlot(param_bank->getBarrelSlot(0));
(param_bank->getPM(1)).setBarrelSlot(param_bank->getBarrelSlot(0));
(param_bank->getPM(2)).setBarrelSlot(param_bank->getBarrelSlot(1));
(param_bank->getPM(3)).setBarrelSlot(param_bank->getBarrelSlot(1));
(param_bank->getScintillator(0)).setBarrelSlot(param_bank->getBarrelSlot(0));
(param_bank->getScintillator(1)).setBarrelSlot(param_bank->getBarrelSlot(1));
return *param_bank;
}
void JPetScopeReader::createInputObjects(const char* inputFilename) {
// Create property tree
ptree prop_tree;
// Check file type
string ext = path((const char*)fInFilename).extension().string();
// Read configuration data to property tree
if (ext.compare(".ini") == 0) {
read_ini(fInFilename.Data(), prop_tree);
} else if (ext.compare(".info") == 0) {
read_info(fInFilename.Data(), prop_tree);
} else if (ext.compare(".json") == 0) {
read_json(fInFilename.Data(), prop_tree);
} else if (ext.compare(".xml") == 0) {
read_xml(fInFilename.Data(), prop_tree);
} else {
ERROR("Cannot open config file. Exiting");
exit(-1);
}
// Fill fConfigs
for (ptree::const_iterator it = prop_tree.begin(); it != prop_tree.end(); ++it) {
string files_location;
const ptree& conf_data = it->second;
files_location = conf_data.get<string>("location");
JPetParamBank const& param_bank = createParamBank (conf_data);
// Fill Configs
string collimator_function;
int a, b, c, n;
BOOST_FOREACH(const ptree::value_type& v, conf_data.get_child("collimator")) {
if (ext.compare(".json") == 0) collimator_function = v.second.get<string>("positions");
else collimator_function = v.second.data();
n = sscanf(collimator_function.c_str(), "%d %d %d", &a, &b, &c);
if (n > 0) {
if (n == 1) {b = a; c = 1;}
if (n == 2) {c = 1;}
for (int j = a; j <=b; j+= c) {
fConfigs.push_back(ScopeConfig());
vector <ScopeConfig> :: iterator current_config = fConfigs.end() - 1;
// Add config name
(*current_config).pName = it->first;
// Add collimator position
(*current_config).pCollPosition = j;
// Add param bank
(*current_config).pParamBank = ¶m_bank;
// Add PMs
(*current_config).pPM1 = &(param_bank.getPM(0));
(*current_config).pPM2 = &(param_bank.getPM(1));
(*current_config).pPM3 = &(param_bank.getPM(2));
(*current_config).pPM4 = &(param_bank.getPM(3));
// Add Scintillators
(*current_config).pScin1 = &(param_bank.getScintillator(0));
(*current_config).pScin2 = &(param_bank.getScintillator(1));
// Add filename prefixes
(*current_config).pPrefix1 = conf_data.get<string>("pm1.prefix");
(*current_config).pPrefix2 = conf_data.get<string>("pm2.prefix");
(*current_config).pPrefix3 = conf_data.get<string>("pm3.prefix");
(*current_config).pPrefix4 = conf_data.get<string>("pm4.prefix");
// Add oscilloscope files
string starting_loc = path((const char*)fInFilename).parent_path().string();
starting_loc += "/";
starting_loc += files_location;
starting_loc += "/";
starting_loc += to_string (j);
path current_dir(starting_loc);
boost::regex pattern(Form("%s_\\d*.txt", (*current_config).pPrefix1.c_str()));
if (exists(current_dir))
for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) {
string name = iter->path().leaf().string();
string dir;
if (regex_match(name, pattern)) {
name[1] = ((*current_config).pPrefix1)[1];
dir = iter->path().parent_path().string();
dir += "/";
dir += name;
(*current_config).pFiles.insert(dir);
}
}
else {
string msg = "Directory: \"";
msg += current_dir.string();
msg += "\" does not exist.";
ERROR(msg.c_str());
}
// Set Iterator to begining
(*current_config).pIter = (*current_config).pFiles.begin();
}
}
}
}
fWriter = nullptr;
fEventNb = 0;
for (vector <ScopeConfig> :: iterator it = fConfigs.begin(); it != fConfigs.end(); ++it) {
fEventNb += (*it).pFiles.size();
}
}
void JPetScopeReader::createOutputObjects(const char* outputFilename) {
fIter = fConfigs.begin();
}
void JPetScopeReader::createNewWriter(const char* outputFilename) {
if (fConfigs.empty()) {
ERROR("No files for processing.");
}
else {
terminate();
INFO (Form("Creating root file for configuration %s and position %d", ((*fIter).pName).c_str(), (*fIter).pCollPosition));
string out_fn(fOutFilename.Data());
int last_dot = out_fn.find_last_of(".");
string out_fn2 = out_fn.substr(0,last_dot );
out_fn2 += "_";
out_fn2 += (*fIter).pName;
out_fn2 += "_";
out_fn2 += to_string((*fIter).pCollPosition);
out_fn2 += ".reco.sig";
out_fn2 += out_fn.substr(last_dot);
fWriter = new JPetWriter(out_fn2.c_str());
auto optionContainer = JPetManager::getManager().getOptions();
assert(optionContainer.size() ==1);
auto options = optionContainer.front();
fHeader = new JPetTreeHeader(options.getRunNumber());
fHeader->setBaseFileName(options.getInputFile());
fHeader->addStageInfo(fTask->GetName(), fTask->GetTitle(), 0, CommonTools::getTimeString());
fHeader->setSourcePosition((*fIter).pCollPosition);
fWriter->writeHeader(fHeader);
}
}
void JPetScopeReader::init() {
INFO( "Starting Scope Reader Module." );
createInputObjects();
createOutputObjects();
}
void JPetScopeReader::exec() {
assert(fTask);
JPetTaskInterface::Options emptyOpts;
fTask->init(emptyOpts);
for(fIter = fConfigs.begin();fIter != fConfigs.end();fIter++){
createNewWriter();
fTask->setWriter(fWriter);
for((*fIter).pIter = (*fIter).pFiles.begin();(*fIter).pIter != (*fIter).pFiles.end(); (*fIter).pIter++){
dynamic_cast<JPetScopeTask*>(fTask)->setScopeConfig(&(*fIter));
fTask->exec();
}
fWriter->writeObject((*fIter).pParamBank, "ParamBank");
}
}
void JPetScopeReader::terminate() {
if(fWriter)
if(fWriter->isOpen()) {
fWriter->closeFile();
delete fWriter;
fWriter = nullptr;
}
}
void JPetScopeReader::setFileName(const char* name)
{
fInFilename = TString(name);
fOutFilename = TString(name);
fOutFilename.ReplaceAll(".ini", "");
fOutFilename.ReplaceAll(".info", "");
fOutFilename.ReplaceAll(".json", "");
fOutFilename.ReplaceAll(".xml", "");
fOutFilename.Append(".root");
}
<|endoftext|> |
<commit_before>#include "config/Base.hh"
#include "containers/PointCloud.hh"
#include "distances/Euclidean.hh"
#include "filtrations/Data.hh"
#include "geometry/BruteForce.hh"
#include "geometry/RipsSkeleton.hh"
#include "tests/Base.hh"
#include "persistentHomology/Calculation.hh"
#include "persistentHomology/ConnectedComponents.hh"
#include "topology/Simplex.hh"
#include "topology/SimplicialComplex.hh"
#include <vector>
using namespace aleph::geometry;
using namespace aleph::topology;
using namespace aleph;
template <class T> void test()
{
ALEPH_TEST_BEGIN( "Point cloud loading" );
using PointCloud = PointCloud<T>;
using Distance = aleph::distances::Euclidean<T>;
PointCloud pointCloud = load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_colon_separated.txt" ) );
ALEPH_ASSERT_THROW( pointCloud.size() == 150 );
ALEPH_ASSERT_THROW( pointCloud.dimension() == 4);
ALEPH_TEST_END();
ALEPH_TEST_BEGIN( "Rips skeleton calculation" );
using Wrapper = BruteForce<PointCloud, Distance>;
using RipsSkeleton = RipsSkeleton<Wrapper>;
Wrapper wrapper( pointCloud );
RipsSkeleton ripsSkeleton;
auto K = ripsSkeleton( wrapper, 1.0 );
using Simplex = typename decltype(K)::ValueType;
ALEPH_ASSERT_THROW( K.empty() == false );
ALEPH_ASSERT_THROW( std::count_if( K.begin(), K.end(), [] ( const Simplex& s ) { return s.dimension() == 1; } ) != 0 );
ALEPH_TEST_END();
ALEPH_TEST_BEGIN( "Zero-dimensional persistent homology calculation" );
K.sort( filtrations::Data<Simplex>() );
auto diagrams = calculatePersistenceDiagrams( K );
auto diagram2 = calculateZeroDimensionalPersistenceDiagram( K );
ALEPH_ASSERT_THROW( diagrams.empty() == false );
auto diagram1 = diagrams.front();
ALEPH_ASSERT_THROW( diagram1.empty() == false );
ALEPH_ASSERT_THROW( diagram1.size() == pointCloud.size() );
ALEPH_ASSERT_THROW( diagram2.empty() == false );
ALEPH_ASSERT_THROW( diagram1.size() == diagram2.size() );
ALEPH_TEST_END();
}
int main()
{
test<float> ();
test<double>();
}
<commit_msg>Added persistence diagram comparison for connected components test<commit_after>#include "config/Base.hh"
#include "containers/PointCloud.hh"
#include "distances/Euclidean.hh"
#include "filtrations/Data.hh"
#include "geometry/BruteForce.hh"
#include "geometry/RipsSkeleton.hh"
#include "tests/Base.hh"
#include "persistentHomology/Calculation.hh"
#include "persistentHomology/ConnectedComponents.hh"
#include "topology/Simplex.hh"
#include "topology/SimplicialComplex.hh"
#include <vector>
using namespace aleph::geometry;
using namespace aleph::topology;
using namespace aleph;
template <class T> void test()
{
ALEPH_TEST_BEGIN( "Point cloud loading" );
using PointCloud = PointCloud<T>;
using Distance = aleph::distances::Euclidean<T>;
PointCloud pointCloud = load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_colon_separated.txt" ) );
ALEPH_ASSERT_THROW( pointCloud.size() == 150 );
ALEPH_ASSERT_THROW( pointCloud.dimension() == 4);
ALEPH_TEST_END();
ALEPH_TEST_BEGIN( "Rips skeleton calculation" );
using Wrapper = BruteForce<PointCloud, Distance>;
using RipsSkeleton = RipsSkeleton<Wrapper>;
Wrapper wrapper( pointCloud );
RipsSkeleton ripsSkeleton;
auto K = ripsSkeleton( wrapper, 1.0 );
using Simplex = typename decltype(K)::ValueType;
ALEPH_ASSERT_THROW( K.empty() == false );
ALEPH_ASSERT_THROW( std::count_if( K.begin(), K.end(), [] ( const Simplex& s ) { return s.dimension() == 1; } ) != 0 );
ALEPH_TEST_END();
ALEPH_TEST_BEGIN( "Zero-dimensional persistent homology calculation" );
K.sort( filtrations::Data<Simplex>() );
auto diagrams = calculatePersistenceDiagrams( K );
auto diagram2 = calculateZeroDimensionalPersistenceDiagram( K );
ALEPH_ASSERT_THROW( diagrams.empty() == false );
auto diagram1 = diagrams.front();
ALEPH_ASSERT_THROW( diagram1.empty() == false );
ALEPH_ASSERT_THROW( diagram1.size() == pointCloud.size() );
ALEPH_ASSERT_THROW( diagram2.empty() == false );
ALEPH_ASSERT_THROW( diagram1.size() == diagram2.size() );
using Point = typename decltype(diagram1)::Point;
auto sortPoints = [] ( const Point& p, const Point& q )
{
return p.x() < q.x() || ( p.x() == q.x() && p.y() < q.y() );
};
std::sort( diagram1.begin(), diagram1.end(), sortPoints );
std::sort( diagram2.begin(), diagram2.end(), sortPoints );
ALEPH_ASSERT_THROW( diagram1 == diagram2 );
ALEPH_TEST_END();
}
int main()
{
test<float> ();
test<double>();
}
<|endoftext|> |
<commit_before>#include "exec.h"
#include <stdio.h>
#include <stdlib.h>
#include <memory>
#include <unordered_map>
#include "dep.h"
#include "eval.h"
#include "log.h"
#include "string_piece.h"
#include "value.h"
namespace {
struct Runner {
Runner()
: echo(true), ignore_error(false) {
}
StringPiece output;
shared_ptr<string> cmd;
bool echo;
bool ignore_error;
//StringPiece shell;
};
} // namespace
class Executor {
public:
explicit Executor(const Vars* vars)
: vars_(vars) {
}
void ExecNode(DepNode* n, DepNode* needed_by) {
if (done_[n->output])
return;
LOG("ExecNode: %s for %s",
n->output.as_string().c_str(),
needed_by ? needed_by->output.as_string().c_str() : "(null)");
for (DepNode* d : n->deps) {
#if 0
if (d.is_order_only && exists(d->output)) {
}
#endif
ExecNode(d, n);
}
vector<Runner*> runners;
CreateRunners(n, &runners);
for (Runner* runner : runners) {
if (runner->echo) {
printf("%s\n", runner->cmd->c_str());
fflush(stdout);
}
system(runner->cmd->c_str());
delete runner;
}
}
void CreateRunners(DepNode* n, vector<Runner*>* runners) {
unique_ptr<Evaluator> ev(new Evaluator(vars_));
for (Value* v : n->cmds) {
Runner* runner = new Runner;
runner->output = n->output;
runner->cmd = v->Eval(ev.get());
runners->push_back(runner);
}
}
private:
const Vars* vars_;
unordered_map<StringPiece, bool> done_;
};
void Exec(const vector<DepNode*>& roots, const Vars* vars) {
unique_ptr<Executor> executor(new Executor(vars));
for (DepNode* root : roots) {
executor->ExecNode(root, NULL);
}
}
<commit_msg>[C++] Split lines in CreateRunners<commit_after>#include "exec.h"
#include <stdio.h>
#include <stdlib.h>
#include <memory>
#include <unordered_map>
#include "dep.h"
#include "eval.h"
#include "log.h"
#include "string_piece.h"
#include "value.h"
namespace {
struct Runner {
Runner()
: echo(true), ignore_error(false) {
}
StringPiece output;
shared_ptr<string> cmd;
bool echo;
bool ignore_error;
//StringPiece shell;
};
} // namespace
class Executor {
public:
explicit Executor(const Vars* vars)
: vars_(vars) {
}
void ExecNode(DepNode* n, DepNode* needed_by) {
if (done_[n->output])
return;
LOG("ExecNode: %s for %s",
n->output.as_string().c_str(),
needed_by ? needed_by->output.as_string().c_str() : "(null)");
for (DepNode* d : n->deps) {
#if 0
if (d.is_order_only && exists(d->output)) {
}
#endif
ExecNode(d, n);
}
vector<Runner*> runners;
CreateRunners(n, &runners);
for (Runner* runner : runners) {
if (runner->echo) {
printf("%s\n", runner->cmd->c_str());
fflush(stdout);
}
system(runner->cmd->c_str());
delete runner;
}
}
void CreateRunners(DepNode* n, vector<Runner*>* runners) {
unique_ptr<Evaluator> ev(new Evaluator(vars_));
for (Value* v : n->cmds) {
shared_ptr<string> cmd = v->Eval(ev.get());
while (true) {
size_t index = cmd->find('\n');
if (index == string::npos)
break;
Runner* runner = new Runner;
runner->output = n->output;
runner->cmd = make_shared<string>(cmd->substr(0, index));
runners->push_back(runner);
cmd = make_shared<string>(cmd->substr(index + 1));
}
Runner* runner = new Runner;
runner->output = n->output;
runner->cmd = cmd;
runners->push_back(runner);
continue;
}
}
private:
const Vars* vars_;
unordered_map<StringPiece, bool> done_;
};
void Exec(const vector<DepNode*>& roots, const Vars* vars) {
unique_ptr<Executor> executor(new Executor(vars));
for (DepNode* root : roots) {
executor->ExecNode(root, NULL);
}
}
<|endoftext|> |
<commit_before>#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QString>
#include <QWidget>
#include <QTimer>
#include <QRandomGenerator>
#include "api.hpp"
#include "common/params.h"
#include "common/util.h"
#if defined(QCOM) || defined(QCOM2)
const std::string private_key_path = "/persist/comma/id_rsa";
#else
const std::string private_key_path = util::getenv_default("HOME", "/.comma/persist/comma/id_rsa", "/persist/comma/id_rsa");
#endif
QByteArray CommaApi::rsa_sign(QByteArray data) {
auto file = QFile(private_key_path.c_str());
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "No RSA private key found, please run manager.py or registration.py";
return QByteArray();
}
auto key = file.readAll();
file.close();
file.deleteLater();
BIO* mem = BIO_new_mem_buf(key.data(), key.size());
assert(mem);
RSA* rsa_private = PEM_read_bio_RSAPrivateKey(mem, NULL, NULL, NULL);
assert(rsa_private);
auto sig = QByteArray();
sig.resize(RSA_size(rsa_private));
unsigned int sig_len;
int ret = RSA_sign(NID_sha256, (unsigned char*)data.data(), data.size(), (unsigned char*)sig.data(), &sig_len, rsa_private);
assert(ret == 1);
assert(sig_len == sig.size());
BIO_free(mem);
RSA_free(rsa_private);
return sig;
}
QString CommaApi::create_jwt(QVector<QPair<QString, QJsonValue>> payloads, int expiry) {
QString dongle_id = QString::fromStdString(Params().get("DongleId"));
QJsonObject header;
header.insert("alg", "RS256");
QJsonObject payload;
payload.insert("identity", dongle_id);
auto t = QDateTime::currentSecsSinceEpoch();
payload.insert("nbf", t);
payload.insert("iat", t);
payload.insert("exp", t + expiry);
for (auto load : payloads) {
payload.insert(load.first, load.second);
}
auto b64_opts = QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals;
QString jwt = QJsonDocument(header).toJson(QJsonDocument::Compact).toBase64(b64_opts) + '.' +
QJsonDocument(payload).toJson(QJsonDocument::Compact).toBase64(b64_opts);
auto hash = QCryptographicHash::hash(jwt.toUtf8(), QCryptographicHash::Sha256);
auto sig = rsa_sign(hash);
jwt += '.' + sig.toBase64(b64_opts);
return jwt;
}
HttpRequest::HttpRequest(QObject *parent, QString requestURL, const QString &cache_key) : cache_key(cache_key), QObject(parent) {
networkAccessManager = new QNetworkAccessManager(this);
reply = NULL;
networkTimer = new QTimer(this);
networkTimer->setSingleShot(true);
networkTimer->setInterval(20000);
connect(networkTimer, SIGNAL(timeout()), this, SLOT(requestTimeout()));
sendRequest(requestURL);
if (!cache_key.isEmpty()) {
if (std::string cached_resp = Params().get(cache_key.toStdString()); !cached_resp.empty()) {
QTimer::singleShot(0, [=]() { emit receivedResponse(QString::fromStdString(cached_resp)); });
}
}
}
void HttpRequest::sendRequest(QString requestURL){
QString token = CommaApi::create_jwt();
QNetworkRequest request;
request.setUrl(QUrl(requestURL));
request.setRawHeader(QByteArray("Authorization"), ("JWT " + token).toUtf8());
#ifdef QCOM
QSslConfiguration ssl = QSslConfiguration::defaultConfiguration();
ssl.setCaCertificates(QSslCertificate::fromPath("/usr/etc/tls/cert.pem",
QSsl::Pem, QRegExp::Wildcard));
request.setSslConfiguration(ssl);
#endif
reply = networkAccessManager->get(request);
networkTimer->start();
connect(reply, SIGNAL(finished()), this, SLOT(requestFinished()));
}
void HttpRequest::requestTimeout(){
reply->abort();
}
// This function should always emit something
void HttpRequest::requestFinished(){
if (reply->error() != QNetworkReply::OperationCanceledError) {
networkTimer->stop();
QString response = reply->readAll();
if (reply->error() == QNetworkReply::NoError) {
// save to cache
if (!cache_key.isEmpty()) {
Params().put(cache_key.toStdString(), response.toStdString());
}
emit receivedResponse(response);
} else {
if (!cache_key.isEmpty()) {
Params().remove(cache_key.toStdString());
}
emit failedResponse(reply->errorString());
}
} else {
emit timeoutResponse("timeout");
}
reply->deleteLater();
reply = NULL;
}
<commit_msg>print error when HttpRequest fails<commit_after>#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QString>
#include <QWidget>
#include <QTimer>
#include <QRandomGenerator>
#include "api.hpp"
#include "common/params.h"
#include "common/util.h"
#if defined(QCOM) || defined(QCOM2)
const std::string private_key_path = "/persist/comma/id_rsa";
#else
const std::string private_key_path = util::getenv_default("HOME", "/.comma/persist/comma/id_rsa", "/persist/comma/id_rsa");
#endif
QByteArray CommaApi::rsa_sign(QByteArray data) {
auto file = QFile(private_key_path.c_str());
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "No RSA private key found, please run manager.py or registration.py";
return QByteArray();
}
auto key = file.readAll();
file.close();
file.deleteLater();
BIO* mem = BIO_new_mem_buf(key.data(), key.size());
assert(mem);
RSA* rsa_private = PEM_read_bio_RSAPrivateKey(mem, NULL, NULL, NULL);
assert(rsa_private);
auto sig = QByteArray();
sig.resize(RSA_size(rsa_private));
unsigned int sig_len;
int ret = RSA_sign(NID_sha256, (unsigned char*)data.data(), data.size(), (unsigned char*)sig.data(), &sig_len, rsa_private);
assert(ret == 1);
assert(sig_len == sig.size());
BIO_free(mem);
RSA_free(rsa_private);
return sig;
}
QString CommaApi::create_jwt(QVector<QPair<QString, QJsonValue>> payloads, int expiry) {
QString dongle_id = QString::fromStdString(Params().get("DongleId"));
QJsonObject header;
header.insert("alg", "RS256");
QJsonObject payload;
payload.insert("identity", dongle_id);
auto t = QDateTime::currentSecsSinceEpoch();
payload.insert("nbf", t);
payload.insert("iat", t);
payload.insert("exp", t + expiry);
for (auto load : payloads) {
payload.insert(load.first, load.second);
}
auto b64_opts = QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals;
QString jwt = QJsonDocument(header).toJson(QJsonDocument::Compact).toBase64(b64_opts) + '.' +
QJsonDocument(payload).toJson(QJsonDocument::Compact).toBase64(b64_opts);
auto hash = QCryptographicHash::hash(jwt.toUtf8(), QCryptographicHash::Sha256);
auto sig = rsa_sign(hash);
jwt += '.' + sig.toBase64(b64_opts);
return jwt;
}
HttpRequest::HttpRequest(QObject *parent, QString requestURL, const QString &cache_key) : cache_key(cache_key), QObject(parent) {
networkAccessManager = new QNetworkAccessManager(this);
reply = NULL;
networkTimer = new QTimer(this);
networkTimer->setSingleShot(true);
networkTimer->setInterval(20000);
connect(networkTimer, SIGNAL(timeout()), this, SLOT(requestTimeout()));
sendRequest(requestURL);
if (!cache_key.isEmpty()) {
if (std::string cached_resp = Params().get(cache_key.toStdString()); !cached_resp.empty()) {
QTimer::singleShot(0, [=]() { emit receivedResponse(QString::fromStdString(cached_resp)); });
}
}
}
void HttpRequest::sendRequest(QString requestURL){
QString token = CommaApi::create_jwt();
QNetworkRequest request;
request.setUrl(QUrl(requestURL));
request.setRawHeader(QByteArray("Authorization"), ("JWT " + token).toUtf8());
#ifdef QCOM
QSslConfiguration ssl = QSslConfiguration::defaultConfiguration();
ssl.setCaCertificates(QSslCertificate::fromPath("/usr/etc/tls/cert.pem",
QSsl::Pem, QRegExp::Wildcard));
request.setSslConfiguration(ssl);
#endif
reply = networkAccessManager->get(request);
networkTimer->start();
connect(reply, SIGNAL(finished()), this, SLOT(requestFinished()));
}
void HttpRequest::requestTimeout(){
reply->abort();
}
// This function should always emit something
void HttpRequest::requestFinished(){
if (reply->error() != QNetworkReply::OperationCanceledError) {
networkTimer->stop();
QString response = reply->readAll();
if (reply->error() == QNetworkReply::NoError) {
// save to cache
if (!cache_key.isEmpty()) {
Params().put(cache_key.toStdString(), response.toStdString());
}
emit receivedResponse(response);
} else {
if (!cache_key.isEmpty()) {
Params().remove(cache_key.toStdString());
}
qDebug() << reply->errorString();
emit failedResponse(reply->errorString());
}
} else {
emit timeoutResponse("timeout");
}
reply->deleteLater();
reply = NULL;
}
<|endoftext|> |
<commit_before>#include "../../generators/envelopegenerator.h"
#include "../../wavetable.h"
#include "../../global.h"
TEST( EnvelopeGenerator, Generation )
{
AudioEngineProps::SAMPLE_RATE = 44100;
int length = randomInt( 24, 512 );
float freq = randomFloat() * 440;
WaveTable* table = new WaveTable( length, freq );
SAMPLE_TYPE startAmplitude = randomSample( 0.0, MAX_PHASE );
SAMPLE_TYPE endAmplitude = randomSample( 0.0, MAX_PHASE );
bool fadeIn = ( endAmplitude > startAmplitude );
// generate envelope
EnvelopeGenerator::generate( table, startAmplitude, endAmplitude );
// evaluate results
SAMPLE_TYPE sample;
SAMPLE_TYPE lastSample = fadeIn ? 0.0f : MAX_PHASE;
for ( int i = 0; i < length; ++i )
{
sample = table->getBuffer()[ i ];
ASSERT_TRUE( fadeIn ? sample > lastSample : sample < lastSample )
<< "sample value " << sample << " doesn't match the expectation relative to " << lastSample;
}
// clean up
delete table;
}
<commit_msg>updated Envelope Generator unit test<commit_after>#include "../../generators/envelopegenerator.h"
#include "../../wavetable.h"
#include "../../global.h"
TEST( EnvelopeGenerator, Generation )
{
AudioEngineProps::SAMPLE_RATE = 44100;
int length = randomInt( 24, 512 );
float freq = randomFloat() * 440;
WaveTable* table = new WaveTable( length, freq );
SAMPLE_TYPE startAmplitude = randomSample( 0.0, MAX_PHASE );
SAMPLE_TYPE endAmplitude = randomSample( 0.0, MAX_PHASE );
bool fadeIn = ( endAmplitude > startAmplitude );
// generate envelope
EnvelopeGenerator::generate( table, startAmplitude, endAmplitude );
// evaluate results
SAMPLE_TYPE sample;
SAMPLE_TYPE lastSample = fadeIn ? 0.0f : MAX_PHASE;
for ( int i = 0; i < length; ++i )
{
sample = table->getBuffer()[ i ];
ASSERT_TRUE( fadeIn ? sample > lastSample : sample < lastSample )
<< "sample value " << sample << " doesn't match the expectation relative to " << lastSample;
lastSample = sample;
}
// clean up
delete table;
}
<|endoftext|> |
<commit_before>#include <string.h>
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
#include <ctime>
#include <assert.h>
#define pi 3.14159
#define mod 1000000007
using namespace std;
long long int a[500000];
int main()
{
long long int n = 0,m = 0,a = 0,need_m = 0,need_n = 0,total_need = 0;
cin>>n>>m>>a;
if(n%a==0)
{
need_n = need_n + (n/a);
}
else
{
need_n = need_n + ((n/a)+1);
}
if(m%a == 0)
{
need_m = need_m + (m/a);
}
else
{
need_m = need_m + ((m/a)+1);
}
total_need = (need_n * need_m);
cout<<total_need;
/*if(a>=n && a>=m)
{
need = 1;
cout<<need;
}
else if(a>=n && a<m)
{
if(m%a==0)
{
need = need + ((m/a)-1);
}
else
{
need = need + (m/a);
}
cout<<need;
}
else if(a<n && a>=m)
{
need++;
if(n%a==0)
{
need = need + ((n/a)-1);
}
else
{
need = need + (n/a);
}
cout<<need;
}
else
{
if(n%a == 0)
{
need = need + (n/a);
}
else
{
need = need + ((n/a)+1);
}
if(m%a == 0)
{
need = need + (m/a);
}
else
{
need = need + ((m/a)+1);
}
cout<<need;
}*/
return 0;
}
<commit_msg>Delete Theatre_Square.cpp<commit_after><|endoftext|> |
<commit_before>//==================================================================================
// BSD 2-Clause License
//
// Copyright (c) 2014-2022, NJIT, Duality Technologies Inc. and other contributors
//
// All rights reserved.
//
// Author TPOC: contact@openfhe.org
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//==================================================================================
/*
This file contains the C++ code for implementing the main class for big integers: gmpint which replaces BBI and uses NTL
*/
//==================================================================================
// This file is included only if WITH_NTL is set to ON in CMakeLists.txt
//==================================================================================
#include "config_core.h"
#ifdef WITH_NTL
#define _SECURE_SCL 0 // to speed up VS
#include <fstream>
#include <iostream>
#include <sstream>
#include "math/hal.h"
#include "math/hal/bigintntl/ubintntl.h"
namespace NTL {
// constant log2 of limb bitlength
const usint myZZ::m_log2LimbBitLength = Log2<NTL_ZZ_NBITS>::value;
// CONSTRUCTORS
myZZ::myZZ() : ZZ() {
SetMSB();
}
myZZ::myZZ(const NTL::ZZ& val) : ZZ(val) {
SetMSB();
}
myZZ::myZZ(NTL::ZZ&& val) : ZZ() {
this->swap(val);
SetMSB();
}
myZZ::myZZ(const std::string& strval) : ZZ(conv<ZZ>(strval.c_str())) {
SetMSB();
}
myZZ::myZZ(uint64_t d) : ZZ(0) {
static_assert(NTL_ZZ_NBITS != sizeof(uint64_t), "can't compile gmpint on this architecture");
if (d == 0) {
return;
}
const ZZ_limb_t d1(d);
ZZ_limbs_set(*this, &d1, 1);
SetMSB();
}
#if defined(HAVE_INT128)
// 128-bit native arithmetic is not supported yet
myZZ::myZZ(unsigned __int128 d) : myZZ((uint64_t)d) {}
#endif
// ASSIGNMENT OPERATIONS
const myZZ& myZZ::operator=(const myZZ& val) {
if (this != &val) {
_ntl_gcopy(val.rep, &(this->rep));
this->m_MSB = val.m_MSB;
}
return *this;
}
// ACCESSORS
void myZZ::SetValue(const std::string& str) {
*this = conv<ZZ>(str.c_str());
SetMSB();
}
void myZZ::SetValue(const myZZ& a) {
*this = a;
SetMSB();
}
// ARITHMETIC OPERATIONS
myZZ myZZ::MultiplyAndRound(const myZZ& p, const myZZ& q) const {
myZZ ans(*this);
ans *= p;
ans = ans.DivideAndRound(q);
return ans;
}
const myZZ& myZZ::MultiplyAndRoundEq(const myZZ& p, const myZZ& q) {
this->MulEq(p);
this->DivideAndRoundEq(q);
return *this;
}
myZZ myZZ::DivideAndRound(const myZZ& q) const {
if (q == myZZ(0)) {
PALISADE_THROW(lbcrypto::math_error, "DivideAndRound() Divisor is zero");
}
myZZ halfQ(q >> 1);
if (*this < q) {
if (*this <= halfQ) {
return myZZ(0);
}
else {
return myZZ(1);
}
}
myZZ ans(0);
myZZ rv(0);
DivRem(ans, rv, *this, q);
ans.SetMSB();
rv.SetMSB();
if (!(rv <= halfQ)) {
ans += myZZ(1);
}
return ans;
}
const myZZ& myZZ::DivideAndRoundEq(const myZZ& q) {
if (q == myZZ(0)) {
PALISADE_THROW(lbcrypto::math_error, "DivideAndRound() Divisor is zero");
}
myZZ halfQ(q >> 1);
if (*this < q) {
if (*this <= halfQ) {
return *this = myZZ(0);
}
else {
return *this = myZZ(1);
}
}
myZZ rv(0);
DivRem(*this, rv, *this, q);
this->SetMSB();
rv.SetMSB();
if (!(rv <= halfQ)) {
*this += myZZ(1);
}
return *this;
}
// CONVERTERS
uint64_t myZZ::ConvertToInt() const {
std::stringstream s; // slower
s << *this;
uint64_t result;
s >> result;
if ((this->GetMSB() > (sizeof(uint64_t) * 8)) || (this->GetMSB() > NTL_ZZ_NBITS)) {
std::cerr << "Warning myZZ::ConvertToInt() Loss of precision. " << std::endl;
std::cerr << "input " << *this << std::endl;
std::cerr << "result " << result << std::endl;
}
return result;
}
double myZZ::ConvertToDouble() const {
return (conv<double>(*this));
}
// Splits the binary string to equi sized chunks and then populates the internal
// array values.
myZZ myZZ::FromBinaryString(const std::string& vin) {
std::string v = vin;
// strip off leading spaces from the input string
v.erase(0, v.find_first_not_of(' '));
// strip off leading zeros from the input string
v.erase(0, v.find_first_not_of('0'));
if (v.size() == 0) {
// caustic case of input string being all zeros
v = "0"; // set to one zero
}
myZZ value;
// value.clear(); //clear out all limbs
clear(value); // clear out all limbs
usint len = v.length();
/// new code here
const unsigned int bitsPerByte = 8;
// parse out string 8 bits at a time into array of bytes
std::vector<unsigned char> bytes;
std::reverse(v.begin(), v.end());
for (usint i = 0; i < len; i += bitsPerByte) {
std::string bits = v.substr(0, bitsPerByte);
// reverse the bits
std::reverse(bits.begin(), bits.end());
int newlen = v.length() - bitsPerByte;
size_t nbits;
unsigned char byte = std::stoi(bits, &nbits, 2);
bytes.push_back(byte);
if (newlen < 1) {
break;
}
v = v.substr(bitsPerByte, newlen);
}
ZZFromBytes(value, bytes.data(), bytes.size());
return (value);
}
// OTHER FUNCTIONS
usint myZZ::GetMSB() const {
// note: originally I did not worry about this, and just set the
// MSB whenever this was called, but then that violated constness in the
// various libraries that used this heavily
// this->SetMSB(); //note no one needs to SetMSB()
// return m_MSB;
// SO INSTEAD I am just regenerating the MSB each time
size_t sz = this->size();
usint MSB;
if (sz == 0) { // special case for empty data
MSB = 0;
return (MSB);
}
MSB = (sz - 1) * NTL_ZZ_NBITS; // figure out bit location of all but last
// limb
const ZZ_limb_t* zlp = ZZ_limbs_get(*this);
usint tmp = GetMSBLimb_t(zlp[sz - 1]); // add the value of that last limb.
MSB += tmp;
m_MSB = MSB;
return (MSB);
}
void myZZ::SetMSB() {
size_t sz = this->size();
if (sz == 0) { // special case for empty data
m_MSB = 0;
}
else {
m_MSB = (sz - 1) * NTL_ZZ_NBITS; // figure out bit location of all but last limb
// could also try
// m_MSB = NumBytes(*this)*8;
const ZZ_limb_t* zlp = ZZ_limbs_get(*this);
usint tmp = GetMSBLimb_t(zlp[sz - 1]); // add the value of that last limb.
m_MSB += tmp;
}
return;
}
// inline static usint GetMSBLimb_t(ZZ_limb_t x){
usint myZZ::GetMSBLimb_t(ZZ_limb_t x) const {
const usint bval[] = {0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4};
uint64_t r = 0;
if (x & 0xFFFFFFFF00000000) {
r += 32 / 1;
x >>= 32 / 1;
}
if (x & 0x00000000FFFF0000) {
r += 32 / 2;
x >>= 32 / 2;
}
if (x & 0x000000000000FF00) {
r += 32 / 4;
x >>= 32 / 4;
}
if (x & 0x00000000000000F0) {
r += 32 / 8;
x >>= 32 / 8;
}
return r + bval[x];
}
// utility function introduced in Backend 6 to get a subset of bits from a
// Bigint
usint myZZ::GetBitRangeAtIndex(usint ppo, usint length) const {
if (ppo == 0 || !this->rep)
return 0;
usint pin = ppo - 1;
uint64_t bl;
int64_t sa;
_ntl_limb_t wh;
usint out(0);
for (usint p = pin, i = 0; i < length; i++, p++) {
bl = p / NTL_ZZ_NBITS;
wh = ((_ntl_limb_t)1) << (p - NTL_ZZ_NBITS * bl);
sa = this->size();
if (sa < 0)
sa = -sa;
if (sa <= bl) {
return out;
}
if (ZZ_limbs_get(*this)[bl] & wh) {
out |= 1 << i;
}
}
return out;
}
usint myZZ::GetDigitAtIndexForBase(usint index, usint base) const {
usint DigitLen = std::ceil(log2(base));
usint digit = 0;
usint newIndex = 1 + (index - 1) * DigitLen;
digit = GetBitRangeAtIndex(newIndex, DigitLen);
return digit;
}
// returns the bit at the index into the binary format of the big integer,
// note that msb is 1 like all other bit indicies in PALISADE.
uschar myZZ::GetBitAtIndex(usint index) const {
return (uschar)GetBitRangeAtIndex(index, 1);
}
// optimized ceiling function after division by number of bits in the limb data
// type.
usint myZZ::ceilIntByUInt(const ZZ_limb_t Number) {
// mask to perform bitwise AND
static ZZ_limb_t mask = NTL_ZZ_NBITS - 1;
if (!Number) {
return 1;
}
if ((Number & mask) != 0) {
return (Number >> m_log2LimbBitLength) + 1;
}
else {
return Number >> m_log2LimbBitLength;
}
}
// STRINGS & STREAMS
const std::string myZZ::ToString() const {
std::stringstream result("");
result << *this;
return result.str();
}
std::ostream& operator<<(std::ostream& os, const myZZ& ptr_obj) {
ZZ tmp = ptr_obj;
os << tmp;
return os;
}
} // namespace NTL
#endif
<commit_msg>Integral datatype fix<commit_after>//==================================================================================
// BSD 2-Clause License
//
// Copyright (c) 2014-2022, NJIT, Duality Technologies Inc. and other contributors
//
// All rights reserved.
//
// Author TPOC: contact@openfhe.org
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//==================================================================================
/*
This file contains the C++ code for implementing the main class for big integers: gmpint which replaces BBI and uses NTL
*/
//==================================================================================
// This file is included only if WITH_NTL is set to ON in CMakeLists.txt
//==================================================================================
#include "config_core.h"
#ifdef WITH_NTL
#define _SECURE_SCL 0 // to speed up VS
#include <fstream>
#include <iostream>
#include <sstream>
#include "math/hal.h"
#include "math/hal/bigintntl/ubintntl.h"
namespace NTL {
// constant log2 of limb bitlength
const usint myZZ::m_log2LimbBitLength = Log2<NTL_ZZ_NBITS>::value;
// CONSTRUCTORS
myZZ::myZZ() : ZZ() {
SetMSB();
}
myZZ::myZZ(const NTL::ZZ& val) : ZZ(val) {
SetMSB();
}
myZZ::myZZ(NTL::ZZ&& val) : ZZ() {
this->swap(val);
SetMSB();
}
myZZ::myZZ(const std::string& strval) : ZZ(conv<ZZ>(strval.c_str())) {
SetMSB();
}
myZZ::myZZ(uint64_t d) : ZZ(0) {
static_assert(NTL_ZZ_NBITS != sizeof(uint64_t), "can't compile gmpint on this architecture");
if (d == 0) {
return;
}
const ZZ_limb_t d1(d);
ZZ_limbs_set(*this, &d1, 1);
SetMSB();
}
#if defined(HAVE_INT128)
// 128-bit native arithmetic is not supported yet
myZZ::myZZ(unsigned __int128 d) : myZZ((uint64_t)d) {}
#endif
// ASSIGNMENT OPERATIONS
const myZZ& myZZ::operator=(const myZZ& val) {
if (this != &val) {
_ntl_gcopy(val.rep, &(this->rep));
this->m_MSB = val.m_MSB;
}
return *this;
}
// ACCESSORS
void myZZ::SetValue(const std::string& str) {
*this = conv<ZZ>(str.c_str());
SetMSB();
}
void myZZ::SetValue(const myZZ& a) {
*this = a;
SetMSB();
}
// ARITHMETIC OPERATIONS
myZZ myZZ::MultiplyAndRound(const myZZ& p, const myZZ& q) const {
myZZ ans(*this);
ans *= p;
ans = ans.DivideAndRound(q);
return ans;
}
const myZZ& myZZ::MultiplyAndRoundEq(const myZZ& p, const myZZ& q) {
this->MulEq(p);
this->DivideAndRoundEq(q);
return *this;
}
myZZ myZZ::DivideAndRound(const myZZ& q) const {
if (q == myZZ(0)) {
PALISADE_THROW(lbcrypto::math_error, "DivideAndRound() Divisor is zero");
}
myZZ halfQ(q >> 1);
if (*this < q) {
if (*this <= halfQ) {
return myZZ(0);
}
else {
return myZZ(1);
}
}
myZZ ans(0);
myZZ rv(0);
DivRem(ans, rv, *this, q);
ans.SetMSB();
rv.SetMSB();
if (!(rv <= halfQ)) {
ans += myZZ(1);
}
return ans;
}
const myZZ& myZZ::DivideAndRoundEq(const myZZ& q) {
if (q == myZZ(0)) {
PALISADE_THROW(lbcrypto::math_error, "DivideAndRound() Divisor is zero");
}
myZZ halfQ(q >> 1);
if (*this < q) {
if (*this <= halfQ) {
return *this = myZZ(0);
}
else {
return *this = myZZ(1);
}
}
myZZ rv(0);
DivRem(*this, rv, *this, q);
this->SetMSB();
rv.SetMSB();
if (!(rv <= halfQ)) {
*this += myZZ(1);
}
return *this;
}
// CONVERTERS
uint64_t myZZ::ConvertToInt() const {
std::stringstream s; // slower
s << *this;
uint64_t result;
s >> result;
if ((this->GetMSB() > (sizeof(uint64_t) * 8)) || (this->GetMSB() > NTL_ZZ_NBITS)) {
std::cerr << "Warning myZZ::ConvertToInt() Loss of precision. " << std::endl;
std::cerr << "input " << *this << std::endl;
std::cerr << "result " << result << std::endl;
}
return result;
}
double myZZ::ConvertToDouble() const {
return (conv<double>(*this));
}
// Splits the binary string to equi sized chunks and then populates the internal
// array values.
myZZ myZZ::FromBinaryString(const std::string& vin) {
std::string v = vin;
// strip off leading spaces from the input string
v.erase(0, v.find_first_not_of(' '));
// strip off leading zeros from the input string
v.erase(0, v.find_first_not_of('0'));
if (v.size() == 0) {
// caustic case of input string being all zeros
v = "0"; // set to one zero
}
myZZ value;
// value.clear(); //clear out all limbs
clear(value); // clear out all limbs
usint len = v.length();
/// new code here
const unsigned int bitsPerByte = 8;
// parse out string 8 bits at a time into array of bytes
std::vector<unsigned char> bytes;
std::reverse(v.begin(), v.end());
for (usint i = 0; i < len; i += bitsPerByte) {
std::string bits = v.substr(0, bitsPerByte);
// reverse the bits
std::reverse(bits.begin(), bits.end());
int newlen = v.length() - bitsPerByte;
size_t nbits;
unsigned char byte = std::stoi(bits, &nbits, 2);
bytes.push_back(byte);
if (newlen < 1) {
break;
}
v = v.substr(bitsPerByte, newlen);
}
ZZFromBytes(value, bytes.data(), bytes.size());
return (value);
}
// OTHER FUNCTIONS
usint myZZ::GetMSB() const {
// note: originally I did not worry about this, and just set the
// MSB whenever this was called, but then that violated constness in the
// various libraries that used this heavily
// this->SetMSB(); //note no one needs to SetMSB()
// return m_MSB;
// SO INSTEAD I am just regenerating the MSB each time
size_t sz = this->size();
usint MSB;
if (sz == 0) { // special case for empty data
MSB = 0;
return (MSB);
}
MSB = (sz - 1) * NTL_ZZ_NBITS; // figure out bit location of all but last
// limb
const ZZ_limb_t* zlp = ZZ_limbs_get(*this);
usint tmp = GetMSBLimb_t(zlp[sz - 1]); // add the value of that last limb.
MSB += tmp;
m_MSB = MSB;
return (MSB);
}
void myZZ::SetMSB() {
size_t sz = this->size();
if (sz == 0) { // special case for empty data
m_MSB = 0;
}
else {
m_MSB = (sz - 1) * NTL_ZZ_NBITS; // figure out bit location of all but last limb
// could also try
// m_MSB = NumBytes(*this)*8;
const ZZ_limb_t* zlp = ZZ_limbs_get(*this);
usint tmp = GetMSBLimb_t(zlp[sz - 1]); // add the value of that last limb.
m_MSB += tmp;
}
return;
}
// inline static usint GetMSBLimb_t(ZZ_limb_t x){
usint myZZ::GetMSBLimb_t(ZZ_limb_t x) const {
const usint bval[] = {0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4};
uint64_t r = 0;
if (x & 0xFFFFFFFF00000000) {
r += 32 / 1;
x >>= 32 / 1;
}
if (x & 0x00000000FFFF0000) {
r += 32 / 2;
x >>= 32 / 2;
}
if (x & 0x000000000000FF00) {
r += 32 / 4;
x >>= 32 / 4;
}
if (x & 0x00000000000000F0) {
r += 32 / 8;
x >>= 32 / 8;
}
return r + bval[x];
}
// utility function introduced in Backend 6 to get a subset of bits from a
// Bigint
usint myZZ::GetBitRangeAtIndex(usint ppo, usint length) const {
if (ppo == 0 || !this->rep)
return 0;
usint pin = ppo - 1;
int64_t bl;
int64_t sa;
_ntl_limb_t wh;
usint out(0);
for (usint p = pin, i = 0; i < length; i++, p++) {
bl = p / NTL_ZZ_NBITS;
wh = ((_ntl_limb_t)1) << (p - NTL_ZZ_NBITS * bl);
sa = this->size();
if (sa < 0)
sa = -sa;
if (sa <= bl) {
return out;
}
if (ZZ_limbs_get(*this)[bl] & wh) {
out |= 1 << i;
}
}
return out;
}
usint myZZ::GetDigitAtIndexForBase(usint index, usint base) const {
usint DigitLen = std::ceil(log2(base));
usint digit = 0;
usint newIndex = 1 + (index - 1) * DigitLen;
digit = GetBitRangeAtIndex(newIndex, DigitLen);
return digit;
}
// returns the bit at the index into the binary format of the big integer,
// note that msb is 1 like all other bit indicies in PALISADE.
uschar myZZ::GetBitAtIndex(usint index) const {
return (uschar)GetBitRangeAtIndex(index, 1);
}
// optimized ceiling function after division by number of bits in the limb data
// type.
usint myZZ::ceilIntByUInt(const ZZ_limb_t Number) {
// mask to perform bitwise AND
static ZZ_limb_t mask = NTL_ZZ_NBITS - 1;
if (!Number) {
return 1;
}
if ((Number & mask) != 0) {
return (Number >> m_log2LimbBitLength) + 1;
}
else {
return Number >> m_log2LimbBitLength;
}
}
// STRINGS & STREAMS
const std::string myZZ::ToString() const {
std::stringstream result("");
result << *this;
return result.str();
}
std::ostream& operator<<(std::ostream& os, const myZZ& ptr_obj) {
ZZ tmp = ptr_obj;
os << tmp;
return os;
}
} // namespace NTL
#endif
<|endoftext|> |
<commit_before>/*
Copyright 2010 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "GrBufferAllocPool.h"
#include "GrTypes.h"
#include "GrVertexBuffer.h"
#include "GrIndexBuffer.h"
#include "GrGpu.h"
#if GR_DEBUG
#define VALIDATE validate
#else
#define VALIDATE()
#endif
#define GrBufferAllocPool_MIN_BLOCK_SIZE ((size_t)1 << 12)
GrBufferAllocPool::GrBufferAllocPool(GrGpu* gpu,
BufferType bufferType,
bool frequentResetHint,
size_t blockSize,
int preallocBufferCnt) :
fBlocks(GrMax(8, 2*preallocBufferCnt)) {
GrAssert(NULL != gpu);
fGpu = gpu;
fGpu->ref();
fGpuIsReffed = true;
fBufferType = bufferType;
fFrequentResetHint = frequentResetHint;
fBufferPtr = NULL;
fMinBlockSize = GrMax(GrBufferAllocPool_MIN_BLOCK_SIZE, blockSize);
fPreallocBuffersInUse = 0;
fFirstPreallocBuffer = 0;
for (int i = 0; i < preallocBufferCnt; ++i) {
GrGeometryBuffer* buffer = this->createBuffer(fMinBlockSize);
if (NULL != buffer) {
*fPreallocBuffers.append() = buffer;
buffer->ref();
}
}
}
GrBufferAllocPool::~GrBufferAllocPool() {
VALIDATE();
if (fBlocks.count()) {
GrGeometryBuffer* buffer = fBlocks.back().fBuffer;
if (buffer->isLocked()) {
buffer->unlock();
}
}
while (!fBlocks.empty()) {
destroyBlock();
}
fPreallocBuffers.unrefAll();
releaseGpuRef();
}
void GrBufferAllocPool::releaseGpuRef() {
if (fGpuIsReffed) {
fGpu->unref();
fGpuIsReffed = false;
}
}
void GrBufferAllocPool::reset() {
VALIDATE();
if (fBlocks.count()) {
GrGeometryBuffer* buffer = fBlocks.back().fBuffer;
if (buffer->isLocked()) {
buffer->unlock();
}
}
while (!fBlocks.empty()) {
destroyBlock();
}
if (fPreallocBuffers.count()) {
// must set this after above loop.
fFirstPreallocBuffer = (fFirstPreallocBuffer + fPreallocBuffersInUse) %
fPreallocBuffers.count();
}
fCpuData.realloc(fGpu->supportsBufferLocking() ? 0 : fMinBlockSize);
GrAssert(0 == fPreallocBuffersInUse);
VALIDATE();
}
void GrBufferAllocPool::unlock() {
VALIDATE();
if (NULL != fBufferPtr) {
BufferBlock& block = fBlocks.back();
if (block.fBuffer->isLocked()) {
block.fBuffer->unlock();
} else {
size_t flushSize = block.fBuffer->size() - block.fBytesFree;
flushCpuData(fBlocks.back().fBuffer, flushSize);
}
fBufferPtr = NULL;
}
VALIDATE();
}
#if GR_DEBUG
void GrBufferAllocPool::validate() const {
if (NULL != fBufferPtr) {
GrAssert(!fBlocks.empty());
if (fBlocks.back().fBuffer->isLocked()) {
GrGeometryBuffer* buf = fBlocks.back().fBuffer;
GrAssert(buf->lockPtr() == fBufferPtr);
} else {
GrAssert(fCpuData.get() == fBufferPtr);
GrAssert(fCpuData.size() == fBlocks.back().fBuffer->size());
}
} else {
GrAssert(fBlocks.empty() || !fBlocks.back().fBuffer->isLocked());
}
for (int i = 0; i < fBlocks.count() - 1; ++i) {
GrAssert(!fBlocks[i].fBuffer->isLocked());
}
}
#endif
void* GrBufferAllocPool::makeSpace(size_t size,
size_t alignment,
const GrGeometryBuffer** buffer,
size_t* offset) {
VALIDATE();
GrAssert(NULL != buffer);
GrAssert(NULL != offset);
if (NULL != fBufferPtr) {
BufferBlock& back = fBlocks.back();
size_t usedBytes = back.fBuffer->size() - back.fBytesFree;
size_t pad = GrSizeAlignUpPad(usedBytes,
alignment);
if ((size + pad) <= back.fBytesFree) {
usedBytes += pad;
*offset = usedBytes;
*buffer = back.fBuffer;
back.fBytesFree -= size + pad;
return (void*)(reinterpret_cast<intptr_t>(fBufferPtr) + usedBytes);
}
}
if (!createBlock(size)) {
return NULL;
}
VALIDATE();
GrAssert(NULL != fBufferPtr);
*offset = 0;
BufferBlock& back = fBlocks.back();
*buffer = back.fBuffer;
back.fBytesFree -= size;
return fBufferPtr;
}
int GrBufferAllocPool::currentBufferItems(size_t itemSize) const {
VALIDATE();
if (NULL != fBufferPtr) {
const BufferBlock& back = fBlocks.back();
size_t usedBytes = back.fBuffer->size() - back.fBytesFree;
size_t pad = GrSizeAlignUpPad(usedBytes, itemSize);
return (back.fBytesFree - pad) / itemSize;
} else if (fPreallocBuffersInUse < fPreallocBuffers.count()) {
return fMinBlockSize / itemSize;
}
return 0;
}
int GrBufferAllocPool::preallocatedBuffersRemaining() const {
return fPreallocBuffers.count() - fPreallocBuffersInUse;
}
int GrBufferAllocPool::preallocatedBufferCount() const {
return fPreallocBuffers.count();
}
void GrBufferAllocPool::putBack(size_t bytes) {
VALIDATE();
if (NULL != fBufferPtr) {
BufferBlock& back = fBlocks.back();
size_t bytesUsed = back.fBuffer->size() - back.fBytesFree;
if (bytes >= bytesUsed) {
destroyBlock();
bytes -= bytesUsed;
} else {
back.fBytesFree += bytes;
return;
}
}
VALIDATE();
GrAssert(NULL == fBufferPtr);
// we don't partially roll-back buffers because our VB semantics say locking
// a VB discards its previous content.
// We could honor it by being sure we use updateSubData and not lock
// we will roll-back fully released buffers, though.
while (!fBlocks.empty() &&
bytes >= fBlocks.back().fBuffer->size()) {
bytes -= fBlocks.back().fBuffer->size();
destroyBlock();
}
VALIDATE();
}
bool GrBufferAllocPool::createBlock(size_t requestSize) {
size_t size = GrMax(requestSize, fMinBlockSize);
GrAssert(size >= GrBufferAllocPool_MIN_BLOCK_SIZE);
VALIDATE();
BufferBlock& block = fBlocks.push_back();
if (size == fMinBlockSize &&
fPreallocBuffersInUse < fPreallocBuffers.count()) {
uint32_t nextBuffer = (fPreallocBuffersInUse + fFirstPreallocBuffer) %
fPreallocBuffers.count();
block.fBuffer = fPreallocBuffers[nextBuffer];
block.fBuffer->ref();
++fPreallocBuffersInUse;
} else {
block.fBuffer = this->createBuffer(size);
if (NULL == block.fBuffer) {
fBlocks.pop_back();
return false;
}
}
block.fBytesFree = size;
if (NULL != fBufferPtr) {
GrAssert(fBlocks.count() > 1);
BufferBlock& prev = fBlocks.fromBack(1);
if (prev.fBuffer->isLocked()) {
prev.fBuffer->unlock();
} else {
flushCpuData(prev.fBuffer,
prev.fBuffer->size() - prev.fBytesFree);
}
fBufferPtr = NULL;
}
GrAssert(NULL == fBufferPtr);
if (fGpu->supportsBufferLocking() &&
size > GR_GEOM_BUFFER_LOCK_THRESHOLD &&
(!fFrequentResetHint || requestSize > GR_GEOM_BUFFER_LOCK_THRESHOLD)) {
fBufferPtr = block.fBuffer->lock();
}
if (NULL == fBufferPtr) {
fBufferPtr = fCpuData.realloc(size);
}
VALIDATE();
return true;
}
void GrBufferAllocPool::destroyBlock() {
GrAssert(!fBlocks.empty());
BufferBlock& block = fBlocks.back();
if (fPreallocBuffersInUse > 0) {
uint32_t prevPreallocBuffer = (fPreallocBuffersInUse +
fFirstPreallocBuffer +
(fPreallocBuffers.count() - 1)) %
fPreallocBuffers.count();
if (block.fBuffer == fPreallocBuffers[prevPreallocBuffer]) {
--fPreallocBuffersInUse;
}
}
GrAssert(!block.fBuffer->isLocked());
block.fBuffer->unref();
fBlocks.pop_back();
fBufferPtr = NULL;
}
void GrBufferAllocPool::flushCpuData(GrGeometryBuffer* buffer,
size_t flushSize) {
GrAssert(NULL != buffer);
GrAssert(!buffer->isLocked());
GrAssert(fCpuData.get() == fBufferPtr);
GrAssert(fCpuData.size() == buffer->size());
GrAssert(flushSize <= buffer->size());
bool updated = false;
if (fGpu->supportsBufferLocking() &&
flushSize > GR_GEOM_BUFFER_LOCK_THRESHOLD) {
void* data = buffer->lock();
if (NULL != data) {
memcpy(data, fBufferPtr, flushSize);
buffer->unlock();
updated = true;
}
}
buffer->updateData(fBufferPtr, flushSize);
}
GrGeometryBuffer* GrBufferAllocPool::createBuffer(size_t size) {
if (kIndex_BufferType == fBufferType) {
return fGpu->createIndexBuffer(size, true);
} else {
GrAssert(kVertex_BufferType == fBufferType);
return fGpu->createVertexBuffer(size, true);
}
}
////////////////////////////////////////////////////////////////////////////////
GrVertexBufferAllocPool::GrVertexBufferAllocPool(GrGpu* gpu,
bool frequentResetHint,
size_t bufferSize,
int preallocBufferCnt)
: GrBufferAllocPool(gpu,
kVertex_BufferType,
frequentResetHint,
bufferSize,
preallocBufferCnt) {
}
void* GrVertexBufferAllocPool::makeSpace(GrVertexLayout layout,
int vertexCount,
const GrVertexBuffer** buffer,
int* startVertex) {
GrAssert(vertexCount >= 0);
GrAssert(NULL != buffer);
GrAssert(NULL != startVertex);
size_t vSize = GrDrawTarget::VertexSize(layout);
size_t offset;
const GrGeometryBuffer* geomBuffer;
void* ptr = INHERITED::makeSpace(vSize * vertexCount,
vSize,
&geomBuffer,
&offset);
*buffer = (const GrVertexBuffer*) geomBuffer;
GrAssert(0 == offset % vSize);
*startVertex = offset / vSize;
return ptr;
}
bool GrVertexBufferAllocPool::appendVertices(GrVertexLayout layout,
int vertexCount,
const void* vertices,
const GrVertexBuffer** buffer,
int* startVertex) {
void* space = makeSpace(layout, vertexCount, buffer, startVertex);
if (NULL != space) {
memcpy(space,
vertices,
GrDrawTarget::VertexSize(layout) * vertexCount);
return true;
} else {
return false;
}
}
int GrVertexBufferAllocPool::preallocatedBufferVertices(GrVertexLayout layout) const {
return INHERITED::preallocatedBufferSize() /
GrDrawTarget::VertexSize(layout);
}
int GrVertexBufferAllocPool::currentBufferVertices(GrVertexLayout layout) const {
return currentBufferItems(GrDrawTarget::VertexSize(layout));
}
////////////////////////////////////////////////////////////////////////////////
GrIndexBufferAllocPool::GrIndexBufferAllocPool(GrGpu* gpu,
bool frequentResetHint,
size_t bufferSize,
int preallocBufferCnt)
: GrBufferAllocPool(gpu,
kIndex_BufferType,
frequentResetHint,
bufferSize,
preallocBufferCnt) {
}
void* GrIndexBufferAllocPool::makeSpace(int indexCount,
const GrIndexBuffer** buffer,
int* startIndex) {
GrAssert(indexCount >= 0);
GrAssert(NULL != buffer);
GrAssert(NULL != startIndex);
size_t offset;
const GrGeometryBuffer* geomBuffer;
void* ptr = INHERITED::makeSpace(indexCount * sizeof(uint16_t),
sizeof(uint16_t),
&geomBuffer,
&offset);
*buffer = (const GrIndexBuffer*) geomBuffer;
GrAssert(0 == offset % sizeof(uint16_t));
*startIndex = offset / sizeof(uint16_t);
return ptr;
}
bool GrIndexBufferAllocPool::appendIndices(int indexCount,
const void* indices,
const GrIndexBuffer** buffer,
int* startIndex) {
void* space = makeSpace(indexCount, buffer, startIndex);
if (NULL != space) {
memcpy(space, indices, sizeof(uint16_t) * indexCount);
return true;
} else {
return false;
}
}
int GrIndexBufferAllocPool::preallocatedBufferIndices() const {
return INHERITED::preallocatedBufferSize() / sizeof(uint16_t);
}
int GrIndexBufferAllocPool::currentBufferIndices() const {
return currentBufferItems(sizeof(uint16_t));
}
<commit_msg>Suppress warnings in GrBufferAllocPool<commit_after>/*
Copyright 2010 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "GrBufferAllocPool.h"
#include "GrTypes.h"
#include "GrVertexBuffer.h"
#include "GrIndexBuffer.h"
#include "GrGpu.h"
#if GR_DEBUG
#define VALIDATE validate
#else
#define VALIDATE()
#endif
#define GrBufferAllocPool_MIN_BLOCK_SIZE ((size_t)1 << 12)
GrBufferAllocPool::GrBufferAllocPool(GrGpu* gpu,
BufferType bufferType,
bool frequentResetHint,
size_t blockSize,
int preallocBufferCnt) :
fBlocks(GrMax(8, 2*preallocBufferCnt)) {
GrAssert(NULL != gpu);
fGpu = gpu;
fGpu->ref();
fGpuIsReffed = true;
fBufferType = bufferType;
fFrequentResetHint = frequentResetHint;
fBufferPtr = NULL;
fMinBlockSize = GrMax(GrBufferAllocPool_MIN_BLOCK_SIZE, blockSize);
fPreallocBuffersInUse = 0;
fFirstPreallocBuffer = 0;
for (int i = 0; i < preallocBufferCnt; ++i) {
GrGeometryBuffer* buffer = this->createBuffer(fMinBlockSize);
if (NULL != buffer) {
*fPreallocBuffers.append() = buffer;
buffer->ref();
}
}
}
GrBufferAllocPool::~GrBufferAllocPool() {
VALIDATE();
if (fBlocks.count()) {
GrGeometryBuffer* buffer = fBlocks.back().fBuffer;
if (buffer->isLocked()) {
buffer->unlock();
}
}
while (!fBlocks.empty()) {
destroyBlock();
}
fPreallocBuffers.unrefAll();
releaseGpuRef();
}
void GrBufferAllocPool::releaseGpuRef() {
if (fGpuIsReffed) {
fGpu->unref();
fGpuIsReffed = false;
}
}
void GrBufferAllocPool::reset() {
VALIDATE();
if (fBlocks.count()) {
GrGeometryBuffer* buffer = fBlocks.back().fBuffer;
if (buffer->isLocked()) {
buffer->unlock();
}
}
while (!fBlocks.empty()) {
destroyBlock();
}
if (fPreallocBuffers.count()) {
// must set this after above loop.
fFirstPreallocBuffer = (fFirstPreallocBuffer + fPreallocBuffersInUse) %
fPreallocBuffers.count();
}
fCpuData.realloc(fGpu->supportsBufferLocking() ? 0 : fMinBlockSize);
GrAssert(0 == fPreallocBuffersInUse);
VALIDATE();
}
void GrBufferAllocPool::unlock() {
VALIDATE();
if (NULL != fBufferPtr) {
BufferBlock& block = fBlocks.back();
if (block.fBuffer->isLocked()) {
block.fBuffer->unlock();
} else {
size_t flushSize = block.fBuffer->size() - block.fBytesFree;
flushCpuData(fBlocks.back().fBuffer, flushSize);
}
fBufferPtr = NULL;
}
VALIDATE();
}
#if GR_DEBUG
void GrBufferAllocPool::validate() const {
if (NULL != fBufferPtr) {
GrAssert(!fBlocks.empty());
if (fBlocks.back().fBuffer->isLocked()) {
GrGeometryBuffer* buf = fBlocks.back().fBuffer;
GrAssert(buf->lockPtr() == fBufferPtr);
} else {
GrAssert(fCpuData.get() == fBufferPtr);
GrAssert(fCpuData.size() == fBlocks.back().fBuffer->size());
}
} else {
GrAssert(fBlocks.empty() || !fBlocks.back().fBuffer->isLocked());
}
for (int i = 0; i < fBlocks.count() - 1; ++i) {
GrAssert(!fBlocks[i].fBuffer->isLocked());
}
}
#endif
void* GrBufferAllocPool::makeSpace(size_t size,
size_t alignment,
const GrGeometryBuffer** buffer,
size_t* offset) {
VALIDATE();
GrAssert(NULL != buffer);
GrAssert(NULL != offset);
if (NULL != fBufferPtr) {
BufferBlock& back = fBlocks.back();
size_t usedBytes = back.fBuffer->size() - back.fBytesFree;
size_t pad = GrSizeAlignUpPad(usedBytes,
alignment);
if ((size + pad) <= back.fBytesFree) {
usedBytes += pad;
*offset = usedBytes;
*buffer = back.fBuffer;
back.fBytesFree -= size + pad;
return (void*)(reinterpret_cast<intptr_t>(fBufferPtr) + usedBytes);
}
}
if (!createBlock(size)) {
return NULL;
}
VALIDATE();
GrAssert(NULL != fBufferPtr);
*offset = 0;
BufferBlock& back = fBlocks.back();
*buffer = back.fBuffer;
back.fBytesFree -= size;
return fBufferPtr;
}
int GrBufferAllocPool::currentBufferItems(size_t itemSize) const {
VALIDATE();
if (NULL != fBufferPtr) {
const BufferBlock& back = fBlocks.back();
size_t usedBytes = back.fBuffer->size() - back.fBytesFree;
size_t pad = GrSizeAlignUpPad(usedBytes, itemSize);
return (back.fBytesFree - pad) / itemSize;
} else if (fPreallocBuffersInUse < fPreallocBuffers.count()) {
return fMinBlockSize / itemSize;
}
return 0;
}
int GrBufferAllocPool::preallocatedBuffersRemaining() const {
return fPreallocBuffers.count() - fPreallocBuffersInUse;
}
int GrBufferAllocPool::preallocatedBufferCount() const {
return fPreallocBuffers.count();
}
void GrBufferAllocPool::putBack(size_t bytes) {
VALIDATE();
if (NULL != fBufferPtr) {
BufferBlock& back = fBlocks.back();
size_t bytesUsed = back.fBuffer->size() - back.fBytesFree;
if (bytes >= bytesUsed) {
destroyBlock();
bytes -= bytesUsed;
} else {
back.fBytesFree += bytes;
return;
}
}
VALIDATE();
GrAssert(NULL == fBufferPtr);
// we don't partially roll-back buffers because our VB semantics say locking
// a VB discards its previous content.
// We could honor it by being sure we use updateSubData and not lock
// we will roll-back fully released buffers, though.
while (!fBlocks.empty() &&
bytes >= fBlocks.back().fBuffer->size()) {
bytes -= fBlocks.back().fBuffer->size();
destroyBlock();
}
VALIDATE();
}
bool GrBufferAllocPool::createBlock(size_t requestSize) {
size_t size = GrMax(requestSize, fMinBlockSize);
GrAssert(size >= GrBufferAllocPool_MIN_BLOCK_SIZE);
VALIDATE();
BufferBlock& block = fBlocks.push_back();
if (size == fMinBlockSize &&
fPreallocBuffersInUse < fPreallocBuffers.count()) {
uint32_t nextBuffer = (fPreallocBuffersInUse + fFirstPreallocBuffer) %
fPreallocBuffers.count();
block.fBuffer = fPreallocBuffers[nextBuffer];
block.fBuffer->ref();
++fPreallocBuffersInUse;
} else {
block.fBuffer = this->createBuffer(size);
if (NULL == block.fBuffer) {
fBlocks.pop_back();
return false;
}
}
block.fBytesFree = size;
if (NULL != fBufferPtr) {
GrAssert(fBlocks.count() > 1);
BufferBlock& prev = fBlocks.fromBack(1);
if (prev.fBuffer->isLocked()) {
prev.fBuffer->unlock();
} else {
flushCpuData(prev.fBuffer,
prev.fBuffer->size() - prev.fBytesFree);
}
fBufferPtr = NULL;
}
GrAssert(NULL == fBufferPtr);
if (fGpu->supportsBufferLocking() &&
size > GR_GEOM_BUFFER_LOCK_THRESHOLD &&
(!fFrequentResetHint || requestSize > GR_GEOM_BUFFER_LOCK_THRESHOLD)) {
fBufferPtr = block.fBuffer->lock();
}
if (NULL == fBufferPtr) {
fBufferPtr = fCpuData.realloc(size);
}
VALIDATE();
return true;
}
void GrBufferAllocPool::destroyBlock() {
GrAssert(!fBlocks.empty());
BufferBlock& block = fBlocks.back();
if (fPreallocBuffersInUse > 0) {
uint32_t prevPreallocBuffer = (fPreallocBuffersInUse +
fFirstPreallocBuffer +
(fPreallocBuffers.count() - 1)) %
fPreallocBuffers.count();
if (block.fBuffer == fPreallocBuffers[prevPreallocBuffer]) {
--fPreallocBuffersInUse;
}
}
GrAssert(!block.fBuffer->isLocked());
block.fBuffer->unref();
fBlocks.pop_back();
fBufferPtr = NULL;
}
void GrBufferAllocPool::flushCpuData(GrGeometryBuffer* buffer,
size_t flushSize) {
GrAssert(NULL != buffer);
GrAssert(!buffer->isLocked());
GrAssert(fCpuData.get() == fBufferPtr);
GrAssert(fCpuData.size() == buffer->size());
GrAssert(flushSize <= buffer->size());
bool updated = false;
if (fGpu->supportsBufferLocking() &&
flushSize > GR_GEOM_BUFFER_LOCK_THRESHOLD) {
void* data = buffer->lock();
if (NULL != data) {
memcpy(data, fBufferPtr, flushSize);
buffer->unlock();
updated = true;
}
}
buffer->updateData(fBufferPtr, flushSize);
}
GrGeometryBuffer* GrBufferAllocPool::createBuffer(size_t size) {
if (kIndex_BufferType == fBufferType) {
return fGpu->createIndexBuffer(size, true);
} else {
GrAssert(kVertex_BufferType == fBufferType);
return fGpu->createVertexBuffer(size, true);
}
}
////////////////////////////////////////////////////////////////////////////////
GrVertexBufferAllocPool::GrVertexBufferAllocPool(GrGpu* gpu,
bool frequentResetHint,
size_t bufferSize,
int preallocBufferCnt)
: GrBufferAllocPool(gpu,
kVertex_BufferType,
frequentResetHint,
bufferSize,
preallocBufferCnt) {
}
void* GrVertexBufferAllocPool::makeSpace(GrVertexLayout layout,
int vertexCount,
const GrVertexBuffer** buffer,
int* startVertex) {
GrAssert(vertexCount >= 0);
GrAssert(NULL != buffer);
GrAssert(NULL != startVertex);
size_t vSize = GrDrawTarget::VertexSize(layout);
size_t offset = 0; // assign to suppress warning
const GrGeometryBuffer* geomBuffer = NULL; // assign to suppress warning
void* ptr = INHERITED::makeSpace(vSize * vertexCount,
vSize,
&geomBuffer,
&offset);
*buffer = (const GrVertexBuffer*) geomBuffer;
GrAssert(0 == offset % vSize);
*startVertex = offset / vSize;
return ptr;
}
bool GrVertexBufferAllocPool::appendVertices(GrVertexLayout layout,
int vertexCount,
const void* vertices,
const GrVertexBuffer** buffer,
int* startVertex) {
void* space = makeSpace(layout, vertexCount, buffer, startVertex);
if (NULL != space) {
memcpy(space,
vertices,
GrDrawTarget::VertexSize(layout) * vertexCount);
return true;
} else {
return false;
}
}
int GrVertexBufferAllocPool::preallocatedBufferVertices(GrVertexLayout layout) const {
return INHERITED::preallocatedBufferSize() /
GrDrawTarget::VertexSize(layout);
}
int GrVertexBufferAllocPool::currentBufferVertices(GrVertexLayout layout) const {
return currentBufferItems(GrDrawTarget::VertexSize(layout));
}
////////////////////////////////////////////////////////////////////////////////
GrIndexBufferAllocPool::GrIndexBufferAllocPool(GrGpu* gpu,
bool frequentResetHint,
size_t bufferSize,
int preallocBufferCnt)
: GrBufferAllocPool(gpu,
kIndex_BufferType,
frequentResetHint,
bufferSize,
preallocBufferCnt) {
}
void* GrIndexBufferAllocPool::makeSpace(int indexCount,
const GrIndexBuffer** buffer,
int* startIndex) {
GrAssert(indexCount >= 0);
GrAssert(NULL != buffer);
GrAssert(NULL != startIndex);
size_t offset = 0; // assign to suppress warning
const GrGeometryBuffer* geomBuffer = NULL; // assign to suppress warning
void* ptr = INHERITED::makeSpace(indexCount * sizeof(uint16_t),
sizeof(uint16_t),
&geomBuffer,
&offset);
*buffer = (const GrIndexBuffer*) geomBuffer;
GrAssert(0 == offset % sizeof(uint16_t));
*startIndex = offset / sizeof(uint16_t);
return ptr;
}
bool GrIndexBufferAllocPool::appendIndices(int indexCount,
const void* indices,
const GrIndexBuffer** buffer,
int* startIndex) {
void* space = makeSpace(indexCount, buffer, startIndex);
if (NULL != space) {
memcpy(space, indices, sizeof(uint16_t) * indexCount);
return true;
} else {
return false;
}
}
int GrIndexBufferAllocPool::preallocatedBufferIndices() const {
return INHERITED::preallocatedBufferSize() / sizeof(uint16_t);
}
int GrIndexBufferAllocPool::currentBufferIndices() const {
return currentBufferItems(sizeof(uint16_t));
}
<|endoftext|> |
<commit_before>#ifndef _SNARKFRONT_SHA_256_HPP_
#define _SNARKFRONT_SHA_256_HPP_
#include <array>
#include <cstdint>
#include "Alg.hpp"
#include "Alg_uint.hpp"
#include "AST.hpp"
#include "BitwiseOps.hpp"
#include "Lazy.hpp"
#include "SecureHashStd.hpp"
namespace snarkfront {
////////////////////////////////////////////////////////////////////////////////
// SHA-256
//
template <typename T, typename MSG, typename U, typename F>
class SHA_256 : public SHA_Base<SHA_256<T, MSG, U, F>,
SHA_BlockSize::BLOCK_512,
MSG>
{
public:
typedef T WordType;
typedef U ByteType;
typedef std::array<T, 16> MsgType;
typedef std::array<T, 8> DigType;
typedef std::array<U, 16 * 4> PreType;
SHA_256() {
initConstants();
}
const std::array<T, 8>& digest() const {
return m_H;
}
virtual void initHashValue() {
// set initial hash value (NIST FIPS 180-4 section 5.3.3)
const std::array<std::uint32_t, 8> a {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 };
for (std::size_t i = 0; i < 8; ++i) {
m_H[i] = F::constant(a[i]);
}
}
void prepMsgSchedule(std::size_t& msgIndex) {
// prepare message schedule (NIST FIPS 180-4 section 6.2.2)
for (std::size_t i = 0; i < 16; ++i) {
m_W[i] = this->msgWord(msgIndex);
}
for (std::size_t i = 16; i < 64; ++i) {
//m_W[i] = F::sigma_256_1(m_W[i-2]) + m_W[i-7] + F::sigma_256_0(m_W[i-15]) + m_W[i-16];
m_W[i] = F::ADDMOD(F::ADDMOD(
F::ADDMOD(
F::sigma_256_1(m_W[i-2]),
m_W[i-7]),
F::sigma_256_0(m_W[i-15])),
m_W[i-16]);
}
}
void initWorkingVars() {
// initialize eight working variables (NIST FIPS 180-4 section 6.2.2)
m_a = m_H[0];
m_b = m_H[1];
m_c = m_H[2];
m_d = m_H[3];
m_e = m_H[4];
m_f = m_H[5];
m_g = m_H[6];
m_h = m_H[7];
}
void workingLoop() {
// inner loop (NIST FIPS 180-4 section 6.2.2)
for (std::size_t i = 0; i < 64; ++i) {
//m_T[0] = m_h + F::SIGMA_256_1(m_e) + F::Ch(m_e, m_f, m_g) + m_K[i] + m_W[i];
m_T[0] = F::ADDMOD(F::ADDMOD(
F::ADDMOD(
F::ADDMOD(m_h,
F::SIGMA_256_1(m_e)),
F::Ch(m_e, m_f, m_g)),
m_K[i]),
m_W[i]);
//m_T[1] = F::SIGMA_256_0(m_a) + F::Maj(m_a, m_b, m_c);
m_T[1] = F::ADDMOD(F::SIGMA_256_0(m_a),
F::Maj(m_a, m_b, m_c));
m_h = m_g;
m_g = m_f;
m_f = m_e;
//m_e = m_d + m_T[0];
m_e = F::ADDMOD(m_d, m_T[0]);
m_d = m_c;
m_c = m_b;
m_b = m_a;
//m_a = m_T[0] + m_T[1];
m_a = F::ADDMOD(m_T[0], m_T[1]);
}
}
void updateHash() {
// compute intermediate hash value (NIST FIPS 180-4 section 6.2.2)
//m_H[0] = m_H[0] + m_a;
//m_H[1] = m_H[1] + m_b;
//m_H[2] = m_H[2] + m_c;
//m_H[3] = m_H[3] + m_d;
//m_H[4] = m_H[4] + m_e;
//m_H[5] = m_H[5] + m_f;
//m_H[6] = m_H[6] + m_g;
//m_H[7] = m_H[7] + m_h;
m_H[0] = F::ADDMOD(m_H[0], m_a);
m_H[1] = F::ADDMOD(m_H[1], m_b);
m_H[2] = F::ADDMOD(m_H[2], m_c);
m_H[3] = F::ADDMOD(m_H[3], m_d);
m_H[4] = F::ADDMOD(m_H[4], m_e);
m_H[5] = F::ADDMOD(m_H[5], m_f);
m_H[6] = F::ADDMOD(m_H[6], m_g);
m_H[7] = F::ADDMOD(m_H[7], m_h);
}
virtual void afterHash() {
}
protected:
void initConstants() {
// set constants (NIST FIPS 180-4 section 4.2.2)
const std::array<std::uint32_t, 64> a {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 };
for (std::size_t i = 0; i < 64; ++i) {
m_K[i] = F::constant(a[i]);
}
}
// eight 32-bit working variables
T m_a, m_b, m_c, m_d, m_e, m_f, m_g, m_h;
// 64 constant 32-bit words
std::array<T, 64> m_K;
// message schedule of 64 32-bit words
std::array<T, 64> m_W;
// 256-bit hash value
std::array<T, 8> m_H;
// two temporary words
std::array<T, 2> m_T;
};
////////////////////////////////////////////////////////////////////////////////
// typedefs
//
namespace zk {
template <typename FR> using
SHA256 = SHA_256<AST_Var<Alg_uint32<FR>>,
Lazy<AST_Var<Alg_uint32<FR>>, std::uint32_t>,
AST_Var<Alg_uint8<FR>>,
SHA_Functions<AST_Node<Alg_uint32<FR>>,
AST_Op<Alg_uint32<FR>>,
BitwiseAST<Alg_uint32<FR>, Alg_uint32<FR>>>>;
} // namespace zk
namespace eval {
typedef SHA_256<std::uint32_t,
std::uint32_t,
std::uint8_t,
SHA_Functions<std::uint32_t,
std::uint32_t,
BitwiseINT<std::uint32_t, std::uint32_t>>>
SHA256;
} // namespace eval
} // namespace snarkfront
#endif
<commit_msg>BitwiseOps templates<commit_after>#ifndef _SNARKFRONT_SHA_256_HPP_
#define _SNARKFRONT_SHA_256_HPP_
#include <array>
#include <cstdint>
#include "Alg.hpp"
#include "Alg_uint.hpp"
#include "AST.hpp"
#include "BitwiseOps.hpp"
#include "Lazy.hpp"
#include "SecureHashStd.hpp"
namespace snarkfront {
////////////////////////////////////////////////////////////////////////////////
// SHA-256
//
template <typename T, typename MSG, typename U, typename F>
class SHA_256 : public SHA_Base<SHA_256<T, MSG, U, F>,
SHA_BlockSize::BLOCK_512,
MSG>
{
public:
typedef T WordType;
typedef U ByteType;
typedef std::array<T, 16> MsgType;
typedef std::array<T, 8> DigType;
typedef std::array<U, 16 * 4> PreType;
SHA_256() {
initConstants();
}
const std::array<T, 8>& digest() const {
return m_H;
}
virtual void initHashValue() {
// set initial hash value (NIST FIPS 180-4 section 5.3.3)
const std::array<std::uint32_t, 8> a {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 };
for (std::size_t i = 0; i < 8; ++i) {
m_H[i] = F::constant(a[i]);
}
}
void prepMsgSchedule(std::size_t& msgIndex) {
// prepare message schedule (NIST FIPS 180-4 section 6.2.2)
for (std::size_t i = 0; i < 16; ++i) {
m_W[i] = this->msgWord(msgIndex);
}
for (std::size_t i = 16; i < 64; ++i) {
//m_W[i] = F::sigma_256_1(m_W[i-2]) + m_W[i-7] + F::sigma_256_0(m_W[i-15]) + m_W[i-16];
m_W[i] = F::ADDMOD(F::ADDMOD(
F::ADDMOD(
F::sigma_256_1(m_W[i-2]),
m_W[i-7]),
F::sigma_256_0(m_W[i-15])),
m_W[i-16]);
}
}
void initWorkingVars() {
// initialize eight working variables (NIST FIPS 180-4 section 6.2.2)
m_a = m_H[0];
m_b = m_H[1];
m_c = m_H[2];
m_d = m_H[3];
m_e = m_H[4];
m_f = m_H[5];
m_g = m_H[6];
m_h = m_H[7];
}
void workingLoop() {
// inner loop (NIST FIPS 180-4 section 6.2.2)
for (std::size_t i = 0; i < 64; ++i) {
//m_T[0] = m_h + F::SIGMA_256_1(m_e) + F::Ch(m_e, m_f, m_g) + m_K[i] + m_W[i];
m_T[0] = F::ADDMOD(F::ADDMOD(
F::ADDMOD(
F::ADDMOD(m_h,
F::SIGMA_256_1(m_e)),
F::Ch(m_e, m_f, m_g)),
m_K[i]),
m_W[i]);
//m_T[1] = F::SIGMA_256_0(m_a) + F::Maj(m_a, m_b, m_c);
m_T[1] = F::ADDMOD(F::SIGMA_256_0(m_a),
F::Maj(m_a, m_b, m_c));
m_h = m_g;
m_g = m_f;
m_f = m_e;
//m_e = m_d + m_T[0];
m_e = F::ADDMOD(m_d, m_T[0]);
m_d = m_c;
m_c = m_b;
m_b = m_a;
//m_a = m_T[0] + m_T[1];
m_a = F::ADDMOD(m_T[0], m_T[1]);
}
}
void updateHash() {
// compute intermediate hash value (NIST FIPS 180-4 section 6.2.2)
//m_H[0] = m_H[0] + m_a;
//m_H[1] = m_H[1] + m_b;
//m_H[2] = m_H[2] + m_c;
//m_H[3] = m_H[3] + m_d;
//m_H[4] = m_H[4] + m_e;
//m_H[5] = m_H[5] + m_f;
//m_H[6] = m_H[6] + m_g;
//m_H[7] = m_H[7] + m_h;
m_H[0] = F::ADDMOD(m_H[0], m_a);
m_H[1] = F::ADDMOD(m_H[1], m_b);
m_H[2] = F::ADDMOD(m_H[2], m_c);
m_H[3] = F::ADDMOD(m_H[3], m_d);
m_H[4] = F::ADDMOD(m_H[4], m_e);
m_H[5] = F::ADDMOD(m_H[5], m_f);
m_H[6] = F::ADDMOD(m_H[6], m_g);
m_H[7] = F::ADDMOD(m_H[7], m_h);
}
virtual void afterHash() {
}
protected:
void initConstants() {
// set constants (NIST FIPS 180-4 section 4.2.2)
const std::array<std::uint32_t, 64> a {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 };
for (std::size_t i = 0; i < 64; ++i) {
m_K[i] = F::constant(a[i]);
}
}
// eight 32-bit working variables
T m_a, m_b, m_c, m_d, m_e, m_f, m_g, m_h;
// 64 constant 32-bit words
std::array<T, 64> m_K;
// message schedule of 64 32-bit words
std::array<T, 64> m_W;
// 256-bit hash value
std::array<T, 8> m_H;
// two temporary words
std::array<T, 2> m_T;
};
////////////////////////////////////////////////////////////////////////////////
// typedefs
//
namespace zk {
template <typename FR> using
SHA256 = SHA_256<AST_Var<Alg_uint32<FR>>,
Lazy<AST_Var<Alg_uint32<FR>>, std::uint32_t>,
AST_Var<Alg_uint8<FR>>,
SHA_Functions<AST_Node<Alg_uint32<FR>>,
AST_Op<Alg_uint32<FR>>,
BitwiseAST<Alg_uint32<FR>>>>;
} // namespace zk
namespace eval {
typedef SHA_256<std::uint32_t,
std::uint32_t,
std::uint8_t,
SHA_Functions<std::uint32_t,
std::uint32_t,
BitwiseINT<std::uint32_t>>>
SHA256;
} // namespace eval
} // namespace snarkfront
#endif
<|endoftext|> |
<commit_before>#include "SDBPShardConnection.h"
#include "SDBPClient.h"
#include "Application/Common/ClientResponse.h"
#include "Application/SDBP/SDBPRequestMessage.h"
#include "Application/SDBP/SDBPResponseMessage.h"
#define CONN_BUFSIZE 4096
#define CLIENT_MUTEX_GUARD_DECLARE() MutexGuard mutexGuard(client->mutex)
#define CLIENT_MUTEX_LOCK() mutexGuard.Lock()
#define CLIENT_MUTEX_UNLOCK() mutexGuard.Unlock()
using namespace SDBPClient;
static bool LessThan(uint64_t a, uint64_t b)
{
return a < b;
}
ShardConnection::ShardConnection(Client* client_, uint64_t nodeID_, Endpoint& endpoint_)
{
client = client_;
nodeID = nodeID_;
endpoint = endpoint_;
autoFlush = false;
isBulkSent = false;
Connect();
}
void ShardConnection::Connect()
{
// Log_Debug("Connecting to %s", endpoint.ToString());
MessageConnection::Connect(endpoint);
}
bool ShardConnection::SendRequest(Request* request)
{
SDBPRequestMessage msg;
if (!request->isBulk)
{
sentRequests.Append(request);
request->numTry++;
request->requestTime = EventLoop::Now();
}
msg.request = request;
Write(msg);
// if (request->numTry > 1)
// Log_Debug("Resending, commandID: %U, conn: %s", request->commandID, endpoint.ToString());
//Log_Debug("Sending conn: %s, writeBuffer = %B", endpoint.ToString(), writeBuffer);
// buffer is saturated
if (writeBuffer->GetLength() >= MESSAGING_BUFFER_THRESHOLD)
return false;
return true;
}
void ShardConnection::SendSubmit(uint64_t /*quorumID*/)
{
Flush();
}
void ShardConnection::Flush()
{
FlushWriteBuffer();
}
uint64_t ShardConnection::GetNodeID()
{
return nodeID;
}
Endpoint& ShardConnection::GetEndpoint()
{
return endpoint;
}
bool ShardConnection::IsWritePending()
{
return tcpwrite.active;
}
void ShardConnection::SetQuorumMembership(uint64_t quorumID)
{
// SortedList takes care of unique IDs
quorums.Add(quorumID, true);
}
void ShardConnection::ClearQuorumMembership(uint64_t quorumID)
{
quorums.Remove(quorumID);
}
void ShardConnection::ClearQuorumMemberships()
{
quorums.Clear();
}
SortedList<uint64_t>& ShardConnection::GetQuorumList()
{
return quorums;
}
bool ShardConnection::OnMessage(ReadBuffer& rbuf)
{
SDBPResponseMessage msg;
Request* request;
CLIENT_MUTEX_GUARD_DECLARE();
//Log_Debug("Shard conn: %s, message: %R", endpoint.ToString(), &rbuf);
response.Init();
msg.response = &response;
if (!msg.Read(rbuf))
return false;
// find the request in sent requests by commandID
FOREACH (request, sentRequests)
{
if (request->commandID == response.commandID)
{
// put back the request to the quorum queue and
// invalidate quorum state on NOSERVICE response
if (response.type == CLIENTRESPONSE_NOSERVICE)
{
sentRequests.Remove(request);
client->AddRequestToQuorum(request, true);
client->SendQuorumRequest(this, request->quorumID);
return false;
}
sentRequests.Remove(request);
break;
}
}
client->result->AppendRequestResponse(&response);
response.Init();
return false;
}
void ShardConnection::OnWrite()
{
CLIENT_MUTEX_GUARD_DECLARE();
MessageConnection::OnWrite();
if (client->IsBulkLoading() && !isBulkSent)
isBulkSent = true;
SendQuorumRequests();
}
void ShardConnection::OnConnect()
{
Log_Trace();
//Log_Debug("Shard connection connected, endpoint: %s", endpoint.ToString());
CLIENT_MUTEX_GUARD_DECLARE();
MessageConnection::OnConnect();
if (client->IsBulkLoading() && !isBulkSent)
{
SendBulkLoadingRequest();
return;
}
SendQuorumRequests();
}
void ShardConnection::OnClose()
{
// Log_Debug("Shard connection closing: %s", endpoint.ToString());
Request* it;
Request* prev;
uint64_t* itQuorum;
uint64_t* itNext;
CLIENT_MUTEX_GUARD_DECLARE();
isBulkSent = false;
// close the socket and try reconnecting
MessageConnection::OnClose();
// restart reconnection with timeout
EventLoop::Reset(&connectTimeout);
// invalidate quorums
for (itQuorum = quorums.First(); itQuorum != NULL; itQuorum = itNext)
{
itNext = quorums.Next(itQuorum);
InvalidateQuorum(*itQuorum);
}
// put back requests that have no response to the client's quorum queue
for (it = sentRequests.Last(); it != NULL; it = prev)
{
prev = sentRequests.Prev(it);
sentRequests.Remove(it);
client->AddRequestToQuorum(it, false);
}
}
void ShardConnection::InvalidateQuorum(uint64_t quorumID)
{
Request* it;
Request* prev;
for (it = sentRequests.Last(); it != NULL; it = prev)
{
prev = sentRequests.Prev(it);
if (it->quorumID == quorumID)
{
sentRequests.Remove(it);
client->AddRequestToQuorum(it, false);
}
}
client->InvalidateQuorum(quorumID, nodeID);
}
void ShardConnection::SendQuorumRequests()
{
uint64_t* qit;
// notify the client so that it can assign the requests to the connection
FOREACH (qit, quorums)
client->SendQuorumRequest(this, *qit);
}
void ShardConnection::SendBulkLoadingRequest()
{
Request req;
req.BulkLoading(0);
req.isBulk = true;
SendRequest(&req);
Flush();
}
<commit_msg>Changed client request resend mechanism.<commit_after>#include "SDBPShardConnection.h"
#include "SDBPClient.h"
#include "Application/Common/ClientResponse.h"
#include "Application/SDBP/SDBPRequestMessage.h"
#include "Application/SDBP/SDBPResponseMessage.h"
#define CONN_BUFSIZE 4096
#define CLIENT_MUTEX_GUARD_DECLARE() MutexGuard mutexGuard(client->mutex)
#define CLIENT_MUTEX_LOCK() mutexGuard.Lock()
#define CLIENT_MUTEX_UNLOCK() mutexGuard.Unlock()
using namespace SDBPClient;
static bool LessThan(uint64_t a, uint64_t b)
{
return a < b;
}
ShardConnection::ShardConnection(Client* client_, uint64_t nodeID_, Endpoint& endpoint_)
{
client = client_;
nodeID = nodeID_;
endpoint = endpoint_;
autoFlush = false;
isBulkSent = false;
Connect();
}
void ShardConnection::Connect()
{
// Log_Debug("Connecting to %s", endpoint.ToString());
MessageConnection::Connect(endpoint);
}
bool ShardConnection::SendRequest(Request* request)
{
SDBPRequestMessage msg;
if (!request->isBulk)
{
sentRequests.Append(request);
request->numTry++;
request->requestTime = EventLoop::Now();
}
msg.request = request;
Write(msg);
// if (request->numTry > 1)
// Log_Debug("Resending, commandID: %U, conn: %s", request->commandID, endpoint.ToString());
//Log_Debug("Sending conn: %s, writeBuffer = %B", endpoint.ToString(), writeBuffer);
// buffer is saturated
if (writeBuffer->GetLength() >= MESSAGING_BUFFER_THRESHOLD)
return false;
return true;
}
void ShardConnection::SendSubmit(uint64_t /*quorumID*/)
{
Flush();
}
void ShardConnection::Flush()
{
FlushWriteBuffer();
}
uint64_t ShardConnection::GetNodeID()
{
return nodeID;
}
Endpoint& ShardConnection::GetEndpoint()
{
return endpoint;
}
bool ShardConnection::IsWritePending()
{
return tcpwrite.active;
}
void ShardConnection::SetQuorumMembership(uint64_t quorumID)
{
// SortedList takes care of unique IDs
quorums.Add(quorumID, true);
}
void ShardConnection::ClearQuorumMembership(uint64_t quorumID)
{
quorums.Remove(quorumID);
}
void ShardConnection::ClearQuorumMemberships()
{
quorums.Clear();
}
SortedList<uint64_t>& ShardConnection::GetQuorumList()
{
return quorums;
}
bool ShardConnection::OnMessage(ReadBuffer& rbuf)
{
SDBPResponseMessage msg;
Request* request;
CLIENT_MUTEX_GUARD_DECLARE();
//Log_Debug("Shard conn: %s, message: %R", endpoint.ToString(), &rbuf);
response.Init();
msg.response = &response;
if (!msg.Read(rbuf))
return false;
// find the request in sent requests by commandID
FOREACH (request, sentRequests)
{
if (request->commandID == response.commandID)
{
sentRequests.Remove(request);
// put back the request to the quorum queue
// on next config state response the client
// will reconfigure the quorums and will resend
// the requests
if (response.type == CLIENTRESPONSE_NOSERVICE)
{
client->AddRequestToQuorum(request, true);
return false;
}
break;
}
}
client->result->AppendRequestResponse(&response);
response.Init();
return false;
}
void ShardConnection::OnWrite()
{
CLIENT_MUTEX_GUARD_DECLARE();
MessageConnection::OnWrite();
if (client->IsBulkLoading() && !isBulkSent)
isBulkSent = true;
SendQuorumRequests();
}
void ShardConnection::OnConnect()
{
Log_Trace();
//Log_Debug("Shard connection connected, endpoint: %s", endpoint.ToString());
CLIENT_MUTEX_GUARD_DECLARE();
MessageConnection::OnConnect();
if (client->IsBulkLoading() && !isBulkSent)
{
SendBulkLoadingRequest();
return;
}
SendQuorumRequests();
}
void ShardConnection::OnClose()
{
// Log_Debug("Shard connection closing: %s", endpoint.ToString());
Request* it;
Request* prev;
uint64_t* itQuorum;
uint64_t* itNext;
CLIENT_MUTEX_GUARD_DECLARE();
isBulkSent = false;
// close the socket and try reconnecting
MessageConnection::OnClose();
// restart reconnection with timeout
EventLoop::Reset(&connectTimeout);
// invalidate quorums
for (itQuorum = quorums.First(); itQuorum != NULL; itQuorum = itNext)
{
itNext = quorums.Next(itQuorum);
InvalidateQuorum(*itQuorum);
}
// put back requests that have no response to the client's quorum queue
for (it = sentRequests.Last(); it != NULL; it = prev)
{
prev = sentRequests.Prev(it);
sentRequests.Remove(it);
client->AddRequestToQuorum(it, false);
}
}
void ShardConnection::InvalidateQuorum(uint64_t quorumID)
{
Request* it;
Request* prev;
for (it = sentRequests.Last(); it != NULL; it = prev)
{
prev = sentRequests.Prev(it);
if (it->quorumID == quorumID)
{
sentRequests.Remove(it);
client->AddRequestToQuorum(it, false);
}
}
client->InvalidateQuorum(quorumID, nodeID);
}
void ShardConnection::SendQuorumRequests()
{
uint64_t* qit;
// notify the client so that it can assign the requests to the connection
FOREACH (qit, quorums)
client->SendQuorumRequest(this, *qit);
}
void ShardConnection::SendBulkLoadingRequest()
{
Request req;
req.BulkLoading(0);
req.isBulk = true;
SendRequest(&req);
Flush();
}
<|endoftext|> |
<commit_before>#include "SysControl.h"
#include "ControlsApp.h"
#include "ControlsXPad360.h"
#include "Engine.h"
#include "App.h"
#include "Engine.h"
#include "App.h"
#include "Input.h"
#include "ObjectGui.h"
#include "WidgetLabel.h"
//解决跨平台字符集兼容问题
#ifdef _WIN32
#pragma execution_character_set("utf-8")
#endif
using namespace MathLib;
class CSysControlLocal : public CSysControl
{
public:
CSysControlLocal();
virtual ~CSysControlLocal();
virtual void Init(); //角色要初始化,着色器要初始化,
virtual void Update(float ifps);
virtual void Shutdown();
virtual int GetState(int state); //鼠标状态,键盘状态,人物状态,子弹状态等等。
virtual int ClearState(int state);
virtual float GetMouseDX();
virtual float GetMouseDY();
virtual void SetMouseGrab(int g); //设置是否显示鼠标
virtual int GetMouseGrab(); //获取鼠标状态,是显示呢还是不显示的状态。
virtual void SetControlMode(ControlMode mode); //控制模式
virtual ControlMode GetControlMode() const; //获取控制模式
private:
void Update_Mouse(float ifps);
void Update_Keyboard(float ifps);
void Update_XPad360(float ifps);
CControlsApp *m_pControlsApp; //控制游戏中移动
CControlsXPad360 *m_pControlsXPad360;
ControlMode m_nControlMode; //控制模式
int m_nOldMouseX; //上一个鼠标坐标X
int m_nOldMouseY; //上一个鼠标坐标Y
CObjectGui *m_pTest3DUI;
CWidgetLabel *m_pTestMessageLabel;
};
CSysControlLocal::CSysControlLocal()
{
}
CSysControlLocal::~CSysControlLocal()
{
}
void CSysControlLocal::Init()
{
m_pControlsApp = new CControlsApp;
m_pControlsXPad360 = new CControlsXPad360(0);
g_Engine.pApp->SetMouseGrab(0);
g_Engine.pApp->SetMouseShow(0);
SetControlMode(CONTROL_KEYBORAD_MOUSE);
m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/");
m_pTest3DUI->SetMouseShow(0);
m_pTest3DUI->SetBackground(1);
m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));
m_pTest3DUI->SetScreenSize(800, 400);
m_pTest3DUI->SetControlDistance(1000.0f);
m_pTest3DUI->CreateMaterial("gui_base"); //show in game
m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));
m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签
m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));
m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签
m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));
m_pTestMessageLabel->SetFontSize(80); //设置字体大小
m_pTestMessageLabel->SetFontOutline(1); //设置字体轮廓
m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船");
void CSysControlLocal::Update(float ifps)
{
Update_Mouse(ifps);
Update_Keyboard(ifps);
Update_XPad360(ifps);
}
m_nOldMouseX = 0;
m_nOldMouseY = 0;
}
void CSysControlLocal::Shutdown()
{
g_Engine.pApp->SetMouseGrab(0);
g_Engine.pApp->SetMouseShow(0);
delete m_pControlsApp;
m_pControlsApp = NULL;
delete m_pControlsXPad360;
m_pControlsXPad360 = NULL;
delete m_pTestMessageLabel;
m_pTestMessageLabel = NULL;
delete m_pTest3DUI;
m_pTest3DUI = NULL;
}
int CSysControlLocal::GetState(int state)
{
return m_pControlsApp->GetState(state);
}
int CSysControlLocal::ClearState(int state)
{
return m_pControlsApp->ClearState(state);
}
float CSysControlLocal::GetMouseDX()
{
return m_pControlsApp->GetMouseDX();
}
float CSysControlLocal::GetMouseDY()
{
return m_pControlsApp->GetMouseDY();
}
void CSysControlLocal::SetMouseGrab(int g)
{
g_Engine.pApp->SetMouseGrab(g);
g_Engine.pGui->SetMouseShow(!g);
}
int CSysControlLocal::GetMouseGrab()
{
return g_Engine.pApp->GetMouseGrab();
}
void CSysControlLocal::SetControlMode(ControlMode mode)
{
m_nControlMode = mode;
}
CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
return m_nControlMode;
}
CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
return m_nControlMode;
}
void CSysControlLocal::Update_Mouse(float ifps)
{
float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大,鼠标移动越快
float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小,鼠标移动越慢
m_pControlsApp->SetMouseDX(dx);
m_pControlsApp->SetMouseDY(dy);
if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())
{
g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2);
}
m_nOldMouseX = g_Engine.pApp->GetMouseX();
m_nOldMouseY = g_Engine.pApp->GetMouseY();
}
void CSysControlLocal::Update_Keyboard(float ifps) //键盘按键响应wsad
{
if (g_Engine.pInput->IsKeyDown('w'))
m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
if (g_Engine.pInput->IsKeyDown('s'))
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
if (g_Engine.pInput->IsKeyDown('a'))
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
if (g_Engine.pInput->IsKeyDown('d'))
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);
if (g_Engine.pInput->IsKeyUp('w'))
m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
else if (g_Engine.pInput->IsKeyUp('s'))
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);
if (g_Engine.pInput->IsKeyUp('a'))
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
else if (g_Engine.pInput->IsKeyUp('d'))
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
if (g_Engine.pInput->IsKeyDown(' ')) //空格跳跃
m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
else
m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
}
void CSysControlLocal::Update_XPad360(float ifps)
{
m_pControlsXPad360->UpdateEvents();
CUtilStr strMessage;
strMessage = CUtilStr("测试3D UI\n"),
strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n";
strMessage += CUtilStr::Format("\n手柄测试\n");
strMessage += CUtilStr::Format("LeftX: %5.2f\n", m_pControlsXPad360->GetLeftX());
strMessage += CUtilStr::Format("LeftY: %5.2f\n", m_pControlsXPad360->GetLeftY());
strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX());
strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY());
strMessage += "\nTriggers:\n";
strMessage += CUtilStr::Format("Left: %5.2f\n", m_pControlsXPad360->GetLeftTrigger());
strMessage += CUtilStr::Format("Right: %5.2f\n", m_pControlsXPad360->GetRightTrigger());
strMessage += CUtilStr::Format("\nButtons:\n");
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "SysControl.h"
#include "ControlsApp.h"
#include "ControlsXPad360.h"
#include "Engine.h"
#include "App.h"
#include "Engine.h"
#include "App.h"
#include "Input.h"
#include "ObjectGui.h"
#include "WidgetLabel.h"
//解决跨平台字符集兼容问题
#ifdef _WIN32
#pragma execution_character_set("utf-8")
#endif
using namespace MathLib;
class CSysControlLocal : public CSysControl
{
public:
CSysControlLocal();
virtual ~CSysControlLocal();
virtual void Init(); //角色要初始化,着色器要初始化,
virtual void Update(float ifps);
virtual void Shutdown();
virtual int GetState(int state); //鼠标状态,键盘状态,人物状态,子弹状态等等。
virtual int ClearState(int state);
virtual float GetMouseDX();
virtual float GetMouseDY();
virtual void SetMouseGrab(int g); //设置是否显示鼠标
virtual int GetMouseGrab(); //获取鼠标状态,是显示呢还是不显示的状态。
virtual void SetControlMode(ControlMode mode); //控制模式
virtual ControlMode GetControlMode() const; //获取控制模式
private:
void Update_Mouse(float ifps);
void Update_Keyboard(float ifps);
void Update_XPad360(float ifps);
CControlsApp *m_pControlsApp; //控制游戏中移动
CControlsXPad360 *m_pControlsXPad360;
ControlMode m_nControlMode; //控制模式
int m_nOldMouseX; //上一个鼠标坐标X
int m_nOldMouseY; //上一个鼠标坐标Y
CObjectGui *m_pTest3DUI;
CWidgetLabel *m_pTestMessageLabel;
};
CSysControlLocal::CSysControlLocal()
{
}
CSysControlLocal::~CSysControlLocal()
{
}
void CSysControlLocal::Init()
{
m_pControlsApp = new CControlsApp;
m_pControlsXPad360 = new CControlsXPad360(0);
g_Engine.pApp->SetMouseGrab(0);
g_Engine.pApp->SetMouseShow(0);
SetControlMode(CONTROL_KEYBORAD_MOUSE);
m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/");
m_pTest3DUI->SetMouseShow(0);
m_pTest3DUI->SetBackground(1);
m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));
m_pTest3DUI->SetScreenSize(800, 400);
m_pTest3DUI->SetControlDistance(1000.0f);
m_pTest3DUI->CreateMaterial("gui_base"); //show in game
m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));
m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签
m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));
m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签
m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));
m_pTestMessageLabel->SetFontSize(80); //设置字体大小
m_pTestMessageLabel->SetFontOutline(1); //设置字体轮廓
m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船");
void CSysControlLocal::Update(float ifps)
{
Update_Mouse(ifps);
Update_Keyboard(ifps);
Update_XPad360(ifps);
}
m_nOldMouseX = 0;
m_nOldMouseY = 0;
}
void CSysControlLocal::Shutdown()
{
g_Engine.pApp->SetMouseGrab(0);
g_Engine.pApp->SetMouseShow(0);
delete m_pControlsApp;
m_pControlsApp = NULL;
delete m_pControlsXPad360;
m_pControlsXPad360 = NULL;
delete m_pTestMessageLabel;
m_pTestMessageLabel = NULL;
delete m_pTest3DUI;
m_pTest3DUI = NULL;
}
int CSysControlLocal::GetState(int state)
{
return m_pControlsApp->GetState(state);
}
int CSysControlLocal::ClearState(int state)
{
return m_pControlsApp->ClearState(state);
}
float CSysControlLocal::GetMouseDX()
{
return m_pControlsApp->GetMouseDX();
}
float CSysControlLocal::GetMouseDY()
{
return m_pControlsApp->GetMouseDY();
}
void CSysControlLocal::SetMouseGrab(int g)
{
g_Engine.pApp->SetMouseGrab(g);
g_Engine.pGui->SetMouseShow(!g);
}
int CSysControlLocal::GetMouseGrab()
{
return g_Engine.pApp->GetMouseGrab();
}
void CSysControlLocal::SetControlMode(ControlMode mode)
{
m_nControlMode = mode;
}
CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
return m_nControlMode;
}
CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
return m_nControlMode;
}
void CSysControlLocal::Update_Mouse(float ifps)
{
float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大,鼠标移动越快
float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小,鼠标移动越慢
m_pControlsApp->SetMouseDX(dx);
m_pControlsApp->SetMouseDY(dy);
if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())
{
g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2);
}
m_nOldMouseX = g_Engine.pApp->GetMouseX();
m_nOldMouseY = g_Engine.pApp->GetMouseY();
}
void CSysControlLocal::Update_Keyboard(float ifps) //键盘按键响应wsad
{
if (g_Engine.pInput->IsKeyDown('w'))
m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
if (g_Engine.pInput->IsKeyDown('s'))
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
if (g_Engine.pInput->IsKeyDown('a'))
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
if (g_Engine.pInput->IsKeyDown('d'))
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);
if (g_Engine.pInput->IsKeyUp('w'))
m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
else if (g_Engine.pInput->IsKeyUp('s'))
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);
if (g_Engine.pInput->IsKeyUp('a'))
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
else if (g_Engine.pInput->IsKeyUp('d'))
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
if (g_Engine.pInput->IsKeyDown(' ')) //空格跳跃
m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
else
m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
}
void CSysControlLocal::Update_XPad360(float ifps)
{
m_pControlsXPad360->UpdateEvents();
CUtilStr strMessage;
strMessage = CUtilStr("测试3D UI\n"),
strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n";
strMessage += CUtilStr::Format("\n手柄测试\n");
strMessage += CUtilStr::Format("LeftX: %5.2f\n", m_pControlsXPad360->GetLeftX());
strMessage += CUtilStr::Format("LeftY: %5.2f\n", m_pControlsXPad360->GetLeftY());
strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX());
strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY());
strMessage += "\nTriggers:\n";
strMessage += CUtilStr::Format("Left: %5.2f\n", m_pControlsXPad360->GetLeftTrigger());
strMessage += CUtilStr::Format("Right: %5.2f\n", m_pControlsXPad360->GetRightTrigger());
strMessage += CUtilStr::Format("\nButtons:\n");
for (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i)
{
strMessage += CUtilStr::Format("%d ", m_pControlsXPad360->GetButton(i));
}
}<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "instance_intersector1.h"
namespace embree
{
namespace isa
{
void InstanceBoundsFunction(void* userPtr, const Instance* instance, size_t item, BBox3fa* bounds_o)
{
Vec3fa lower = instance->object->bounds.lower;
Vec3fa upper = instance->object->bounds.upper;
AffineSpace3fa local2world = instance->local2world;
Vec3fa p000 = xfmPoint(local2world,Vec3fa(lower.x,lower.y,lower.z));
Vec3fa p001 = xfmPoint(local2world,Vec3fa(lower.x,lower.y,upper.z));
Vec3fa p010 = xfmPoint(local2world,Vec3fa(lower.x,upper.y,lower.z));
Vec3fa p011 = xfmPoint(local2world,Vec3fa(lower.x,upper.y,upper.z));
Vec3fa p100 = xfmPoint(local2world,Vec3fa(upper.x,lower.y,lower.z));
Vec3fa p101 = xfmPoint(local2world,Vec3fa(upper.x,lower.y,upper.z));
Vec3fa p110 = xfmPoint(local2world,Vec3fa(upper.x,upper.y,lower.z));
Vec3fa p111 = xfmPoint(local2world,Vec3fa(upper.x,upper.y,upper.z));
bounds_o->lower = min(min(min(p000,p001),min(p010,p011)),min(min(p100,p101),min(p110,p111)));
bounds_o->upper = max(max(max(p000,p001),max(p010,p011)),max(max(p100,p101),max(p110,p111)));
}
RTCBoundsFunc2 InstanceBoundsFunc = (RTCBoundsFunc2) InstanceBoundsFunction;
void FastInstanceIntersector1::intersect(const Instance* instance, Ray& ray, size_t item)
{
const Vec3fa ray_org = ray.org;
const Vec3fa ray_dir = ray.dir;
const int ray_geomID = ray.geomID;
const int ray_instID = ray.instID;
ray.org = xfmPoint (instance->world2local,ray_org);
ray.dir = xfmVector(instance->world2local,ray_dir);
ray.geomID = -1;
ray.instID = instance->id;
instance->object->intersect((RTCRay&)ray);
ray.org = ray_org;
ray.dir = ray_dir;
if (ray.geomID == -1) {
ray.geomID = ray_geomID;
ray.instID = ray_instID;
}
}
void FastInstanceIntersector1::occluded (const Instance* instance, Ray& ray, size_t item)
{
const Vec3fa ray_org = ray.org;
const Vec3fa ray_dir = ray.dir;
ray.org = xfmPoint (instance->world2local,ray_org);
ray.dir = xfmVector(instance->world2local,ray_dir);
ray.instID = instance->id;
instance->object->occluded((RTCRay&)ray);
ray.org = ray_org;
ray.dir = ray_dir;
}
DEFINE_SET_INTERSECTOR1(InstanceIntersector1,FastInstanceIntersector1);
}
}
<commit_msg>using xfmBounds function in InstanceBoundsFunction<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "instance_intersector1.h"
namespace embree
{
namespace isa
{
void InstanceBoundsFunction(void* userPtr, const Instance* instance, size_t item, BBox3fa* bounds_o) {
*bounds_o = xfmBounds(instance->local2world,instance->object->bounds);
}
RTCBoundsFunc2 InstanceBoundsFunc = (RTCBoundsFunc2) InstanceBoundsFunction;
void FastInstanceIntersector1::intersect(const Instance* instance, Ray& ray, size_t item)
{
const Vec3fa ray_org = ray.org;
const Vec3fa ray_dir = ray.dir;
const int ray_geomID = ray.geomID;
const int ray_instID = ray.instID;
ray.org = xfmPoint (instance->world2local,ray_org);
ray.dir = xfmVector(instance->world2local,ray_dir);
ray.geomID = -1;
ray.instID = instance->id;
instance->object->intersect((RTCRay&)ray);
ray.org = ray_org;
ray.dir = ray_dir;
if (ray.geomID == -1) {
ray.geomID = ray_geomID;
ray.instID = ray_instID;
}
}
void FastInstanceIntersector1::occluded (const Instance* instance, Ray& ray, size_t item)
{
const Vec3fa ray_org = ray.org;
const Vec3fa ray_dir = ray.dir;
ray.org = xfmPoint (instance->world2local,ray_org);
ray.dir = xfmVector(instance->world2local,ray_dir);
ray.instID = instance->id;
instance->object->occluded((RTCRay&)ray);
ray.org = ray_org;
ray.dir = ray_dir;
}
DEFINE_SET_INTERSECTOR1(InstanceIntersector1,FastInstanceIntersector1);
}
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <stdlib.h>
#include <stdio.h>
#include "Utility/Env.h"
#include "Utility/BookKeeper.h"
#include "Utility/Table.h"
class BookKeeperTest : public ::testing::Test {
protected:
// some test strings
file_path fpath;
std::string test_filename;
table_ptr test_table;
// this sets up the fixtures
virtual void SetUp() {
BI->turnLoggingOn();
fpath = Env::getCyclusPath() + "/Testing/Temporary";
test_filename = "testBK.sqlite";
table_ptr test_table = new Table("test_tbl");
};
// this tears down the fixtures
virtual void TearDown() {
if ( BI->dbIsOpen() ) {
BI->closeDB();
}
BI->turnLoggingOff();
};
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(BookKeeperTest, createDB) {
EXPECT_NO_THROW( BI->createDB(test_filename,fpath) );
EXPECT_EQ( BI->dbExists(), true );
EXPECT_EQ( BI->dbName(), test_filename );
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(BookKeeperTest, openDB) {
EXPECT_NO_THROW( BI->openDB() );
EXPECT_EQ( BI->dbIsOpen(), true );
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(BookKeeperTest, closeDB) {
EXPECT_NO_THROW( BI->openDB() );
EXPECT_EQ( BI->dbIsOpen(), true );
EXPECT_NO_THROW( BI->closeDB() );
EXPECT_EQ( BI->dbIsOpen(), false );
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(BookKeeperTest, loggingOnOff){
BI->turnLoggingOn();
EXPECT_EQ( BI->loggingIsOn(), true );
EXPECT_NO_THROW( BI->turnLoggingOff() );
EXPECT_EQ( BI->loggingIsOn(), false );
BI->turnLoggingOn();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(BookKeeperTest, tableTests){
EXPECT_NO_THROW( BI->registerTable(test_table) );
EXPECT_EQ( BI->nTables(), 1 );
EXPECT_NO_THROW( BI->tableAtThreshold(test_table) );
EXPECT_NO_THROW( BI->removeTable(test_table) );
EXPECT_EQ( BI->nTables(), 0 );
}
<commit_msg>Fixed failing BookKeeperTests, caused by re-structuring of cyclus executable. Needed build path rather than cyclus path .<commit_after>#include <gtest/gtest.h>
#include <stdlib.h>
#include <stdio.h>
#include "Utility/Env.h"
#include "Utility/BookKeeper.h"
#include "Utility/Table.h"
class BookKeeperTest : public ::testing::Test {
protected:
// some test strings
file_path fpath;
std::string test_filename;
table_ptr test_table;
// this sets up the fixtures
virtual void SetUp() {
BI->turnLoggingOn();
fpath = Env::getBuildPath() + "/Testing/Temporary";
test_filename = "testBK.sqlite";
table_ptr test_table = new Table("test_tbl");
};
// this tears down the fixtures
virtual void TearDown() {
if ( BI->dbIsOpen() ) {
BI->closeDB();
}
BI->turnLoggingOff();
};
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(BookKeeperTest, createDB) {
EXPECT_NO_THROW( BI->createDB(test_filename,fpath) );
EXPECT_EQ( BI->dbExists(), true );
EXPECT_EQ( BI->dbName(), test_filename );
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(BookKeeperTest, openDB) {
EXPECT_NO_THROW( BI->openDB() );
EXPECT_EQ( BI->dbIsOpen(), true );
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(BookKeeperTest, closeDB) {
EXPECT_NO_THROW( BI->openDB() );
EXPECT_EQ( BI->dbIsOpen(), true );
EXPECT_NO_THROW( BI->closeDB() );
EXPECT_EQ( BI->dbIsOpen(), false );
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(BookKeeperTest, loggingOnOff){
BI->turnLoggingOn();
EXPECT_EQ( BI->loggingIsOn(), true );
EXPECT_NO_THROW( BI->turnLoggingOff() );
EXPECT_EQ( BI->loggingIsOn(), false );
BI->turnLoggingOn();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(BookKeeperTest, tableTests){
EXPECT_NO_THROW( BI->registerTable(test_table) );
EXPECT_EQ( BI->nTables(), 1 );
EXPECT_NO_THROW( BI->tableAtThreshold(test_table) );
EXPECT_NO_THROW( BI->removeTable(test_table) );
EXPECT_EQ( BI->nTables(), 0 );
}
<|endoftext|> |
<commit_before>// Do not remove the include below
#include "LCD_Experiments.h"
/*
SainSmart 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:
ST7735(uint8_t CS, uint8_t RS, uint8_t SID,
uint8_t SCLK, uint8_t RST);
ST7735(uint8_t CS, uint8_t RS, uint8_t RST);
Description
The base class for drawing to the ST7735. Use this to create a named
instance of the ST7735 class to refer to in your sketch.
Syntax
ST7735(cs, dc, rst); for using hardware SPI
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
ST7735 myScreen = 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 ;
ST7735 lcd = ST7735(CS, DC, RESET);
GLBall ball=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.
//
//The setup function is called once at startup of the sketch
void setup()
{
// Add your initialization code here
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) ;
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(2000) ;
clearScreen(lcd) ;
//
// Set up ball parameters
//
ball.setBallColor(CYAN)
.setTrailColor(YELLOW)
.begin() ;
}
// The loop function is called in an endless loop
void loop()
{
//Add your repeated code here
//
// Knowing when it is time to switch trail colors
//
int xVelPrevious = ball.getXVel() ;
if (ball.update()) {
int xVelCurrent = ball.getXVel() ;
if (xVelCurrent == -xVelPrevious) {
xBouncesRemaining-- ;
}
if (xBouncesRemaining==0) {
ball.setTrailColor(~ball.getTrailColor()) ;
ball.setBallColor(~ball.getBallColor()) ;
xBouncesRemaining=xBouncesToRepeat ;
}
}
}
void clearScreen(ST7735 obj) {
obj.fillRect(0, 0, lcd.width, lcd.height, BLACK); // Clear screen.
}
<commit_msg>Modified to bounce 3 balls of various sizes, initial positions, colors, trail colors, and directions simultaneously.<commit_after>// Do not remove the include below
#include "LCD_Experiments.h"
/*
SainSmart 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:
ST7735(uint8_t CS, uint8_t RS, uint8_t SID,
uint8_t SCLK, uint8_t RST);
ST7735(uint8_t CS, uint8_t RS, uint8_t RST);
Description
The base class for drawing to the ST7735. Use this to create a named
instance of the ST7735 class to refer to in your sketch.
Syntax
ST7735(cs, dc, rst); for using hardware SPI
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
ST7735 myScreen = 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 ;
ST7735 lcd = 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.
//
//The setup function is called once at startup of the sketch
void setup()
{
// Add your initialization code here
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) ;
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) ;
//
// 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(PURPLE)
.setTrailColor(GREEN)
.setRadius(8)
.setXCurrent(50)
.setYCurrent(ball[2].getRadius())
.setXVel(-ball[2].getXVel())
.begin() ;
}
// The loop function is called in an endless loop
void loop() {
//Add your repeated code here
//
// 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(ST7735 obj) {
obj.fillRect(0, 0, lcd.width, lcd.height, BLACK); // Clear screen.
}
<|endoftext|> |
<commit_before>#include "src/input.h"
#include <conio.h>
#include <memory.h>
static uint16_t keys[0x81];
// faster keyhit detector than kbhit()
const uint16_t *kbd_getInput()
{
uint8_t key = '\0';
// get last key
_asm {
in al, 60h
mov key, al
in al, 61h
mov ah, al
or al, 80h
out 61h, al
xchg ah, al
out 61h, al
mov al, 20h
out 20h, al
}
if (key >= 0x80) keys[key - 0x80] = 0;
if (key < 0x80) keys[key] = 1;
return &keys[0];
}
void kbd_flush()
{
memset(keys, 0, sizeof(uint16_t) * 0x81);
}
<commit_msg>flush keyboard buffer after fetch (prevents outputting contents after program termination)<commit_after>#include "src/input.h"
#include <conio.h>
#include <memory.h>
static uint16_t keys[0x81];
// faster keyhit detector than kbhit()
const uint16_t *kbd_getInput()
{
uint8_t key = '\0';
// get last key and flush keyboard buffer
_asm {
in al, 60h
mov key, al
in al, 61h
mov ah, al
or al, 80h
out 61h, al
xchg ah, al
out 61h, al
mov al, 20h
out 20h, al
mov ah, 0Ch
mov al, 0h
int 21h
}
if (key >= 0x80) keys[key - 0x80] = 0;
if (key < 0x80) keys[key] = 1;
return &keys[0];
}
void kbd_flush()
{
memset(keys, 0, sizeof(uint16_t) * 0x81);
}
<|endoftext|> |
<commit_before>#ifndef itkNeighborhoodFunctorImageFilter_cpp
#define itkNeighborhoodFunctorImageFilter_cpp
#include "itkNeighborhoodFunctorImageFilter.h"
#include "itkNeighborhoodAlgorithm.h"
#include <itkVectorImageToImageAdaptor.h>
namespace itk
{
template< typename TInputImage, typename TFeatureImageType , class FunctorType>
void
NeighborhoodFunctorImageFilter< TInputImage, TFeatureImageType, FunctorType >
::BeforeThreadedGenerateData()
{
const TInputImage * input = this->GetInput(0);
for(unsigned int i = 0 ; i < FunctorType::OutputCount; i ++)
{
typename FeatureImageType::Pointer output = TFeatureImageType::New();
output->SetRegions(input->GetLargestPossibleRegion());
output->SetSpacing(input->GetSpacing());
output->SetOrigin(input->GetOrigin());
output->SetDirection(input->GetDirection());
output->Allocate();
this->SetNthOutput( i, output.GetPointer() );
}
if(m_MaskImage.IsNull())
{
m_MaskImage = MaskImageType::New();
m_MaskImage->SetRegions(input->GetLargestPossibleRegion());
m_MaskImage->Allocate();
m_MaskImage->FillBuffer(1);
}
}
template< typename TInputImage, typename TFeatureImageType , class FunctorType>
void
NeighborhoodFunctorImageFilter< TInputImage, TFeatureImageType, FunctorType >
::GenerateInputRequestedRegion()
{
// call the superclass' implementation of this method. this should
// copy the output requested region to the input requested region
Superclass::GenerateInputRequestedRegion();
// get pointers to the input and output
TInputImage * inputPtr = this->GetInput();
if ( !inputPtr )
{
return;
}
// get a copy of the input requested region (should equal the output
// requested region)
typename TInputImage::RegionType inputRequestedRegion;
inputRequestedRegion = inputPtr->GetRequestedRegion();
// pad the input requested region by the operator radius
inputRequestedRegion.PadByRadius( m_Size );
// crop the input requested region at the input's largest possible region
if ( inputRequestedRegion.Crop( inputPtr->GetLargestPossibleRegion() ) )
{
inputPtr->SetRequestedRegion(inputRequestedRegion);
return;
}
else
{
// Couldn't crop the region (requested region is outside the largest
// possible region). Throw an exception.
// store what we tried to request (prior to trying to crop)
inputPtr->SetRequestedRegion(inputRequestedRegion);
// build an exception
InvalidRequestedRegionError e(__FILE__, __LINE__);
e.SetLocation(ITK_LOCATION);
e.SetDescription("Requested region is (at least partially) outside the largest possible region.");
e.SetDataObject(inputPtr);
throw e;
}
}
template< typename TInputImage, typename TFeatureImageType, class FunctorType >
void
NeighborhoodFunctorImageFilter< TInputImage, TFeatureImageType, FunctorType >
::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread,
ThreadIdType /*threadId*/)
{
typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< InputImageType > BFC;
typedef typename BFC::FaceListType FaceListType;
BFC faceCalculator;
FaceListType faceList;
// Allocate output
const InputImageType *input = this->GetInput();
// Break the input into a series of regions. The first region is free
// of boundary conditions, the rest with boundary conditions. Note,
// we pass in the input image and the OUTPUT requested region. We are
// only concerned with centering the neighborhood operator at the
// pixels that correspond to output pixels.
faceList = faceCalculator( input, outputRegionForThread, m_Size );
typename FaceListType::iterator fit;
ImageRegionConstIterator< MaskImageType > mit;
// Process non-boundary region and each of the boundary faces.
// These are N-d regions which border the edge of the buffer.
ConstNeighborhoodIterator< InputImageType > bit;
// for ( fit = faceList.begin(); fit != faceList.end(); ++fit )
// {
bit = ConstNeighborhoodIterator< InputImageType >(m_Size, input, outputRegionForThread);
mit = ImageRegionConstIterator< MaskImageType >(m_MaskImage, outputRegionForThread);
std::vector<ImageRegionIterator< FeatureImageType > > featureImageIterators;
for(unsigned int i = 0; i < FunctorType::OutputCount; i++)
{
featureImageIterators.push_back(ImageRegionIterator< FeatureImageType >(this->GetOutput(i), outputRegionForThread));
featureImageIterators[i].GoToBegin();
}
mit.GoToBegin();
bit.GoToBegin();
while ( !bit.IsAtEnd() || !mit.IsAtEnd() )
{
if(mit.Value() != 0)
{
//bit.GetNeighborhood().Print(std::cout);
typename FunctorType::OutputVectorType features = ( m_Functor( bit ) );
for(unsigned int i = 0 ; i < FunctorType::OutputCount; i++)
featureImageIterators[i].Set(features[i]);
}
for(unsigned int i = 0 ; i < FunctorType::OutputCount; i++)
++featureImageIterators[i];
++bit;
++mit;
}
// }
std::cout << "Thread done!" << std::endl;
}
} // end namespace itk
#endif //itkNeighborhoodFunctorImageFilter_cpp
<commit_msg>Add const cast<commit_after>#ifndef itkNeighborhoodFunctorImageFilter_cpp
#define itkNeighborhoodFunctorImageFilter_cpp
#include "itkNeighborhoodFunctorImageFilter.h"
#include "itkNeighborhoodAlgorithm.h"
#include <itkVectorImageToImageAdaptor.h>
namespace itk
{
template< typename TInputImage, typename TFeatureImageType , class FunctorType>
void
NeighborhoodFunctorImageFilter< TInputImage, TFeatureImageType, FunctorType >
::BeforeThreadedGenerateData()
{
const TInputImage * input = this->GetInput(0);
for(unsigned int i = 0 ; i < FunctorType::OutputCount; i ++)
{
typename FeatureImageType::Pointer output = TFeatureImageType::New();
output->SetRegions(input->GetLargestPossibleRegion());
output->SetSpacing(input->GetSpacing());
output->SetOrigin(input->GetOrigin());
output->SetDirection(input->GetDirection());
output->Allocate();
this->SetNthOutput( i, output.GetPointer() );
}
if(m_MaskImage.IsNull())
{
m_MaskImage = MaskImageType::New();
m_MaskImage->SetRegions(input->GetLargestPossibleRegion());
m_MaskImage->Allocate();
m_MaskImage->FillBuffer(1);
}
}
template< typename TInputImage, typename TFeatureImageType , class FunctorType>
void
NeighborhoodFunctorImageFilter< TInputImage, TFeatureImageType, FunctorType >
::GenerateInputRequestedRegion()
{
// call the superclass' implementation of this method. this should
// copy the output requested region to the input requested region
Superclass::GenerateInputRequestedRegion();
// get pointers to the input and output
auto inputPtr = const_cast<InputImageType *>(this->GetInput());
if ( !inputPtr )
{
return;
}
// get a copy of the input requested region (should equal the output
// requested region)
typename TInputImage::RegionType inputRequestedRegion;
inputRequestedRegion = inputPtr->GetRequestedRegion();
// pad the input requested region by the operator radius
inputRequestedRegion.PadByRadius( m_Size );
// crop the input requested region at the input's largest possible region
if ( inputRequestedRegion.Crop( inputPtr->GetLargestPossibleRegion() ) )
{
inputPtr->SetRequestedRegion(inputRequestedRegion);
return;
}
else
{
// Couldn't crop the region (requested region is outside the largest
// possible region). Throw an exception.
// store what we tried to request (prior to trying to crop)
inputPtr->SetRequestedRegion(inputRequestedRegion);
// build an exception
InvalidRequestedRegionError e(__FILE__, __LINE__);
e.SetLocation(ITK_LOCATION);
e.SetDescription("Requested region is (at least partially) outside the largest possible region.");
e.SetDataObject(inputPtr);
throw e;
}
}
template< typename TInputImage, typename TFeatureImageType, class FunctorType >
void
NeighborhoodFunctorImageFilter< TInputImage, TFeatureImageType, FunctorType >
::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread,
ThreadIdType /*threadId*/)
{
typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< InputImageType > BFC;
typedef typename BFC::FaceListType FaceListType;
BFC faceCalculator;
FaceListType faceList;
// Allocate output
const InputImageType *input = this->GetInput();
// Break the input into a series of regions. The first region is free
// of boundary conditions, the rest with boundary conditions. Note,
// we pass in the input image and the OUTPUT requested region. We are
// only concerned with centering the neighborhood operator at the
// pixels that correspond to output pixels.
faceList = faceCalculator( input, outputRegionForThread, m_Size );
typename FaceListType::iterator fit;
ImageRegionConstIterator< MaskImageType > mit;
// Process non-boundary region and each of the boundary faces.
// These are N-d regions which border the edge of the buffer.
ConstNeighborhoodIterator< InputImageType > bit;
// for ( fit = faceList.begin(); fit != faceList.end(); ++fit )
// {
bit = ConstNeighborhoodIterator< InputImageType >(m_Size, input, outputRegionForThread);
mit = ImageRegionConstIterator< MaskImageType >(m_MaskImage, outputRegionForThread);
std::vector<ImageRegionIterator< FeatureImageType > > featureImageIterators;
for(unsigned int i = 0; i < FunctorType::OutputCount; i++)
{
featureImageIterators.push_back(ImageRegionIterator< FeatureImageType >(this->GetOutput(i), outputRegionForThread));
featureImageIterators[i].GoToBegin();
}
mit.GoToBegin();
bit.GoToBegin();
while ( !bit.IsAtEnd() || !mit.IsAtEnd() )
{
if(mit.Value() != 0)
{
//bit.GetNeighborhood().Print(std::cout);
typename FunctorType::OutputVectorType features = ( m_Functor( bit ) );
for(unsigned int i = 0 ; i < FunctorType::OutputCount; i++)
featureImageIterators[i].Set(features[i]);
}
for(unsigned int i = 0 ; i < FunctorType::OutputCount; i++)
++featureImageIterators[i];
++bit;
++mit;
}
// }
std::cout << "Thread done!" << std::endl;
}
} // end namespace itk
#endif //itkNeighborhoodFunctorImageFilter_cpp
<|endoftext|> |
<commit_before>#include <chrono>
#include <cmath>
#include <iostream>
#include <vector>
#include "model.hpp"
#include "CartesianGrid.hpp"
#include "Observer.hpp"
#include "Photon.hpp"
#include "Random.hpp"
#include "Directions.hpp"
#include "IDust.hpp"
#include "Sources.hpp"
int run(int argc, char *argv[])
{
auto const initTime = std::chrono::high_resolution_clock::now();
std::vector<Observer> observers;
// read the model parameters
Model& model = Model::instance(&observers, argc == 2 ? argv[1] : "parameters.json");
IGridCPtr grid = model.grid();
SourcesPtr sources = model.sources();
Random ran{ model.createRandomGenerator() };
std::cout << "Matter mass:\t" << grid->computeMatterMass() << "\t Solar Masses" << std::endl;
sources->writeObserversOpticalDepths(grid, &observers);
auto startTime = std::chrono::high_resolution_clock::now();
// Scattered photon loop
if (model.fMonteCarlo())
{
for (;;)
{
Photon ph{ sources->emitPhoton(&ran) };
if (ph.termination())
{
break;
}
// Find optical depth, tau1, to edge of grid
double tau1 = grid->findOpticalDepth(ph);
if (tau1 < model.taumin())
{
continue;
}
double w = 1.0 - std::exp(-tau1);
ph.weight() = w;
// Force photon to scatter at optical depth tau before edge of grid
double tau = -std::log(1.0 - ran.Get() * w);
// Find scattering location of tau
grid->movePhotonAtDepth(ph, tau, 0.0);
// Photon scatters in grid until it exits (tflag=1) or number
// of scatterings exceeds a set value (nscatt)
int tflag = 0;
while (!tflag && (ph.nscat() <= model.nscat()))
{
ph.weight() *= model.dust()->albedo();
// Do peeling off and project weighted photons into image
// учитыается нерассеяшийся свет от каждой точки рассеяния и последующие рассеяния, пока фотон не изыдет
for (Observer &observer : observers)
{
grid->peeloff(ph, observer, model.dust());
}
// Scatter photon into new direction and update Stokes parameters
ph.Stokes(model.dust(), Direction3d(), 0.0, false, &ran);
ph.nscat() += 1;
if (ph.nscat() > model.nscat()) break;
// Find next scattering location
tflag = grid->movePhotonAtRandomDepth(ph, &ran);
}
}
} else {
// Set up directions grid
Directions sdir( model.SecondaryDirectionsLevel(), model.useHEALPixGrid() );
startTime = std::chrono::high_resolution_clock::now();
// Loop over scattering dots
if (model.NumOfPrimaryScatterings() > 0)
{
for (;;)
{
Photon ph0{sources->emitPhoton(&ran)};
if (ph0.termination())
{
break;
}
// Find optical depth, tau1, to edge of grid
double tau1 = grid->findOpticalDepth(ph0);
if (tau1 < model.taumin())
{
continue;
}
double const w = (1.0 - exp(-tau1)) / model.NumOfPrimaryScatterings();
double tauold = 0.0, tau = 0.0;
Vector3d spos = ph0.pos();
std::uint64_t sCellId = ph0.cellId();
for (std::uint64_t s = 0; s != model.NumOfPrimaryScatterings(); ++s)
{
Photon ph(spos, sCellId, ph0.dir(), ph0.weight() * w, 1);
// Force photon to scatter at optical depth tau before edge of grid
tauold = tau;
tau = -log(1.0 - 0.5 * w * (2 * s + 1));
// Find scattering location of tau
grid->movePhotonAtDepth(ph, tau, tauold);
spos = ph.pos();
sCellId = ph.cellId();
// Photon scatters in grid until it exits (tflag=1) or number
// of scatterings exceeds a set value (nscatt)
// Photons scattering
ph.weight() *= model.dust()->albedo();
for (Observer &observer : observers)
{
grid->peeloff(ph, observer, model.dust());
}
if (ph.nscat() < model.nscat()) ph.Scatt(model, sdir, grid, observers, &ran);
}
}
}
else
{
double const sqrtPiN = std::sqrt(PI / sources->num_photons());
double const base = 1. + 2. * sqrtPiN / (1 - sqrtPiN);
// pessimistic estimation of scattering number, as we use it only for minimal optical depth estimation
double const nScatteringsRev = std::log(base) / std::log(std::sqrt(3.) * grid->max());
double const minWeight = 1. - std::exp(-model.taumin() * nScatteringsRev);
std::cout << minWeight << std::endl;
for (;;)
{
Photon ph0{sources->emitPhoton(&ran)};
if (ph0.termination())
{
break;
}
Vector3d spos = ph0.pos();
// skip empty inner regions
grid->movePhotonAtDepth(ph0, std::numeric_limits<double>::epsilon(), 0.0);
double oldR = std::max(model.defaultStarRadius(), (spos - ph0.pos()).norm());
while (grid->inside(ph0) && ph0.weight() > minWeight)
{
Photon ph{ ph0 };
// estimate tau
double const r = oldR * base;
Vector3d oldpos = ph0.pos();
double const tau = grid->movePhotonAtDistance(ph0, r - oldR);
ph0.weight() *= std::exp(-tau);
// Photons scattering
if (tau > model.taumin() * nScatteringsRev)
{
// Find scattering location of tau
double const tauScattering = -log(0.5 + 0.5 * exp(-tau));
grid->movePhotonAtDepth(ph, tauScattering, 0.0);
ph.weight() *= model.dust()->albedo() * (1.0 - std::exp(-tau));
for (Observer &observer : observers)
{
grid->peeloff(ph, observer, model.dust(), oldpos, ph0.pos());
}
if (ph.nscat() < model.nscat()) ph.Scatt(model, sdir, grid, observers, &ran);
}
oldR = r;
}
}
}
}
sources->directPhotons(grid, &observers);
std::cout << "Finishing..." << std::endl;
// Normalize images
for(std::uint64_t cnt=0; cnt!=observers.size(); ++cnt)
{
observers[cnt].normalize(sources->num_photons());
}
// put results into output files
for (std::uint64_t cnt = 0; cnt != observers.size(); ++cnt)
{
observers[cnt].writeToMapFiles(model.writeScatterings(), model.nscat());
}
// put general information into file
std::ofstream observersResultFile("observers.dat");
for (std::uint64_t cnt = 0; cnt != observers.size(); ++cnt)
{
observers[cnt].write(observersResultFile);
}
observersResultFile.close();
ran.save();
auto const endTime = std::chrono::high_resolution_clock::now();
std::cout.precision(4);
std::cout << "Initialization time:\t" << std::chrono::duration_cast<std::chrono::milliseconds>(startTime - initTime).count() * 0.001 << "s\n"
<< "Computation time:\t" << std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count() * 0.001 << "s" << std::endl;
{
std::ofstream timefile("time.txt");
timefile.precision(4);
timefile << "Initialization time: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(startTime - initTime).count() * 0.001 << "s\n"
<< "Computation time: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count() * 0.001 << "s"
<< std::endl;
timefile.close();
}
return 0;
}
int main(int argc, char *argv[])
{
try
{
return run(argc, argv);
}
catch (std::exception const& ex) {
std::cerr << "Terminated after throwing an exception:\n" << ex.what() << std::endl;
}
return 0;
}
<commit_msg>Remove debug output<commit_after>#include <chrono>
#include <cmath>
#include <iostream>
#include <vector>
#include "model.hpp"
#include "CartesianGrid.hpp"
#include "Observer.hpp"
#include "Photon.hpp"
#include "Random.hpp"
#include "Directions.hpp"
#include "IDust.hpp"
#include "Sources.hpp"
int run(int argc, char *argv[])
{
auto const initTime = std::chrono::high_resolution_clock::now();
std::vector<Observer> observers;
// read the model parameters
Model& model = Model::instance(&observers, argc == 2 ? argv[1] : "parameters.json");
IGridCPtr grid = model.grid();
SourcesPtr sources = model.sources();
Random ran{ model.createRandomGenerator() };
std::cout << "Matter mass:\t" << grid->computeMatterMass() << "\t Solar Masses" << std::endl;
sources->writeObserversOpticalDepths(grid, &observers);
auto startTime = std::chrono::high_resolution_clock::now();
// Scattered photon loop
if (model.fMonteCarlo())
{
for (;;)
{
Photon ph{ sources->emitPhoton(&ran) };
if (ph.termination())
{
break;
}
// Find optical depth, tau1, to edge of grid
double tau1 = grid->findOpticalDepth(ph);
if (tau1 < model.taumin())
{
continue;
}
double w = 1.0 - std::exp(-tau1);
ph.weight() = w;
// Force photon to scatter at optical depth tau before edge of grid
double tau = -std::log(1.0 - ran.Get() * w);
// Find scattering location of tau
grid->movePhotonAtDepth(ph, tau, 0.0);
// Photon scatters in grid until it exits (tflag=1) or number
// of scatterings exceeds a set value (nscatt)
int tflag = 0;
while (!tflag && (ph.nscat() <= model.nscat()))
{
ph.weight() *= model.dust()->albedo();
// Do peeling off and project weighted photons into image
// учитыается нерассеяшийся свет от каждой точки рассеяния и последующие рассеяния, пока фотон не изыдет
for (Observer &observer : observers)
{
grid->peeloff(ph, observer, model.dust());
}
// Scatter photon into new direction and update Stokes parameters
ph.Stokes(model.dust(), Direction3d(), 0.0, false, &ran);
ph.nscat() += 1;
if (ph.nscat() > model.nscat()) break;
// Find next scattering location
tflag = grid->movePhotonAtRandomDepth(ph, &ran);
}
}
} else {
// Set up directions grid
Directions sdir( model.SecondaryDirectionsLevel(), model.useHEALPixGrid() );
startTime = std::chrono::high_resolution_clock::now();
// Loop over scattering dots
if (model.NumOfPrimaryScatterings() > 0)
{
for (;;)
{
Photon ph0{sources->emitPhoton(&ran)};
if (ph0.termination())
{
break;
}
// Find optical depth, tau1, to edge of grid
double tau1 = grid->findOpticalDepth(ph0);
if (tau1 < model.taumin())
{
continue;
}
double const w = (1.0 - exp(-tau1)) / model.NumOfPrimaryScatterings();
double tauold = 0.0, tau = 0.0;
Vector3d spos = ph0.pos();
std::uint64_t sCellId = ph0.cellId();
for (std::uint64_t s = 0; s != model.NumOfPrimaryScatterings(); ++s)
{
Photon ph(spos, sCellId, ph0.dir(), ph0.weight() * w, 1);
// Force photon to scatter at optical depth tau before edge of grid
tauold = tau;
tau = -log(1.0 - 0.5 * w * (2 * s + 1));
// Find scattering location of tau
grid->movePhotonAtDepth(ph, tau, tauold);
spos = ph.pos();
sCellId = ph.cellId();
// Photon scatters in grid until it exits (tflag=1) or number
// of scatterings exceeds a set value (nscatt)
// Photons scattering
ph.weight() *= model.dust()->albedo();
for (Observer &observer : observers)
{
grid->peeloff(ph, observer, model.dust());
}
if (ph.nscat() < model.nscat()) ph.Scatt(model, sdir, grid, observers, &ran);
}
}
}
else
{
double const sqrtPiN = std::sqrt(PI / sources->num_photons());
double const base = 1. + 2. * sqrtPiN / (1 - sqrtPiN);
// pessimistic estimation of scattering number, as we use it only for minimal optical depth estimation
double const nScatteringsRev = std::log(base) / std::log(std::sqrt(3.) * grid->max());
double const minWeight = 1. - std::exp(-model.taumin() * nScatteringsRev);
for (;;)
{
Photon ph0{sources->emitPhoton(&ran)};
if (ph0.termination())
{
break;
}
Vector3d spos = ph0.pos();
// skip empty inner regions
grid->movePhotonAtDepth(ph0, std::numeric_limits<double>::epsilon(), 0.0);
double oldR = std::max(model.defaultStarRadius(), (spos - ph0.pos()).norm());
while (grid->inside(ph0) && ph0.weight() > minWeight)
{
Photon ph{ ph0 };
// estimate tau
double const r = oldR * base;
Vector3d oldpos = ph0.pos();
double const tau = grid->movePhotonAtDistance(ph0, r - oldR);
ph0.weight() *= std::exp(-tau);
// Photons scattering
if (tau > model.taumin() * nScatteringsRev)
{
// Find scattering location of tau
double const tauScattering = -log(0.5 + 0.5 * exp(-tau));
grid->movePhotonAtDepth(ph, tauScattering, 0.0);
ph.weight() *= model.dust()->albedo() * (1.0 - std::exp(-tau));
for (Observer &observer : observers)
{
grid->peeloff(ph, observer, model.dust(), oldpos, ph0.pos());
}
if (ph.nscat() < model.nscat()) ph.Scatt(model, sdir, grid, observers, &ran);
}
oldR = r;
}
}
}
}
sources->directPhotons(grid, &observers);
std::cout << "Finishing..." << std::endl;
// Normalize images
for(std::uint64_t cnt=0; cnt!=observers.size(); ++cnt)
{
observers[cnt].normalize(sources->num_photons());
}
// put results into output files
for (std::uint64_t cnt = 0; cnt != observers.size(); ++cnt)
{
observers[cnt].writeToMapFiles(model.writeScatterings(), model.nscat());
}
// put general information into file
std::ofstream observersResultFile("observers.dat");
for (std::uint64_t cnt = 0; cnt != observers.size(); ++cnt)
{
observers[cnt].write(observersResultFile);
}
observersResultFile.close();
ran.save();
auto const endTime = std::chrono::high_resolution_clock::now();
std::cout.precision(4);
std::cout << "Initialization time:\t" << std::chrono::duration_cast<std::chrono::milliseconds>(startTime - initTime).count() * 0.001 << "s\n"
<< "Computation time:\t" << std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count() * 0.001 << "s" << std::endl;
{
std::ofstream timefile("time.txt");
timefile.precision(4);
timefile << "Initialization time: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(startTime - initTime).count() * 0.001 << "s\n"
<< "Computation time: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count() * 0.001 << "s"
<< std::endl;
timefile.close();
}
return 0;
}
int main(int argc, char *argv[])
{
try
{
return run(argc, argv);
}
catch (std::exception const& ex) {
std::cerr << "Terminated after throwing an exception:\n" << ex.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>[discretefunction.default] allow move of ConstDiscreteFunction<commit_after><|endoftext|> |
<commit_before>#include "node.h"
#define WINDOWS_H_A80B5674
typedef unsigned short sqfs_mode_t;
typedef uint32_t sqfs_id_t;
typedef DWORD64 sqfs_off_t;
struct dirent
{
long d_namlen;
ino_t d_ino;
char *d_name;
char *d_altname; /* short name */
short d_altlen;
uint8_t d_type;
};
extern "C" {
#include "enclose_io.h"
}
sqfs *enclose_io_fs;
#ifdef _WIN32
#include <VersionHelpers.h>
#include <WinError.h>
int wmain(int argc, wchar_t *wargv[]) {
sqfs_err enclose_io_ret;
enclose_io_fs = (sqfs *)malloc(sizeof(sqfs));
assert(NULL != enclose_io_fs);
memset(enclose_io_fs, 0, sizeof(sqfs));
enclose_io_ret = sqfs_open_image(enclose_io_fs, enclose_io_memfs, 0);
assert(SQFS_OK == enclose_io_ret);
wchar_t *argv_memory = NULL;
int new_argc = argc;
wchar_t **new_argv = wargv;
if (NULL == getenv("ENCLOSE_IO_USE_ORIGINAL_NODE")) {
ENCLOSE_IO_ENTRANCE;
}
if (!IsWindows7OrGreater()) {
fprintf(stderr, "This application is only supported on Windows 7, "
"Windows Server 2008 R2, or higher.");
exit(ERROR_EXE_MACHINE_TYPE_MISMATCH);
}
// Convert argv to to UTF8
char** argv = new char*[new_argc + 1];
for (int i = 0; i < new_argc; i++) {
// Compute the size of the required buffer
DWORD size = WideCharToMultiByte(CP_UTF8,
0,
new_argv[i],
-1,
nullptr,
0,
nullptr,
nullptr);
if (size == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
// Do the actual conversion
argv[i] = new char[size];
DWORD result = WideCharToMultiByte(CP_UTF8,
0,
new_argv[i],
-1,
argv[i],
size,
nullptr,
nullptr);
if (result == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
}
argv[new_argc] = nullptr;
// Now that conversion is done, we can finally start.
return node::Start(new_argc, argv);
}
#else
// UNIX
int main(int argc, char *argv[]) {
sqfs_err enclose_io_ret;
enclose_io_fs = (sqfs *)malloc(sizeof(sqfs));
assert(NULL != enclose_io_fs);
memset(enclose_io_fs, 0, sizeof(sqfs));
enclose_io_ret = sqfs_open_image(enclose_io_fs, enclose_io_memfs, 0);
assert(SQFS_OK == enclose_io_ret);
char *argv_memory = NULL;
int new_argc = argc;
char **new_argv = argv;
if (NULL == getenv("ENCLOSE_IO_USE_ORIGINAL_NODE")) {
ENCLOSE_IO_ENTRANCE;
}
// Disable stdio buffering, it interacts poorly with printf()
// calls elsewhere in the program (e.g., any logging from V8.)
setvbuf(stdout, nullptr, _IONBF, 0);
setvbuf(stderr, nullptr, _IONBF, 0);
return node::Start(new_argc, new_argv);
}
#endif
<commit_msg>hack WINDOWS_H_A80B5674 only ifdef _WIN32<commit_after>#include "node.h"
#ifdef _WIN32
#define WINDOWS_H_A80B5674
typedef unsigned short sqfs_mode_t;
typedef uint32_t sqfs_id_t;
typedef DWORD64 sqfs_off_t;
struct dirent
{
long d_namlen;
ino_t d_ino;
char *d_name;
char *d_altname; /* short name */
short d_altlen;
uint8_t d_type;
};
#endif
extern "C" {
#include "enclose_io.h"
}
sqfs *enclose_io_fs;
#ifdef _WIN32
#include <VersionHelpers.h>
#include <WinError.h>
int wmain(int argc, wchar_t *wargv[]) {
sqfs_err enclose_io_ret;
enclose_io_fs = (sqfs *)malloc(sizeof(sqfs));
assert(NULL != enclose_io_fs);
memset(enclose_io_fs, 0, sizeof(sqfs));
enclose_io_ret = sqfs_open_image(enclose_io_fs, enclose_io_memfs, 0);
assert(SQFS_OK == enclose_io_ret);
wchar_t *argv_memory = NULL;
int new_argc = argc;
wchar_t **new_argv = wargv;
if (NULL == getenv("ENCLOSE_IO_USE_ORIGINAL_NODE")) {
ENCLOSE_IO_ENTRANCE;
}
if (!IsWindows7OrGreater()) {
fprintf(stderr, "This application is only supported on Windows 7, "
"Windows Server 2008 R2, or higher.");
exit(ERROR_EXE_MACHINE_TYPE_MISMATCH);
}
// Convert argv to to UTF8
char** argv = new char*[new_argc + 1];
for (int i = 0; i < new_argc; i++) {
// Compute the size of the required buffer
DWORD size = WideCharToMultiByte(CP_UTF8,
0,
new_argv[i],
-1,
nullptr,
0,
nullptr,
nullptr);
if (size == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
// Do the actual conversion
argv[i] = new char[size];
DWORD result = WideCharToMultiByte(CP_UTF8,
0,
new_argv[i],
-1,
argv[i],
size,
nullptr,
nullptr);
if (result == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
}
argv[new_argc] = nullptr;
// Now that conversion is done, we can finally start.
return node::Start(new_argc, argv);
}
#else
// UNIX
int main(int argc, char *argv[]) {
sqfs_err enclose_io_ret;
enclose_io_fs = (sqfs *)malloc(sizeof(sqfs));
assert(NULL != enclose_io_fs);
memset(enclose_io_fs, 0, sizeof(sqfs));
enclose_io_ret = sqfs_open_image(enclose_io_fs, enclose_io_memfs, 0);
assert(SQFS_OK == enclose_io_ret);
char *argv_memory = NULL;
int new_argc = argc;
char **new_argv = argv;
if (NULL == getenv("ENCLOSE_IO_USE_ORIGINAL_NODE")) {
ENCLOSE_IO_ENTRANCE;
}
// Disable stdio buffering, it interacts poorly with printf()
// calls elsewhere in the program (e.g., any logging from V8.)
setvbuf(stdout, nullptr, _IONBF, 0);
setvbuf(stderr, nullptr, _IONBF, 0);
return node::Start(new_argc, new_argv);
}
#endif
<|endoftext|> |
<commit_before>#include "Screens.h"
#include <iostream>
Graphics *characterSprites = NULL;
Graphics *selectScreen = NULL;
Character *mainCharacter = NULL;
void SelectionScreen::init()
{
characterSprites = new Graphics(".\\images\\characters.bmp");
selectScreen = new Graphics(".\\images\\selectScreen.png");
}
SelectionScreen::SelectionScreen()
{
}
SelectionScreen::SelectionScreen(SDL_Surface *newScreen)
{
screen = newScreen;
init();
}
void SelectionScreen::paint()
{
// paint background
// if player graphic selected? paint in selected character area
// if race selected?
applySurface(0,0,selectScreen->image,screen);
}
void SelectionScreen::mouseLeft(int x, int y)
{
if (x >= 672 && x <= 784 && y >= 544 && y <= 591)
{
//state = STATE_MAIN_GAME;
//mainGame.init();
}
}
void SelectionScreen::mouseRight(int x, int y)
{
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
const int MainGame::LEVEL_1 = 1;
const int MainGame::STATE_LEVEL_START = 0;
const int MainGame::STATE_HUMAN_TURN = 1;
const int MainGame::STATE_AI_TURN = 2;
MainGame::MainGame()
{
std::cout << "called";
}
MainGame::MainGame(SDL_Surface *newScreen)
{
screen = newScreen;
currentLevel = LEVEL_1;
gameMap = Map(16,16,640,480);
std::cout << gameMap.limit.x << "----\n";
}
void MainGame::init()
{
loadLevel();
gameMap.loadGraphics(level->graphics, level->alphaR, level->alphaG, level->alphaB);
gameMap.parseIndex(level->index);
state = STATE_LEVEL_START;
// hacked in, fake character
mainCharacter = new Fighter(HUMAN);
mainCharacter->graphics = characterSprites;
SDL_Rect *tempRect = new SDL_Rect();
tempRect->x = 0;
tempRect->y = 0;
tempRect->w = 16;
tempRect->h = 16;
mainCharacter->x = 10;
mainCharacter->y = 14;
mainCharacter->clip = tempRect;
}
void MainGame::loadLevel()
{
switch(currentLevel)
{
case LEVEL_1:
level = new Level();
level->graphics = ".\\levels\\level00\\graphicTiles.bmp";
level->index = ".\\levels\\level00\\index.map";
level->alphaR = 0xFF;
level->alphaG = 0xE2;
level->alphaB = 0xAA;
break;
}
}
void MainGame::paint()
{
gameMap.paint();
if(gameMap.isOnScreen(mainCharacter->x,mainCharacter->y))
{
paintCharacter(mainCharacter);
}
}
void MainGame::paintCharacter(Character* c)
{
int x = gameMap.limit.x + (c->x - gameMap.x)*16;
int y = gameMap.limit.y + (c->y - gameMap.y)*16;
applySurface(x, y, c->graphics->image, screen, c->clip);
}
void MainGame::keyUp()
{
if(mainCharacter->y > 0)
{
if(gameMap.ts[mainCharacter->x][mainCharacter->y-1].isWalkable)
mainCharacter->y -= 1;
}
}
void MainGame::keyDown()
{
if(mainCharacter->y < gameMap.h)
{
if(gameMap.ts[mainCharacter->x][mainCharacter->y+1].isWalkable)
mainCharacter->y += 1;
}
}
void MainGame::keyLeft()
{
if(mainCharacter->x > 0)
{
if(gameMap.ts[mainCharacter->x-1][mainCharacter->y].isWalkable)
mainCharacter->x -= 1;
}
}
void MainGame::keyRight()
{
if(mainCharacter->x < gameMap.w)
{
if(gameMap.ts[mainCharacter->x+1][mainCharacter->y].isWalkable)
mainCharacter->x += 1;
}
}<commit_msg>sprites added to the selection screen<commit_after>#include "Screens.h"
#include <iostream>
Graphics *characterSprites = NULL;
Graphics *selectScreen = NULL;
Character *mainCharacter = NULL;
void SelectionScreen::init()
{
characterSprites = new Graphics(".\\images\\characters.bmp");
selectScreen = new Graphics(".\\images\\selectScreen.png");
}
SelectionScreen::SelectionScreen()
{
}
SelectionScreen::SelectionScreen(SDL_Surface *newScreen)
{
screen = newScreen;
init();
}
void SelectionScreen::paint()
{
// paint background
// if player graphic selected? paint in selected character area
// if race selected?
SDL_Rect *character1 = new SDL_Rect();
SDL_Rect *character2 = new SDL_Rect();
SDL_Rect *character3 = new SDL_Rect();
SDL_Rect *character4 = new SDL_Rect();
SDL_Rect *character5 = new SDL_Rect();
character1->x = 0; character1->y = 0; character1->w = 16; character1->h = 16;
character2->x = 272; character2->y = 0; character2->w = 16; character2->h = 16;
character3->x = 0; character3->y = 152; character3->w = 16; character3->h = 16;
character4->x = 152; character4->y = 152; character4->w = 16; character4->h = 16;
character5->x = 272; character5->y = 152; character5->w = 16; character5->h = 16;
//coordinates for the player selection squares
int cx1 = 272;
int cy = 96;
int cx2 = cx1 + 64;
int cx3 = cx2 + 64;
int cx4 = cx3 + 64;
int cx5 = cx4 + 64;
applySurface(0,0,selectScreen->image,screen);
applySurface(cx1,cy,characterSprites->image,screen, character1);
applySurface(cx2,cy,characterSprites->image,screen, character2);
applySurface(cx3,cy,characterSprites->image,screen, character3);
applySurface(cx4,cy,characterSprites->image,screen, character4);
applySurface(cx5,cy,characterSprites->image,screen, character5);
}
void SelectionScreen::mouseLeft(int x, int y)
{
if (x >= 672 && x <= 784 && y >= 544 && y <= 591)
{
//state = STATE_MAIN_GAME;
//mainGame.init();
}
}
void SelectionScreen::mouseRight(int x, int y)
{
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
const int MainGame::LEVEL_1 = 1;
const int MainGame::STATE_LEVEL_START = 0;
const int MainGame::STATE_HUMAN_TURN = 1;
const int MainGame::STATE_AI_TURN = 2;
MainGame::MainGame()
{
std::cout << "called";
}
MainGame::MainGame(SDL_Surface *newScreen)
{
screen = newScreen;
currentLevel = LEVEL_1;
gameMap = Map(16,16,640,480);
std::cout << gameMap.limit.x << "----\n";
}
void MainGame::init()
{
loadLevel();
gameMap.loadGraphics(level->graphics, level->alphaR, level->alphaG, level->alphaB);
gameMap.parseIndex(level->index);
state = STATE_LEVEL_START;
// hacked in, fake character
mainCharacter = new Fighter(HUMAN);
mainCharacter->graphics = characterSprites;
SDL_Rect *tempRect = new SDL_Rect();
tempRect->x = 0;
tempRect->y = 0;
tempRect->w = 16;
tempRect->h = 16;
mainCharacter->x = 10;
mainCharacter->y = 14;
mainCharacter->clip = tempRect;
}
void MainGame::loadLevel()
{
switch(currentLevel)
{
case LEVEL_1:
level = new Level();
level->graphics = ".\\levels\\level00\\graphicTiles.bmp";
level->index = ".\\levels\\level00\\index.map";
level->alphaR = 0xFF;
level->alphaG = 0xE2;
level->alphaB = 0xAA;
break;
}
}
void MainGame::paint()
{
gameMap.paint();
if(gameMap.isOnScreen(mainCharacter->x,mainCharacter->y))
{
paintCharacter(mainCharacter);
}
}
void MainGame::paintCharacter(Character* c)
{
int x = gameMap.limit.x + (c->x - gameMap.x)*16;
int y = gameMap.limit.y + (c->y - gameMap.y)*16;
applySurface(x, y, c->graphics->image, screen, c->clip);
}
void MainGame::keyUp()
{
if(mainCharacter->y > 0)
{
if(gameMap.ts[mainCharacter->x][mainCharacter->y-1].isWalkable)
mainCharacter->y -= 1;
}
}
void MainGame::keyDown()
{
if(mainCharacter->y < gameMap.h)
{
if(gameMap.ts[mainCharacter->x][mainCharacter->y+1].isWalkable)
mainCharacter->y += 1;
}
}
void MainGame::keyLeft()
{
if(mainCharacter->x > 0)
{
if(gameMap.ts[mainCharacter->x-1][mainCharacter->y].isWalkable)
mainCharacter->x -= 1;
}
}
void MainGame::keyRight()
{
if(mainCharacter->x < gameMap.w)
{
if(gameMap.ts[mainCharacter->x+1][mainCharacter->y].isWalkable)
mainCharacter->x += 1;
}
}<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////
// //
// VideoDisplay - Cheap and cheeful way of creating a GL X //
// display //
// //
// Tom Drummong & Paul Smith 2002 //
// //
//////////////////////////////////////////////////////////////////////
#include "cvd/videodisplay.h"
//#include <cmath>
//#include <cstdlib>
//#include <iostream>
//#include <cassert>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
using namespace std;
//namespace CVD {
int CVD::defAttr[] = {GLX_RGBA,
GLX_RED_SIZE, 3,
GLX_GREEN_SIZE, 3,
GLX_BLUE_SIZE, 2,
GLX_DOUBLEBUFFER, 0,
// GLX_DEPTH_SIZE, 8,
// GLX_STENCIL_SIZE, 8,
0};
CVD::VideoDisplay::VideoDisplay(double left, double top, double right, double bottom, double scale, int* visualAttr) :
my_left(left),
my_top(top),
my_right(right),
my_bottom(bottom),
my_scale(scale),
my_orig_left(left),
my_orig_top(top),
my_orig_right(right),
my_orig_bottom(bottom),
my_orig_scale(scale)
{
// Need these for converting mouse clicks efficiently
// (This stays the same even when zooming)
my_positive_right = right > left;
my_positive_down = bottom > top;
cerr << "creating a video display from ("
<< left << "," << top << ") to (" << right << "," << bottom
<< ")" << endl;
my_display = XOpenDisplay(NULL);
if (my_display == NULL) {
cerr << "Can't connect to display " << getenv("DISPLAY") << endl;
exit(0);
}
// smallest single buffered RGBA visual
/*int visualAttr[] = {GLX_RGBA,
GLX_RED_SIZE, 3,
GLX_GREEN_SIZE, 3,
GLX_BLUE_SIZE, 2,
GLX_DOUBLEBUFFER, 0,
// GLX_DEPTH_SIZE, 8,
// GLX_STENCIL_SIZE, 8,
0};
*/
// get an appropriate visual
my_visual = glXChooseVisual(my_display, DefaultScreen(my_display), visualAttr);
if (my_visual == NULL) {
cerr << "No matching visual on display " << getenv("DISPLAY") << endl;
exit(0);
}
// check I got an rgba visual (32 bit)
int isRgba;
(void) glXGetConfig(my_display, my_visual, GLX_RGBA, &isRgba);
assert(isRgba);
// create a GLX context
if ((my_glx_context = glXCreateContext(my_display, my_visual, 0, GL_TRUE)) == NULL){
cerr << "Cannot create a context" << endl;
exit(0);
}
// create a colormap (it's empty for rgba visuals)
my_cmap = XCreateColormap(my_display,
RootWindow(my_display, my_visual->screen),
my_visual->visual,
AllocNone);
// set the attributes for the window
XSetWindowAttributes swa;
swa.colormap = my_cmap;
swa.border_pixel = 0;
swa.event_mask = StructureNotifyMask;
// Work out how big the display is
int xsize = static_cast<int>(fabs(right - left) * scale);
int ysize = static_cast<int>(fabs(bottom - top) * scale);
// create a window
my_window = XCreateWindow(my_display,
RootWindow(my_display, my_visual->screen),
0, // init_x
0, // init_y
xsize,
ysize,
0,
my_visual->depth,
InputOutput,
my_visual->visual,
CWBorderPixel | CWColormap | CWEventMask, &swa);
if (my_window == 0) {
cerr << "Cannot create a window" << endl;
exit(0);
}
set_title("Video Display");
XMapWindow(my_display, my_window);
// discard all event up to the MapNotify
XEvent ev;
do
{
XNextEvent(my_display,&ev);
}
while (ev.type != MapNotify);
// Connect the GLX context to the window
if (!glXMakeCurrent(my_display, my_window, my_glx_context))
{
cerr << "Can't make window current to gl context" << endl;
exit(0);
}
XSelectInput(my_display,
my_window,
ButtonPressMask |
ButtonReleaseMask |
Button1MotionMask |
PointerMotionHintMask |
KeyPressMask);
// Sort out the GL scaling
glLoadIdentity();
glViewport(0, 0, xsize, ysize);
glColor3f(1.0, 1.0, 1.0);
glDrawBuffer(GL_FRONT); // On Vino, we only use the front buffer
set_zoom(left, top, right, bottom, scale);
}
void CVD::VideoDisplay::set_zoom(double left, double top, double right, double bottom, double scale)
{
// Make sure that this is the current window
make_current();
my_left = left;
my_top = top;
my_right = right;
my_bottom = bottom;
my_scale = scale;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(left, right, bottom, top, -1 , 1); // If the origin is the top left
glRasterPos2f(left, top);
// video is now the same way as upside down to graphics!
glPixelZoom(scale, -scale);
//glPixelZoom(1,-1);
cerr << "New range is ("
<< left << "," << top << ") to (" << right << "," << bottom
<< ")" << endl;
}
void CVD::VideoDisplay::zoom_in(double cx, double cy, double factor)
{
cerr << "Zooming about (" << cx << "," << cy << ") with a scale of " << factor << endl;
double width = my_right - my_left;
double height = my_bottom - my_top;
//Work out the new half-widths
width = width / 2 / factor;
height = height / 2 / factor;
// Work out the new image corners. scale is how much things are zoomed up, so
// this is just multipled by the factor
set_zoom(cx - width, cy - height, cx + width, cy + height, my_scale * factor);
}
CVD::VideoDisplay::~VideoDisplay()
{
glXMakeCurrent(my_display, None, NULL);
glXDestroyContext(my_display, my_glx_context);
XUnmapWindow(my_display, my_window);
XDestroyWindow(my_display, my_window);
}
void CVD::VideoDisplay::set_title(const string& s)
{
// give the window a name
XStoreName(my_display, my_window, s.c_str());
}
void CVD::VideoDisplay::select_events(long event_mask){
cerr << "selecting input with mask " << event_mask << endl;
XSelectInput(my_display, my_window, event_mask);
XFlush(my_display);
}
void CVD::VideoDisplay::flush(){
XFlush(my_display);
}
void CVD::VideoDisplay::get_event(XEvent* event){
XNextEvent(my_display, event);
}
int CVD::VideoDisplay::pending()
{
return XPending(my_display);
}
void CVD::VideoDisplay::make_current()
{
// Connect the GLX context to the window
if (!glXMakeCurrent(my_display, my_window, my_glx_context)) {
cerr << "Can't make window current to gl context" << endl;
exit(0);
}
}
//
// DISPLAY TO VIDEO
// Converts a point on the display to the video's coordinates
//
void CVD::VideoDisplay::display_to_video(int dx, int dy, double& vx, double& vy)
{
vx = dx / my_scale;
if(my_positive_right)
vx = my_left + vx;
else
vx = my_left - vx;
vy = dy / my_scale;
if(my_positive_down)
vy = my_top + vy;
else
vy = my_top - vy;
}
//
// VIDEO TO DISPLAY
// Converts a point on the display to the video's coordinates
//
void CVD::VideoDisplay::video_to_display(double vx, double vy, int& dx, int& dy)
{
double ix, iy;
if(my_positive_right)
ix = vx - my_left;
else
ix = my_left - vx;
ix = ix * my_scale;
if(my_positive_down)
iy = vy - my_top;
else
iy = my_top - vy;
iy = iy * my_scale;
dx = static_cast<int>(ix);
dy = static_cast<int>(iy);
}
//
// LOCATE DISPLAY POINTER
// Where is the pointer in the window?
//
void CVD::VideoDisplay::locate_display_pointer(int& x, int& y)
{
Window root_return;
Window child_return;
int root_x_return;
int root_y_return;
unsigned int mask_return;
XQueryPointer(my_display,
my_window,
&root_return,
&child_return,
&root_x_return,
&root_y_return,
&x,
&y,
&mask_return);
}
//
// LOCATE DISPLAY POINTER
// Where is the pointer in the video frame?
//
void CVD::VideoDisplay::locate_video_pointer(double& x, double& y)
{
int dx, dy;
locate_display_pointer(dx, dy);
display_to_video(dx, dy, x, y);
}
//} // namespace CVD
<commit_msg>Replaced fatal errors with exceptions.<commit_after>//////////////////////////////////////////////////////////////////////
// //
// VideoDisplay - Cheap and cheeful way of creating a GL X //
// display //
// //
// Tom Drummong & Paul Smith 2002 //
// //
//////////////////////////////////////////////////////////////////////
#include "cvd/videodisplay.h"
//#include <cmath>
//#include <cstdlib>
//#include <iostream>
//#include <cassert>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
using namespace std;
using namespace CVD;
CVD::Exceptions::VideoDisplay::InitialisationError::InitialisationError(string w)
{
what="VideoDisplay inintialisation error: " + w;
}
CVD::Exceptions::VideoDisplay::RuntimeError::RuntimeError(string w)
{
what="VideoDisplay error: " + w;
}
//namespace CVD {
int CVD::defAttr[] = {GLX_RGBA,
GLX_RED_SIZE, 3,
GLX_GREEN_SIZE, 3,
GLX_BLUE_SIZE, 2,
GLX_DOUBLEBUFFER, 0,
// GLX_DEPTH_SIZE, 8,
// GLX_STENCIL_SIZE, 8,
0};
CVD::VideoDisplay::VideoDisplay(double left, double top, double right, double bottom, double scale, int* visualAttr) :
my_left(left),
my_top(top),
my_right(right),
my_bottom(bottom),
my_scale(scale),
my_orig_left(left),
my_orig_top(top),
my_orig_right(right),
my_orig_bottom(bottom),
my_orig_scale(scale)
{
// Need these for converting mouse clicks efficiently
// (This stays the same even when zooming)
my_positive_right = right > left;
my_positive_down = bottom > top;
my_display = XOpenDisplay(NULL);
if (my_display == NULL)
throw Exceptions::VideoDisplay::InitialisationError(string("Can't connect to display ") + getenv("DISPLAY"));
// get an appropriate visual
my_visual = glXChooseVisual(my_display, DefaultScreen(my_display), visualAttr);
if (my_visual == NULL)
throw Exceptions::VideoDisplay::InitialisationError(string("No matching visual on display ") + getenv("DISPLAY"));
// check I got an rgba visual (32 bit)
int isRgba;
(void) glXGetConfig(my_display, my_visual, GLX_RGBA, &isRgba);
assert(isRgba);
// create a GLX context
if ((my_glx_context = glXCreateContext(my_display, my_visual, 0, GL_TRUE)) == NULL)
throw Exceptions::VideoDisplay::InitialisationError(string("Cannot create GL context on ") + getenv("DISPLAY"));
// create a colormap (it's empty for rgba visuals)
my_cmap = XCreateColormap(my_display,
RootWindow(my_display, my_visual->screen),
my_visual->visual,
AllocNone);
// set the attributes for the window
XSetWindowAttributes swa;
swa.colormap = my_cmap;
swa.border_pixel = 0;
swa.event_mask = StructureNotifyMask;
// Work out how big the display is
int xsize = static_cast<int>(fabs(right - left) * scale);
int ysize = static_cast<int>(fabs(bottom - top) * scale);
// create a window
my_window = XCreateWindow(my_display,
RootWindow(my_display, my_visual->screen),
0, // init_x
0, // init_y
xsize,
ysize,
0,
my_visual->depth,
InputOutput,
my_visual->visual,
CWBorderPixel | CWColormap | CWEventMask, &swa);
if (my_window == 0)
throw Exceptions::VideoDisplay::InitialisationError(string("Cannot create a window on ") + getenv("DISPLAY"));
set_title("Video Display");
XMapWindow(my_display, my_window);
// discard all event up to the MapNotify
XEvent ev;
do
{
XNextEvent(my_display,&ev);
}
while (ev.type != MapNotify);
// Connect the GLX context to the window
if (!glXMakeCurrent(my_display, my_window, my_glx_context))
throw Exceptions::VideoDisplay::InitialisationError("Cannot make window current to GL context");
XSelectInput(my_display,
my_window,
ButtonPressMask |
ButtonReleaseMask |
Button1MotionMask |
PointerMotionHintMask |
KeyPressMask);
// Sort out the GL scaling
glLoadIdentity();
glViewport(0, 0, xsize, ysize);
glColor3f(1.0, 1.0, 1.0);
glDrawBuffer(GL_FRONT); // On Vino, we only use the front buffer
set_zoom(left, top, right, bottom, scale);
}
void CVD::VideoDisplay::set_zoom(double left, double top, double right, double bottom, double scale)
{
// Make sure that this is the current window
make_current();
my_left = left;
my_top = top;
my_right = right;
my_bottom = bottom;
my_scale = scale;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(left, right, bottom, top, -1 , 1); // If the origin is the top left
glRasterPos2f(left, top);
// video is now the same way as upside down to graphics!
glPixelZoom(scale, -scale);
//glPixelZoom(1,-1);
}
void CVD::VideoDisplay::zoom_in(double cx, double cy, double factor)
{
double width = my_right - my_left;
double height = my_bottom - my_top;
//Work out the new half-widths
width = width / 2 / factor;
height = height / 2 / factor;
// Work out the new image corners. scale is how much things are zoomed up, so
// this is just multipled by the factor
set_zoom(cx - width, cy - height, cx + width, cy + height, my_scale * factor);
}
CVD::VideoDisplay::~VideoDisplay()
{
glXMakeCurrent(my_display, None, NULL);
glXDestroyContext(my_display, my_glx_context);
XUnmapWindow(my_display, my_window);
XDestroyWindow(my_display, my_window);
}
void CVD::VideoDisplay::set_title(const string& s)
{
// give the window a name
XStoreName(my_display, my_window, s.c_str());
}
void CVD::VideoDisplay::select_events(long event_mask){
XSelectInput(my_display, my_window, event_mask);
XFlush(my_display);
}
void CVD::VideoDisplay::flush(){
XFlush(my_display);
}
void CVD::VideoDisplay::get_event(XEvent* event){
XNextEvent(my_display, event);
}
int CVD::VideoDisplay::pending()
{
return XPending(my_display);
}
void CVD::VideoDisplay::make_current()
{
// Connect the GLX context to the window
if (!glXMakeCurrent(my_display, my_window, my_glx_context))
throw Exceptions::VideoDisplay::InitialisationError("Cannot make window current to GL context");
}
//
// DISPLAY TO VIDEO
// Converts a point on the display to the video's coordinates
//
void CVD::VideoDisplay::display_to_video(int dx, int dy, double& vx, double& vy)
{
vx = dx / my_scale;
if(my_positive_right)
vx = my_left + vx;
else
vx = my_left - vx;
vy = dy / my_scale;
if(my_positive_down)
vy = my_top + vy;
else
vy = my_top - vy;
}
//
// VIDEO TO DISPLAY
// Converts a point on the display to the video's coordinates
//
void CVD::VideoDisplay::video_to_display(double vx, double vy, int& dx, int& dy)
{
double ix, iy;
if(my_positive_right)
ix = vx - my_left;
else
ix = my_left - vx;
ix = ix * my_scale;
if(my_positive_down)
iy = vy - my_top;
else
iy = my_top - vy;
iy = iy * my_scale;
dx = static_cast<int>(ix);
dy = static_cast<int>(iy);
}
//
// LOCATE DISPLAY POINTER
// Where is the pointer in the window?
//
void CVD::VideoDisplay::locate_display_pointer(int& x, int& y)
{
Window root_return;
Window child_return;
int root_x_return;
int root_y_return;
unsigned int mask_return;
XQueryPointer(my_display,
my_window,
&root_return,
&child_return,
&root_x_return,
&root_y_return,
&x,
&y,
&mask_return);
}
//
// LOCATE DISPLAY POINTER
// Where is the pointer in the video frame?
//
void CVD::VideoDisplay::locate_video_pointer(double& x, double& y)
{
int dx, dy;
locate_display_pointer(dx, dy);
display_to_video(dx, dy, x, y);
}
//} // namespace CVD
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2000 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 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) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XALAN_OUTPUTCONTEXTSTACK_HEADER_GUARD)
#define XALAN_OUTPUTCONTEXTSTACK_HEADER_GUARD
// Base include file. Must be first.
#include <XSLT/XSLTDefinitions.hpp>
#include <deque>
#include <XalanDOM/XalanDOMString.hpp>
#include <PlatformSupport/AttributeListImpl.hpp>
class FormatterListener;
class XALAN_XSLT_EXPORT OutputContextStack
{
public:
struct OutputContext
{
OutputContext(FormatterListener* theListener = 0) :
m_flistener(theListener),
m_pendingAttributes(),
m_pendingElementName(),
m_hasPendingStartDocument(false),
m_mustFlushPendingStartDocument(false)
{
}
~OutputContext()
{
}
void
reset()
{
m_flistener = 0;
m_pendingAttributes.clear();
::clear(m_pendingElementName);
m_hasPendingStartDocument = false;
m_mustFlushPendingStartDocument = false;
}
FormatterListener* m_flistener;
AttributeListImpl m_pendingAttributes;
XalanDOMString m_pendingElementName;
bool m_hasPendingStartDocument;
bool m_mustFlushPendingStartDocument;
};
#if defined(XALAN_NO_NAMESPACES)
typedef deque<OutputContext> OutputContextStackType;
#else
typedef std::deque<OutputContext> OutputContextStackType;
#endif
typedef OutputContextStackType::size_type size_type;
explicit
OutputContextStack();
~OutputContextStack();
void
pushContext(FormatterListener* theListener = 0);
void
popContext();
FormatterListener*
getFormatterListener() const
{
return (*m_stackPosition).m_flistener;
}
FormatterListener*&
getFormatterListener()
{
return (*m_stackPosition).m_flistener;
}
const AttributeListImpl&
getPendingAttributes() const
{
return (*m_stackPosition).m_pendingAttributes;
}
AttributeListImpl&
getPendingAttributes()
{
return (*m_stackPosition).m_pendingAttributes;
}
const XalanDOMString&
getPendingElementName() const
{
return (*m_stackPosition).m_pendingElementName;
}
XalanDOMString&
getPendingElementName()
{
return (*m_stackPosition).m_pendingElementName;
}
const bool&
getHasPendingStartDocument() const
{
return (*m_stackPosition).m_hasPendingStartDocument;
}
bool&
getHasPendingStartDocument()
{
return (*m_stackPosition).m_hasPendingStartDocument;
}
const bool&
getMustFlushPendingStartDocument() const
{
return (*m_stackPosition).m_mustFlushPendingStartDocument;
}
bool&
getMustFlushPendingStartDocument()
{
return (*m_stackPosition).m_mustFlushPendingStartDocument;
}
size_type
size() const
{
// Since we always keep one dummy entry at the beginning,
// subtract one from the size
return m_stack.size() - 1;
}
bool
empty() const
{
return size() == 0 ? true : false;
}
void
clear();
void
reset();
private:
// not implemented
OutputContextStack(const OutputContextStack&);
bool
operator==(const OutputContextStack&) const;
OutputContextStack&
operator=(const OutputContextStack&);
/**
* A stack to hold the output contexts...
*/
OutputContextStackType m_stack;
OutputContextStackType::iterator m_stackPosition;
};
#endif // XALAN_RESULTNAMESPACESSTACK_HEADER_GUARD
<commit_msg>Added header file.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2000 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 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) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XALAN_OUTPUTCONTEXTSTACK_HEADER_GUARD)
#define XALAN_OUTPUTCONTEXTSTACK_HEADER_GUARD
// Base include file. Must be first.
#include <XSLT/XSLTDefinitions.hpp>
#include <deque>
#include <XalanDOM/XalanDOMString.hpp>
#include <PlatformSupport/AttributeListImpl.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
class FormatterListener;
class XALAN_XSLT_EXPORT OutputContextStack
{
public:
struct OutputContext
{
OutputContext(FormatterListener* theListener = 0) :
m_flistener(theListener),
m_pendingAttributes(),
m_pendingElementName(),
m_hasPendingStartDocument(false),
m_mustFlushPendingStartDocument(false)
{
}
~OutputContext()
{
}
void
reset()
{
m_flistener = 0;
m_pendingAttributes.clear();
::clear(m_pendingElementName);
m_hasPendingStartDocument = false;
m_mustFlushPendingStartDocument = false;
}
FormatterListener* m_flistener;
AttributeListImpl m_pendingAttributes;
XalanDOMString m_pendingElementName;
bool m_hasPendingStartDocument;
bool m_mustFlushPendingStartDocument;
};
#if defined(XALAN_NO_NAMESPACES)
typedef deque<OutputContext> OutputContextStackType;
#else
typedef std::deque<OutputContext> OutputContextStackType;
#endif
typedef OutputContextStackType::size_type size_type;
explicit
OutputContextStack();
~OutputContextStack();
void
pushContext(FormatterListener* theListener = 0);
void
popContext();
FormatterListener*
getFormatterListener() const
{
return (*m_stackPosition).m_flistener;
}
FormatterListener*&
getFormatterListener()
{
return (*m_stackPosition).m_flistener;
}
const AttributeListImpl&
getPendingAttributes() const
{
return (*m_stackPosition).m_pendingAttributes;
}
AttributeListImpl&
getPendingAttributes()
{
return (*m_stackPosition).m_pendingAttributes;
}
const XalanDOMString&
getPendingElementName() const
{
return (*m_stackPosition).m_pendingElementName;
}
XalanDOMString&
getPendingElementName()
{
return (*m_stackPosition).m_pendingElementName;
}
const bool&
getHasPendingStartDocument() const
{
return (*m_stackPosition).m_hasPendingStartDocument;
}
bool&
getHasPendingStartDocument()
{
return (*m_stackPosition).m_hasPendingStartDocument;
}
const bool&
getMustFlushPendingStartDocument() const
{
return (*m_stackPosition).m_mustFlushPendingStartDocument;
}
bool&
getMustFlushPendingStartDocument()
{
return (*m_stackPosition).m_mustFlushPendingStartDocument;
}
size_type
size() const
{
// Since we always keep one dummy entry at the beginning,
// subtract one from the size
return m_stack.size() - 1;
}
bool
empty() const
{
return size() == 0 ? true : false;
}
void
clear();
void
reset();
private:
// not implemented
OutputContextStack(const OutputContextStack&);
bool
operator==(const OutputContextStack&) const;
OutputContextStack&
operator=(const OutputContextStack&);
/**
* A stack to hold the output contexts...
*/
OutputContextStackType m_stack;
OutputContextStackType::iterator m_stackPosition;
};
#endif // XALAN_RESULTNAMESPACESSTACK_HEADER_GUARD
<|endoftext|> |
<commit_before>#include <cmd_game_delete_handler.h>
#include <runtasks.h>
#include <QJsonArray>
#include <QCryptographicHash>
CmdGameDeleteHandler::CmdGameDeleteHandler(){
m_vInputs.push_back(CmdInputDef("uuid").uuid_().required().description("Global Identificator of the Game"));
m_vInputs.push_back(CmdInputDef("logo").string_().required().description("Logo"));
m_vInputs.push_back(CmdInputDef("name").string_().required().description("Name of the Game"));
m_vInputs.push_back(CmdInputDef("description").string_().required().description("Description of the Game"));
m_vInputs.push_back(CmdInputDef("state").string_().required().description("State of the game"));
m_vInputs.push_back(CmdInputDef("form").string_().required().description("Form of the game"));
m_vInputs.push_back(CmdInputDef("type").string_().required().description("Type of the game"));
m_vInputs.push_back(CmdInputDef("date_start").string_().required().description("Date start"));
m_vInputs.push_back(CmdInputDef("date_stop").string_().required().description("Date stop"));
m_vInputs.push_back(CmdInputDef("date_restart").string_().required().description("Date restart"));
m_vInputs.push_back(CmdInputDef("organizators").string_().required().description("Organizators"));
}
QString CmdGameDeleteHandler::cmd(){
return "game_delete";
}
bool CmdGameDeleteHandler::accessUnauthorized(){
return false;
}
bool CmdGameDeleteHandler::accessUser(){
return false;
}
bool CmdGameDeleteHandler::accessTester(){
return false;
}
bool CmdGameDeleteHandler::accessAdmin(){
return true;
}
const QVector<CmdInputDef> &CmdGameDeleteHandler::inputs(){
return m_vInputs;
};
QString CmdGameDeleteHandler::description(){
return "Delete the game";
}
QStringList CmdGameDeleteHandler::errors(){
QStringList list;
return list;
}
void CmdGameDeleteHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){
// TODO
pWebSocketServer->sendMessageError(pClient, cmd(), m, Errors::NotImplementedYet());
return;
QJsonObject jsonData;
jsonData["cmd"] = QJsonValue(cmd());
jsonData["result"] = QJsonValue("DONE");
jsonData["m"] = QJsonValue(m);
pWebSocketServer->sendMessage(pClient, jsonData);
}
<commit_msg>Implemneted game delete<commit_after>#include <cmd_game_delete_handler.h>
#include <runtasks.h>
#include <QJsonArray>
#include <QCryptographicHash>
CmdGameDeleteHandler::CmdGameDeleteHandler(){
m_vInputs.push_back(CmdInputDef("gameid").integer_().required().description("Game ID"));
m_vInputs.push_back(CmdInputDef("admin_password").string_().required().description("Admin Password"));
}
QString CmdGameDeleteHandler::cmd(){
return "game_delete";
}
bool CmdGameDeleteHandler::accessUnauthorized(){
return false;
}
bool CmdGameDeleteHandler::accessUser(){
return false;
}
bool CmdGameDeleteHandler::accessTester(){
return false;
}
bool CmdGameDeleteHandler::accessAdmin(){
return true;
}
const QVector<CmdInputDef> &CmdGameDeleteHandler::inputs(){
return m_vInputs;
};
QString CmdGameDeleteHandler::description(){
return "Remove game and all quests";
}
QStringList CmdGameDeleteHandler::errors(){
QStringList list;
return list;
}
void CmdGameDeleteHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){
int nGameID = obj["gameid"].toInt();
QString sAdminPassword = obj["admin_password"].toString();
IUserToken *pUserToken = pWebSocketServer->getUserToken(pClient);
int nUserID = pUserToken->userid();
QSqlDatabase db = *(pWebSocketServer->database());
{
QSqlQuery query(db);
query.prepare("SELECT * FROM users WHERE id = :userid");
query.bindValue(":userid", nUserID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
QString sPass = "";
QString sEmail = "";
if (query.next()) {
QSqlRecord record = query.record();
sEmail = record.value("email").toString();
sPass = record.value("pass").toString();
}else{
pWebSocketServer->sendMessageError(pClient, cmd(), m, Errors::NotFound("user"));
return;
}
if(sAdminPassword != sPass){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(401, "Wrong password"));
return;
}
}
{
QSqlQuery query(db);
query.prepare("SELECT * FROM games WHERE id = :gameid");
query.bindValue(":gameid", nGameID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if(!query.next()) {
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Game not found"));
return;
}
}
// delete from users_games
{
QSqlQuery query_del(db);
query_del.prepare("DELETE FROM users_games WHERE gameid = :gameid");
query_del.bindValue(":gameid", nGameID);
if(!query_del.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query_del.lastError().text()));
return;
}
}
// delete from users_quests_answers
{
QSqlQuery query_del(db);
query_del.prepare("DELETE FROM users_quests_answers WHERE questid IN (SELECT idquest FROM quest q WHERE q.gameid = :gameid)");
query_del.bindValue(":gameid", nGameID);
if(!query_del.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query_del.lastError().text()));
return;
}
}
// delete from users_quests
{
QSqlQuery query_del(db);
query_del.prepare("DELETE FROM users_quests WHERE questid IN (SELECT idquest FROM quest q WHERE q.gameid = :gameid)");
query_del.bindValue(":gameid", nGameID);
if(!query_del.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query_del.lastError().text()));
return;
}
}
// delete from quests
{
QSqlQuery query_del(db);
query_del.prepare("DELETE FROM quest WHERE gameid = :gameid");
query_del.bindValue(":gameid", nGameID);
if(!query_del.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query_del.lastError().text()));
return;
}
}
// delete from games
{
QSqlQuery query_del(db);
query_del.prepare("DELETE FROM games WHERE id = :gameid");
query_del.bindValue(":gameid", nGameID);
if(!query_del.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query_del.lastError().text()));
return;
}
}
QJsonObject jsonData;
jsonData["cmd"] = QJsonValue(cmd());
jsonData["result"] = QJsonValue("DONE");
jsonData["m"] = QJsonValue(m);
pWebSocketServer->sendMessage(pClient, jsonData);
}
<|endoftext|> |
<commit_before>#include <cphvb.h>
#include <cphvb_compute.h>
/**
* cphvb_compute_reduce
*
* Implementation of the user-defined funtion "reduce".
* Note that we follow the function signature defined by cphvb_userfunc_impl.
*
*/
cphvb_error cphvb_compute_reduce(cphvb_userfunc *arg, void* ve_arg)
{
cphvb_reduce_type *a = (cphvb_reduce_type *) arg;
cphvb_instruction tinst;
cphvb_instruction *inst[1] = {&tinst};
cphvb_error err;
cphvb_intp i,j;
cphvb_index coord[CPHVB_MAXDIM];
memset(coord, 0, a->operand[1]->ndim * sizeof(cphvb_index));
if(cphvb_operands(a->opcode) != 3)
{
fprintf(stderr, "Reduce only support binary operations.\n");
exit(-1);
}
// Make sure that the array memory is allocated.
if(cphvb_data_malloc(a->operand[0]) != CPHVB_SUCCESS ||
cphvb_data_malloc(a->operand[1]) != CPHVB_SUCCESS)
{
return CPHVB_OUT_OF_MEMORY;
}
//We need a tmp copy of the arrays.
cphvb_array *out = a->operand[0];
cphvb_array *in = a->operand[1];
cphvb_array tmp = *in;
tmp.base = cphvb_base_array(in);
cphvb_intp step = in->stride[a->axis];
tmp.start = 0;
j=0;
for(i=0; i<in->ndim; ++i)//Remove the 'axis' dimension from in
if(i != a->axis)
{
tmp.shape[j] = in->shape[i];
tmp.stride[j] = in->stride[i];
++j;
}
--tmp.ndim;
//We copy the first element to the output.
inst[0]->status = CPHVB_INST_UNDONE;
inst[0]->opcode = CPHVB_IDENTITY;
inst[0]->operand[0] = out;
inst[0]->operand[1] = &tmp;
err = cphvb_compute_apply( inst[0] ); // execute the instruction...
if(err != CPHVB_SUCCESS)
return err;
tmp.start += step;
//Reduce over the 'axis' dimension.
//NB: the first element is already handled.
inst[0]->status = CPHVB_INST_UNDONE;
inst[0]->opcode = a->opcode;
inst[0]->operand[0] = out;
inst[0]->operand[1] = out;
inst[0]->operand[2] = &tmp;
cphvb_intp axis_size = in->shape[a->axis];
for(i=1; i<axis_size; ++i)
{
//One block per thread.
err = cphvb_compute_apply(inst[0]);
if(err != CPHVB_SUCCESS)
return err;
tmp.start += step;
}
return CPHVB_SUCCESS;
}
<commit_msg>Some cleanup during debugging.<commit_after>#include <cphvb.h>
#include <cphvb_compute.h>
/**
* cphvb_compute_reduce
*
* Implementation of the user-defined funtion "reduce".
* Note that we follow the function signature defined by cphvb_userfunc_impl.
*
*/
cphvb_error cphvb_compute_reduce(cphvb_userfunc *arg, void* ve_arg)
{
cphvb_reduce_type *a = (cphvb_reduce_type *) arg;
cphvb_instruction inst;
cphvb_error err;
cphvb_intp i,j;
cphvb_index coord[CPHVB_MAXDIM];
memset(coord, 0, a->operand[1]->ndim * sizeof(cphvb_index));
cphvb_array *out, *in, tmp; // We need a tmp copy of the arrays.
if(cphvb_operands(a->opcode) != 3)
{
fprintf(stderr, "Reduce only support binary operations.\n");
exit(-1);
}
// Make sure that the array memory is allocated.
if(cphvb_data_malloc(a->operand[0]) != CPHVB_SUCCESS ||
cphvb_data_malloc(a->operand[1]) != CPHVB_SUCCESS)
{
return CPHVB_OUT_OF_MEMORY;
}
//We need a tmp copy of the arrays.
out = a->operand[0];
in = a->operand[1];
// WARN: This does not always succeed!
tmp = *in;
tmp.base = cphvb_base_array(in);
cphvb_intp step = in->stride[a->axis];
tmp.start = 0;
j=0;
for(i=0; i<in->ndim; ++i) //Remove the 'axis' dimension from in
if(i != a->axis)
{
tmp.shape[j] = in->shape[i];
tmp.stride[j] = in->stride[i];
++j;
}
--tmp.ndim;
//We copy the first element to the output.
inst.status = NULL;
inst.opcode = CPHVB_IDENTITY;
inst.operand[0] = out;
inst.operand[1] = &tmp;
inst.operand[2] = NULL;
err = cphvb_compute_apply( &inst ); // execute the instruction...
if(err != CPHVB_SUCCESS)
return err;
tmp.start += step;
//Reduce over the 'axis' dimension.
//NB: the first element is already handled.
inst.status = NULL;
inst.opcode = a->opcode;
inst.operand[0] = out;
inst.operand[1] = out;
inst.operand[2] = &tmp;
cphvb_intp axis_size = in->shape[a->axis];
for(i=1; i<axis_size; ++i)
{
// One block per thread.
err = cphvb_compute_apply( &inst );
if(err != CPHVB_SUCCESS)
return err;
tmp.start += step;
}
return CPHVB_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
*
*/
#include <iostream>
#include <iomanip>
using namespace std;
class CSlist
{
private:
unsigned long int list[20];
unsigned int howMany;
void shiftList(unsigned int);
public:
CSlist();
int add(unsigned long int);
int remove(unsigned long int);
void show(void);
unsigned int getHowMany(void);
int search(unsigned long int);
void batchAdd(void);
int userInteract(void);
};
int main()
{
CSlist students;
while (students.userInteract())
{
cout << '\n';
}
return 0;
}
CSlist::CSlist()
{
howMany = 0;
}
void CSlist::shiftList(unsigned int index)
{
for (unsigned int i = index; i < 20; i++)
{
list[i] = list[i + 1];
}
list[19] = 0;
}
int CSlist::add(unsigned long int stuid)
{
if (howMany < 20)
{
if (search(stuid) > -1)
{
return -1;
}
else
{
list[howMany] = stuid;
return ++howMany;
}
}
return 0;
}
int CSlist::remove(unsigned long int stuid)
{
for (int i = 0; i < 20; i++)
{
if (list[i] == stuid)
{
shiftList(i);
return --howMany;
}
}
return 0;
}
void CSlist::show(void)
{
for (unsigned int i = 0; i < howMany; i++)
{
cout << setw(2) << setfill('0') << i + 1;
cout << ") " << list[i] << endl;
}
}
unsigned int CSlist::getHowMany(void)
{
return howMany;
}
int CSlist::search(unsigned long int stuid)
{
for (unsigned int i = 0; i < howMany; i++)
{
if (list[i] == stuid)
{
return i;
}
}
return -1;
}
void CSlist::batchAdd(void)
{
cout << "Getting student IDs (Enter 0 to break):" << endl;
do
{
unsigned long int userInput;
cout << "New student ID: ";
cin >> userInput;
if (userInput == 0)
{
break;
}
int res = add(userInput);
if (res > 0)
{
cout << "Added successfully (" << getHowMany() << ")" << endl;
}
else if (res == 0)
{
cerr << "Can't add. no more room!" << endl;
break;
}
else if (res == -1)
{
cerr << "Duplicate entery!" << endl;
}
} while(true);
}
int CSlist::userInteract(void)
{
cout << "1. Batch add\n2. Show all\n3. Remove\n4. eXit" << endl;
char selected;
cin >> selected;
switch (selected)
{
case '1':
case 'B':
case 'b':
batchAdd();
return 1;
case '2':
case 'S':
case 's':
show();
return 2;
case '3':
case 'R':
case 'r':
long unsigned int stuid;
cout << "Enter a student ID to remove:" << endl;
cin >> stuid;
cout << "There are " << remove(stuid) << " students in the list." << endl;
return 3;
case '4':
case 'X':
case 'x':
case 'Q':
case 'q':
return 0;
default:
userInteract();
}
return 0; // never happens. it's here to avoid compiler warning.
}
<commit_msg>Added comment in head<commit_after>/*
* Class to store student IDs of 20 students.
* source available at (Github repo - MIT licence):
* http://dstjrd.ir/s/cppx
* https://github.com/mohsend/cpp-examples
*/
#include <iostream>
#include <iomanip>
using namespace std;
class CSlist
{
private:
unsigned long int list[20];
unsigned int howMany;
void shiftList(unsigned int);
public:
CSlist();
int add(unsigned long int);
int remove(unsigned long int);
void show(void);
unsigned int getHowMany(void);
int search(unsigned long int);
void batchAdd(void);
int userInteract(void);
};
int main()
{
CSlist students;
while (students.userInteract())
{
cout << '\n';
}
return 0;
}
CSlist::CSlist()
{
howMany = 0;
}
void CSlist::shiftList(unsigned int index)
{
for (unsigned int i = index; i < 20; i++)
{
list[i] = list[i + 1];
}
list[19] = 0;
}
int CSlist::add(unsigned long int stuid)
{
if (howMany < 20)
{
if (search(stuid) > -1)
{
return -1;
}
else
{
list[howMany] = stuid;
return ++howMany;
}
}
return 0;
}
int CSlist::remove(unsigned long int stuid)
{
for (int i = 0; i < 20; i++)
{
if (list[i] == stuid)
{
shiftList(i);
return --howMany;
}
}
return 0;
}
void CSlist::show(void)
{
for (unsigned int i = 0; i < howMany; i++)
{
cout << setw(2) << setfill('0') << i + 1;
cout << ") " << list[i] << endl;
}
}
unsigned int CSlist::getHowMany(void)
{
return howMany;
}
int CSlist::search(unsigned long int stuid)
{
for (unsigned int i = 0; i < howMany; i++)
{
if (list[i] == stuid)
{
return i;
}
}
return -1;
}
void CSlist::batchAdd(void)
{
cout << "Getting student IDs (Enter 0 to break):" << endl;
do
{
unsigned long int userInput;
cout << "New student ID: ";
cin >> userInput;
if (userInput == 0)
{
break;
}
int res = add(userInput);
if (res > 0)
{
cout << "Added successfully (" << getHowMany() << ")" << endl;
}
else if (res == 0)
{
cerr << "Can't add. no more room!" << endl;
break;
}
else if (res == -1)
{
cerr << "Duplicate entery!" << endl;
}
} while(true);
}
int CSlist::userInteract(void)
{
cout << "1. Batch add\n2. Show all\n3. Remove\n4. eXit" << endl;
char selected;
cin >> selected;
switch (selected)
{
case '1':
case 'B':
case 'b':
batchAdd();
return 1;
case '2':
case 'S':
case 's':
show();
return 2;
case '3':
case 'R':
case 'r':
long unsigned int stuid;
cout << "Enter a student ID to remove:" << endl;
cin >> stuid;
cout << "There are " << remove(stuid) << " students in the list." << endl;
return 3;
case '4':
case 'X':
case 'x':
case 'Q':
case 'q':
return 0;
default:
userInteract();
}
return 0; // never happens. it's here to avoid compiler warning.
}
<|endoftext|> |
<commit_before><commit_msg>fwk139: #i108330# integrate patch<commit_after><|endoftext|> |
<commit_before>/*
* Copyright © 2013 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 link_interface_blocks.cpp
* Linker support for GLSL's interface blocks.
*/
#include "ir.h"
#include "glsl_symbol_table.h"
#include "linker.h"
#include "main/macros.h"
#include "util/hash_table.h"
namespace {
/**
* Check if two interfaces match, according to intrastage interface matching
* rules. If they do, and the first interface uses an unsized array, it will
* be updated to reflect the array size declared in the second interface.
*/
bool
intrastage_match(ir_variable *a,
ir_variable *b,
struct gl_shader_program *prog)
{
/* Types must match. */
if (a->get_interface_type() != b->get_interface_type()) {
/* Exception: if both the interface blocks are implicitly declared,
* don't force their types to match. They might mismatch due to the two
* shaders using different GLSL versions, and that's ok.
*/
if (a->data.how_declared != ir_var_declared_implicitly ||
b->data.how_declared != ir_var_declared_implicitly)
return false;
}
/* Presence/absence of interface names must match. */
if (a->is_interface_instance() != b->is_interface_instance())
return false;
/* For uniforms, instance names need not match. For shader ins/outs,
* it's not clear from the spec whether they need to match, but
* Mesa's implementation relies on them matching.
*/
if (a->is_interface_instance() && b->data.mode != ir_var_uniform &&
b->data.mode != ir_var_shader_storage &&
strcmp(a->name, b->name) != 0) {
return false;
}
/* If a block is an array then it must match across the shader.
* Unsized arrays are also processed and matched agaist sized arrays.
*/
if (b->type != a->type &&
(b->is_interface_instance() || a->is_interface_instance()) &&
!validate_intrastage_arrays(prog, b, a))
return false;
return true;
}
/**
* Check if two interfaces match, according to interstage (in/out) interface
* matching rules.
*
* If \c extra_array_level is true, the consumer interface is required to be
* an array and the producer interface is required to be a non-array.
* This is used for tessellation control and geometry shader consumers.
*/
bool
interstage_match(ir_variable *producer,
ir_variable *consumer,
bool extra_array_level)
{
/* Unsized arrays should not occur during interstage linking. They
* should have all been assigned a size by link_intrastage_shaders.
*/
assert(!consumer->type->is_unsized_array());
assert(!producer->type->is_unsized_array());
/* Types must match. */
if (consumer->get_interface_type() != producer->get_interface_type()) {
/* Exception: if both the interface blocks are implicitly declared,
* don't force their types to match. They might mismatch due to the two
* shaders using different GLSL versions, and that's ok.
*/
if (consumer->data.how_declared != ir_var_declared_implicitly ||
producer->data.how_declared != ir_var_declared_implicitly)
return false;
}
/* Ignore outermost array if geom shader */
const glsl_type *consumer_instance_type;
if (extra_array_level) {
consumer_instance_type = consumer->type->fields.array;
} else {
consumer_instance_type = consumer->type;
}
/* If a block is an array then it must match across shaders.
* Since unsized arrays have been ruled out, we can check this by just
* making sure the types are equal.
*/
if ((consumer->is_interface_instance() &&
consumer_instance_type->is_array()) ||
(producer->is_interface_instance() &&
producer->type->is_array())) {
if (consumer_instance_type != producer->type)
return false;
}
return true;
}
/**
* This class keeps track of a mapping from an interface block name to the
* necessary information about that interface block to determine whether to
* generate a link error.
*
* Note: this class is expected to be short lived, so it doesn't make copies
* of the strings it references; it simply borrows the pointers from the
* ir_variable class.
*/
class interface_block_definitions
{
public:
interface_block_definitions()
: mem_ctx(ralloc_context(NULL)),
ht(_mesa_hash_table_create(NULL, _mesa_key_hash_string,
_mesa_key_string_equal))
{
}
~interface_block_definitions()
{
ralloc_free(mem_ctx);
_mesa_hash_table_destroy(ht, NULL);
}
/**
* Lookup the interface definition. Return NULL if none is found.
*/
ir_variable *lookup(ir_variable *var)
{
if (var->data.explicit_location &&
var->data.location >= VARYING_SLOT_VAR0) {
char location_str[11];
snprintf(location_str, 11, "%d", var->data.location);
const struct hash_entry *entry =
_mesa_hash_table_search(ht, location_str);
return entry ? (ir_variable *) entry->data : NULL;
} else {
const struct hash_entry *entry =
_mesa_hash_table_search(ht, var->get_interface_type()->name);
return entry ? (ir_variable *) entry->data : NULL;
}
}
/**
* Add a new interface definition.
*/
void store(ir_variable *var)
{
if (var->data.explicit_location &&
var->data.location >= VARYING_SLOT_VAR0) {
/* If explicit location is given then lookup the variable by location.
* We turn the location into a string and use this as the hash key
* rather than the name. Note: We allocate enough space for a 32-bit
* unsigned location value which is overkill but future proof.
*/
char location_str[11];
snprintf(location_str, 11, "%d", var->data.location);
_mesa_hash_table_insert(ht, ralloc_strdup(mem_ctx, location_str), var);
} else {
_mesa_hash_table_insert(ht, var->get_interface_type()->name, var);
}
}
private:
/**
* Ralloc context for data structures allocated by this class.
*/
void *mem_ctx;
/**
* Hash table mapping interface block name to an \c
* ir_variable.
*/
hash_table *ht;
};
}; /* anonymous namespace */
void
validate_intrastage_interface_blocks(struct gl_shader_program *prog,
const gl_shader **shader_list,
unsigned num_shaders)
{
interface_block_definitions in_interfaces;
interface_block_definitions out_interfaces;
interface_block_definitions uniform_interfaces;
interface_block_definitions buffer_interfaces;
for (unsigned int i = 0; i < num_shaders; i++) {
if (shader_list[i] == NULL)
continue;
foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
ir_variable *var = node->as_variable();
if (!var)
continue;
const glsl_type *iface_type = var->get_interface_type();
if (iface_type == NULL)
continue;
interface_block_definitions *definitions;
switch (var->data.mode) {
case ir_var_shader_in:
definitions = &in_interfaces;
break;
case ir_var_shader_out:
definitions = &out_interfaces;
break;
case ir_var_uniform:
definitions = &uniform_interfaces;
break;
case ir_var_shader_storage:
definitions = &buffer_interfaces;
break;
default:
/* Only in, out, and uniform interfaces are legal, so we should
* never get here.
*/
assert(!"illegal interface type");
continue;
}
ir_variable *prev_def = definitions->lookup(var);
if (prev_def == NULL) {
/* This is the first time we've seen the interface, so save
* it into the appropriate data structure.
*/
definitions->store(var);
} else if (!intrastage_match(prev_def, var, prog)) {
linker_error(prog, "definitions of interface block `%s' do not"
" match\n", iface_type->name);
return;
}
}
}
}
void
validate_interstage_inout_blocks(struct gl_shader_program *prog,
const gl_shader *producer,
const gl_shader *consumer)
{
interface_block_definitions definitions;
/* VS -> GS, VS -> TCS, VS -> TES, TES -> GS */
const bool extra_array_level = (producer->Stage == MESA_SHADER_VERTEX &&
consumer->Stage != MESA_SHADER_FRAGMENT) ||
consumer->Stage == MESA_SHADER_GEOMETRY;
/* Add input interfaces from the consumer to the symbol table. */
foreach_in_list(ir_instruction, node, consumer->ir) {
ir_variable *var = node->as_variable();
if (!var || !var->get_interface_type() || var->data.mode != ir_var_shader_in)
continue;
definitions.store(var);
}
/* Verify that the producer's output interfaces match. */
foreach_in_list(ir_instruction, node, producer->ir) {
ir_variable *var = node->as_variable();
if (!var || !var->get_interface_type() || var->data.mode != ir_var_shader_out)
continue;
ir_variable *consumer_def = definitions.lookup(var);
/* The consumer doesn't use this output block. Ignore it. */
if (consumer_def == NULL)
continue;
if (!interstage_match(var, consumer_def, extra_array_level)) {
linker_error(prog, "definitions of interface block `%s' do not "
"match\n", var->get_interface_type()->name);
return;
}
}
}
void
validate_interstage_uniform_blocks(struct gl_shader_program *prog,
gl_shader **stages, int num_stages)
{
interface_block_definitions definitions;
for (int i = 0; i < num_stages; i++) {
if (stages[i] == NULL)
continue;
const gl_shader *stage = stages[i];
foreach_in_list(ir_instruction, node, stage->ir) {
ir_variable *var = node->as_variable();
if (!var || !var->get_interface_type() ||
(var->data.mode != ir_var_uniform &&
var->data.mode != ir_var_shader_storage))
continue;
ir_variable *old_def = definitions.lookup(var);
if (old_def == NULL) {
definitions.store(var);
} else {
/* Interstage uniform matching rules are the same as intrastage
* uniform matchin rules (for uniforms, it is as though all
* shaders are in the same shader stage).
*/
if (!intrastage_match(old_def, var, prog)) {
linker_error(prog, "definitions of interface block `%s' do not "
"match\n", var->get_interface_type()->name);
return;
}
}
}
}
}
<commit_msg>glsl: make interstage_match() static<commit_after>/*
* Copyright © 2013 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 link_interface_blocks.cpp
* Linker support for GLSL's interface blocks.
*/
#include "ir.h"
#include "glsl_symbol_table.h"
#include "linker.h"
#include "main/macros.h"
#include "util/hash_table.h"
namespace {
/**
* Check if two interfaces match, according to intrastage interface matching
* rules. If they do, and the first interface uses an unsized array, it will
* be updated to reflect the array size declared in the second interface.
*/
bool
intrastage_match(ir_variable *a,
ir_variable *b,
struct gl_shader_program *prog)
{
/* Types must match. */
if (a->get_interface_type() != b->get_interface_type()) {
/* Exception: if both the interface blocks are implicitly declared,
* don't force their types to match. They might mismatch due to the two
* shaders using different GLSL versions, and that's ok.
*/
if (a->data.how_declared != ir_var_declared_implicitly ||
b->data.how_declared != ir_var_declared_implicitly)
return false;
}
/* Presence/absence of interface names must match. */
if (a->is_interface_instance() != b->is_interface_instance())
return false;
/* For uniforms, instance names need not match. For shader ins/outs,
* it's not clear from the spec whether they need to match, but
* Mesa's implementation relies on them matching.
*/
if (a->is_interface_instance() && b->data.mode != ir_var_uniform &&
b->data.mode != ir_var_shader_storage &&
strcmp(a->name, b->name) != 0) {
return false;
}
/* If a block is an array then it must match across the shader.
* Unsized arrays are also processed and matched agaist sized arrays.
*/
if (b->type != a->type &&
(b->is_interface_instance() || a->is_interface_instance()) &&
!validate_intrastage_arrays(prog, b, a))
return false;
return true;
}
/**
* Check if two interfaces match, according to interstage (in/out) interface
* matching rules.
*
* If \c extra_array_level is true, the consumer interface is required to be
* an array and the producer interface is required to be a non-array.
* This is used for tessellation control and geometry shader consumers.
*/
static bool
interstage_match(ir_variable *producer,
ir_variable *consumer,
bool extra_array_level)
{
/* Unsized arrays should not occur during interstage linking. They
* should have all been assigned a size by link_intrastage_shaders.
*/
assert(!consumer->type->is_unsized_array());
assert(!producer->type->is_unsized_array());
/* Types must match. */
if (consumer->get_interface_type() != producer->get_interface_type()) {
/* Exception: if both the interface blocks are implicitly declared,
* don't force their types to match. They might mismatch due to the two
* shaders using different GLSL versions, and that's ok.
*/
if (consumer->data.how_declared != ir_var_declared_implicitly ||
producer->data.how_declared != ir_var_declared_implicitly)
return false;
}
/* Ignore outermost array if geom shader */
const glsl_type *consumer_instance_type;
if (extra_array_level) {
consumer_instance_type = consumer->type->fields.array;
} else {
consumer_instance_type = consumer->type;
}
/* If a block is an array then it must match across shaders.
* Since unsized arrays have been ruled out, we can check this by just
* making sure the types are equal.
*/
if ((consumer->is_interface_instance() &&
consumer_instance_type->is_array()) ||
(producer->is_interface_instance() &&
producer->type->is_array())) {
if (consumer_instance_type != producer->type)
return false;
}
return true;
}
/**
* This class keeps track of a mapping from an interface block name to the
* necessary information about that interface block to determine whether to
* generate a link error.
*
* Note: this class is expected to be short lived, so it doesn't make copies
* of the strings it references; it simply borrows the pointers from the
* ir_variable class.
*/
class interface_block_definitions
{
public:
interface_block_definitions()
: mem_ctx(ralloc_context(NULL)),
ht(_mesa_hash_table_create(NULL, _mesa_key_hash_string,
_mesa_key_string_equal))
{
}
~interface_block_definitions()
{
ralloc_free(mem_ctx);
_mesa_hash_table_destroy(ht, NULL);
}
/**
* Lookup the interface definition. Return NULL if none is found.
*/
ir_variable *lookup(ir_variable *var)
{
if (var->data.explicit_location &&
var->data.location >= VARYING_SLOT_VAR0) {
char location_str[11];
snprintf(location_str, 11, "%d", var->data.location);
const struct hash_entry *entry =
_mesa_hash_table_search(ht, location_str);
return entry ? (ir_variable *) entry->data : NULL;
} else {
const struct hash_entry *entry =
_mesa_hash_table_search(ht, var->get_interface_type()->name);
return entry ? (ir_variable *) entry->data : NULL;
}
}
/**
* Add a new interface definition.
*/
void store(ir_variable *var)
{
if (var->data.explicit_location &&
var->data.location >= VARYING_SLOT_VAR0) {
/* If explicit location is given then lookup the variable by location.
* We turn the location into a string and use this as the hash key
* rather than the name. Note: We allocate enough space for a 32-bit
* unsigned location value which is overkill but future proof.
*/
char location_str[11];
snprintf(location_str, 11, "%d", var->data.location);
_mesa_hash_table_insert(ht, ralloc_strdup(mem_ctx, location_str), var);
} else {
_mesa_hash_table_insert(ht, var->get_interface_type()->name, var);
}
}
private:
/**
* Ralloc context for data structures allocated by this class.
*/
void *mem_ctx;
/**
* Hash table mapping interface block name to an \c
* ir_variable.
*/
hash_table *ht;
};
}; /* anonymous namespace */
void
validate_intrastage_interface_blocks(struct gl_shader_program *prog,
const gl_shader **shader_list,
unsigned num_shaders)
{
interface_block_definitions in_interfaces;
interface_block_definitions out_interfaces;
interface_block_definitions uniform_interfaces;
interface_block_definitions buffer_interfaces;
for (unsigned int i = 0; i < num_shaders; i++) {
if (shader_list[i] == NULL)
continue;
foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
ir_variable *var = node->as_variable();
if (!var)
continue;
const glsl_type *iface_type = var->get_interface_type();
if (iface_type == NULL)
continue;
interface_block_definitions *definitions;
switch (var->data.mode) {
case ir_var_shader_in:
definitions = &in_interfaces;
break;
case ir_var_shader_out:
definitions = &out_interfaces;
break;
case ir_var_uniform:
definitions = &uniform_interfaces;
break;
case ir_var_shader_storage:
definitions = &buffer_interfaces;
break;
default:
/* Only in, out, and uniform interfaces are legal, so we should
* never get here.
*/
assert(!"illegal interface type");
continue;
}
ir_variable *prev_def = definitions->lookup(var);
if (prev_def == NULL) {
/* This is the first time we've seen the interface, so save
* it into the appropriate data structure.
*/
definitions->store(var);
} else if (!intrastage_match(prev_def, var, prog)) {
linker_error(prog, "definitions of interface block `%s' do not"
" match\n", iface_type->name);
return;
}
}
}
}
void
validate_interstage_inout_blocks(struct gl_shader_program *prog,
const gl_shader *producer,
const gl_shader *consumer)
{
interface_block_definitions definitions;
/* VS -> GS, VS -> TCS, VS -> TES, TES -> GS */
const bool extra_array_level = (producer->Stage == MESA_SHADER_VERTEX &&
consumer->Stage != MESA_SHADER_FRAGMENT) ||
consumer->Stage == MESA_SHADER_GEOMETRY;
/* Add input interfaces from the consumer to the symbol table. */
foreach_in_list(ir_instruction, node, consumer->ir) {
ir_variable *var = node->as_variable();
if (!var || !var->get_interface_type() || var->data.mode != ir_var_shader_in)
continue;
definitions.store(var);
}
/* Verify that the producer's output interfaces match. */
foreach_in_list(ir_instruction, node, producer->ir) {
ir_variable *var = node->as_variable();
if (!var || !var->get_interface_type() || var->data.mode != ir_var_shader_out)
continue;
ir_variable *consumer_def = definitions.lookup(var);
/* The consumer doesn't use this output block. Ignore it. */
if (consumer_def == NULL)
continue;
if (!interstage_match(var, consumer_def, extra_array_level)) {
linker_error(prog, "definitions of interface block `%s' do not "
"match\n", var->get_interface_type()->name);
return;
}
}
}
void
validate_interstage_uniform_blocks(struct gl_shader_program *prog,
gl_shader **stages, int num_stages)
{
interface_block_definitions definitions;
for (int i = 0; i < num_stages; i++) {
if (stages[i] == NULL)
continue;
const gl_shader *stage = stages[i];
foreach_in_list(ir_instruction, node, stage->ir) {
ir_variable *var = node->as_variable();
if (!var || !var->get_interface_type() ||
(var->data.mode != ir_var_uniform &&
var->data.mode != ir_var_shader_storage))
continue;
ir_variable *old_def = definitions.lookup(var);
if (old_def == NULL) {
definitions.store(var);
} else {
/* Interstage uniform matching rules are the same as intrastage
* uniform matchin rules (for uniforms, it is as though all
* shaders are in the same shader stage).
*/
if (!intrastage_match(old_def, var, prog)) {
linker_error(prog, "definitions of interface block `%s' do not "
"match\n", var->get_interface_type()->name);
return;
}
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Adam Chyła, adam@chyla.org
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include <boost/log/trivial.hpp>
#include <patlms/dbus/detail/dbus.h>
#include <patlms/dbus/detail/dbus_wrapper.h>
#include <patlms/dbus/detail/dbus_error_guard.h>
#include <patlms/dbus/exception/dbus_exception.h>
namespace dbus
{
namespace detail
{
DBusWrapperPtr DBusWrapper::Create() {
auto ptr = DBus::Create();
return DBusWrapper::Create(ptr);
}
DBusWrapperPtr DBusWrapper::Create(DBusInterfacePtr dbus_interface) {
return DBusWrapperPtr(new DBusWrapper(dbus_interface));
}
void DBusWrapper::ConnectionOpenPrivate(const std::string &address) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionOpenPrivate: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
connection_ = dbus_interface_->connection_open_private(address.c_str(), &error_);
if (connection_ == nullptr) {
BOOST_LOG_TRIVIAL(error) << "dbus::detail::DBusWrapper::ConnectionOpenPrivate: Failed to connect to the bus: " << GetErrorMessage(error_);
throw ::dbus::exception::DBusException();
}
}
void DBusWrapper::BusRegister() {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::BusRegister: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
auto ret = dbus_interface_->bus_register(connection_, &error_);
CheckForFalseThenThrowException(ret, error_);
}
void DBusWrapper::ConnectionSetExitOnDisconnect(dbus_bool_t exit_on_disconnect) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::BusRegister: Function call (exit_on_disconnect=" << exit_on_disconnect;
dbus_interface_->connection_set_exit_on_disconnect(connection_, exit_on_disconnect);
}
void DBusWrapper::ConnectionClose() {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionClose: Function call";
dbus_interface_->connection_close(connection_);
dbus_interface_->connection_unref(connection_);
connection_ = nullptr;
}
int DBusWrapper::BusRequestName(const std::string &name,
unsigned int flags) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::BusRequestName: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
auto ret = dbus_interface_->bus_request_name(connection_, name.c_str(), flags, &error_);
if (ret < 0)
CheckForFalseThenThrowException(false, error_);
return ret;
}
void DBusWrapper::ConnectionRegisterObjectPath(const std::string &path,
const DBusObjectPathVTable *vtable,
void *user_data) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionRegisterObjectPath: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
auto ret = dbus_interface_->connection_register_object_path(connection_, path.c_str(), vtable, user_data);
CheckForFalseThenThrowException(ret, error_);
}
void DBusWrapper::ConnectionReadWrite(int timeout_milliseconds) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionReadWrite: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
auto ret = dbus_interface_->connection_read_write(connection_, timeout_milliseconds);
CheckForFalseThenThrowException(ret, error_);
}
DBusMessage* DBusWrapper::ConnectionBorrowMessage() {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionBorrowMessage: Function call";
auto msg = dbus_interface_->connection_borrow_message(connection_);
if (msg == nullptr)
BOOST_LOG_TRIVIAL(warning) << "dbus::detail::DBusWrapper::ConnectionBorrowMessage: Message pointer is null";
return msg;
}
void DBusWrapper::ConnectionReturnMessage(DBusMessage *message) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionReturnMessage: Function call";
dbus_interface_->connection_return_message(connection_, message);
}
DBusDispatchStatus DBusWrapper::ConnectionDispatch() {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionDispatch: Function call";
return dbus_interface_->connection_dispatch(connection_);
}
void DBusWrapper::ConnectionSendWithReply(DBusMessage *message,
DBusPendingCall **pending_return,
int timeout_milliseconds) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionSendWithReply: Function call";
auto ret = dbus_interface_->connection_send_with_reply(connection_, message, pending_return, timeout_milliseconds);
CheckForFalseThenThrowException(ret);
if (*pending_return == nullptr) {
BOOST_LOG_TRIVIAL(error) << "dbus::detail::DBusWrapper::ConnectionSendWithReply: pending_return is null";
throw ::dbus::exception::DBusException();
}
}
void DBusWrapper::ConnectionFlush() {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionFlush: Function call";
dbus_interface_->connection_flush(connection_);
}
void DBusWrapper::ConnectionUnregisterObjectPath(const std::string &path) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionUnregisterObjectPath: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
auto ret = dbus_interface_->connection_unregister_object_path(connection_, path.c_str());
CheckForFalseThenThrowException(ret, error_);
}
DBusConnection* DBusWrapper::GetConnection() {
return connection_;
}
DBusWrapper::DBusWrapper(DBusInterfacePtr dbus_interface) :
dbus_interface_(dbus_interface),
connection_(nullptr) {
}
void DBusWrapper::CheckForFalseThenThrowException(dbus_bool_t ret) {
if (ret == false) {
BOOST_LOG_TRIVIAL(error) << "dbus::detail::DBusWrapper::CheckForFalseThenThrowException: DBus error";
throw ::dbus::exception::DBusException();
}
}
void DBusWrapper::CheckForFalseThenThrowException(dbus_bool_t ret, const DBusError &error) {
if (ret == false) {
BOOST_LOG_TRIVIAL(error) << "dbus::detail::DBusWrapper::CheckForFalseThenThrowException: DBus error: " << GetErrorMessage(error_);
throw ::dbus::exception::DBusException();
}
}
std::string DBusWrapper::GetErrorMessage(const DBusError &error) {
return error.message != nullptr ? error.message : "";
}
}
}
<commit_msg>Change warning to debug message<commit_after>/*
* Copyright 2016 Adam Chyła, adam@chyla.org
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include <boost/log/trivial.hpp>
#include <patlms/dbus/detail/dbus.h>
#include <patlms/dbus/detail/dbus_wrapper.h>
#include <patlms/dbus/detail/dbus_error_guard.h>
#include <patlms/dbus/exception/dbus_exception.h>
namespace dbus
{
namespace detail
{
DBusWrapperPtr DBusWrapper::Create() {
auto ptr = DBus::Create();
return DBusWrapper::Create(ptr);
}
DBusWrapperPtr DBusWrapper::Create(DBusInterfacePtr dbus_interface) {
return DBusWrapperPtr(new DBusWrapper(dbus_interface));
}
void DBusWrapper::ConnectionOpenPrivate(const std::string &address) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionOpenPrivate: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
connection_ = dbus_interface_->connection_open_private(address.c_str(), &error_);
if (connection_ == nullptr) {
BOOST_LOG_TRIVIAL(error) << "dbus::detail::DBusWrapper::ConnectionOpenPrivate: Failed to connect to the bus: " << GetErrorMessage(error_);
throw ::dbus::exception::DBusException();
}
}
void DBusWrapper::BusRegister() {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::BusRegister: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
auto ret = dbus_interface_->bus_register(connection_, &error_);
CheckForFalseThenThrowException(ret, error_);
}
void DBusWrapper::ConnectionSetExitOnDisconnect(dbus_bool_t exit_on_disconnect) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::BusRegister: Function call (exit_on_disconnect=" << exit_on_disconnect;
dbus_interface_->connection_set_exit_on_disconnect(connection_, exit_on_disconnect);
}
void DBusWrapper::ConnectionClose() {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionClose: Function call";
dbus_interface_->connection_close(connection_);
dbus_interface_->connection_unref(connection_);
connection_ = nullptr;
}
int DBusWrapper::BusRequestName(const std::string &name,
unsigned int flags) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::BusRequestName: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
auto ret = dbus_interface_->bus_request_name(connection_, name.c_str(), flags, &error_);
if (ret < 0)
CheckForFalseThenThrowException(false, error_);
return ret;
}
void DBusWrapper::ConnectionRegisterObjectPath(const std::string &path,
const DBusObjectPathVTable *vtable,
void *user_data) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionRegisterObjectPath: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
auto ret = dbus_interface_->connection_register_object_path(connection_, path.c_str(), vtable, user_data);
CheckForFalseThenThrowException(ret, error_);
}
void DBusWrapper::ConnectionReadWrite(int timeout_milliseconds) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionReadWrite: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
auto ret = dbus_interface_->connection_read_write(connection_, timeout_milliseconds);
CheckForFalseThenThrowException(ret, error_);
}
DBusMessage* DBusWrapper::ConnectionBorrowMessage() {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionBorrowMessage: Function call";
auto msg = dbus_interface_->connection_borrow_message(connection_);
if (msg == nullptr)
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionBorrowMessage: Message pointer is null";
return msg;
}
void DBusWrapper::ConnectionReturnMessage(DBusMessage *message) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionReturnMessage: Function call";
dbus_interface_->connection_return_message(connection_, message);
}
DBusDispatchStatus DBusWrapper::ConnectionDispatch() {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionDispatch: Function call";
return dbus_interface_->connection_dispatch(connection_);
}
void DBusWrapper::ConnectionSendWithReply(DBusMessage *message,
DBusPendingCall **pending_return,
int timeout_milliseconds) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionSendWithReply: Function call";
auto ret = dbus_interface_->connection_send_with_reply(connection_, message, pending_return, timeout_milliseconds);
CheckForFalseThenThrowException(ret);
if (*pending_return == nullptr) {
BOOST_LOG_TRIVIAL(error) << "dbus::detail::DBusWrapper::ConnectionSendWithReply: pending_return is null";
throw ::dbus::exception::DBusException();
}
}
void DBusWrapper::ConnectionFlush() {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionFlush: Function call";
dbus_interface_->connection_flush(connection_);
}
void DBusWrapper::ConnectionUnregisterObjectPath(const std::string &path) {
BOOST_LOG_TRIVIAL(debug) << "dbus::detail::DBusWrapper::ConnectionUnregisterObjectPath: Function call";
DBusErrorGuard error_guard(dbus_interface_, &error_);
auto ret = dbus_interface_->connection_unregister_object_path(connection_, path.c_str());
CheckForFalseThenThrowException(ret, error_);
}
DBusConnection* DBusWrapper::GetConnection() {
return connection_;
}
DBusWrapper::DBusWrapper(DBusInterfacePtr dbus_interface) :
dbus_interface_(dbus_interface),
connection_(nullptr) {
}
void DBusWrapper::CheckForFalseThenThrowException(dbus_bool_t ret) {
if (ret == false) {
BOOST_LOG_TRIVIAL(error) << "dbus::detail::DBusWrapper::CheckForFalseThenThrowException: DBus error";
throw ::dbus::exception::DBusException();
}
}
void DBusWrapper::CheckForFalseThenThrowException(dbus_bool_t ret, const DBusError &error) {
if (ret == false) {
BOOST_LOG_TRIVIAL(error) << "dbus::detail::DBusWrapper::CheckForFalseThenThrowException: DBus error: " << GetErrorMessage(error_);
throw ::dbus::exception::DBusException();
}
}
std::string DBusWrapper::GetErrorMessage(const DBusError &error) {
return error.message != nullptr ? error.message : "";
}
}
}
<|endoftext|> |
<commit_before>/* KPilot
**
** Copyright (C) 2001 by Dan Pilone
** Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
**
** This file defines the base class of all KPilot conduit plugins configuration
** dialogs. This is necessary so that we have a fixed API to talk to from
** inside KPilot.
**
** The factories used by KPilot plugins are also documented here.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "options.h"
#include <stdlib.h>
#include <qstringlist.h>
#include <qfileinfo.h>
#include <qdir.h>
#include <qregexp.h>
#include <qtextcodec.h>
#include <dcopclient.h>
#include <kapplication.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <klibloader.h>
#include "pilotSerialDatabase.h"
#include "pilotLocalDatabase.h"
#include "pilotAppCategory.h"
#include "plugin.moc"
ConduitConfigBase::ConduitConfigBase(QWidget *parent,
const char *name) :
QObject(parent,name),
fModified(false),
fWidget(0L),
fConduitName(i18n("Unnamed"))
{
FUNCTIONSETUP;
}
ConduitConfigBase::~ConduitConfigBase()
{
FUNCTIONSETUP;
}
/* slot */ void ConduitConfigBase::modified()
{
fModified=true;
emit changed(true);
}
/* virtual */ QString ConduitConfigBase::maybeSaveText() const
{
FUNCTIONSETUP;
return i18n("<qt>The <i>%1</i> conduit's settings have been changed. Do you "
"want to save the changes before continuing?</qt>").arg(this->conduitName());
}
/* virtual */ bool ConduitConfigBase::maybeSave()
{
FUNCTIONSETUP;
if (!isModified()) return true;
int r = KMessageBox::questionYesNoCancel(fWidget,
maybeSaveText(),
i18n("%1 Conduit").arg(this->conduitName()));
if (r == KMessageBox::Cancel) return false;
if (r == KMessageBox::Yes) commit();
return true;
}
ConduitAction::ConduitAction(KPilotDeviceLink *p,
const char *name,
const QStringList &args) :
SyncAction(p,name),
fDatabase(0L),
fLocalDatabase(0L),
fTest(args.contains(CSL1("--test"))),
fBackup(args.contains(CSL1("--backup"))),
fLocal(args.contains(CSL1("--local"))),
fConflictResolution(SyncAction::eAskUser),
fFirstSync(false)
{
FUNCTIONSETUP;
if (args.contains(CSL1("--copyPCToHH"))) fSyncDirection=SyncAction::eCopyPCToHH;
else if (args.contains(CSL1("--copyHHToPC"))) fSyncDirection=SyncAction::eCopyHHToPC;
else if (args.contains(CSL1("--full"))) fSyncDirection=SyncAction::eFullSync;
else fSyncDirection=SyncAction::eFastSync;
QString cResolution(args.grep(QRegExp(CSL1("--conflictResolution \\d*"))).first());
if (cResolution.isEmpty())
{
fConflictResolution=(SyncAction::ConflictResolution)
cResolution.replace(QRegExp(CSL1("--conflictResolution (\\d*)")), CSL1("\\1")).toInt();
}
#ifdef DEBUG
for (QStringList::ConstIterator it = args.begin();
it != args.end();
++it)
{
DEBUGCONDUIT << fname << ": " << *it << endl;
}
DEBUGCONDUIT << fname << ": Direction=" << fSyncDirection << endl;
#endif
}
/* virtual */ ConduitAction::~ConduitAction()
{
FUNCTIONSETUP;
KPILOT_DELETE(fDatabase);
KPILOT_DELETE(fLocalDatabase);
}
bool ConduitAction::openDatabases_(const QString &name, bool *retrieved)
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Trying to open database "
<< name << endl;
#endif
KPILOT_DELETE(fLocalDatabase);
PilotLocalDatabase *localDB = new PilotLocalDatabase(name, true);
if (!localDB)
{
kdWarning() << k_funcinfo
<< ": Could not initialize object for local copy of database \""
<< name
<< "\"" << endl;
if (retrieved) *retrieved = false;
return false;
}
// if there is no backup db yet, fetch it from the palm, open it and set the full sync flag.
if (!localDB->isDBOpen() )
{
QString dbpath(localDB->dbPathName());
KPILOT_DELETE(localDB);
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Backup database "<< dbpath <<" could not be opened. Will fetch a copy from the palm and do a full sync"<<endl;
#endif
struct DBInfo dbinfo;
if (fHandle->findDatabase(PilotAppCategory::codec()->fromUnicode( name ), &dbinfo)<0 )
{
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Could not get DBInfo for "<<name<<"! "<<endl;
#endif
if (retrieved) *retrieved = false;
return false;
}
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Found Palm database: "<<dbinfo.name<<endl
<<"type = "<< dbinfo.type<<endl
<<"creator = "<< dbinfo.creator<<endl
<<"version = "<< dbinfo.version<<endl
<<"index = "<< dbinfo.index<<endl;
#endif
dbinfo.flags &= ~dlpDBFlagOpen;
// make sure the dir for the backup db really exists!
QFileInfo fi(dbpath);
QString path(QFileInfo(dbpath).dir(TRUE).absPath());
if (!path.endsWith(CSL1("/"))) path.append(CSL1("/"));
if (!KStandardDirs::exists(path))
{
#ifdef DEBUG
DEBUGCONDUIT << fname << ": Trying to create path for database: <"
<< path << ">" << endl;
#endif
KStandardDirs::makeDir(path);
}
if (!KStandardDirs::exists(path))
{
#ifdef DEBUG
DEBUGCONDUIT << fname << ": Database directory does not exist." << endl;
#endif
if (retrieved) *retrieved = false;
return false;
}
if (!fHandle->retrieveDatabase(dbpath, &dbinfo) )
{
#ifdef DEBUG
DEBUGCONDUIT << fname << ": Could not retrieve database "<<name<<" from the handheld."<<endl;
#endif
if (retrieved) *retrieved = false;
return false;
}
localDB = new PilotLocalDatabase(name, true);
if (!localDB || !localDB->isDBOpen())
{
#ifdef DEBUG
DEBUGCONDUIT << fname << ": local backup of database "<<name<<" could not be initialized."<<endl;
#endif
if (retrieved) *retrieved = false;
return false;
}
if (retrieved) *retrieved=true;
}
fLocalDatabase = localDB;
// These latin1()'s are ok, since database names are latin1-coded.
fDatabase = new PilotSerialDatabase(pilotSocket(), name /* On pilot */);
if (!fDatabase)
{
kdWarning() << k_funcinfo
<< ": Could not open database \""
<< name
<< "\" on the pilot."
<< endl;
}
return (fDatabase && fDatabase->isDBOpen() &&
fLocalDatabase && fLocalDatabase->isDBOpen() );
}
// This whole function is for debugging purposes only.
bool ConduitAction::openDatabases_(const QString &dbName,const QString &localPath)
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGCONDUIT << fname << ": Doing local test mode for " << dbName << endl;
#endif
if (localPath.isNull())
{
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": local mode test for one database only."
<< endl;
#endif
fDatabase = new PilotLocalDatabase(dbName);
fLocalDatabase = 0L;
return false;
}
fDatabase = new PilotLocalDatabase(localPath,dbName);
fLocalDatabase= new PilotLocalDatabase(dbName, true); // From default
if (!fLocalDatabase || !fDatabase)
{
#ifdef DEBUG
const QString *where2 = PilotLocalDatabase::getDBPath();
QString none = CSL1("<null>");
DEBUGCONDUIT << fname
<< ": Could not open both local copies of \""
<< dbName
<< "\"" << endl
<< "Using \""
<< (where2 ? *where2 : none)
<< "\" and \""
<< (localPath.isEmpty() ? localPath : none)
<< "\""
<< endl;
#endif
}
#ifdef DEBUG
if (fLocalDatabase)
{
DEBUGCONDUIT << fname
<< ": Opened local database "
<< fLocalDatabase->dbPathName()
<< (fLocalDatabase->isDBOpen() ? " OK" : "")
<< endl;
}
if (fDatabase)
{
DEBUGCONDUIT << fname
<< ": Opened database "
<< fDatabase->dbPathName()
<< (fDatabase->isDBOpen() ? " OK" : "")
<< endl;
}
#endif
return (fDatabase && fLocalDatabase);
}
bool ConduitAction::openDatabases(const QString &dbName, bool *retrieved)
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Mode="
<< (isTest() ? "test " : "")
<< (isLocal() ? "local " : "")
<< endl ;
#endif
if (isLocal())
{
return openDatabases_(dbName,CSL1("/tmp/"));
}
else
{
return openDatabases_(dbName, retrieved);
}
}
int PluginUtility::findHandle(const QStringList &a)
{
FUNCTIONSETUP;
int handle = -1;
for (QStringList::ConstIterator i = a.begin();
i != a.end(); ++i)
{
if ((*i).left(7) == CSL1("handle="))
{
QString s = (*i).mid(7);
if (s.isEmpty()) continue;
handle = s.toInt();
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Got handle "
<< handle
<< endl;
#endif
if (handle<1)
{
kdWarning() << k_funcinfo
<< ": Improbable handle value found."
<< endl;
}
return handle;
}
}
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": No handle= parameter found."
<< endl;
#endif
return -1;
}
bool PluginUtility::isModal(const QStringList &a)
{
return a.contains(CSL1("modal"));
}
/* static */ bool PluginUtility::isRunning(const QCString &n)
{
FUNCTIONSETUP;
DCOPClient *dcop = KApplication::kApplication()->dcopClient();
QCStringList apps = dcop->registeredApplications();
return apps.contains(n);
}
/* static */ long PluginUtility::pluginVersion(const KLibrary *lib)
{
QString symbol = CSL1("version_");
symbol.append(lib->name());
if (!lib->hasSymbol(symbol.latin1())) return 0;
long *p = (long *)(lib->symbol(symbol.latin1()));
return *p;
}
/* static */ QString PluginUtility::pluginVersionString(const KLibrary *lib)
{
QString symbol= CSL1("id_");
symbol.append(lib->name());
if (!lib->hasSymbol(symbol.latin1())) return QString::null;
return QString::fromLatin1(*((const char **)(lib->symbol(symbol.latin1()))));
}
<commit_msg>Database names not necessarily latin1<commit_after>/* KPilot
**
** Copyright (C) 2001 by Dan Pilone
** Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
**
** This file defines the base class of all KPilot conduit plugins configuration
** dialogs. This is necessary so that we have a fixed API to talk to from
** inside KPilot.
**
** The factories used by KPilot plugins are also documented here.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "options.h"
#include <stdlib.h>
#include <qstringlist.h>
#include <qfileinfo.h>
#include <qdir.h>
#include <qregexp.h>
#include <qtextcodec.h>
#include <dcopclient.h>
#include <kapplication.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <klibloader.h>
#include "pilotSerialDatabase.h"
#include "pilotLocalDatabase.h"
#include "pilotAppCategory.h"
#include "plugin.moc"
ConduitConfigBase::ConduitConfigBase(QWidget *parent,
const char *name) :
QObject(parent,name),
fModified(false),
fWidget(0L),
fConduitName(i18n("Unnamed"))
{
FUNCTIONSETUP;
}
ConduitConfigBase::~ConduitConfigBase()
{
FUNCTIONSETUP;
}
/* slot */ void ConduitConfigBase::modified()
{
fModified=true;
emit changed(true);
}
/* virtual */ QString ConduitConfigBase::maybeSaveText() const
{
FUNCTIONSETUP;
return i18n("<qt>The <i>%1</i> conduit's settings have been changed. Do you "
"want to save the changes before continuing?</qt>").arg(this->conduitName());
}
/* virtual */ bool ConduitConfigBase::maybeSave()
{
FUNCTIONSETUP;
if (!isModified()) return true;
int r = KMessageBox::questionYesNoCancel(fWidget,
maybeSaveText(),
i18n("%1 Conduit").arg(this->conduitName()));
if (r == KMessageBox::Cancel) return false;
if (r == KMessageBox::Yes) commit();
return true;
}
ConduitAction::ConduitAction(KPilotDeviceLink *p,
const char *name,
const QStringList &args) :
SyncAction(p,name),
fDatabase(0L),
fLocalDatabase(0L),
fTest(args.contains(CSL1("--test"))),
fBackup(args.contains(CSL1("--backup"))),
fLocal(args.contains(CSL1("--local"))),
fConflictResolution(SyncAction::eAskUser),
fFirstSync(false)
{
FUNCTIONSETUP;
if (args.contains(CSL1("--copyPCToHH"))) fSyncDirection=SyncAction::eCopyPCToHH;
else if (args.contains(CSL1("--copyHHToPC"))) fSyncDirection=SyncAction::eCopyHHToPC;
else if (args.contains(CSL1("--full"))) fSyncDirection=SyncAction::eFullSync;
else fSyncDirection=SyncAction::eFastSync;
QString cResolution(args.grep(QRegExp(CSL1("--conflictResolution \\d*"))).first());
if (cResolution.isEmpty())
{
fConflictResolution=(SyncAction::ConflictResolution)
cResolution.replace(QRegExp(CSL1("--conflictResolution (\\d*)")), CSL1("\\1")).toInt();
}
#ifdef DEBUG
for (QStringList::ConstIterator it = args.begin();
it != args.end();
++it)
{
DEBUGCONDUIT << fname << ": " << *it << endl;
}
DEBUGCONDUIT << fname << ": Direction=" << fSyncDirection << endl;
#endif
}
/* virtual */ ConduitAction::~ConduitAction()
{
FUNCTIONSETUP;
KPILOT_DELETE(fDatabase);
KPILOT_DELETE(fLocalDatabase);
}
bool ConduitAction::openDatabases_(const QString &name, bool *retrieved)
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Trying to open database "
<< name << endl;
#endif
KPILOT_DELETE(fLocalDatabase);
PilotLocalDatabase *localDB = new PilotLocalDatabase(name, true);
if (!localDB)
{
kdWarning() << k_funcinfo
<< ": Could not initialize object for local copy of database \""
<< name
<< "\"" << endl;
if (retrieved) *retrieved = false;
return false;
}
// if there is no backup db yet, fetch it from the palm, open it and set the full sync flag.
if (!localDB->isDBOpen() )
{
QString dbpath(localDB->dbPathName());
KPILOT_DELETE(localDB);
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Backup database "<< dbpath <<" could not be opened. Will fetch a copy from the palm and do a full sync"<<endl;
#endif
struct DBInfo dbinfo;
if (fHandle->findDatabase(PilotAppCategory::codec()->fromUnicode( name ), &dbinfo)<0 )
{
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Could not get DBInfo for "<<name<<"! "<<endl;
#endif
if (retrieved) *retrieved = false;
return false;
}
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Found Palm database: "<<dbinfo.name<<endl
<<"type = "<< dbinfo.type<<endl
<<"creator = "<< dbinfo.creator<<endl
<<"version = "<< dbinfo.version<<endl
<<"index = "<< dbinfo.index<<endl;
#endif
dbinfo.flags &= ~dlpDBFlagOpen;
// make sure the dir for the backup db really exists!
QFileInfo fi(dbpath);
QString path(QFileInfo(dbpath).dir(TRUE).absPath());
if (!path.endsWith(CSL1("/"))) path.append(CSL1("/"));
if (!KStandardDirs::exists(path))
{
#ifdef DEBUG
DEBUGCONDUIT << fname << ": Trying to create path for database: <"
<< path << ">" << endl;
#endif
KStandardDirs::makeDir(path);
}
if (!KStandardDirs::exists(path))
{
#ifdef DEBUG
DEBUGCONDUIT << fname << ": Database directory does not exist." << endl;
#endif
if (retrieved) *retrieved = false;
return false;
}
if (!fHandle->retrieveDatabase(dbpath, &dbinfo) )
{
#ifdef DEBUG
DEBUGCONDUIT << fname << ": Could not retrieve database "<<name<<" from the handheld."<<endl;
#endif
if (retrieved) *retrieved = false;
return false;
}
localDB = new PilotLocalDatabase(name, true);
if (!localDB || !localDB->isDBOpen())
{
#ifdef DEBUG
DEBUGCONDUIT << fname << ": local backup of database "<<name<<" could not be initialized."<<endl;
#endif
if (retrieved) *retrieved = false;
return false;
}
if (retrieved) *retrieved=true;
}
fLocalDatabase = localDB;
fDatabase = new PilotSerialDatabase(pilotSocket(), name /* On pilot */);
if (!fDatabase)
{
kdWarning() << k_funcinfo
<< ": Could not open database \""
<< name
<< "\" on the pilot."
<< endl;
}
return (fDatabase && fDatabase->isDBOpen() &&
fLocalDatabase && fLocalDatabase->isDBOpen() );
}
// This whole function is for debugging purposes only.
bool ConduitAction::openDatabases_(const QString &dbName,const QString &localPath)
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGCONDUIT << fname << ": Doing local test mode for " << dbName << endl;
#endif
if (localPath.isNull())
{
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": local mode test for one database only."
<< endl;
#endif
fDatabase = new PilotLocalDatabase(dbName);
fLocalDatabase = 0L;
return false;
}
fDatabase = new PilotLocalDatabase(localPath,dbName);
fLocalDatabase= new PilotLocalDatabase(dbName, true); // From default
if (!fLocalDatabase || !fDatabase)
{
#ifdef DEBUG
const QString *where2 = PilotLocalDatabase::getDBPath();
QString none = CSL1("<null>");
DEBUGCONDUIT << fname
<< ": Could not open both local copies of \""
<< dbName
<< "\"" << endl
<< "Using \""
<< (where2 ? *where2 : none)
<< "\" and \""
<< (localPath.isEmpty() ? localPath : none)
<< "\""
<< endl;
#endif
}
#ifdef DEBUG
if (fLocalDatabase)
{
DEBUGCONDUIT << fname
<< ": Opened local database "
<< fLocalDatabase->dbPathName()
<< (fLocalDatabase->isDBOpen() ? " OK" : "")
<< endl;
}
if (fDatabase)
{
DEBUGCONDUIT << fname
<< ": Opened database "
<< fDatabase->dbPathName()
<< (fDatabase->isDBOpen() ? " OK" : "")
<< endl;
}
#endif
return (fDatabase && fLocalDatabase);
}
bool ConduitAction::openDatabases(const QString &dbName, bool *retrieved)
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Mode="
<< (isTest() ? "test " : "")
<< (isLocal() ? "local " : "")
<< endl ;
#endif
if (isLocal())
{
return openDatabases_(dbName,CSL1("/tmp/"));
}
else
{
return openDatabases_(dbName, retrieved);
}
}
int PluginUtility::findHandle(const QStringList &a)
{
FUNCTIONSETUP;
int handle = -1;
for (QStringList::ConstIterator i = a.begin();
i != a.end(); ++i)
{
if ((*i).left(7) == CSL1("handle="))
{
QString s = (*i).mid(7);
if (s.isEmpty()) continue;
handle = s.toInt();
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Got handle "
<< handle
<< endl;
#endif
if (handle<1)
{
kdWarning() << k_funcinfo
<< ": Improbable handle value found."
<< endl;
}
return handle;
}
}
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": No handle= parameter found."
<< endl;
#endif
return -1;
}
bool PluginUtility::isModal(const QStringList &a)
{
return a.contains(CSL1("modal"));
}
/* static */ bool PluginUtility::isRunning(const QCString &n)
{
FUNCTIONSETUP;
DCOPClient *dcop = KApplication::kApplication()->dcopClient();
QCStringList apps = dcop->registeredApplications();
return apps.contains(n);
}
/* static */ long PluginUtility::pluginVersion(const KLibrary *lib)
{
QString symbol = CSL1("version_");
symbol.append(lib->name());
if (!lib->hasSymbol(symbol.latin1())) return 0;
long *p = (long *)(lib->symbol(symbol.latin1()));
return *p;
}
/* static */ QString PluginUtility::pluginVersionString(const KLibrary *lib)
{
QString symbol= CSL1("id_");
symbol.append(lib->name());
if (!lib->hasSymbol(symbol.latin1())) return QString::null;
return QString::fromLatin1(*((const char **)(lib->symbol(symbol.latin1()))));
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2010 Interactive Visualization and Data Analysis Group.
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.
*/
//! File : MedAlyVisFiberTractGeoConverter.cpp
//! Author : Jens Krueger
//! IVCI & DFKI & MMCI, Saarbruecken
//! SCI Institute, University of Utah
//! Date : July 2010
//
//! Copyright (C) 2010 DFKI, MMCI, SCI Institute
#include "MedAlyVisFiberTractGeoConverter.h"
#include "Controller/Controller.h"
#include "SysTools.h"
#include "Mesh.h"
#include <fstream>
#include "TuvokIOError.h"
using namespace tuvok;
using namespace std;
MedAlyVisFiberTractGeoConverter::MedAlyVisFiberTractGeoConverter() :
AbstrGeoConverter()
{
m_vConverterDesc = "MedAlyVis Fiber Tract File";
m_vSupportedExt.push_back("TRK");
}
Mesh* MedAlyVisFiberTractGeoConverter::ConvertToMesh(const std::string& strFilename) {
VertVec vertices;
ColorVec colors;
IndexVec VertIndices;
IndexVec COLIndices;
std::ifstream fs;
std::string line;
fs.open(strFilename.c_str());
if (fs.fail()) {
throw tuvok::io::DSOpenFailed(strFilename.c_str(), __FILE__, __LINE__);
}
int iReaderState = SEARCHING_DIM;
UINTVECTOR3 iDim;
FLOATVECTOR3 fScale;
FLOATVECTOR3 fTranslation;
INTVECTOR4 iMetadata;
size_t iElementCounter=0;
size_t iElementReadCounter=0;
int iLineCounter=-1;
while (!fs.fail() || iLineCounter == iMetadata[2]) {
getline(fs, line);
if (fs.fail()) break; // no more lines to read
// remove comments
size_t cPos = line.find_first_of('#');
if (cPos != std::string::npos) line = line.substr(0,cPos);
line = SysTools::TrimStr(line);
if (line.length() == 0) continue; // skips empty and comment lines
switch (iReaderState) {
case SEARCHING_DIM : {
iDim[0] = atoi(line.c_str());
line = TrimToken(line);
iDim[1] = atoi(line.c_str());
line = TrimToken(line);
iDim[2] = atoi(line.c_str());
iReaderState++;
}
break;
case SEARCHING_SCALE : {
fScale[0] = float(atof(line.c_str()));
line = TrimToken(line);
fScale[1] = float(atof(line.c_str()));
line = TrimToken(line);
fScale[2] = float(atof(line.c_str()));
iReaderState++;
}
break;
case SEARCHING_TRANSLATION : {
fTranslation[0] = float(atof(line.c_str()));
line = TrimToken(line);
fTranslation[1] = float(atof(line.c_str()));
line = TrimToken(line);
fTranslation[2] = float(atof(line.c_str()));
iReaderState++;
}
break;
case SEARCHING_METADATA : {
iMetadata[0] = atoi(line.c_str());
line = TrimToken(line);
iMetadata[1] = atoi(line.c_str());
line = TrimToken(line);
iMetadata[2] = atoi(line.c_str());
line = TrimToken(line);
iMetadata[3] = atoi(line.c_str());
iLineCounter = 0;
iReaderState++;
}
break;
case PARSING_COUNTER : {
iElementCounter = atoi(line.c_str());
iElementReadCounter = 0;
iReaderState++;
}
break;
case PARSING_DATA : {
FLOATVECTOR3 vec;
vec[0] = float(atof(line.c_str()));
line = TrimToken(line);
vec[1] = float(atof(line.c_str()));
line = TrimToken(line);
vec[2] = float(atof(line.c_str()));
vec = (vec + 0.5f*FLOATVECTOR3(iDim)*fScale) / (FLOATVECTOR3(iDim)*fScale) - 0.5f;
vertices.push_back(vec);
iElementReadCounter++;
if (iElementCounter == iElementReadCounter) {
size_t iStartIndex = vertices.size() - iElementCounter;
for (size_t i = 0;i<iElementCounter-1;i++) {
VertIndices.push_back(UINT32(iStartIndex));
VertIndices.push_back(UINT32(iStartIndex+1));
COLIndices.push_back(UINT32(iStartIndex));
COLIndices.push_back(UINT32(iStartIndex+1));
if (i == 0) {
FLOATVECTOR3 direction = (vertices[iStartIndex+1]-vertices[iStartIndex]).normalized();
colors.push_back((direction).abs());
} else if (i == iElementCounter-2) {
FLOATVECTOR3 directionB = (vertices[iStartIndex]-vertices[iStartIndex-1]).normalized();
FLOATVECTOR3 directionF = (vertices[iStartIndex+1]-vertices[iStartIndex]).normalized();
colors.push_back(((directionB+directionF)/2.0f).abs());
colors.push_back((directionF).abs());
} else {
FLOATVECTOR3 directionB = (vertices[iStartIndex]-vertices[iStartIndex-1]).normalized();
FLOATVECTOR3 directionF = (vertices[iStartIndex+1]-vertices[iStartIndex]).normalized();
colors.push_back(((directionB+directionF)/2.0f).abs());
}
iStartIndex++;
}
iLineCounter++;
iReaderState = PARSING_COUNTER;
}
}
break;
default : throw std::runtime_error("unknown parser state");
}
}
std::string desc = m_vConverterDesc + " data converted from " + SysTools::GetFilename(strFilename);
Mesh* m = new Mesh(vertices,NormVec(),TexCoordVec(),colors,
VertIndices,IndexVec(),IndexVec(),COLIndices,
false,false,desc,Mesh::MT_LINES);
return m;
}<commit_msg>the usual newline at eof<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2010 Interactive Visualization and Data Analysis Group.
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.
*/
//! File : MedAlyVisFiberTractGeoConverter.cpp
//! Author : Jens Krueger
//! IVCI & DFKI & MMCI, Saarbruecken
//! SCI Institute, University of Utah
//! Date : July 2010
//
//! Copyright (C) 2010 DFKI, MMCI, SCI Institute
#include "MedAlyVisFiberTractGeoConverter.h"
#include "Controller/Controller.h"
#include "SysTools.h"
#include "Mesh.h"
#include <fstream>
#include "TuvokIOError.h"
using namespace tuvok;
using namespace std;
MedAlyVisFiberTractGeoConverter::MedAlyVisFiberTractGeoConverter() :
AbstrGeoConverter()
{
m_vConverterDesc = "MedAlyVis Fiber Tract File";
m_vSupportedExt.push_back("TRK");
}
Mesh* MedAlyVisFiberTractGeoConverter::ConvertToMesh(const std::string& strFilename) {
VertVec vertices;
ColorVec colors;
IndexVec VertIndices;
IndexVec COLIndices;
std::ifstream fs;
std::string line;
fs.open(strFilename.c_str());
if (fs.fail()) {
throw tuvok::io::DSOpenFailed(strFilename.c_str(), __FILE__, __LINE__);
}
int iReaderState = SEARCHING_DIM;
UINTVECTOR3 iDim;
FLOATVECTOR3 fScale;
FLOATVECTOR3 fTranslation;
INTVECTOR4 iMetadata;
size_t iElementCounter=0;
size_t iElementReadCounter=0;
int iLineCounter=-1;
while (!fs.fail() || iLineCounter == iMetadata[2]) {
getline(fs, line);
if (fs.fail()) break; // no more lines to read
// remove comments
size_t cPos = line.find_first_of('#');
if (cPos != std::string::npos) line = line.substr(0,cPos);
line = SysTools::TrimStr(line);
if (line.length() == 0) continue; // skips empty and comment lines
switch (iReaderState) {
case SEARCHING_DIM : {
iDim[0] = atoi(line.c_str());
line = TrimToken(line);
iDim[1] = atoi(line.c_str());
line = TrimToken(line);
iDim[2] = atoi(line.c_str());
iReaderState++;
}
break;
case SEARCHING_SCALE : {
fScale[0] = float(atof(line.c_str()));
line = TrimToken(line);
fScale[1] = float(atof(line.c_str()));
line = TrimToken(line);
fScale[2] = float(atof(line.c_str()));
iReaderState++;
}
break;
case SEARCHING_TRANSLATION : {
fTranslation[0] = float(atof(line.c_str()));
line = TrimToken(line);
fTranslation[1] = float(atof(line.c_str()));
line = TrimToken(line);
fTranslation[2] = float(atof(line.c_str()));
iReaderState++;
}
break;
case SEARCHING_METADATA : {
iMetadata[0] = atoi(line.c_str());
line = TrimToken(line);
iMetadata[1] = atoi(line.c_str());
line = TrimToken(line);
iMetadata[2] = atoi(line.c_str());
line = TrimToken(line);
iMetadata[3] = atoi(line.c_str());
iLineCounter = 0;
iReaderState++;
}
break;
case PARSING_COUNTER : {
iElementCounter = atoi(line.c_str());
iElementReadCounter = 0;
iReaderState++;
}
break;
case PARSING_DATA : {
FLOATVECTOR3 vec;
vec[0] = float(atof(line.c_str()));
line = TrimToken(line);
vec[1] = float(atof(line.c_str()));
line = TrimToken(line);
vec[2] = float(atof(line.c_str()));
vec = (vec + 0.5f*FLOATVECTOR3(iDim)*fScale) / (FLOATVECTOR3(iDim)*fScale) - 0.5f;
vertices.push_back(vec);
iElementReadCounter++;
if (iElementCounter == iElementReadCounter) {
size_t iStartIndex = vertices.size() - iElementCounter;
for (size_t i = 0;i<iElementCounter-1;i++) {
VertIndices.push_back(UINT32(iStartIndex));
VertIndices.push_back(UINT32(iStartIndex+1));
COLIndices.push_back(UINT32(iStartIndex));
COLIndices.push_back(UINT32(iStartIndex+1));
if (i == 0) {
FLOATVECTOR3 direction = (vertices[iStartIndex+1]-vertices[iStartIndex]).normalized();
colors.push_back((direction).abs());
} else if (i == iElementCounter-2) {
FLOATVECTOR3 directionB = (vertices[iStartIndex]-vertices[iStartIndex-1]).normalized();
FLOATVECTOR3 directionF = (vertices[iStartIndex+1]-vertices[iStartIndex]).normalized();
colors.push_back(((directionB+directionF)/2.0f).abs());
colors.push_back((directionF).abs());
} else {
FLOATVECTOR3 directionB = (vertices[iStartIndex]-vertices[iStartIndex-1]).normalized();
FLOATVECTOR3 directionF = (vertices[iStartIndex+1]-vertices[iStartIndex]).normalized();
colors.push_back(((directionB+directionF)/2.0f).abs());
}
iStartIndex++;
}
iLineCounter++;
iReaderState = PARSING_COUNTER;
}
}
break;
default : throw std::runtime_error("unknown parser state");
}
}
std::string desc = m_vConverterDesc + " data converted from " + SysTools::GetFilename(strFilename);
Mesh* m = new Mesh(vertices,NormVec(),TexCoordVec(),colors,
VertIndices,IndexVec(),IndexVec(),COLIndices,
false,false,desc,Mesh::MT_LINES);
return m;
}
<|endoftext|> |
<commit_before>#include "Game.h"
#include "InputHandler.h"
#include "MenuState.h"
#include "NoJoystickState.h"
#include "PlayState.h"
#include <iostream>
#include <errno.h>
static Game* s_pInstance;
Game::Game() {
m_pWindow = 0;
m_pRenderer = 0;
fileNames.push_back(std::make_pair("animate", "resources/char9.bmp"));
fileNames.push_back(std::make_pair("mainmenu", "resources/menu-buttons.png"));
nbFiles = 2;
}
Game::~Game() {
InputHandler::Instance()->clean();
InputHandler::free();
_cleanResources();
TextureManager::free();
_cleanGameMachine();
SDL_DestroyWindow(m_pWindow);
SDL_DestroyRenderer(m_pRenderer);
// clean up SDL
SDL_Quit();
}
Game *Game::Instance() {
if (s_pInstance == 0) {
s_pInstance = new Game();
}
return s_pInstance;
}
void Game::free() {
delete s_pInstance;
s_pInstance = 0;
}
bool Game::init(
const char* title,
const int x,
const int y,
const int w,
const int h,
const bool fullScreen
) {
bool l_bReturn = true;
m_textureManager = TextureManager::Instance();
l_bReturn &= _initSDL(title, x, y, w, h, fullScreen);
l_bReturn &= _loadResources();
m_bRunning = l_bReturn;
if (l_bReturn) {
InputHandler::Instance()->initialiseJoysticks();
_initGameMachine();
}
return l_bReturn;
}
bool Game::_initSDL(
const char* title,
const int x,
const int y,
const int w,
const int h,
const bool fullScreen
) {
bool l_bReturn = true;
int flags = 0;
if (fullScreen) {
flags |= SDL_WINDOW_FULLSCREEN;
}
// initialize SDL
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
std::cout << "SDL Init failed\n";
l_bReturn = false;
}
else {
// if succeeded create our window
m_pWindow = SDL_CreateWindow(title, x, y, w, h, flags);
// if the window creation succeeded create our renderer
if (m_pWindow == 0) {
std::cout << "Window creation failed\n";
l_bReturn = false;
}
else {
m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);
if (m_pRenderer == 0) {
std::cout << "Renderer creation failed\n";
l_bReturn = false;
}
}
}
return l_bReturn;
}
bool Game::_loadResources() {
const char* errorPattern = "An error occured while loading the file %s\n%s\n";
std::cout << "Load resources \n";
for (int i = 0; i < nbFiles; ++i) {
char errorMessage[strlen(fileNames[i].second) + strlen(errorPattern) - 2];
std::cout << "Load resource " << fileNames[i].second << "\n";
bool textureLoaded = m_textureManager->load(
fileNames[i].second,
fileNames[i].first,
m_pRenderer
);
if (!textureLoaded) {
sprintf(errorMessage, errorPattern, fileNames[i].second, strerror(errno));
std::cout << errorMessage;
return false;
}
else {
std::cout << "Resource " << fileNames[i].second << " loaded\n";
}
}
return true;
}
void Game::_initGameMachine() {
m_pGameStateMachine = new GameStateMachine();
GameState* initialState;
if (!InputHandler::Instance()->joysticksInitialised()) {
initialState = new NoJoystickState();
}
else {
initialState = new MenuState();
}
m_pGameStateMachine->changeState(initialState);
}
void Game::handleEvents() {
bool keepRunning = InputHandler::Instance()->update();
if (!keepRunning) {
m_bRunning = false;
}
else {
if (InputHandler::Instance()->getButtonState(0, 0)) {
m_pGameStateMachine->changeState(new PlayState());
}
}
}
void Game::update() {
m_pGameStateMachine->update();
}
void Game::render() {
// set to black
// This function expects Red, Green, Blue and
// Alpha as color values
SDL_SetRenderDrawColor(m_pRenderer, 0, 0, 0, 255);
// clear the window to black
SDL_RenderClear(m_pRenderer);
m_pGameStateMachine->render();
// show the window
SDL_RenderPresent(m_pRenderer);
}
void Game::_cleanGameMachine() {
m_pGameStateMachine->clean();
delete m_pGameStateMachine;
m_pGameStateMachine = NULL;
}
void Game::_cleanResources() {
std::cout << "Clean resources\n";
for (int i = 0; i < nbFiles; ++i) {
std::cout << "Clean resource " << fileNames[i].second << "\n";
TextureManager::Instance()->clearFromTextureMap(fileNames[i].first);
}
}
bool Game::isRunning() {
return m_bRunning;
}
SDL_Renderer* Game::getRenderer() {
return m_pRenderer;
}
<commit_msg>not possible to access the play state from the game class<commit_after>#include "Game.h"
#include "InputHandler.h"
#include "MenuState.h"
#include "NoJoystickState.h"
#include <iostream>
#include <errno.h>
static Game* s_pInstance;
Game::Game() {
m_pWindow = 0;
m_pRenderer = 0;
fileNames.push_back(std::make_pair("animate", "resources/char9.bmp"));
fileNames.push_back(std::make_pair("mainmenu", "resources/menu-buttons.png"));
nbFiles = 2;
}
Game::~Game() {
InputHandler::Instance()->clean();
InputHandler::free();
_cleanResources();
TextureManager::free();
_cleanGameMachine();
SDL_DestroyWindow(m_pWindow);
SDL_DestroyRenderer(m_pRenderer);
// clean up SDL
SDL_Quit();
}
Game *Game::Instance() {
if (s_pInstance == 0) {
s_pInstance = new Game();
}
return s_pInstance;
}
void Game::free() {
delete s_pInstance;
s_pInstance = 0;
}
bool Game::init(
const char* title,
const int x,
const int y,
const int w,
const int h,
const bool fullScreen
) {
bool l_bReturn = true;
m_textureManager = TextureManager::Instance();
l_bReturn &= _initSDL(title, x, y, w, h, fullScreen);
l_bReturn &= _loadResources();
m_bRunning = l_bReturn;
if (l_bReturn) {
InputHandler::Instance()->initialiseJoysticks();
_initGameMachine();
}
return l_bReturn;
}
bool Game::_initSDL(
const char* title,
const int x,
const int y,
const int w,
const int h,
const bool fullScreen
) {
bool l_bReturn = true;
int flags = 0;
if (fullScreen) {
flags |= SDL_WINDOW_FULLSCREEN;
}
// initialize SDL
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
std::cout << "SDL Init failed\n";
l_bReturn = false;
}
else {
// if succeeded create our window
m_pWindow = SDL_CreateWindow(title, x, y, w, h, flags);
// if the window creation succeeded create our renderer
if (m_pWindow == 0) {
std::cout << "Window creation failed\n";
l_bReturn = false;
}
else {
m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);
if (m_pRenderer == 0) {
std::cout << "Renderer creation failed\n";
l_bReturn = false;
}
}
}
return l_bReturn;
}
bool Game::_loadResources() {
const char* errorPattern = "An error occured while loading the file %s\n%s\n";
std::cout << "Load resources \n";
for (int i = 0; i < nbFiles; ++i) {
char errorMessage[strlen(fileNames[i].second) + strlen(errorPattern) - 2];
std::cout << "Load resource " << fileNames[i].second << "\n";
bool textureLoaded = m_textureManager->load(
fileNames[i].second,
fileNames[i].first,
m_pRenderer
);
if (!textureLoaded) {
sprintf(errorMessage, errorPattern, fileNames[i].second, strerror(errno));
std::cout << errorMessage;
return false;
}
else {
std::cout << "Resource " << fileNames[i].second << " loaded\n";
}
}
return true;
}
void Game::_initGameMachine() {
m_pGameStateMachine = new GameStateMachine();
GameState* initialState;
if (!InputHandler::Instance()->joysticksInitialised()) {
initialState = new NoJoystickState();
}
else {
initialState = new MenuState();
}
m_pGameStateMachine->changeState(initialState);
}
void Game::handleEvents() {
bool keepRunning = InputHandler::Instance()->update();
if (!keepRunning) {
m_bRunning = false;
}
}
void Game::update() {
m_pGameStateMachine->update();
}
void Game::render() {
// set to black
// This function expects Red, Green, Blue and
// Alpha as color values
SDL_SetRenderDrawColor(m_pRenderer, 0, 0, 0, 255);
// clear the window to black
SDL_RenderClear(m_pRenderer);
m_pGameStateMachine->render();
// show the window
SDL_RenderPresent(m_pRenderer);
}
void Game::_cleanGameMachine() {
m_pGameStateMachine->clean();
delete m_pGameStateMachine;
m_pGameStateMachine = NULL;
}
void Game::_cleanResources() {
std::cout << "Clean resources\n";
for (int i = 0; i < nbFiles; ++i) {
std::cout << "Clean resource " << fileNames[i].second << "\n";
TextureManager::Instance()->clearFromTextureMap(fileNames[i].first);
}
}
bool Game::isRunning() {
return m_bRunning;
}
SDL_Renderer* Game::getRenderer() {
return m_pRenderer;
}
<|endoftext|> |
<commit_before>#include <sys/stat.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <ctime>
#include "HTTP.h"
using namespace std;
using namespace HTTP;
HTTP::Request::Request(const string& request){
string line;
stringstream sreq(request);
getline(sreq, line);
stringstream(line) >> this->method >> this->target >> this->protocol;
while(getline(sreq, line)){
int spos = line.find(' ');
this->header[line.substr(0, spos - 1)] = line.substr(spos + 1);
}
}
HTTP::Response::Response(Request& request){
char tbuffer[80];
time_t now = time(NULL);
struct tm gmt = *gmtime(&now);
strftime(tbuffer, sizeof(tbuffer), "%a, %d %b %Y %H:%M:%S %Z", &gmt);
this->protocol = "HTTP/1.1";
this->header["Connection"] = request.header["Connection"];
this->header["Server"] = "HTTPd by Rodrigo Siqueira, Marcos Iseki e Thiago Ikeda";
this->header["Date"] = tbuffer;
this->process(request);
}
void HTTP::Response::process(Request& request){
if(request.protocol != "HTTP/1.1"){
this->nothttp();
}
else if(request.method != "GET" && request.method != "POST"){
this->notmethod();
}
else if(this->isobj("www" + request.target)){
this->makeobj("www" + request.target);
}
/* else if(this->ismoved(request.target)){
this->makemoved();
}
*/
else{
this->notfound();
}
}
void HTTP::Response::nothttp(){
this->status = 505;
this->makefile("error/505.html");
}
void HTTP::Response::notfound(){
this->status = 404;
this->makefile("error/404.html");
}
void HTTP::Response::notmethod(){
this->status = 501;
this->makefile("error/501.html");
}
void HTTP::Response::makeobj(const string& target){
struct stat st;
lstat(target.c_str(), &st);
if(S_ISREG(st.st_mode)){
this->status = 200;
this->makefile(target);
}
else if(S_ISDIR(st.st_mode)){
this->status = 200;
this->makedir(target);
}
else{
this->status = 500;
this->makefile("error/500.html");
}
}
void HTTP::Response::makedir(const string& target){
this->notfound();
}
void HTTP::Response::makefile(const string& target){
ifstream file(target);
this->content.assign(
istreambuf_iterator<char>(file),
istreambuf_iterator<char>()
);
this->header["Content-Type"] = MIME[target.substr(target.rfind('.') + 1)];
this->header["Content-Length"] = to_string(this->content.length());
}
bool HTTP::Response::isobj(const string& target) const {
struct stat st;
lstat(target.c_str(), &st);
return S_ISDIR(st.st_mode) || S_ISREG(st.st_mode);
}
int HTTP::Response::generate(string& target){
stringstream tgt;
tgt << this->protocol << " " << this->status << " " << Code[this->status] << endl;
for(auto it = this->header.begin(); it != this->header.end(); it++){
tgt << it->first << ": " << it->second << endl;
}
tgt << endl;
tgt << endl;
tgt << this->content;
target = tgt.str();
return target.length();
}<commit_msg>Índice de diretório<commit_after>#include <sys/stat.h>
#include <dirent.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <ctime>
#include "HTTP.h"
using namespace std;
using namespace HTTP;
HTTP::Request::Request(const string& request){
string line;
stringstream sreq(request);
getline(sreq, line);
stringstream(line) >> this->method >> this->target >> this->protocol;
while(getline(sreq, line)){
int spos = line.find(' ');
this->header[line.substr(0, spos - 1)] = line.substr(spos + 1);
}
}
HTTP::Response::Response(Request& request){
char tbuffer[80];
time_t now = time(NULL);
struct tm gmt = *gmtime(&now);
strftime(tbuffer, sizeof(tbuffer), "%a, %d %b %Y %H:%M:%S %Z", &gmt);
this->protocol = "HTTP/1.1";
this->header["Connection"] = request.header["Connection"];
this->header["Server"] = "HTTPd by Rodrigo Siqueira, Marcos Iseki e Thiago Ikeda";
this->header["Date"] = tbuffer;
this->process(request);
}
void HTTP::Response::process(Request& request){
if(request.protocol != "HTTP/1.1"){
this->nothttp();
}
else if(request.method != "GET" && request.method != "POST"){
this->notmethod();
}
else if(this->isobj("www" + request.target)){
this->makeobj("www" + request.target);
}
/* else if(this->ismoved(request.target)){
this->makemoved();
}
*/
else{
this->notfound();
}
}
void HTTP::Response::nothttp(){
this->status = 505;
this->makefile("error/505.html");
}
void HTTP::Response::notfound(){
this->status = 404;
this->makefile("error/404.html");
}
void HTTP::Response::notmethod(){
this->status = 501;
this->makefile("error/501.html");
}
void HTTP::Response::makeobj(const string& target){
struct stat st;
lstat(target.c_str(), &st);
if(S_ISREG(st.st_mode)){
this->status = 200;
this->makefile(target);
}
else if(S_ISDIR(st.st_mode)){
this->status = 200;
this->makedir(target);
}
else{
this->status = 500;
this->makefile("error/500.html");
}
}
void HTTP::Response::makedir(const string& target){
struct stat st;
if(stat( (target + "/index.html").c_str() , &st) == 0){
this->makefile(target + "/index.html");
return;
}
DIR *dir;
struct dirent *ent;
stringstream index;
index << "<!DOCTYPE html>" << endl;
index << "<html><head><meta charset=\"UTF-8\">" << endl;
index << "<title>Index of " << target.substr(target.find('/')) << "</title>" << endl;
index << "</head><body>" << endl;
index << "<h1>Index of " << target.substr(target.find('/')) << "</h1><ul>" << endl;
dir = opendir(target.c_str());
while((ent = readdir(dir)) != NULL){
index << "<li><a href='" << target.substr(target.find('/')) << "/" << ent->d_name << "'>";
index << ent->d_name << "</a></li>" << endl;
}
index << "</ul></body></html>";
this->content = index.str();
this->header["Content-Type"] = MIME["html"];
this->header["Content-Length"] = to_string(this->content.length());
}
void HTTP::Response::makefile(const string& target){
ifstream file(target);
this->content.assign(
istreambuf_iterator<char>(file),
istreambuf_iterator<char>()
);
this->header["Content-Type"] = MIME[target.substr(target.rfind('.') + 1)];
this->header["Content-Length"] = to_string(this->content.length());
}
bool HTTP::Response::isobj(const string& target) const {
struct stat st;
lstat(target.c_str(), &st);
return S_ISDIR(st.st_mode) || S_ISREG(st.st_mode);
}
int HTTP::Response::generate(string& target){
stringstream tgt;
tgt << this->protocol << " " << this->status << " " << Code[this->status] << endl;
for(auto it = this->header.begin(); it != this->header.end(); it++){
tgt << it->first << ": " << it->second << endl;
}
tgt << endl;
tgt << endl;
tgt << this->content;
target = tgt.str();
return target.length();
}<|endoftext|> |
<commit_before>#include "cudarray/common.hpp"
#include "cudarray/blas.hpp"
namespace cudarray {
cublasStatus_t cublas_dot(cublasHandle_t handle, int n, const float *x,
int incx, const float *y, int incy, float *result) {
return cublasSdot(handle, n, x, incx, y, incy, result);
}
template<typename T>
T dot(const T *a, const T *b, unsigned int n) {
T result;
CUBLAS_CHECK(cublas_dot(CUBLAS::handle(), n, a, 1, b, 1, &result));
return result;
}
template float dot<float>(const float *x, const float *y, unsigned int n);
cublasStatus_t cublas_gemv(cublasHandle_t handle, cublasOperation_t trans,
int m, int n, const float *alpha, const float *A, int lda, const float *x,
int incx, const float *beta, float *y, int incy) {
return cublasSgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y,
incy);
}
template<typename T>
void gemv(const T *A, const T *b, TransposeOp trans, unsigned int m,
unsigned int n, T alpha, T beta, T *c) {
cublasOperation_t cuTrans;
if (trans == OP_TRANS) {
cuTrans = CUBLAS_OP_N;
unsigned int tmp = n;
n = m;
m = tmp;
} else {
cuTrans = CUBLAS_OP_T;
}
int lda = n;
CUBLAS_CHECK(cublas_gemv(CUBLAS::handle(), cuTrans, n, m, &alpha, A, lda, b,
1, &beta, c, 1));
}
template void gemv<float>(const float *A, const float *b, TransposeOp trans,
unsigned int m, unsigned int n, float alpha, float beta, float *c);
cublasStatus_t cublas_gemm(cublasHandle_t handle, cublasOperation_t transA,
cublasOperation_t transB, int m, int n, int k, const float *alpha,
const float *A, int lda, const float *B, int ldb, const float *beta,
float *C, int ldc) {
return cublasSgemm(handle, transA, transB, m, n, k, alpha, A, lda, B, ldb,
beta, C, ldc);
}
template <typename T>
void gemm(const T *A, const T *B, TransposeOp transA, TransposeOp transB,
unsigned int m, unsigned int n, unsigned int k, T alpha, T beta,
T *C) {
int lda = (transA == OP_NO_TRANS) ? k : m;
int ldb = (transB == OP_NO_TRANS) ? n : k;
int ldc = n;
cublasOperation_t cuTransA = (cublasOperation_t) transA;
cublasOperation_t cuTransB = (cublasOperation_t) transB;
CUBLAS_CHECK(cublas_gemm(CUBLAS::handle(), cuTransB, cuTransA, n, m, k,
&alpha, B, ldb, A, lda, &beta, C, ldc));
}
template void gemm<float>(const float *A, const float *B, TransposeOp transA,
TransposeOp transB, unsigned int m, unsigned int n, unsigned int k,
float alpha, float beta, float *C);
template <typename T>
T **dev_ptrs(const T *base, int num, int stride) {
T *ptrs_host[num];
int idx = 0;
for(int n = 0; n < num; ++n){
ptrs_host[idx] = (T *) base + n * stride;
idx++;
}
T **ptrs_dev;
CUDA_CHECK(cudaMalloc((void **) &ptrs_dev, num*sizeof(T *)));
CUDA_CHECK(cudaMemcpy(ptrs_dev, ptrs_host, num*sizeof(T *),
cudaMemcpyHostToDevice));
return ptrs_dev;
}
template <typename T>
BLASBatch<T>::BLASBatch(const T **As, const T **Bs, T **Cs,
unsigned int batch_size) : batch_size(batch_size) {
size_t ptrs_size = batch_size * sizeof(T **);
CUDA_CHECK(cudaMalloc((void **) &As_dev, ptrs_size));
CUDA_CHECK(cudaMemcpy(As_dev, As, batch_size*sizeof(float *),
cudaMemcpyHostToDevice));
CUDA_CHECK(cudaMalloc((void **) &Bs_dev, ptrs_size));
CUDA_CHECK(cudaMemcpy(Bs_dev, Bs, batch_size*sizeof(float *),
cudaMemcpyHostToDevice));
CUDA_CHECK(cudaMalloc((void **) &Cs_dev, ptrs_size));
CUDA_CHECK(cudaMemcpy(Cs_dev, Cs, batch_size*sizeof(float *),
cudaMemcpyHostToDevice));
}
template <typename T>
BLASBatch<T>::BLASBatch(const T *A, const T *B, T *C,
unsigned int batch_size, int Astride, int Bstride, int Cstride)
: batch_size(batch_size) {
As_dev = (const float **) dev_ptrs(A, batch_size, Astride);
Bs_dev = (const float **) dev_ptrs(B, batch_size, Bstride);
Cs_dev = dev_ptrs(C, batch_size, Cstride);
}
template <typename T>
BLASBatch<T>::~BLASBatch() {
CUDA_CHECK(cudaFree(As_dev));
CUDA_CHECK(cudaFree(Bs_dev));
CUDA_CHECK(cudaFree(Cs_dev));
}
cublasStatus_t cublas_gemm_batched(cublasHandle_t handle,
cublasOperation_t transA, cublasOperation_t transB, int m, int n, int k,
const float *alpha, const float *Aarray[], int lda, const float *Barray[],
int ldb, const float *beta, float *Carray[], int ldc, int batchCount) {
return cublasSgemmBatched(handle, transA, transB, m, n, k, alpha, Aarray,
lda, Barray, ldb, beta, Carray, ldc, batchCount);
}
template <typename T>
void BLASBatch<T>::gemm(TransposeOp transA, TransposeOp transB, unsigned int m,
unsigned int n, unsigned int k, T alpha, T beta) {
int lda = (transA == OP_NO_TRANS) ? k : m;
int ldb = (transB == OP_NO_TRANS) ? n : k;
int ldc = n;
cublasOperation_t cuTransA = (cublasOperation_t) transA;
cublasOperation_t cuTransB = (cublasOperation_t) transB;
CUBLAS_CHECK(cublas_gemm_batched(CUBLAS::handle(), cuTransB, cuTransA, n, m,
k, &alpha, Bs_dev, ldb, As_dev, lda, &beta, Cs_dev, ldc, batch_size));
}
template class BLASBatch<float>;
const char *cublas_message(cublasStatus_t status){
switch(status) {
case CUBLAS_STATUS_SUCCESS:
return "The operation completed successfully.";
case CUBLAS_STATUS_NOT_INITIALIZED:
return "The cuBLAS library was not initialized.";
case CUBLAS_STATUS_ALLOC_FAILED:
return "Resource allocation failed inside the cuBLAS library.";
case CUBLAS_STATUS_INVALID_VALUE:
return "An unsupported value or parameter was passed to the function.";
case CUBLAS_STATUS_ARCH_MISMATCH:
return "The function requires a feature absent from the GPU.";
case CUBLAS_STATUS_MAPPING_ERROR:
return "An access to GPU memory space failed.";
case CUBLAS_STATUS_EXECUTION_FAILED:
return "The GPU program failed to execute.";
case CUBLAS_STATUS_INTERNAL_ERROR:
return "An internal cuBLAS operation failed.";
// case CUBLAS_STATUS_NOT_SUPPORTED:
// return "The functionnality requested is not supported.";
// case CUBLAS_STATUS_LICENSE_ERROR:
// return "The functionality requested requires some license.";
default:
throw std::runtime_error("invalid cublasStatus_t");
}
}
}
<commit_msg>fix dynamic array creation<commit_after>#include "cudarray/common.hpp"
#include "cudarray/blas.hpp"
namespace cudarray {
cublasStatus_t cublas_dot(cublasHandle_t handle, int n, const float *x,
int incx, const float *y, int incy, float *result) {
return cublasSdot(handle, n, x, incx, y, incy, result);
}
template<typename T>
T dot(const T *a, const T *b, unsigned int n) {
T result;
CUBLAS_CHECK(cublas_dot(CUBLAS::handle(), n, a, 1, b, 1, &result));
return result;
}
template float dot<float>(const float *x, const float *y, unsigned int n);
cublasStatus_t cublas_gemv(cublasHandle_t handle, cublasOperation_t trans,
int m, int n, const float *alpha, const float *A, int lda, const float *x,
int incx, const float *beta, float *y, int incy) {
return cublasSgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y,
incy);
}
template<typename T>
void gemv(const T *A, const T *b, TransposeOp trans, unsigned int m,
unsigned int n, T alpha, T beta, T *c) {
cublasOperation_t cuTrans;
if (trans == OP_TRANS) {
cuTrans = CUBLAS_OP_N;
unsigned int tmp = n;
n = m;
m = tmp;
} else {
cuTrans = CUBLAS_OP_T;
}
int lda = n;
CUBLAS_CHECK(cublas_gemv(CUBLAS::handle(), cuTrans, n, m, &alpha, A, lda, b,
1, &beta, c, 1));
}
template void gemv<float>(const float *A, const float *b, TransposeOp trans,
unsigned int m, unsigned int n, float alpha, float beta, float *c);
cublasStatus_t cublas_gemm(cublasHandle_t handle, cublasOperation_t transA,
cublasOperation_t transB, int m, int n, int k, const float *alpha,
const float *A, int lda, const float *B, int ldb, const float *beta,
float *C, int ldc) {
return cublasSgemm(handle, transA, transB, m, n, k, alpha, A, lda, B, ldb,
beta, C, ldc);
}
template <typename T>
void gemm(const T *A, const T *B, TransposeOp transA, TransposeOp transB,
unsigned int m, unsigned int n, unsigned int k, T alpha, T beta,
T *C) {
int lda = (transA == OP_NO_TRANS) ? k : m;
int ldb = (transB == OP_NO_TRANS) ? n : k;
int ldc = n;
cublasOperation_t cuTransA = (cublasOperation_t) transA;
cublasOperation_t cuTransB = (cublasOperation_t) transB;
CUBLAS_CHECK(cublas_gemm(CUBLAS::handle(), cuTransB, cuTransA, n, m, k,
&alpha, B, ldb, A, lda, &beta, C, ldc));
}
template void gemm<float>(const float *A, const float *B, TransposeOp transA,
TransposeOp transB, unsigned int m, unsigned int n, unsigned int k,
float alpha, float beta, float *C);
template <typename T>
T **dev_ptrs(const T *base, int num, int stride) {
T **ptrs_host = new T*[num];
int idx = 0;
for(int n = 0; n < num; ++n){
ptrs_host[idx] = (T *) base + n * stride;
idx++;
}
T **ptrs_dev;
CUDA_CHECK(cudaMalloc((void **) &ptrs_dev, num*sizeof(T *)));
CUDA_CHECK(cudaMemcpy(ptrs_dev, ptrs_host, num*sizeof(T *),
cudaMemcpyHostToDevice));
delete ptrs_host;
return ptrs_dev;
}
template <typename T>
BLASBatch<T>::BLASBatch(const T **As, const T **Bs, T **Cs,
unsigned int batch_size) : batch_size(batch_size) {
size_t ptrs_size = batch_size * sizeof(T **);
CUDA_CHECK(cudaMalloc((void **) &As_dev, ptrs_size));
CUDA_CHECK(cudaMemcpy(As_dev, As, batch_size*sizeof(float *),
cudaMemcpyHostToDevice));
CUDA_CHECK(cudaMalloc((void **) &Bs_dev, ptrs_size));
CUDA_CHECK(cudaMemcpy(Bs_dev, Bs, batch_size*sizeof(float *),
cudaMemcpyHostToDevice));
CUDA_CHECK(cudaMalloc((void **) &Cs_dev, ptrs_size));
CUDA_CHECK(cudaMemcpy(Cs_dev, Cs, batch_size*sizeof(float *),
cudaMemcpyHostToDevice));
}
template <typename T>
BLASBatch<T>::BLASBatch(const T *A, const T *B, T *C,
unsigned int batch_size, int Astride, int Bstride, int Cstride)
: batch_size(batch_size) {
As_dev = (const float **) dev_ptrs(A, batch_size, Astride);
Bs_dev = (const float **) dev_ptrs(B, batch_size, Bstride);
Cs_dev = dev_ptrs(C, batch_size, Cstride);
}
template <typename T>
BLASBatch<T>::~BLASBatch() {
CUDA_CHECK(cudaFree(As_dev));
CUDA_CHECK(cudaFree(Bs_dev));
CUDA_CHECK(cudaFree(Cs_dev));
}
cublasStatus_t cublas_gemm_batched(cublasHandle_t handle,
cublasOperation_t transA, cublasOperation_t transB, int m, int n, int k,
const float *alpha, const float *Aarray[], int lda, const float *Barray[],
int ldb, const float *beta, float *Carray[], int ldc, int batchCount) {
return cublasSgemmBatched(handle, transA, transB, m, n, k, alpha, Aarray,
lda, Barray, ldb, beta, Carray, ldc, batchCount);
}
template <typename T>
void BLASBatch<T>::gemm(TransposeOp transA, TransposeOp transB, unsigned int m,
unsigned int n, unsigned int k, T alpha, T beta) {
int lda = (transA == OP_NO_TRANS) ? k : m;
int ldb = (transB == OP_NO_TRANS) ? n : k;
int ldc = n;
cublasOperation_t cuTransA = (cublasOperation_t) transA;
cublasOperation_t cuTransB = (cublasOperation_t) transB;
CUBLAS_CHECK(cublas_gemm_batched(CUBLAS::handle(), cuTransB, cuTransA, n, m,
k, &alpha, Bs_dev, ldb, As_dev, lda, &beta, Cs_dev, ldc, batch_size));
}
template class BLASBatch<float>;
const char *cublas_message(cublasStatus_t status){
switch(status) {
case CUBLAS_STATUS_SUCCESS:
return "The operation completed successfully.";
case CUBLAS_STATUS_NOT_INITIALIZED:
return "The cuBLAS library was not initialized.";
case CUBLAS_STATUS_ALLOC_FAILED:
return "Resource allocation failed inside the cuBLAS library.";
case CUBLAS_STATUS_INVALID_VALUE:
return "An unsupported value or parameter was passed to the function.";
case CUBLAS_STATUS_ARCH_MISMATCH:
return "The function requires a feature absent from the GPU.";
case CUBLAS_STATUS_MAPPING_ERROR:
return "An access to GPU memory space failed.";
case CUBLAS_STATUS_EXECUTION_FAILED:
return "The GPU program failed to execute.";
case CUBLAS_STATUS_INTERNAL_ERROR:
return "An internal cuBLAS operation failed.";
// case CUBLAS_STATUS_NOT_SUPPORTED:
// return "The functionnality requested is not supported.";
// case CUBLAS_STATUS_LICENSE_ERROR:
// return "The functionality requested requires some license.";
default:
throw std::runtime_error("invalid cublasStatus_t");
}
}
}
<|endoftext|> |
<commit_before>#include "solverconfiguration.h"
#include "process.h"
#include "exception.h"
#include <QFileInfo>
#include <QFile>
#include <QJsonArray>
#include <QDir>
namespace {
void parseArgList(const QString& s, QVariantMap& map) {
QStringList ret;
bool hadEscape = false;
bool inSingleQuote = false;
bool inDoubleQuote = false;
QString currentArg;
foreach (const QChar c, s) {
if (hadEscape) {
currentArg += c;
hadEscape = false;
} else {
if (c=='\\') {
hadEscape = true;
} else if (c=='"') {
if (inDoubleQuote) {
inDoubleQuote=false;
ret.push_back(currentArg);
currentArg = "";
} else if (inSingleQuote) {
currentArg += c;
} else {
inDoubleQuote = true;
}
} else if (c=='\'') {
if (inSingleQuote) {
inSingleQuote=false;
ret.push_back(currentArg);
currentArg = "";
} else if (inDoubleQuote) {
currentArg += c;
} else {
inSingleQuote = true;
}
} else if (!inSingleQuote && !inDoubleQuote && c==' ') {
if (currentArg.size() > 0) {
ret.push_back(currentArg);
currentArg = "";
}
} else {
currentArg += c;
}
}
}
if (currentArg.size() > 0) {
ret.push_back(currentArg);
}
QString flag;
for (auto& arg : ret) {
if (arg.startsWith("-")) {
if (!flag.isEmpty()) {
// Must be a boolean switch
map[flag] = true;
}
flag = arg;
} else if (!flag.isEmpty()) {
// Flag with arg
map[flag] = arg;
flag.clear();
} else {
// Arg with no flag
map[arg] = true;
}
}
}
}
SolverConfiguration::SolverConfiguration(const Solver& _solver, bool builtin) :
solverDefinition(_solver),
isBuiltin(builtin),
timeLimit(0),
printIntermediate(true),
numSolutions(1),
numOptimal(1),
verboseCompilation(false),
verboseSolving(false),
compilationStats(false),
solvingStats(false),
outputTiming(false),
optimizationLevel(1),
numThreads(1),
freeSearch(false),
modified(false)
{
solver = _solver.id + "@" + _solver.version;
}
SolverConfiguration SolverConfiguration::loadJSON(const QString& filename)
{
QFile file(filename);
QFileInfo fi(file);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
throw FileError("Failed to open file " + filename);
}
auto json = QJsonDocument::fromJson(file.readAll());
file.close();
auto sc = loadJSON(json);
sc.paramFile = fi.canonicalFilePath();
return sc;
}
SolverConfiguration SolverConfiguration::loadJSON(const QJsonDocument& json)
{
auto configObject = json.object();
QString solverValue = configObject.value("--solver").isUndefined() ? configObject.value("solver").toString() : configObject.value("--solver").toString();
auto solver = Solver::lookup(solverValue);
int i = 0;
auto& solvers = MznDriver::get().solvers();
for (auto& s : solvers) {
if (solver == s) {
// Solver already loaded
break;
}
i++;
}
if (i == solvers.length()) {
solvers.append(solver);
}
bool syncedPrintIntermediate = true;
int syncedNumSolutions = 1;
int syncedNumOptimal = 1;
SolverConfiguration sc(solvers[i]);
for (auto it = configObject.begin(); it != configObject.end(); it++) {
QString key = (it.key().startsWith("-") || it.key().startsWith("_")) ? it.key() : "--" + it.key();
if (key == "--solver") {
sc.solver = it.value().toString();
} else if (key == "_syncedPrintIntermediate") {
syncedPrintIntermediate = it.value().toBool(true);
} else if (key == "_syncedNumSolutions") {
syncedNumSolutions= it.value().toInt(1);
} else if (key == "_syncedNumOptimal") {
syncedNumOptimal = it.value().toInt(1);
} else if (key == "-t" || key == "--time-limit") {
sc.timeLimit = it.value().toInt();
} else if (key == "-a" || key == "--all-solutions") {
sc.numSolutions = 0;
sc.printIntermediate = true;
} else if (key == "-i" || key == "--intermediate" || key == "--intermediate-solutions") {
sc.printIntermediate = it.value().toBool(true);
} else if (key == "--all-satisfaction") {
sc.numSolutions = 0;
} else if (key == "-n" || key == "--num-solutions") {
sc.numSolutions = it.value().toInt(1);
} else if (key == "-a-o" || key == "--all-optimal") {
sc.numOptimal = 0;
} else if (key == "-n-o" || key == "--num-optimal") {
sc.numOptimal = it.value().toInt(1);
} else if (key == "--verbose-compilation" || key == "--verbose" || key == "-v") {
sc.verboseCompilation = it.value().toBool();
} else if (key == "--verbose-solving" || key == "--verbose" || key == "-v") {
sc.verboseSolving = it.value().toBool();
} else if (key == "--compiler-statistics" || key == "--statistics" || key == "-s") {
sc.compilationStats = it.value().toBool();
} else if (key == "--solving-statistics" || key == "--statistics" || key == "-s") {
sc.solvingStats = it.value().toBool();
} else if (key == "--output-time") {
sc.outputTiming = it.value().toBool();
} else if (key == "-O0" && it.value().toBool()) {
sc.optimizationLevel = 0;
} else if (key == "-O1" && it.value().toBool()) {
sc.optimizationLevel = 1;
} else if (key == "-O2" && it.value().toBool()) {
sc.optimizationLevel = 2;
} else if (key == "-O3" && it.value().toBool()) {
sc.optimizationLevel = 3;
} else if (key == "-O4" && it.value().toBool()) {
sc.optimizationLevel = 4;
} else if (key == "-O5" && it.value().toBool()) {
sc.optimizationLevel = 5;
} else if (key == "-O") {
sc.optimizationLevel = it.value().toInt();
} else if (key == "-D" || key == "--cmdline-data") {
if (it.value().isArray()) {
for (auto v : it.value().toArray()) {
sc.additionalData.push_back(v.toString());
}
} else {
sc.additionalData.push_back(it.value().toString());
}
} else if (key == "-p" || key == "--parallel") {
sc.numThreads = it.value().toInt(1);
} else if (key == "-r" || key == "--random-seed") {
sc.randomSeed = it.value().toVariant();
} else if (key == "-f" || key == "--free-search") {
sc.freeSearch = it.value().toBool();
} else {
sc.extraOptions[key] = it.value().toVariant();
}
}
for (auto f : solver.extraFlags) {
if (f.t == SolverFlag::T_BOOL_ONOFF && sc.extraOptions.contains(f.name)) {
// Convert on/off string to bool (TODO: would be nice to handle this in minizinc)
sc.extraOptions[f.name] = sc.extraOptions[f.name] == f.options[0];
}
}
return sc;
}
SolverConfiguration SolverConfiguration::loadLegacy(const QJsonDocument &json)
{
auto sco = json.object();
auto& solver = Solver::lookup(sco["id"].toString(), sco["version"].toString(), false);
SolverConfiguration newSc(solver);
// if (sco["name"].isString()) {
// newSc.name = sco["name"].toString();
// }
if (sco["timeLimit"].isDouble()) {
newSc.timeLimit = sco["timeLimit"].toInt();
}
// if (sco["defaultBehavior"].isBool()) {
// newSc.defaultBehaviour = sco["defaultBehavior"].toBool();
// }
if (sco["printIntermediate"].isBool()) {
newSc.printIntermediate = sco["printIntermediate"].toBool();
}
if (sco["stopAfter"].isDouble()) {
newSc.numSolutions = sco["stopAfter"].toInt();
}
if (sco["verboseFlattening"].isBool()) {
newSc.verboseCompilation = sco["verboseFlattening"].toBool();
}
if (sco["flatteningStats"].isBool()) {
newSc.compilationStats = sco["flatteningStats"].toBool();
}
if (sco["optimizationLevel"].isDouble()) {
newSc.optimizationLevel = sco["optimizationLevel"].toInt();
}
if (sco["additionalData"].isString()) {
newSc.additionalData << sco["additionalData"].toString();
}
if (sco["additionalCompilerCommandline"].isString()) {
parseArgList(sco["additionalCompilerCommandline"].toString(), newSc.extraOptions);
}
if (sco["nThreads"].isDouble()) {
newSc.numThreads = sco["nThreads"].toInt();
}
if (sco["randomSeed"].isDouble()) {
newSc.randomSeed = sco["randomSeed"].toDouble();
}
if (sco["solverFlags"].isString()) {
parseArgList(sco["solverFlags"].toString(), newSc.extraOptions);
}
if (sco["freeSearch"].isBool()) {
newSc.freeSearch = sco["freeSearch"].toBool();
}
if (sco["verboseSolving"].isBool()) {
newSc.verboseSolving = sco["verboseSolving"].toBool();
}
if (sco["outputTiming"].isBool()) {
newSc.outputTiming = sco["outputTiming"].toBool();
}
if (sco["solvingStats"].isBool()) {
newSc.solvingStats = sco["solvingStats"].toBool();
}
if (sco["extraOptions"].isObject()) {
QJsonObject extraOptions = sco["extraOptions"].toObject();
for (auto& k : extraOptions.keys()) {
newSc.extraOptions[k] = extraOptions[k].toString();
}
}
return newSc;
}
QString SolverConfiguration::name() const
{
QStringList parts;
if (isBuiltin) {
parts << solverDefinition.name
<< solverDefinition.version;
} else {
if (paramFile.isEmpty()) {
parts << "Unsaved Configuration";
} else {
parts << QFileInfo(paramFile).completeBaseName();
}
parts << "(" + solverDefinition.name + " " + solverDefinition.version + ")";
}
if (modified) {
parts << "*";
}
return parts.join(" ");
}
QByteArray SolverConfiguration::toJSON(void) const
{
QJsonDocument jsonDoc;
jsonDoc.setObject(toJSONObject());
return jsonDoc.toJson();
}
QJsonObject SolverConfiguration::toJSONObject(void) const
{
QJsonObject config;
config["solver"] = solver;
if (timeLimit > 0) {
config["time-limit"] = timeLimit;
}
if ((supports("-a") || supports("-i"))) {
config["intermediate-solutions"] = printIntermediate;
}
if (numSolutions > 1 && supports("-n")) {
config["num-solutions"] = numSolutions;
}
if (numSolutions == 0 && supports("-a")) {
config["all-satisfaction"] = true;
}
if (numOptimal > 1 && supports("-n-o")) {
config["num-optimal"] = numOptimal;
}
if (numOptimal == 0 && supports("-a-o")) {
config["all-optimal"] = true;
}
if (verboseCompilation) {
config["verbose-compilation"] = verboseCompilation;
}
if (verboseSolving && supports("-v")) {
config["verbose-solving"] = verboseSolving;
}
if (compilationStats) {
config["compiler-statistics"] = compilationStats;
}
if (solvingStats && supports("-s")) {
config["solving-statistics"] = solvingStats;
}
if (outputTiming) {
config["output-time"] = outputTiming;
}
if (optimizationLevel != 1) {
config["-O"] = optimizationLevel;
}
QJsonArray arr;
for (auto d : additionalData) {
arr.push_back(d);
}
if (arr.size() > 0) {
config["cmdline-data"] = arr;
}
if (numThreads > 1 && supports("-p")) {
config["parallel"] = numThreads;
}
if (!randomSeed.isNull() && supports("-r")) {
config["random-seed"] = QJsonValue::fromVariant(randomSeed);
}
if (freeSearch && supports("-f")) {
config["free-search"] = freeSearch;
}
for (auto it = extraOptions.begin(); it != extraOptions.end(); it++) {
config[it.key()] = QJsonValue::fromVariant(it.value());
}
for (auto f : solverDefinition.extraFlags) {
if (f.t == SolverFlag::T_BOOL_ONOFF && extraOptions.contains(f.name)) {
// Convert to on/off string instead of bool (TODO: would be nice to handle this in minizinc)
config[f.name] = extraOptions[f.name].toBool() ? f.options[0] : f.options[1];
}
}
return config;
}
bool SolverConfiguration::syncedOptionsMatch(const SolverConfiguration& sc) const
{
if (isBuiltin || sc.isBuiltin) {
// Built-in configs always can have their options overidden
return true;
}
if (timeLimit != sc.timeLimit) {
return false;
}
if ((supports("-a") || supports("-i")) &&
(sc.supports("-a") || sc.supports("-i")) &&
printIntermediate != sc.printIntermediate) {
return false;
}
if (supports("-n") && sc.supports("-n") &&
(numSolutions > 0 || sc.numSolutions > 0) &&
numSolutions != sc.numSolutions) {
return false;
}
if (supports("-a") && sc.supports("-a") &&
(numSolutions == 0 || sc.numSolutions == 0) &&
numSolutions != sc.numSolutions) {
return false;
}
if (supports("-n-o") && sc.supports("-n-o") &&
(numOptimal > 0 || sc.numOptimal > 0) &&
numOptimal != sc.numOptimal) {
return false;
}
if (supports("-a-o") && sc.supports("-a-o") &&
(numOptimal == 0 || sc.numOptimal == 0) &&
numOptimal != sc.numOptimal) {
return false;
}
if (verboseCompilation != sc.verboseCompilation) {
return false;
}
if (supports("-v") && sc.supports("-v") &&
verboseSolving != sc.verboseSolving) {
return false;
}
if (compilationStats != sc.compilationStats) {
return false;
}
if (supports("-s") && sc.supports("-s") &&
solvingStats != sc.solvingStats) {
return false;
}
if (outputTiming != sc.outputTiming) {
return false;
}
return true;
}
bool SolverConfiguration::supports(const QString &flag) const
{
return solverDefinition.stdFlags.contains(flag);
}
bool SolverConfiguration::operator==(const SolverConfiguration& sc) const
{
return solver == sc.solver &&
solverDefinition.id == sc.solverDefinition.id &&
solverDefinition.version == sc.solverDefinition.version &&
isBuiltin == sc.isBuiltin &&
timeLimit == sc.timeLimit &&
printIntermediate == sc.printIntermediate &&
numSolutions == sc.numSolutions &&
verboseCompilation == sc.verboseCompilation &&
verboseSolving == sc.verboseSolving &&
compilationStats == sc.compilationStats &&
solvingStats == sc.solvingStats &&
outputTiming == sc.outputTiming &&
optimizationLevel == sc.optimizationLevel &&
additionalData == sc.additionalData &&
numThreads == sc.numThreads &&
randomSeed == sc.randomSeed &&
freeSearch == sc.freeSearch &&
extraOptions == sc.extraOptions;
}
<commit_msg>Fix loading of old projects with empty string cmdline data<commit_after>#include "solverconfiguration.h"
#include "process.h"
#include "exception.h"
#include <QFileInfo>
#include <QFile>
#include <QJsonArray>
#include <QDir>
namespace {
void parseArgList(const QString& s, QVariantMap& map) {
QStringList ret;
bool hadEscape = false;
bool inSingleQuote = false;
bool inDoubleQuote = false;
QString currentArg;
foreach (const QChar c, s) {
if (hadEscape) {
currentArg += c;
hadEscape = false;
} else {
if (c=='\\') {
hadEscape = true;
} else if (c=='"') {
if (inDoubleQuote) {
inDoubleQuote=false;
ret.push_back(currentArg);
currentArg = "";
} else if (inSingleQuote) {
currentArg += c;
} else {
inDoubleQuote = true;
}
} else if (c=='\'') {
if (inSingleQuote) {
inSingleQuote=false;
ret.push_back(currentArg);
currentArg = "";
} else if (inDoubleQuote) {
currentArg += c;
} else {
inSingleQuote = true;
}
} else if (!inSingleQuote && !inDoubleQuote && c==' ') {
if (currentArg.size() > 0) {
ret.push_back(currentArg);
currentArg = "";
}
} else {
currentArg += c;
}
}
}
if (currentArg.size() > 0) {
ret.push_back(currentArg);
}
QString flag;
for (auto& arg : ret) {
if (arg.startsWith("-")) {
if (!flag.isEmpty()) {
// Must be a boolean switch
map[flag] = true;
}
flag = arg;
} else if (!flag.isEmpty()) {
// Flag with arg
map[flag] = arg;
flag.clear();
} else {
// Arg with no flag
map[arg] = true;
}
}
}
}
SolverConfiguration::SolverConfiguration(const Solver& _solver, bool builtin) :
solverDefinition(_solver),
isBuiltin(builtin),
timeLimit(0),
printIntermediate(true),
numSolutions(1),
numOptimal(1),
verboseCompilation(false),
verboseSolving(false),
compilationStats(false),
solvingStats(false),
outputTiming(false),
optimizationLevel(1),
numThreads(1),
freeSearch(false),
modified(false)
{
solver = _solver.id + "@" + _solver.version;
}
SolverConfiguration SolverConfiguration::loadJSON(const QString& filename)
{
QFile file(filename);
QFileInfo fi(file);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
throw FileError("Failed to open file " + filename);
}
auto json = QJsonDocument::fromJson(file.readAll());
file.close();
auto sc = loadJSON(json);
sc.paramFile = fi.canonicalFilePath();
return sc;
}
SolverConfiguration SolverConfiguration::loadJSON(const QJsonDocument& json)
{
auto configObject = json.object();
QString solverValue = configObject.value("--solver").isUndefined() ? configObject.value("solver").toString() : configObject.value("--solver").toString();
auto solver = Solver::lookup(solverValue);
int i = 0;
auto& solvers = MznDriver::get().solvers();
for (auto& s : solvers) {
if (solver == s) {
// Solver already loaded
break;
}
i++;
}
if (i == solvers.length()) {
solvers.append(solver);
}
bool syncedPrintIntermediate = true;
int syncedNumSolutions = 1;
int syncedNumOptimal = 1;
SolverConfiguration sc(solvers[i]);
for (auto it = configObject.begin(); it != configObject.end(); it++) {
QString key = (it.key().startsWith("-") || it.key().startsWith("_")) ? it.key() : "--" + it.key();
if (key == "--solver") {
sc.solver = it.value().toString();
} else if (key == "_syncedPrintIntermediate") {
syncedPrintIntermediate = it.value().toBool(true);
} else if (key == "_syncedNumSolutions") {
syncedNumSolutions= it.value().toInt(1);
} else if (key == "_syncedNumOptimal") {
syncedNumOptimal = it.value().toInt(1);
} else if (key == "-t" || key == "--time-limit") {
sc.timeLimit = it.value().toInt();
} else if (key == "-a" || key == "--all-solutions") {
sc.numSolutions = 0;
sc.printIntermediate = true;
} else if (key == "-i" || key == "--intermediate" || key == "--intermediate-solutions") {
sc.printIntermediate = it.value().toBool(true);
} else if (key == "--all-satisfaction") {
sc.numSolutions = 0;
} else if (key == "-n" || key == "--num-solutions") {
sc.numSolutions = it.value().toInt(1);
} else if (key == "-a-o" || key == "--all-optimal") {
sc.numOptimal = 0;
} else if (key == "-n-o" || key == "--num-optimal") {
sc.numOptimal = it.value().toInt(1);
} else if (key == "--verbose-compilation" || key == "--verbose" || key == "-v") {
sc.verboseCompilation = it.value().toBool();
} else if (key == "--verbose-solving" || key == "--verbose" || key == "-v") {
sc.verboseSolving = it.value().toBool();
} else if (key == "--compiler-statistics" || key == "--statistics" || key == "-s") {
sc.compilationStats = it.value().toBool();
} else if (key == "--solving-statistics" || key == "--statistics" || key == "-s") {
sc.solvingStats = it.value().toBool();
} else if (key == "--output-time") {
sc.outputTiming = it.value().toBool();
} else if (key == "-O0" && it.value().toBool()) {
sc.optimizationLevel = 0;
} else if (key == "-O1" && it.value().toBool()) {
sc.optimizationLevel = 1;
} else if (key == "-O2" && it.value().toBool()) {
sc.optimizationLevel = 2;
} else if (key == "-O3" && it.value().toBool()) {
sc.optimizationLevel = 3;
} else if (key == "-O4" && it.value().toBool()) {
sc.optimizationLevel = 4;
} else if (key == "-O5" && it.value().toBool()) {
sc.optimizationLevel = 5;
} else if (key == "-O") {
sc.optimizationLevel = it.value().toInt();
} else if (key == "-D" || key == "--cmdline-data") {
if (it.value().isArray()) {
for (auto v : it.value().toArray()) {
sc.additionalData.push_back(v.toString());
}
} else {
sc.additionalData.push_back(it.value().toString());
}
} else if (key == "-p" || key == "--parallel") {
sc.numThreads = it.value().toInt(1);
} else if (key == "-r" || key == "--random-seed") {
sc.randomSeed = it.value().toVariant();
} else if (key == "-f" || key == "--free-search") {
sc.freeSearch = it.value().toBool();
} else {
sc.extraOptions[key] = it.value().toVariant();
}
}
for (auto f : solver.extraFlags) {
if (f.t == SolverFlag::T_BOOL_ONOFF && sc.extraOptions.contains(f.name)) {
// Convert on/off string to bool (TODO: would be nice to handle this in minizinc)
sc.extraOptions[f.name] = sc.extraOptions[f.name] == f.options[0];
}
}
return sc;
}
SolverConfiguration SolverConfiguration::loadLegacy(const QJsonDocument &json)
{
auto sco = json.object();
auto& solver = Solver::lookup(sco["id"].toString(), sco["version"].toString(), false);
SolverConfiguration newSc(solver);
// if (sco["name"].isString()) {
// newSc.name = sco["name"].toString();
// }
if (sco["timeLimit"].isDouble()) {
newSc.timeLimit = sco["timeLimit"].toInt();
}
// if (sco["defaultBehavior"].isBool()) {
// newSc.defaultBehaviour = sco["defaultBehavior"].toBool();
// }
if (sco["printIntermediate"].isBool()) {
newSc.printIntermediate = sco["printIntermediate"].toBool();
}
if (sco["stopAfter"].isDouble()) {
newSc.numSolutions = sco["stopAfter"].toInt();
}
if (sco["verboseFlattening"].isBool()) {
newSc.verboseCompilation = sco["verboseFlattening"].toBool();
}
if (sco["flatteningStats"].isBool()) {
newSc.compilationStats = sco["flatteningStats"].toBool();
}
if (sco["optimizationLevel"].isDouble()) {
newSc.optimizationLevel = sco["optimizationLevel"].toInt();
}
if (sco["additionalData"].isString() && !sco["additionalData"].toString().isEmpty()) {
newSc.additionalData << sco["additionalData"].toString();
}
if (sco["additionalCompilerCommandline"].isString() && !sco["additionalCompilerCommandline"].toString().isEmpty()) {
parseArgList(sco["additionalCompilerCommandline"].toString(), newSc.extraOptions);
}
if (sco["nThreads"].isDouble()) {
newSc.numThreads = sco["nThreads"].toInt();
}
if (sco["randomSeed"].isDouble()) {
newSc.randomSeed = sco["randomSeed"].toDouble();
}
if (sco["solverFlags"].isString() && !sco["solverFlags"].toString().isEmpty()) {
parseArgList(sco["solverFlags"].toString(), newSc.extraOptions);
}
if (sco["freeSearch"].isBool()) {
newSc.freeSearch = sco["freeSearch"].toBool();
}
if (sco["verboseSolving"].isBool()) {
newSc.verboseSolving = sco["verboseSolving"].toBool();
}
if (sco["outputTiming"].isBool()) {
newSc.outputTiming = sco["outputTiming"].toBool();
}
if (sco["solvingStats"].isBool()) {
newSc.solvingStats = sco["solvingStats"].toBool();
}
if (sco["extraOptions"].isObject()) {
QJsonObject extraOptions = sco["extraOptions"].toObject();
for (auto& k : extraOptions.keys()) {
newSc.extraOptions[k] = extraOptions[k].toString();
}
}
return newSc;
}
QString SolverConfiguration::name() const
{
QStringList parts;
if (isBuiltin) {
parts << solverDefinition.name
<< solverDefinition.version;
} else {
if (paramFile.isEmpty()) {
parts << "Unsaved Configuration";
} else {
parts << QFileInfo(paramFile).completeBaseName();
}
parts << "(" + solverDefinition.name + " " + solverDefinition.version + ")";
}
if (modified) {
parts << "*";
}
return parts.join(" ");
}
QByteArray SolverConfiguration::toJSON(void) const
{
QJsonDocument jsonDoc;
jsonDoc.setObject(toJSONObject());
return jsonDoc.toJson();
}
QJsonObject SolverConfiguration::toJSONObject(void) const
{
QJsonObject config;
config["solver"] = solver;
if (timeLimit > 0) {
config["time-limit"] = timeLimit;
}
if ((supports("-a") || supports("-i"))) {
config["intermediate-solutions"] = printIntermediate;
}
if (numSolutions > 1 && supports("-n")) {
config["num-solutions"] = numSolutions;
}
if (numSolutions == 0 && supports("-a")) {
config["all-satisfaction"] = true;
}
if (numOptimal > 1 && supports("-n-o")) {
config["num-optimal"] = numOptimal;
}
if (numOptimal == 0 && supports("-a-o")) {
config["all-optimal"] = true;
}
if (verboseCompilation) {
config["verbose-compilation"] = verboseCompilation;
}
if (verboseSolving && supports("-v")) {
config["verbose-solving"] = verboseSolving;
}
if (compilationStats) {
config["compiler-statistics"] = compilationStats;
}
if (solvingStats && supports("-s")) {
config["solving-statistics"] = solvingStats;
}
if (outputTiming) {
config["output-time"] = outputTiming;
}
if (optimizationLevel != 1) {
config["-O"] = optimizationLevel;
}
QJsonArray arr;
for (auto d : additionalData) {
arr.push_back(d);
}
if (arr.size() > 0) {
config["cmdline-data"] = arr;
}
if (numThreads > 1 && supports("-p")) {
config["parallel"] = numThreads;
}
if (!randomSeed.isNull() && supports("-r")) {
config["random-seed"] = QJsonValue::fromVariant(randomSeed);
}
if (freeSearch && supports("-f")) {
config["free-search"] = freeSearch;
}
for (auto it = extraOptions.begin(); it != extraOptions.end(); it++) {
config[it.key()] = QJsonValue::fromVariant(it.value());
}
for (auto f : solverDefinition.extraFlags) {
if (f.t == SolverFlag::T_BOOL_ONOFF && extraOptions.contains(f.name)) {
// Convert to on/off string instead of bool (TODO: would be nice to handle this in minizinc)
config[f.name] = extraOptions[f.name].toBool() ? f.options[0] : f.options[1];
}
}
return config;
}
bool SolverConfiguration::syncedOptionsMatch(const SolverConfiguration& sc) const
{
if (isBuiltin || sc.isBuiltin) {
// Built-in configs always can have their options overidden
return true;
}
if (timeLimit != sc.timeLimit) {
return false;
}
if ((supports("-a") || supports("-i")) &&
(sc.supports("-a") || sc.supports("-i")) &&
printIntermediate != sc.printIntermediate) {
return false;
}
if (supports("-n") && sc.supports("-n") &&
(numSolutions > 0 || sc.numSolutions > 0) &&
numSolutions != sc.numSolutions) {
return false;
}
if (supports("-a") && sc.supports("-a") &&
(numSolutions == 0 || sc.numSolutions == 0) &&
numSolutions != sc.numSolutions) {
return false;
}
if (supports("-n-o") && sc.supports("-n-o") &&
(numOptimal > 0 || sc.numOptimal > 0) &&
numOptimal != sc.numOptimal) {
return false;
}
if (supports("-a-o") && sc.supports("-a-o") &&
(numOptimal == 0 || sc.numOptimal == 0) &&
numOptimal != sc.numOptimal) {
return false;
}
if (verboseCompilation != sc.verboseCompilation) {
return false;
}
if (supports("-v") && sc.supports("-v") &&
verboseSolving != sc.verboseSolving) {
return false;
}
if (compilationStats != sc.compilationStats) {
return false;
}
if (supports("-s") && sc.supports("-s") &&
solvingStats != sc.solvingStats) {
return false;
}
if (outputTiming != sc.outputTiming) {
return false;
}
return true;
}
bool SolverConfiguration::supports(const QString &flag) const
{
return solverDefinition.stdFlags.contains(flag);
}
bool SolverConfiguration::operator==(const SolverConfiguration& sc) const
{
return solver == sc.solver &&
solverDefinition.id == sc.solverDefinition.id &&
solverDefinition.version == sc.solverDefinition.version &&
isBuiltin == sc.isBuiltin &&
timeLimit == sc.timeLimit &&
printIntermediate == sc.printIntermediate &&
numSolutions == sc.numSolutions &&
verboseCompilation == sc.verboseCompilation &&
verboseSolving == sc.verboseSolving &&
compilationStats == sc.compilationStats &&
solvingStats == sc.solvingStats &&
outputTiming == sc.outputTiming &&
optimizationLevel == sc.optimizationLevel &&
additionalData == sc.additionalData &&
numThreads == sc.numThreads &&
randomSeed == sc.randomSeed &&
freeSearch == sc.freeSearch &&
extraOptions == sc.extraOptions;
}
<|endoftext|> |
<commit_before>//
// sync_client.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <regex>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <fc/variant.hpp>
#include <fc/io/json.hpp>
#include <fc/network/platform_root_ca.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/http_plugin/http_plugin.hpp>
#include <eosio/chain_plugin/chain_plugin.hpp>
#include <boost/asio/ssl/rfc2818_verification.hpp>
#include "httpc.hpp"
using boost::asio::ip::tcp;
using namespace eosio::chain;
namespace eosio { namespace client { namespace http {
namespace detail {
class http_context_impl {
public:
boost::asio::io_service ios;
};
void http_context_deleter::operator()(http_context_impl* p) const {
delete p;
}
}
http_context create_http_context() {
return http_context(new detail::http_context_impl, detail::http_context_deleter());
}
void do_connect(tcp::socket& sock, const resolved_url& url) {
// Get a list of endpoints corresponding to the server name.
vector<tcp::endpoint> endpoints;
endpoints.reserve(url.resolved_addresses.size());
for (const auto& addr: url.resolved_addresses) {
endpoints.emplace_back(boost::asio::ip::make_address(addr), url.resolved_port);
}
boost::asio::connect(sock, endpoints);
}
template<class T>
std::string do_txrx(T& socket, boost::asio::streambuf& request_buff, unsigned int& status_code) {
// Send the request.
boost::asio::write(socket, request_buff);
// Read the response status line. The response streambuf will automatically
// grow to accommodate the entire line. The growth may be limited by passing
// a maximum size to the streambuf constructor.
boost::asio::streambuf response;
boost::asio::read_until(socket, response, "\r\n");
// Check that response is OK.
std::istream response_stream(&response);
std::string http_version;
response_stream >> http_version;
response_stream >> status_code;
std::string status_message;
std::getline(response_stream, status_message);
EOS_ASSERT( !(!response_stream || http_version.substr(0, 5) != "HTTP/"), invalid_http_response, "Invalid Response" );
// Read the response headers, which are terminated by a blank line.
boost::asio::read_until(socket, response, "\r\n\r\n");
// Process the response headers.
std::string header;
int response_content_length = -1;
std::regex clregex(R"xx(^content-length:\s+(\d+))xx", std::regex_constants::icase);
while (std::getline(response_stream, header) && header != "\r") {
std::smatch match;
if(std::regex_search(header, match, clregex))
response_content_length = std::stoi(match[1]);
}
// Attempt to read the response body using the length indicated by the
// Content-length header. If the header was not present just read all available bytes.
if( response_content_length != -1 ) {
response_content_length -= response.size();
if( response_content_length > 0 )
boost::asio::read(socket, response, boost::asio::transfer_exactly(response_content_length));
} else {
boost::system::error_code ec;
boost::asio::read(socket, response, boost::asio::transfer_all(), ec);
EOS_ASSERT(!ec || ec == boost::asio::ssl::error::stream_truncated, http_exception, "Unable to read http response: ${err}", ("err",ec.message()));
}
std::stringstream re;
re << &response;
return re.str();
}
parsed_url parse_url( const string& server_url ) {
parsed_url res;
//unix socket doesn't quite follow classical "URL" rules so deal with it manually
if(boost::algorithm::starts_with(server_url, "unix://")) {
res.scheme = "unix";
res.server = server_url.substr(strlen("unix://"));
return res;
}
//via rfc3986 and modified a bit to suck out the port number
//Sadly this doesn't work for ipv6 addresses
std::regex rgx(R"xx(^(([^:/?#]+):)?(//([^:/?#]*)(:(\d+))?)?([^?#]*)(\?([^#]*))?(#(.*))?)xx");
std::smatch match;
if(std::regex_search(server_url.begin(), server_url.end(), match, rgx)) {
res.scheme = match[2];
res.server = match[4];
res.port = match[6];
res.path = match[7];
}
if(res.scheme != "http" && res.scheme != "https")
EOS_THROW(fail_to_resolve_host, "Unrecognized URL scheme (${s}) in URL \"${u}\"", ("s", res.scheme)("u", server_url));
if(res.server.empty())
EOS_THROW(fail_to_resolve_host, "No server parsed from URL \"${u}\"", ("u", server_url));
if(res.port.empty())
res.port = res.scheme == "http" ? "80" : "443";
boost::trim_right_if(res.path, boost::is_any_of("/"));
return res;
}
resolved_url resolve_url( const http_context& context, const parsed_url& url ) {
if(url.scheme == "unix")
return resolved_url(url);
tcp::resolver resolver(context->ios);
boost::system::error_code ec;
auto result = resolver.resolve(tcp::v4(), url.server, url.port, ec);
if (ec) {
EOS_THROW(fail_to_resolve_host, "Error resolving \"${server}:${port}\" : ${m}", ("server", url.server)("port",url.port)("m",ec.message()));
}
// non error results are guaranteed to return a non-empty range
vector<string> resolved_addresses;
resolved_addresses.reserve(result.size());
optional<uint16_t> resolved_port;
bool is_loopback = true;
for(const auto& r : result) {
const auto& addr = r.endpoint().address();
if (addr.is_v6()) continue;
uint16_t port = r.endpoint().port();
resolved_addresses.emplace_back(addr.to_string());
is_loopback = is_loopback && addr.is_loopback();
if (resolved_port) {
EOS_ASSERT(*resolved_port == port, resolved_to_multiple_ports, "Service name \"${port}\" resolved to multiple ports and this is not supported!", ("port",url.port));
} else {
resolved_port = port;
}
}
return resolved_url(url, std::move(resolved_addresses), *resolved_port, is_loopback);
}
string format_host_header(const resolved_url& url) {
// common practice is to only make the port explicit when it is the non-default port
if (
(url.scheme == "https" && url.resolved_port == 443) ||
(url.scheme == "http" && url.resolved_port == 80)
) {
return url.server;
} else {
return url.server + ":" + url.port;
}
}
fc::variant do_http_call( const connection_param& cp,
const fc::variant& postdata,
bool print_request,
bool print_response ) {
std::string postjson;
if( !postdata.is_null() ) {
postjson = print_request ? fc::json::to_pretty_string( postdata ) : fc::json::to_string( postdata, fc::time_point::maximum() );
}
const auto& url = cp.url;
boost::asio::streambuf request;
std::ostream request_stream(&request);
auto host_header_value = format_host_header(url);
request_stream << "POST " << url.path << " HTTP/1.1\r\n";
request_stream << "Host: " << host_header_value << "\r\n";
request_stream << "content-length: " << postjson.size() << "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: close\r\n";
// append more customized headers
std::vector<string>::iterator itr;
for (itr = cp.headers.begin(); itr != cp.headers.end(); itr++) {
request_stream << *itr << "\r\n";
}
request_stream << "\r\n";
request_stream << postjson;
if ( print_request ) {
string s(request.size(), '\0');
buffer_copy(boost::asio::buffer(s), request.data());
std::cerr << "REQUEST:" << std::endl
<< "---------------------" << std::endl
<< s << std::endl
<< "---------------------" << std::endl;
}
unsigned int status_code;
std::string re;
try {
if(url.scheme == "unix") {
boost::asio::local::stream_protocol::socket unix_socket(cp.context->ios);
unix_socket.connect(boost::asio::local::stream_protocol::endpoint(url.server));
re = do_txrx(unix_socket, request, status_code);
}
else if(url.scheme == "http") {
tcp::socket socket(cp.context->ios);
do_connect(socket, url);
re = do_txrx(socket, request, status_code);
}
else { //https
boost::asio::ssl::context ssl_context(boost::asio::ssl::context::sslv23_client);
fc::add_platform_root_cas_to_context(ssl_context);
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket(cp.context->ios, ssl_context);
SSL_set_tlsext_host_name(socket.native_handle(), url.server.c_str());
if(cp.verify_cert) {
socket.set_verify_mode(boost::asio::ssl::verify_peer);
socket.set_verify_callback(boost::asio::ssl::rfc2818_verification(url.server));
}
do_connect(socket.next_layer(), url);
socket.handshake(boost::asio::ssl::stream_base::client);
re = do_txrx(socket, request, status_code);
//try and do a clean shutdown; but swallow if this fails (other side could have already gave TCP the ax)
try {socket.shutdown();} catch(...) {}
}
} catch ( invalid_http_request& e ) {
e.append_log( FC_LOG_MESSAGE( info, "Please verify this url is valid: ${url}", ("url", url.scheme + "://" + url.server + ":" + url.port + url.path) ) );
e.append_log( FC_LOG_MESSAGE( info, "If the condition persists, please contact the RPC server administrator for ${server}!", ("server", url.server) ) );
throw;
}
fc::variant response_result;
try {
response_result = fc::json::from_string(re);
} catch(...) {
// re reported below if print_response requested
}
if( print_response ) {
std::cerr << "RESPONSE:" << std::endl
<< "---------------------" << std::endl
<< ( response_result.is_null() ? re : fc::json::to_pretty_string( response_result ) ) << std::endl
<< "---------------------" << std::endl;
}
if( status_code == 200 || status_code == 201 || status_code == 202 ) {
return response_result;
} else if( status_code == 404 ) {
// Unknown endpoint
if (url.path.compare(0, chain_func_base.size(), chain_func_base) == 0) {
throw chain::missing_chain_api_plugin_exception(FC_LOG_MESSAGE(error, "Chain API plugin is not enabled"));
} else if (url.path.compare(0, wallet_func_base.size(), wallet_func_base) == 0) {
throw chain::missing_wallet_api_plugin_exception(FC_LOG_MESSAGE(error, "Wallet is not available"));
} else if (url.path.compare(0, history_func_base.size(), history_func_base) == 0) {
throw chain::missing_history_api_plugin_exception(FC_LOG_MESSAGE(error, "History API plugin is not enabled"));
} else if (url.path.compare(0, net_func_base.size(), net_func_base) == 0) {
throw chain::missing_net_api_plugin_exception(FC_LOG_MESSAGE(error, "Net API plugin is not enabled"));
}
} else {
auto &&error_info = response_result.as<eosio::error_results>().error;
// Construct fc exception from error
const auto &error_details = error_info.details;
fc::log_messages logs;
for (auto itr = error_details.begin(); itr != error_details.end(); itr++) {
const auto& context = fc::log_context(fc::log_level::error, itr->file.data(), itr->line_number, itr->method.data());
logs.emplace_back(fc::log_message(context, itr->message));
}
throw fc::exception(logs, error_info.code, error_info.name, error_info.what);
}
EOS_ASSERT( status_code == 200, http_request_fail, "Error code ${c}\n: ${msg}\n", ("c", status_code)("msg", re) );
return response_result;
}
}}}
<commit_msg>Better handling of invalid response<commit_after>//
// sync_client.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <regex>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <fc/variant.hpp>
#include <fc/io/json.hpp>
#include <fc/network/platform_root_ca.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/http_plugin/http_plugin.hpp>
#include <eosio/chain_plugin/chain_plugin.hpp>
#include <boost/asio/ssl/rfc2818_verification.hpp>
#include "httpc.hpp"
using boost::asio::ip::tcp;
using namespace eosio::chain;
namespace eosio { namespace client { namespace http {
namespace detail {
class http_context_impl {
public:
boost::asio::io_service ios;
};
void http_context_deleter::operator()(http_context_impl* p) const {
delete p;
}
}
http_context create_http_context() {
return http_context(new detail::http_context_impl, detail::http_context_deleter());
}
void do_connect(tcp::socket& sock, const resolved_url& url) {
// Get a list of endpoints corresponding to the server name.
vector<tcp::endpoint> endpoints;
endpoints.reserve(url.resolved_addresses.size());
for (const auto& addr: url.resolved_addresses) {
endpoints.emplace_back(boost::asio::ip::make_address(addr), url.resolved_port);
}
boost::asio::connect(sock, endpoints);
}
template<class T>
std::string do_txrx(T& socket, boost::asio::streambuf& request_buff, unsigned int& status_code) {
// Send the request.
boost::asio::write(socket, request_buff);
// Read the response status line. The response streambuf will automatically
// grow to accommodate the entire line. The growth may be limited by passing
// a maximum size to the streambuf constructor.
boost::asio::streambuf response;
boost::asio::read_until(socket, response, "\r\n");
// Check that response is OK.
std::istream response_stream(&response);
std::string http_version;
response_stream >> http_version;
response_stream >> status_code;
std::string status_message;
std::getline(response_stream, status_message);
EOS_ASSERT( !(!response_stream || http_version.substr(0, 5) != "HTTP/"), invalid_http_response, "Invalid Response" );
// Read the response headers, which are terminated by a blank line.
boost::asio::read_until(socket, response, "\r\n\r\n");
// Process the response headers.
std::string header;
int response_content_length = -1;
std::regex clregex(R"xx(^content-length:\s+(\d+))xx", std::regex_constants::icase);
while (std::getline(response_stream, header) && header != "\r") {
std::smatch match;
if(std::regex_search(header, match, clregex))
response_content_length = std::stoi(match[1]);
}
// Attempt to read the response body using the length indicated by the
// Content-length header. If the header was not present just read all available bytes.
if( response_content_length != -1 ) {
response_content_length -= response.size();
if( response_content_length > 0 )
boost::asio::read(socket, response, boost::asio::transfer_exactly(response_content_length));
} else {
boost::system::error_code ec;
boost::asio::read(socket, response, boost::asio::transfer_all(), ec);
EOS_ASSERT(!ec || ec == boost::asio::ssl::error::stream_truncated, http_exception, "Unable to read http response: ${err}", ("err",ec.message()));
}
std::stringstream re;
re << &response;
return re.str();
}
parsed_url parse_url( const string& server_url ) {
parsed_url res;
//unix socket doesn't quite follow classical "URL" rules so deal with it manually
if(boost::algorithm::starts_with(server_url, "unix://")) {
res.scheme = "unix";
res.server = server_url.substr(strlen("unix://"));
return res;
}
//via rfc3986 and modified a bit to suck out the port number
//Sadly this doesn't work for ipv6 addresses
std::regex rgx(R"xx(^(([^:/?#]+):)?(//([^:/?#]*)(:(\d+))?)?([^?#]*)(\?([^#]*))?(#(.*))?)xx");
std::smatch match;
if(std::regex_search(server_url.begin(), server_url.end(), match, rgx)) {
res.scheme = match[2];
res.server = match[4];
res.port = match[6];
res.path = match[7];
}
if(res.scheme != "http" && res.scheme != "https")
EOS_THROW(fail_to_resolve_host, "Unrecognized URL scheme (${s}) in URL \"${u}\"", ("s", res.scheme)("u", server_url));
if(res.server.empty())
EOS_THROW(fail_to_resolve_host, "No server parsed from URL \"${u}\"", ("u", server_url));
if(res.port.empty())
res.port = res.scheme == "http" ? "80" : "443";
boost::trim_right_if(res.path, boost::is_any_of("/"));
return res;
}
resolved_url resolve_url( const http_context& context, const parsed_url& url ) {
if(url.scheme == "unix")
return resolved_url(url);
tcp::resolver resolver(context->ios);
boost::system::error_code ec;
auto result = resolver.resolve(tcp::v4(), url.server, url.port, ec);
if (ec) {
EOS_THROW(fail_to_resolve_host, "Error resolving \"${server}:${port}\" : ${m}", ("server", url.server)("port",url.port)("m",ec.message()));
}
// non error results are guaranteed to return a non-empty range
vector<string> resolved_addresses;
resolved_addresses.reserve(result.size());
optional<uint16_t> resolved_port;
bool is_loopback = true;
for(const auto& r : result) {
const auto& addr = r.endpoint().address();
if (addr.is_v6()) continue;
uint16_t port = r.endpoint().port();
resolved_addresses.emplace_back(addr.to_string());
is_loopback = is_loopback && addr.is_loopback();
if (resolved_port) {
EOS_ASSERT(*resolved_port == port, resolved_to_multiple_ports, "Service name \"${port}\" resolved to multiple ports and this is not supported!", ("port",url.port));
} else {
resolved_port = port;
}
}
return resolved_url(url, std::move(resolved_addresses), *resolved_port, is_loopback);
}
string format_host_header(const resolved_url& url) {
// common practice is to only make the port explicit when it is the non-default port
if (
(url.scheme == "https" && url.resolved_port == 443) ||
(url.scheme == "http" && url.resolved_port == 80)
) {
return url.server;
} else {
return url.server + ":" + url.port;
}
}
fc::variant do_http_call( const connection_param& cp,
const fc::variant& postdata,
bool print_request,
bool print_response ) {
std::string postjson;
if( !postdata.is_null() ) {
postjson = print_request ? fc::json::to_pretty_string( postdata ) : fc::json::to_string( postdata, fc::time_point::maximum() );
}
const auto& url = cp.url;
boost::asio::streambuf request;
std::ostream request_stream(&request);
auto host_header_value = format_host_header(url);
request_stream << "POST " << url.path << " HTTP/1.1\r\n";
request_stream << "Host: " << host_header_value << "\r\n";
request_stream << "content-length: " << postjson.size() << "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: close\r\n";
// append more customized headers
std::vector<string>::iterator itr;
for (itr = cp.headers.begin(); itr != cp.headers.end(); itr++) {
request_stream << *itr << "\r\n";
}
request_stream << "\r\n";
request_stream << postjson;
if ( print_request ) {
string s(request.size(), '\0');
buffer_copy(boost::asio::buffer(s), request.data());
std::cerr << "REQUEST:" << std::endl
<< "---------------------" << std::endl
<< s << std::endl
<< "---------------------" << std::endl;
}
unsigned int status_code;
std::string re;
try {
if(url.scheme == "unix") {
boost::asio::local::stream_protocol::socket unix_socket(cp.context->ios);
unix_socket.connect(boost::asio::local::stream_protocol::endpoint(url.server));
re = do_txrx(unix_socket, request, status_code);
}
else if(url.scheme == "http") {
tcp::socket socket(cp.context->ios);
do_connect(socket, url);
re = do_txrx(socket, request, status_code);
}
else { //https
boost::asio::ssl::context ssl_context(boost::asio::ssl::context::sslv23_client);
fc::add_platform_root_cas_to_context(ssl_context);
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket(cp.context->ios, ssl_context);
SSL_set_tlsext_host_name(socket.native_handle(), url.server.c_str());
if(cp.verify_cert) {
socket.set_verify_mode(boost::asio::ssl::verify_peer);
socket.set_verify_callback(boost::asio::ssl::rfc2818_verification(url.server));
}
do_connect(socket.next_layer(), url);
socket.handshake(boost::asio::ssl::stream_base::client);
re = do_txrx(socket, request, status_code);
//try and do a clean shutdown; but swallow if this fails (other side could have already gave TCP the ax)
try {socket.shutdown();} catch(...) {}
}
} catch ( invalid_http_request& e ) {
e.append_log( FC_LOG_MESSAGE( info, "Please verify this url is valid: ${url}", ("url", url.scheme + "://" + url.server + ":" + url.port + url.path) ) );
e.append_log( FC_LOG_MESSAGE( info, "If the condition persists, please contact the RPC server administrator for ${server}!", ("server", url.server) ) );
throw;
}
fc::variant response_result;
try {
response_result = fc::json::from_string(re);
} catch(...) {
// re reported below if print_response requested
}
if( print_response ) {
std::cerr << "RESPONSE:" << std::endl
<< "---------------------" << std::endl
<< ( response_result.is_null() ? re : fc::json::to_pretty_string( response_result ) ) << std::endl
<< "---------------------" << std::endl;
}
if( !response_result.is_null() ) {
if( status_code == 200 || status_code == 201 || status_code == 202 ) {
return response_result;
} else if( status_code == 404 ) {
// Unknown endpoint
if (url.path.compare(0, chain_func_base.size(), chain_func_base) == 0) {
throw chain::missing_chain_api_plugin_exception(FC_LOG_MESSAGE(error, "Chain API plugin is not enabled"));
} else if (url.path.compare(0, wallet_func_base.size(), wallet_func_base) == 0) {
throw chain::missing_wallet_api_plugin_exception(FC_LOG_MESSAGE(error, "Wallet is not available"));
} else if (url.path.compare(0, history_func_base.size(), history_func_base) == 0) {
throw chain::missing_history_api_plugin_exception(FC_LOG_MESSAGE(error, "History API plugin is not enabled"));
} else if (url.path.compare(0, net_func_base.size(), net_func_base) == 0) {
throw chain::missing_net_api_plugin_exception(FC_LOG_MESSAGE(error, "Net API plugin is not enabled"));
}
} else {
auto &&error_info = response_result.as<eosio::error_results>().error;
// Construct fc exception from error
const auto &error_details = error_info.details;
fc::log_messages logs;
for (auto itr = error_details.begin(); itr != error_details.end(); itr++) {
const auto& context = fc::log_context(fc::log_level::error, itr->file.data(), itr->line_number, itr->method.data());
logs.emplace_back(fc::log_message(context, itr->message));
}
throw fc::exception(logs, error_info.code, error_info.name, error_info.what);
}
}
EOS_ASSERT( status_code == 200 && !response_result.is_null(), http_request_fail,
"Error code ${c}\n: ${msg}\n", ("c", status_code)("msg", re) );
return response_result;
}
}}}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include "IRPrinter.h"
#include "IROperator.h"
#include "IR.h"
namespace Halide {
using std::ostream;
using std::vector;
using std::string;
using std::ostringstream;
ostream &operator<<(ostream &out, const Type &type) {
switch (type.code) {
case Type::Int:
out << "int";
break;
case Type::UInt:
out << "uint";
break;
case Type::Float:
out << "float";
break;
case Type::Handle:
out << "handle";
break;
}
out << type.bits;
if (type.width > 1) out << 'x' << type.width;
return out;
}
ostream &operator<<(ostream &stream, const Expr &ir) {
if (!ir.defined()) {
stream << "(undefined)";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
namespace Internal {
void IRPrinter::test() {
Type i32 = Int(32);
Type f32 = Float(32);
Expr x = Variable::make(Int(32), "x");
Expr y = Variable::make(Int(32), "y");
ostringstream expr_source;
expr_source << (x + 3) * (y / 2 + 17);
internal_assert(expr_source.str() == "((x + 3)*((y/2) + 17))");
Stmt store = Store::make("buf", (x * 17) / (x - 3), y - 1);
Stmt for_loop = For::make("x", -2, y + 2, For::Parallel, store);
vector<Expr> args(1); args[0] = x % 3;
Expr call = Call::make(i32, "buf", args, Call::Extern);
Stmt store2 = Store::make("out", call + 1, x);
Stmt for_loop2 = For::make("x", 0, y, For::Vectorized , store2);
Stmt pipeline = Pipeline::make("buf", for_loop, Stmt(), for_loop2);
Stmt assertion = AssertStmt::make(y > 3, vec<Expr>(Expr("y is greater than "), 3));
Stmt block = Block::make(assertion, pipeline);
Stmt let_stmt = LetStmt::make("y", 17, block);
Stmt allocate = Allocate::make("buf", f32, vec(Expr(1023)), const_true(), let_stmt);
ostringstream source;
source << allocate;
std::string correct_source = \
"allocate buf[float32 * 1023]\n"
"let y = 17\n"
"assert((y > 3), stringify(\"y is greater than \", 3))\n"
"produce buf {\n"
" parallel (x, -2, (y + 2)) {\n"
" buf[(y - 1)] = ((x*17)/(x - 3))\n"
" }\n"
"}\n"
"vectorized (x, 0, y) {\n"
" out[x] = (buf((x % 3)) + 1)\n"
"}\n";
if (source.str() != correct_source) {
internal_error << "Correct output:\n" << correct_source
<< "Actual output:\n" << source.str();
}
std::cout << "IRPrinter test passed\n";
}
ostream &operator<<(ostream &out, const For::ForType &type) {
switch (type) {
case For::Serial:
out << "for";
break;
case For::Parallel:
out << "parallel";
break;
case For::Unrolled:
out << "unrolled";
break;
case For::Vectorized:
out << "vectorized";
break;
}
return out;
}
ostream &operator<<(ostream &stream, const Stmt &ir) {
if (!ir.defined()) {
stream << "(undefined)\n";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
IRPrinter::IRPrinter(ostream &s) : stream(s), indent(0) {
s.setf(std::ios::fixed, std::ios::floatfield);
}
void IRPrinter::print(Expr ir) {
ir.accept(this);
}
void IRPrinter::print(Stmt ir) {
ir.accept(this);
}
void IRPrinter::do_indent() {
for (int i = 0; i < indent; i++) stream << ' ';
}
void IRPrinter::visit(const IntImm *op) {
stream << op->value;
}
void IRPrinter::visit(const FloatImm *op) {
stream << op->value << 'f';
}
void IRPrinter::visit(const StringImm *op) {
stream << '"';
for (size_t i = 0; i < op->value.size(); i++) {
unsigned char c = op->value[i];
if (c >= ' ' && c <= '~' && c != '\\' && c != '"') {
stream << c;
} else {
stream << '\\';
switch (c) {
case '"':
stream << '"';
break;
case '\\':
stream << '\\';
break;
case '\t':
stream << 't';
break;
case '\r':
stream << 'r';
break;
case '\n':
stream << 'n';
break;
default:
string hex_digits = "0123456789ABCDEF";
stream << 'x' << hex_digits[c >> 4] << hex_digits[c & 0xf];
}
}
}
stream << '"';
}
void IRPrinter::visit(const Cast *op) {
stream << op->type << '(';
print(op->value);
stream << ')';
}
void IRPrinter::visit(const Variable *op) {
// omit the type
// stream << op->name << "." << op->type;
stream << op->name;
}
void IRPrinter::visit(const Add *op) {
stream << '(';
print(op->a);
stream << " + ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Sub *op) {
stream << '(';
print(op->a);
stream << " - ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mul *op) {
stream << '(';
print(op->a);
stream << "*";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Div *op) {
stream << '(';
print(op->a);
stream << "/";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mod *op) {
stream << '(';
print(op->a);
stream << " % ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Min *op) {
stream << "min(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const Max *op) {
stream << "max(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const EQ *op) {
stream << '(';
print(op->a);
stream << " == ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const NE *op) {
stream << '(';
print(op->a);
stream << " != ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LT *op) {
stream << '(';
print(op->a);
stream << " < ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LE *op) {
stream << '(';
print(op->a);
stream << " <= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GT *op) {
stream << '(';
print(op->a);
stream << " > ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GE *op) {
stream << '(';
print(op->a);
stream << " >= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const And *op) {
stream << '(';
print(op->a);
stream << " && ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Or *op) {
stream << '(';
print(op->a);
stream << " || ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Not *op) {
stream << '!';
print(op->a);
}
void IRPrinter::visit(const Select *op) {
stream << "select(";
print(op->condition);
stream << ", ";
print(op->true_value);
stream << ", ";
print(op->false_value);
stream << ")";
}
void IRPrinter::visit(const Load *op) {
stream << op->name << "[";
print(op->index);
stream << "]";
}
void IRPrinter::visit(const Ramp *op) {
stream << "ramp(";
print(op->base);
stream << ", ";
print(op->stride);
stream << ", " << op->width << ")";
}
void IRPrinter::visit(const Broadcast *op) {
stream << "x" << op->width << "(";
print(op->value);
stream << ")";
}
void IRPrinter::visit(const Call *op) {
// Special-case some intrinsics for readability
if (op->call_type == Call::Intrinsic) {
if (op->name == Call::extract_buffer_min) {
print(op->args[0]);
stream << ".min[" << op->args[1] << "]";
return;
} else if (op->name == Call::extract_buffer_max) {
print(op->args[0]);
stream << ".max[" << op->args[1] << "]";
return;
}
}
stream << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) {
stream << ", ";
}
}
stream << ")";
}
void IRPrinter::visit(const Let *op) {
stream << "(let " << op->name << " = ";
print(op->value);
stream << " in ";
print(op->body);
stream << ")";
}
void IRPrinter::visit(const LetStmt *op) {
do_indent();
stream << "let " << op->name << " = ";
print(op->value);
stream << '\n';
print(op->body);
}
void IRPrinter::visit(const AssertStmt *op) {
do_indent();
stream << "assert(";
print(op->condition);
stream << ", ";
print(op->message);
stream << ")\n";
}
void IRPrinter::visit(const Pipeline *op) {
do_indent();
stream << "produce " << op->name << " {\n";
indent += 2;
print(op->produce);
indent -= 2;
if (op->update.defined()) {
do_indent();
stream << "} update " << op->name << " {\n";
indent += 2;
print(op->update);
indent -= 2;
}
do_indent();
stream << "}\n";
print(op->consume);
}
void IRPrinter::visit(const For *op) {
do_indent();
stream << op->for_type << " (" << op->name << ", ";
print(op->min);
stream << ", ";
print(op->extent);
stream << ") {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Store *op) {
do_indent();
stream << op->name << "[";
print(op->index);
stream << "] = ";
print(op->value);
stream << '\n';
}
void IRPrinter::visit(const Provide *op) {
do_indent();
stream << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) stream << ", ";
}
stream << ") = ";
if (op->values.size() > 1) {
stream << "{";
}
for (size_t i = 0; i < op->values.size(); i++) {
if (i > 0) {
stream << ", ";
}
print(op->values[i]);
}
if (op->values.size() > 1) {
stream << "}";
}
stream << '\n';
}
void IRPrinter::visit(const Allocate *op) {
do_indent();
stream << "allocate " << op->name << "[" << op->type;
for (size_t i = 0; i < op->extents.size(); i++) {
stream << " * ";
print(op->extents[i]);
}
stream << "]";
if (!is_one(op->condition)) {
stream << " if ";
print(op->condition);
}
stream << "\n";
print(op->body);
}
void IRPrinter::visit(const Free *op) {
do_indent();
stream << "free " << op->name << '\n';
}
void IRPrinter::visit(const Realize *op) {
do_indent();
stream << "realize " << op->name << "(";
for (size_t i = 0; i < op->bounds.size(); i++) {
stream << "[";
print(op->bounds[i].min);
stream << ", ";
print(op->bounds[i].extent);
stream << "]";
if (i < op->bounds.size() - 1) stream << ", ";
}
stream << ")";
if (!is_one(op->condition)) {
stream << " if ";
print(op->condition);
}
stream << " {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Block *op) {
print(op->first);
if (op->rest.defined()) print(op->rest);
}
void IRPrinter::visit(const IfThenElse *op) {
do_indent();
while (1) {
stream << "if (" << op->condition << ") {\n";
indent += 2;
print(op->then_case);
indent -= 2;
if (!op->else_case.defined()) {
break;
}
if (const IfThenElse *nested_if = op->else_case.as<IfThenElse>()) {
do_indent();
stream << "} else ";
op = nested_if;
} else {
do_indent();
stream << "} else {\n";
indent += 2;
print(op->else_case);
indent -= 2;
break;
}
}
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Evaluate *op) {
do_indent();
print(op->value);
stream << "\n";
}
}}
<commit_msg>Output the type of certain expressions in stmt output for debugging<commit_after>#include <iostream>
#include <sstream>
#include "IRPrinter.h"
#include "IROperator.h"
#include "IR.h"
namespace Halide {
using std::ostream;
using std::vector;
using std::string;
using std::ostringstream;
ostream &operator<<(ostream &out, const Type &type) {
switch (type.code) {
case Type::Int:
out << "int";
break;
case Type::UInt:
out << "uint";
break;
case Type::Float:
out << "float";
break;
case Type::Handle:
out << "handle";
break;
}
out << type.bits;
if (type.width > 1) out << 'x' << type.width;
return out;
}
ostream &operator<<(ostream &stream, const Expr &ir) {
if (!ir.defined()) {
stream << "(undefined)";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
namespace Internal {
void IRPrinter::test() {
Type i32 = Int(32);
Type f32 = Float(32);
Expr x = Variable::make(Int(32), "x");
Expr y = Variable::make(Int(32), "y");
ostringstream expr_source;
expr_source << (x + 3) * (y / 2 + 17);
internal_assert(expr_source.str() == "((x + 3)*((y/2) + 17))");
Stmt store = Store::make("buf", (x * 17) / (x - 3), y - 1);
Stmt for_loop = For::make("x", -2, y + 2, For::Parallel, store);
vector<Expr> args(1); args[0] = x % 3;
Expr call = Call::make(i32, "buf", args, Call::Extern);
Stmt store2 = Store::make("out", call + 1, x);
Stmt for_loop2 = For::make("x", 0, y, For::Vectorized , store2);
Stmt pipeline = Pipeline::make("buf", for_loop, Stmt(), for_loop2);
Stmt assertion = AssertStmt::make(y > 3, vec<Expr>(Expr("y is greater than "), 3));
Stmt block = Block::make(assertion, pipeline);
Stmt let_stmt = LetStmt::make("y", 17, block);
Stmt allocate = Allocate::make("buf", f32, vec(Expr(1023)), const_true(), let_stmt);
ostringstream source;
source << allocate;
std::string correct_source = \
"allocate buf[float32 * 1023]\n"
"let y = 17\n"
"assert((y > 3), stringify(\"y is greater than \", 3))\n"
"produce buf {\n"
" parallel (x, -2, (y + 2)) {\n"
" buf[(y - 1)] = ((x*17)/(x - 3))\n"
" }\n"
"}\n"
"vectorized (x, 0, y) {\n"
" out[x] = (buf((x % 3)) + 1)\n"
"}\n";
if (source.str() != correct_source) {
internal_error << "Correct output:\n" << correct_source
<< "Actual output:\n" << source.str();
}
std::cout << "IRPrinter test passed\n";
}
ostream &operator<<(ostream &out, const For::ForType &type) {
switch (type) {
case For::Serial:
out << "for";
break;
case For::Parallel:
out << "parallel";
break;
case For::Unrolled:
out << "unrolled";
break;
case For::Vectorized:
out << "vectorized";
break;
}
return out;
}
ostream &operator<<(ostream &stream, const Stmt &ir) {
if (!ir.defined()) {
stream << "(undefined)\n";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
IRPrinter::IRPrinter(ostream &s) : stream(s), indent(0) {
s.setf(std::ios::fixed, std::ios::floatfield);
}
void IRPrinter::print(Expr ir) {
ir.accept(this);
}
void IRPrinter::print(Stmt ir) {
ir.accept(this);
}
void IRPrinter::do_indent() {
for (int i = 0; i < indent; i++) stream << ' ';
}
void IRPrinter::visit(const IntImm *op) {
stream << op->value;
}
void IRPrinter::visit(const FloatImm *op) {
stream << op->value << 'f';
}
void IRPrinter::visit(const StringImm *op) {
stream << '"';
for (size_t i = 0; i < op->value.size(); i++) {
unsigned char c = op->value[i];
if (c >= ' ' && c <= '~' && c != '\\' && c != '"') {
stream << c;
} else {
stream << '\\';
switch (c) {
case '"':
stream << '"';
break;
case '\\':
stream << '\\';
break;
case '\t':
stream << 't';
break;
case '\r':
stream << 'r';
break;
case '\n':
stream << 'n';
break;
default:
string hex_digits = "0123456789ABCDEF";
stream << 'x' << hex_digits[c >> 4] << hex_digits[c & 0xf];
}
}
}
stream << '"';
}
void IRPrinter::visit(const Cast *op) {
stream << op->type << '(';
print(op->value);
stream << ')';
}
void IRPrinter::visit(const Variable *op) {
// omit the type
// stream << op->name << "." << op->type;
stream << "<" << op->type << "> " << op->name;
}
void IRPrinter::visit(const Add *op) {
stream << '(';
print(op->a);
stream << " + ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Sub *op) {
stream << '(';
print(op->a);
stream << " - ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mul *op) {
stream << '(';
print(op->a);
stream << "*";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Div *op) {
stream << '(';
print(op->a);
stream << "/";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mod *op) {
stream << '(';
print(op->a);
stream << " % ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Min *op) {
stream << "min(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const Max *op) {
stream << "max(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const EQ *op) {
stream << '(';
print(op->a);
stream << " == ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const NE *op) {
stream << '(';
print(op->a);
stream << " != ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LT *op) {
stream << '(';
print(op->a);
stream << " < ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LE *op) {
stream << '(';
print(op->a);
stream << " <= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GT *op) {
stream << '(';
print(op->a);
stream << " > ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GE *op) {
stream << '(';
print(op->a);
stream << " >= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const And *op) {
stream << '(';
print(op->a);
stream << " && ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Or *op) {
stream << '(';
print(op->a);
stream << " || ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Not *op) {
stream << '!';
print(op->a);
}
void IRPrinter::visit(const Select *op) {
stream << "select(";
print(op->condition);
stream << ", ";
print(op->true_value);
stream << ", ";
print(op->false_value);
stream << ")";
}
void IRPrinter::visit(const Load *op) {
stream << op->name << "[";
print(op->index);
stream << "]";
}
void IRPrinter::visit(const Ramp *op) {
stream << "ramp(";
print(op->base);
stream << ", ";
print(op->stride);
stream << ", " << op->width << ")";
}
void IRPrinter::visit(const Broadcast *op) {
stream << "x" << op->width << "(";
print(op->value);
stream << ")";
}
void IRPrinter::visit(const Call *op) {
// Special-case some intrinsics for readability
if (op->call_type == Call::Intrinsic) {
if (op->name == Call::extract_buffer_min) {
print(op->args[0]);
stream << ".min[" << op->args[1] << "]";
return;
} else if (op->name == Call::extract_buffer_max) {
print(op->args[0]);
stream << ".max[" << op->args[1] << "]";
return;
}
}
stream << "<" << op->type << "> " << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) {
stream << ", ";
}
}
stream << ")";
}
void IRPrinter::visit(const Let *op) {
stream << "<" << op->value.type() << "> ";
stream << "(let " << op->name << " = ";
print(op->value);
stream << " in\n";
print(op->body);
stream << ")";
}
void IRPrinter::visit(const LetStmt *op) {
do_indent();
stream << "let " << op->name << " = ";
print(op->value);
stream << '\n';
print(op->body);
}
void IRPrinter::visit(const AssertStmt *op) {
do_indent();
stream << "assert(";
print(op->condition);
stream << ", ";
print(op->message);
stream << ")\n";
}
void IRPrinter::visit(const Pipeline *op) {
do_indent();
stream << "produce " << op->name << " {\n";
indent += 2;
print(op->produce);
indent -= 2;
if (op->update.defined()) {
do_indent();
stream << "} update " << op->name << " {\n";
indent += 2;
print(op->update);
indent -= 2;
}
do_indent();
stream << "}\n";
print(op->consume);
}
void IRPrinter::visit(const For *op) {
do_indent();
stream << op->for_type << " (" << op->name << ", ";
print(op->min);
stream << ", ";
print(op->extent);
stream << ") {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Store *op) {
do_indent();
stream << op->name << "[";
print(op->index);
stream << "] = ";
print(op->value);
stream << '\n';
}
void IRPrinter::visit(const Provide *op) {
do_indent();
stream << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) stream << ", ";
}
stream << ") = ";
if (op->values.size() > 1) {
stream << "{";
}
for (size_t i = 0; i < op->values.size(); i++) {
if (i > 0) {
stream << ", ";
}
print(op->values[i]);
}
if (op->values.size() > 1) {
stream << "}";
}
stream << '\n';
}
void IRPrinter::visit(const Allocate *op) {
do_indent();
stream << "allocate " << op->name << "[" << op->type;
for (size_t i = 0; i < op->extents.size(); i++) {
stream << " * ";
print(op->extents[i]);
}
stream << "]";
if (!is_one(op->condition)) {
stream << " if ";
print(op->condition);
}
stream << "\n";
print(op->body);
}
void IRPrinter::visit(const Free *op) {
do_indent();
stream << "free " << op->name << '\n';
}
void IRPrinter::visit(const Realize *op) {
do_indent();
stream << "realize " << op->name << "(";
for (size_t i = 0; i < op->bounds.size(); i++) {
stream << "[";
print(op->bounds[i].min);
stream << ", ";
print(op->bounds[i].extent);
stream << "]";
if (i < op->bounds.size() - 1) stream << ", ";
}
stream << ")";
if (!is_one(op->condition)) {
stream << " if ";
print(op->condition);
}
stream << " {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Block *op) {
print(op->first);
if (op->rest.defined()) print(op->rest);
}
void IRPrinter::visit(const IfThenElse *op) {
do_indent();
while (1) {
stream << "if (" << op->condition << ") {\n";
indent += 2;
print(op->then_case);
indent -= 2;
if (!op->else_case.defined()) {
break;
}
if (const IfThenElse *nested_if = op->else_case.as<IfThenElse>()) {
do_indent();
stream << "} else ";
op = nested_if;
} else {
do_indent();
stream << "} else {\n";
indent += 2;
print(op->else_case);
indent -= 2;
break;
}
}
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Evaluate *op) {
do_indent();
print(op->value);
stream << "\n";
}
}}
<|endoftext|> |
<commit_before>#include "StdAfx.h"
#include "utypes.h"
#include <assert.h>
#include <stdlib.h>
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
typedef ULONGLONG (WINAPI GetTickCount64Proc)(void);
static GetTickCount64Proc *pt2GetTickCount64;
static GetTickCount64Proc *pt2RealGetTickCount;
static uint64 startPerformanceCounter;
static uint64 startGetTickCount;
// MSVC 6 standard doesn't like division with uint64s
static double counterPerMicrosecond;
uint64 UTGetTickCount64()
{
if (pt2GetTickCount64) {
return pt2GetTickCount64();
}
if (pt2RealGetTickCount) {
uint64 v = pt2RealGetTickCount();
// fix return value from GetTickCount
return (DWORD)v | ((v >> 0x18) & 0xFFFFFFFF00000000);
}
return (uint64)GetTickCount();
}
uint32 UTP_GetMilliseconds()
{
return GetTickCount();
}
void Time_Initialize()
{
HMODULE kernel32 = GetModuleHandleA("kernel32.dll");
pt2GetTickCount64 = (GetTickCount64Proc*)GetProcAddress(kernel32, "GetTickCount64");
// not a typo. GetTickCount actually returns 64 bits
pt2RealGetTickCount = (GetTickCount64Proc*)GetProcAddress(kernel32, "GetTickCount");
uint64 frequency;
QueryPerformanceCounter((LARGE_INTEGER*)&startPerformanceCounter);
QueryPerformanceFrequency((LARGE_INTEGER*)&frequency);
counterPerMicrosecond = (double)frequency / 1000000.0f;
startGetTickCount = UTGetTickCount64();
}
int64 abs64(int64 x) { return x < 0 ? -x : x; }
uint64 UTP_GetMicroseconds()
{
static bool time_init = false;
if (!time_init) {
time_init = true;
Time_Initialize();
}
uint64 counter;
uint64 tick;
QueryPerformanceCounter((LARGE_INTEGER*) &counter);
tick = UTGetTickCount64();
// unfortunately, QueryPerformanceCounter is not guaranteed
// to be monotonic. Make it so.
int64 ret = (int64)(((int64)counter - (int64)startPerformanceCounter) / counterPerMicrosecond);
// if the QPC clock leaps more than one second off GetTickCount64()
// something is seriously fishy. Adjust QPC to stay monotonic
int64 tick_diff = tick - startGetTickCount;
if (abs64(ret / 100000 - tick_diff / 100) > 10) {
startPerformanceCounter -= (uint64)((int64)(tick_diff * 1000 - ret) * counterPerMicrosecond);
ret = (int64)((counter - startPerformanceCounter) / counterPerMicrosecond);
}
return ret;
}
#else //!WIN32
#include <time.h>
#include <sys/time.h> // Linux needs both time.h and sys/time.h
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#if defined(__APPLE__)
#include <mach/mach_time.h>
uint64 UTP_GetMicroseconds()
{
// http://developer.apple.com/mac/library/qa/qa2004/qa1398.html
// http://www.macresearch.org/tutorial_performance_and_time
static mach_timebase_info_data_t sTimebaseInfo;
static uint64_t start_tick = 0;
uint64_t tick;
// Returns a counter in some fraction of a nanoseconds
tick = mach_absolute_time();
if (sTimebaseInfo.denom == 0) {
// Get the timer ratio to convert mach_absolute_time to nanoseconds
mach_timebase_info(&sTimebaseInfo);
start_tick = tick;
}
// Calculate the elapsed time, convert it to microseconds and return it.
return ((tick - start_tick) * sTimebaseInfo.numer) / (sTimebaseInfo.denom * 1000);
}
#elif _POSIX_TIMERS && defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0) && defined(CLOCK_MONOTONIC)
uint64 UTP_GetMicroseconds()
{
timespec t;
int status = clock_gettime(CLOCK_MONOTONIC, &t);
#ifdef _DEBUG
if (status) printf("clock_gettime returned %d - error %d %s", status, errno, ::strerror(errno));
#endif
assert(status == 0);
uint64 tick = uint64(t.tv_sec) * 1000000 + uint64(t.tv_nsec) / 1000;
return tick;
}
#else
#warning "Using non-monotonic function gettimeofday() in UTP_GetMicroseconds()"
// Fallback
uint64 UTP_GetMicroseconds()
{
static time_t start_time = 0;
timeval t;
::gettimeofday(&t, NULL);
// avoid overflow by subtracting the seconds
if (start_time == 0) start_time = t.tv_sec;
return uint64(t.tv_sec - start_time) * 1000000 + (t.tv_usec);
}
#endif
uint32 UTP_GetMilliseconds()
{
return UTP_GetMicroseconds() / 1000;
}
#endif
#define ETHERNET_MTU 1500
#define IPV4_HEADER_SIZE 20
#define IPV6_HEADER_SIZE 40
#define UDP_HEADER_SIZE 8
#define GRE_HEADER_SIZE 24
#define PPPOE_HEADER_SIZE 8
#define MPPE_HEADER_SIZE 2
// packets have been observed in the wild that were fragmented
// with a payload of 1416 for the first fragment
// There are reports of routers that have MTU sizes as small as 1392
#define FUDGE_HEADER_SIZE 36
#define TEREDO_MTU 1280
#define UDP_IPV4_OVERHEAD (IPV4_HEADER_SIZE + UDP_HEADER_SIZE)
#define UDP_IPV6_OVERHEAD (IPV6_HEADER_SIZE + UDP_HEADER_SIZE)
#define UDP_TEREDO_OVERHEAD (UDP_IPV4_OVERHEAD + UDP_IPV6_OVERHEAD)
#define UDP_IPV4_MTU (ETHERNET_MTU - IPV4_HEADER_SIZE - UDP_HEADER_SIZE - GRE_HEADER_SIZE - PPPOE_HEADER_SIZE - MPPE_HEADER_SIZE - FUDGE_HEADER_SIZE)
#define UDP_IPV6_MTU (ETHERNET_MTU - IPV6_HEADER_SIZE - UDP_HEADER_SIZE - GRE_HEADER_SIZE - PPPOE_HEADER_SIZE - MPPE_HEADER_SIZE - FUDGE_HEADER_SIZE)
#define UDP_TEREDO_MTU (TEREDO_MTU - UDP_HEADER_SIZE)
uint16 UTP_GetUDPMTU(const struct sockaddr *remote, socklen_t remotelen)
{
// Since we don't know the local address of the interface,
// be conservative and assume all IPv6 connections are Teredo.
return remote->sa_family == AF_INET6 ? UDP_TEREDO_MTU : UDP_IPV4_MTU;
}
uint16 UTP_GetUDPOverhead(const struct sockaddr *remote, socklen_t remotelen)
{
// Since we don't know the local address of the interface,
// be conservative and assume all IPv6 connections are Teredo.
return remote->sa_family == AF_INET6 ? UDP_TEREDO_OVERHEAD : UDP_IPV4_OVERHEAD;
}
uint32 UTP_Random()
{
return rand();
}
void UTP_DelaySample(const struct sockaddr *remote, int sample_ms) {}
size_t UTP_GetPacketSize(const struct sockaddr *remote) { return 1500; }
<commit_msg>Portable Unix version of UTP_GetMicroseconds<commit_after>#include "StdAfx.h"
#include "utypes.h"
#include <assert.h>
#include <stdlib.h>
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
typedef ULONGLONG (WINAPI GetTickCount64Proc)(void);
static GetTickCount64Proc *pt2GetTickCount64;
static GetTickCount64Proc *pt2RealGetTickCount;
static uint64 startPerformanceCounter;
static uint64 startGetTickCount;
// MSVC 6 standard doesn't like division with uint64s
static double counterPerMicrosecond;
uint64 UTGetTickCount64()
{
if (pt2GetTickCount64) {
return pt2GetTickCount64();
}
if (pt2RealGetTickCount) {
uint64 v = pt2RealGetTickCount();
// fix return value from GetTickCount
return (DWORD)v | ((v >> 0x18) & 0xFFFFFFFF00000000);
}
return (uint64)GetTickCount();
}
uint32 UTP_GetMilliseconds()
{
return GetTickCount();
}
void Time_Initialize()
{
HMODULE kernel32 = GetModuleHandleA("kernel32.dll");
pt2GetTickCount64 = (GetTickCount64Proc*)GetProcAddress(kernel32, "GetTickCount64");
// not a typo. GetTickCount actually returns 64 bits
pt2RealGetTickCount = (GetTickCount64Proc*)GetProcAddress(kernel32, "GetTickCount");
uint64 frequency;
QueryPerformanceCounter((LARGE_INTEGER*)&startPerformanceCounter);
QueryPerformanceFrequency((LARGE_INTEGER*)&frequency);
counterPerMicrosecond = (double)frequency / 1000000.0f;
startGetTickCount = UTGetTickCount64();
}
int64 abs64(int64 x) { return x < 0 ? -x : x; }
uint64 UTP_GetMicroseconds()
{
static bool time_init = false;
if (!time_init) {
time_init = true;
Time_Initialize();
}
uint64 counter;
uint64 tick;
QueryPerformanceCounter((LARGE_INTEGER*) &counter);
tick = UTGetTickCount64();
// unfortunately, QueryPerformanceCounter is not guaranteed
// to be monotonic. Make it so.
int64 ret = (int64)(((int64)counter - (int64)startPerformanceCounter) / counterPerMicrosecond);
// if the QPC clock leaps more than one second off GetTickCount64()
// something is seriously fishy. Adjust QPC to stay monotonic
int64 tick_diff = tick - startGetTickCount;
if (abs64(ret / 100000 - tick_diff / 100) > 10) {
startPerformanceCounter -= (uint64)((int64)(tick_diff * 1000 - ret) * counterPerMicrosecond);
ret = (int64)((counter - startPerformanceCounter) / counterPerMicrosecond);
}
return ret;
}
#else //!WIN32
#include <time.h>
#include <sys/time.h> // Linux needs both time.h and sys/time.h
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#if defined(__APPLE__)
#include <mach/mach_time.h>
uint64 UTP_GetMicroseconds()
{
// http://developer.apple.com/mac/library/qa/qa2004/qa1398.html
// http://www.macresearch.org/tutorial_performance_and_time
static mach_timebase_info_data_t sTimebaseInfo;
static uint64_t start_tick = 0;
uint64_t tick;
// Returns a counter in some fraction of a nanoseconds
tick = mach_absolute_time();
if (sTimebaseInfo.denom == 0) {
// Get the timer ratio to convert mach_absolute_time to nanoseconds
mach_timebase_info(&sTimebaseInfo);
start_tick = tick;
}
// Calculate the elapsed time, convert it to microseconds and return it.
return ((tick - start_tick) * sTimebaseInfo.numer) / (sTimebaseInfo.denom * 1000);
}
#else
/* Unfortunately, #ifdef CLOCK_MONOTONIC is not enough to make sure that
POSIX clocks work -- we could be running a recent libc with an ancient
kernel (think OpenWRT). -- jch */
uint64 UTP_GetMicroseconds()
{
static int have_posix_clocks = -1;
int rc;
#if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 && defined(CLOCK_MONOTONIC)
if (have_posix_clocks < 0) {
struct timespec ts;
rc = clock_gettime(CLOCK_MONOTONIC, &ts);
if (rc < 0) {
have_posix_clocks = 0;
} else {
have_posix_clocks = 1;
}
}
if (have_posix_clocks) {
struct timespec ts;
rc = clock_gettime(CLOCK_MONOTONIC, &ts);
return uint64(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000;
}
#endif
{
static time_t offset = 0, previous = 0;
struct timeval tv;
rc = gettimeofday(&tv, NULL);
tv.tv_sec += offset;
if (previous > tv.tv_sec) {
offset += previous - tv.tv_sec;
tv.tv_sec = previous;
}
previous = tv.tv_sec;
return uint64(tv.tv_sec) * 1000000 + tv.tv_usec;
}
}
#endif
uint32 UTP_GetMilliseconds()
{
return UTP_GetMicroseconds() / 1000;
}
#endif
#define ETHERNET_MTU 1500
#define IPV4_HEADER_SIZE 20
#define IPV6_HEADER_SIZE 40
#define UDP_HEADER_SIZE 8
#define GRE_HEADER_SIZE 24
#define PPPOE_HEADER_SIZE 8
#define MPPE_HEADER_SIZE 2
// packets have been observed in the wild that were fragmented
// with a payload of 1416 for the first fragment
// There are reports of routers that have MTU sizes as small as 1392
#define FUDGE_HEADER_SIZE 36
#define TEREDO_MTU 1280
#define UDP_IPV4_OVERHEAD (IPV4_HEADER_SIZE + UDP_HEADER_SIZE)
#define UDP_IPV6_OVERHEAD (IPV6_HEADER_SIZE + UDP_HEADER_SIZE)
#define UDP_TEREDO_OVERHEAD (UDP_IPV4_OVERHEAD + UDP_IPV6_OVERHEAD)
#define UDP_IPV4_MTU (ETHERNET_MTU - IPV4_HEADER_SIZE - UDP_HEADER_SIZE - GRE_HEADER_SIZE - PPPOE_HEADER_SIZE - MPPE_HEADER_SIZE - FUDGE_HEADER_SIZE)
#define UDP_IPV6_MTU (ETHERNET_MTU - IPV6_HEADER_SIZE - UDP_HEADER_SIZE - GRE_HEADER_SIZE - PPPOE_HEADER_SIZE - MPPE_HEADER_SIZE - FUDGE_HEADER_SIZE)
#define UDP_TEREDO_MTU (TEREDO_MTU - UDP_HEADER_SIZE)
uint16 UTP_GetUDPMTU(const struct sockaddr *remote, socklen_t remotelen)
{
// Since we don't know the local address of the interface,
// be conservative and assume all IPv6 connections are Teredo.
return remote->sa_family == AF_INET6 ? UDP_TEREDO_MTU : UDP_IPV4_MTU;
}
uint16 UTP_GetUDPOverhead(const struct sockaddr *remote, socklen_t remotelen)
{
// Since we don't know the local address of the interface,
// be conservative and assume all IPv6 connections are Teredo.
return remote->sa_family == AF_INET6 ? UDP_TEREDO_OVERHEAD : UDP_IPV4_OVERHEAD;
}
uint32 UTP_Random()
{
return rand();
}
void UTP_DelaySample(const struct sockaddr *remote, int sample_ms) {}
size_t UTP_GetPacketSize(const struct sockaddr *remote) { return 1500; }
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2014 Flowgrammable.org
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS"
// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing
// permissions and limitations under the License.
#ifndef FREEFLOW_SOCKET_HPP
#define FREEFLOW_SOCKET_HPP
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <type_traits>
#include <freeflow/sys/error.hpp>
#include <freeflow/proto/ipv4.hpp>
#include <freeflow/proto/ipv6.hpp>
namespace freeflow {
// -------------------------------------------------------------------------- //
// Internet protocol support
//
// TODO: Consider moving this into a separate file.
/// A class used to encapsulate static information about address
/// families. This provides names for derived classes, to help improve
/// writability.
struct Address_info {
enum Family : sa_family_t {
IPv4 = AF_INET,
IPv6 = AF_INET6,
#if defined(BSD)
RAW = PF_NDRV, // This is BSD only
#elif defined(LINUX)
RAW = AF_PACKET, // This is Linux only
#endif
};
};
/// The type of an Internet port.
using Ip_port = in_port_t;
// =====
// Ipv4
// =====
/// An Ipv4 host adress.
struct Ipv4_addr : in_addr, Address_info {
static constexpr Family family = IPv4;
};
/// An Ipv4 socket address is a host and port. This class provides a
/// read-only view of the underlying system structure.
struct Ipv4_sockaddr : sockaddr_in, Address_info {
static constexpr Family family = IPv4;
Ipv4_sockaddr() = default;
Ipv4_sockaddr(const Ipv4_addr&, Ip_port);
Ipv4_sockaddr(const std::string&, Ip_port);
Ip_port port() const;
Ipv4_addr& addr();
const Ipv4_addr& addr() const;
};
bool operator==(const Ipv4_addr& a, const Ipv4_addr& b);
bool operator!=(const Ipv4_addr& a, const Ipv4_addr& b);
bool operator==(const Ipv4_sockaddr& a, const Ipv4_sockaddr& b);
bool operator!=(const Ipv4_sockaddr& a, const Ipv4_sockaddr& b);
// =====
// Ipv6
// =====
/// In Ipv6 host address.
struct Ipv6_addr : in6_addr, Address_info {
static constexpr Family family = IPv6;
};
/// An Ipv6 socket address is a host and port. This class provides a
/// read-only view of the underlying system structure.
struct Ipv6_sockaddr : sockaddr_in6, Address_info {
static constexpr Family family = IPv6;
Ipv6_sockaddr() = default;
Ipv6_sockaddr(const Ipv6_addr&, Ip_port);
Ipv6_sockaddr(const std::string&, Ip_port);
Ip_port port() const;
Ipv6_addr& addr();
const Ipv6_addr& addr() const;
};
bool operator==(const Ipv6_addr& a, const Ipv6_addr& b);
bool operator!=(const Ipv6_addr& a, const Ipv6_addr& b);
bool operator==(const Ipv6_sockaddr& a, const Ipv6_sockaddr& b);
bool operator!=(const Ipv6_sockaddr& a, const Ipv6_sockaddr& b);
// -------------------------------------------------------------------------- //
// Socket address
/// The address class represents a socket address for a local or remote
/// host. The details of the address are determined by its address family.
/// Examples include IPv4 and IPv6 socket addresses, which are comprised
/// of a 32 or 128 bit host address and a 16 bit port number.
///
/// This is the primary interface for constructing and working with
/// socket addresses.
struct Address : Address_info {
Address() = default;
Address(Family t, const std::string& n, Ip_port p);
Address(const Ipv4_addr& a, Ip_port p = 0);
Address(const Ipv6_addr& a, Ip_port p = 0);
Family family() const;
// Returns the underlying IPv4 address.
Ipv4_sockaddr& as_ipv4();
const Ipv4_sockaddr& as_ipv4() const;
// Returns the underlying IPv6 address.
Ipv6_sockaddr& as_ipv6();
const Ipv6_sockaddr& as_ipv6() const;
// Returns the underlying general address.
sockaddr* addr();
const sockaddr* addr() const;
// Returns the size of the address object.
socklen_t len() const;
sockaddr_storage storage;
};
bool operator==(const Address& l, const Address& r);
bool operator!=(const Address& l, const Address& r);
// Printing
std::string to_string(const Address& a);
// -------------------------------------------------------------------------- //
// Socket
// The socket base class encapsulates informaiton about a socket. This
// is used to provide efficient move semantics for a Socket (since the
// state is a trivial type).
struct Socket_base : Address_info {
enum Transport {
// Internet protocols
UDP,
TCP,
TLS,
SCTP,
// Raw sockets
RAW_IPV4,
RAW_IPV6,
RAW_UDP,
RAW_TCP,
RAW_ICMPv4,
RAW_ICMPv6,
};
Socket_base() = default;
Socket_base(Family f, Transport t);
Socket_base(int, Transport, const Address&, const Address&);
static int type(Transport);
static int protocol(Transport);
int type() const;
int protocol() const;
Family family;
Transport transport;
Address local;
Address peer;
int fd;
int backlog;
};
/// The socket is an endpoint for communicating systems.
///
/// Note that sockets are resources; they can be moved but not copied.
///
/// TODO: Document me!
struct Socket : Socket_base {
// Not default constructible.
Socket() = delete;
// Not copyable.
Socket(const Socket&) = delete;
Socket& operator=(const Socket&) = delete;
// Move semantics
Socket(Socket&&);
Socket& operator=(Socket&&);
// Socket construction
Socket(Family, Transport);
Socket(int, Transport, const Address&, const Address&);
~Socket();
};
// Socket operations
Error bind(Socket& s, Address a = Address());
Error connect(Socket& s, const Address& a);
Error listen(Socket& s, int backlog = SOMAXCONN);
Socket accept(Socket& s);
int read(Socket& s);
int write(Socket& s);
int send_to(Socket& s);
int recv_from(Socket& s);
// Pretty printing
std::string to_string(const Socket& s);
} // namespace freeflow
#include "socket.ipp"
#endif
<commit_msg>Renaming enum values.<commit_after>// Copyright (c) 2013-2014 Flowgrammable.org
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS"
// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing
// permissions and limitations under the License.
#ifndef FREEFLOW_SOCKET_HPP
#define FREEFLOW_SOCKET_HPP
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <type_traits>
#include <freeflow/sys/error.hpp>
#include <freeflow/proto/ipv4.hpp>
#include <freeflow/proto/ipv6.hpp>
namespace freeflow {
// -------------------------------------------------------------------------- //
// Internet protocol support
//
// TODO: Consider moving this into a separate file.
/// A class used to encapsulate static information about address
/// families. This provides names for derived classes, to help improve
/// writability.
struct Address_info {
enum Family : sa_family_t {
IPv4 = AF_INET,
IPv6 = AF_INET6,
#if defined(BSD)
RAW = PF_NDRV, // This is BSD only
#elif defined(LINUX)
RAW = AF_PACKET, // This is Linux only
#endif
};
};
/// The type of an Internet port.
using Ip_port = in_port_t;
// =====
// Ipv4
// =====
/// An Ipv4 host adress.
struct Ipv4_addr : in_addr, Address_info {
static constexpr Family family = IPv4;
};
/// An Ipv4 socket address is a host and port. This class provides a
/// read-only view of the underlying system structure.
struct Ipv4_sockaddr : sockaddr_in, Address_info {
static constexpr Family family = IPv4;
Ipv4_sockaddr() = default;
Ipv4_sockaddr(const Ipv4_addr&, Ip_port);
Ipv4_sockaddr(const std::string&, Ip_port);
Ip_port port() const;
Ipv4_addr& addr();
const Ipv4_addr& addr() const;
};
bool operator==(const Ipv4_addr& a, const Ipv4_addr& b);
bool operator!=(const Ipv4_addr& a, const Ipv4_addr& b);
bool operator==(const Ipv4_sockaddr& a, const Ipv4_sockaddr& b);
bool operator!=(const Ipv4_sockaddr& a, const Ipv4_sockaddr& b);
// =====
// Ipv6
// =====
/// In Ipv6 host address.
struct Ipv6_addr : in6_addr, Address_info {
static constexpr Family family = IPv6;
};
/// An Ipv6 socket address is a host and port. This class provides a
/// read-only view of the underlying system structure.
struct Ipv6_sockaddr : sockaddr_in6, Address_info {
static constexpr Family family = IPv6;
Ipv6_sockaddr() = default;
Ipv6_sockaddr(const Ipv6_addr&, Ip_port);
Ipv6_sockaddr(const std::string&, Ip_port);
Ip_port port() const;
Ipv6_addr& addr();
const Ipv6_addr& addr() const;
};
bool operator==(const Ipv6_addr& a, const Ipv6_addr& b);
bool operator!=(const Ipv6_addr& a, const Ipv6_addr& b);
bool operator==(const Ipv6_sockaddr& a, const Ipv6_sockaddr& b);
bool operator!=(const Ipv6_sockaddr& a, const Ipv6_sockaddr& b);
// -------------------------------------------------------------------------- //
// Socket address
/// The address class represents a socket address for a local or remote
/// host. The details of the address are determined by its address family.
/// Examples include IPv4 and IPv6 socket addresses, which are comprised
/// of a 32 or 128 bit host address and a 16 bit port number.
///
/// This is the primary interface for constructing and working with
/// socket addresses.
struct Address : Address_info {
Address() = default;
Address(Family t, const std::string& n, Ip_port p);
Address(const Ipv4_addr& a, Ip_port p = 0);
Address(const Ipv6_addr& a, Ip_port p = 0);
Family family() const;
// Returns the underlying IPv4 address.
Ipv4_sockaddr& as_ipv4();
const Ipv4_sockaddr& as_ipv4() const;
// Returns the underlying IPv6 address.
Ipv6_sockaddr& as_ipv6();
const Ipv6_sockaddr& as_ipv6() const;
// Returns the underlying general address.
sockaddr* addr();
const sockaddr* addr() const;
// Returns the size of the address object.
socklen_t len() const;
sockaddr_storage storage;
};
bool operator==(const Address& l, const Address& r);
bool operator!=(const Address& l, const Address& r);
// Printing
std::string to_string(const Address& a);
// -------------------------------------------------------------------------- //
// Socket
// The socket base class encapsulates informaiton about a socket. This
// is used to provide efficient move semantics for a Socket (since the
// state is a trivial type).
struct Socket_base : Address_info {
enum Transport {
// Internet protocols
UDP,
TCP,
TLS,
SCTP,
// Raw sockets
RAW_IPv4,
RAW_IPv6,
RAW_UDP,
RAW_TCP,
RAW_ICMPv4,
RAW_ICMPv6,
};
Socket_base() = default;
Socket_base(Family f, Transport t);
Socket_base(int, Transport, const Address&, const Address&);
static int type(Transport);
static int protocol(Transport);
int type() const;
int protocol() const;
Family family;
Transport transport;
Address local;
Address peer;
int fd;
int backlog;
};
/// The socket is an endpoint for communicating systems.
///
/// Note that sockets are resources; they can be moved but not copied.
///
/// TODO: Document me!
struct Socket : Socket_base {
// Not default constructible.
Socket() = delete;
// Not copyable.
Socket(const Socket&) = delete;
Socket& operator=(const Socket&) = delete;
// Move semantics
Socket(Socket&&);
Socket& operator=(Socket&&);
// Socket construction
Socket(Family, Transport);
Socket(int, Transport, const Address&, const Address&);
~Socket();
};
// Socket operations
Error bind(Socket& s, Address a = Address());
Error connect(Socket& s, const Address& a);
Error listen(Socket& s, int backlog = SOMAXCONN);
Socket accept(Socket& s);
int read(Socket& s);
int write(Socket& s);
int send_to(Socket& s);
int recv_from(Socket& s);
// Pretty printing
std::string to_string(const Socket& s);
} // namespace freeflow
#include "socket.ipp"
#endif
<|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 %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;
}
<commit_msg>add "|" 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>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* 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 <modules/autonavigation/helperfunctions.h>
#include <ghoul/logging/logmanager.h>
namespace {
constexpr const char* _loggerCat = "Helpers";
const double Epsilon = 1E-7;
} // namespace
namespace openspace::autonavigation::helpers {
// Shift and scale to a subinterval [start,end]
double shiftAndScale(double t, double start, double end) {
ghoul_assert(0.0 < start && start < end&& end < 1.0,
"Values must be 0.0 < start < end < 1.0!");
double tScaled = t / (end - start) - start;
return std::max(0.0, std::min(tScaled, 1.0));
}
glm::dquat getLookAtQuaternion(glm::dvec3 eye, glm::dvec3 center, glm::dvec3 up) {
glm::dmat4 lookAtMat = glm::lookAt(eye, center, up);
return glm::normalize(glm::inverse(glm::quat_cast(lookAtMat)));
}
/*
* Calculate the intersection of a line and a sphere
* The line segment is defined from p1 to p2
* The sphere is of radius r and centered at sc
* There are potentially two points of intersection given by
* p = p1 + mu1 (p2 - p1)
* p = p1 + mu2 (p2 - p1)
* Source: http://paulbourke.net/geometry/circlesphere/raysphere.c
*/
bool lineSphereIntersection(glm::dvec3 p1, glm::dvec3 p2, glm::dvec3 sc,
double r, glm::dvec3& intersectionPoint)
{
long double a, b, c;
glm::dvec3 dp = p2 - p1;
a = dp.x * dp.x + dp.y * dp.y + dp.z * dp.z;
b = 2 * (dp.x * (p1.x - sc.x) + dp.y * (p1.y - sc.y) + dp.z * (p1.z - sc.z));
c = sc.x * sc.x + sc.y * sc.y + sc.z * sc.z;
c += p1.x * p1.x + p1.y * p1.y + p1.z * p1.z;
c -= 2 * (sc.x * p1.x + sc.y * p1.y + sc.z * p1.z);
c -= r * r;
long double intersectionTest = b * b - 4.0 * a * c;
// no intersection
if (std::abs(a) < Epsilon || intersectionTest < 0.0) {
return false;
}
else {
// only care about the first intersection point if we have two
double t = (-b - std::sqrt(intersectionTest)) / (2.0 *a);
if (t <= Epsilon || t >= abs(1.0 - Epsilon)) return false;
intersectionPoint = p1 + t * dp;
return true;
}
}
bool isPointInsideSphere(const glm::dvec3& p, const glm::dvec3& c, double r) {
glm::dvec3 v = c - p;
long double squaredDistance = v.x * v.x + v.y * v.y + v.z * v.z;
long double squaredRadius = r * r;
if (squaredDistance <= squaredRadius) {
return true;
}
return false;
}
double simpsonsRule(double t0, double t1, int n, std::function<double(double)> f) {
double h = (t1 - t0) / n;
double times4 = 0.0;
double times2 = 0.0;
double endpoints = f(t0) + f(t1);
// weight 4
for (int i = 1; i < n; i += 2) {
double t = t0 + i * h;
times4 += f(t);
}
// weight 2
for (int i = 2; i < n; i += 2) {
double t = t0 + i * h;
times2 += f(t);
}
return (h / 3) * (endpoints + 4 * times4 + 2 * times2);
}
/*
* Approximate area under a function using 5-point Gaussian quadrature
* https://en.wikipedia.org/wiki/Gaussian_quadrature
*/
double fivePointGaussianQuadrature(double t0, double t1,
std::function<double(double)> f)
{
struct GaussLengendreCoefficient {
double abscissa; // xi
double weight; // wi
};
static constexpr GaussLengendreCoefficient coefficients[] = {
{ 0.0, 0.5688889 },
{ -0.5384693, 0.47862867 },
{ 0.5384693, 0.47862867 },
{ -0.90617985, 0.23692688 },
{ 0.90617985, 0.23692688 }
};
const double a = t0;
const double b = t1;
double length = 0.0;
for (auto coefficient : coefficients) {
// change of interval to [a, b] from [-1, 1] (also 0.5 * (b - a) below)
double const t = 0.5 * ((b - a) * coefficient.abscissa + (b + a));
length += f(t) * coefficient.weight;
}
return 0.5 * (b - a) * length;
}
} // helpers
namespace openspace::autonavigation::interpolation {
// Based on implementation by Mika Rantanen
// https://qroph.github.io/2018/07/30/smooth-paths-using-catmull-rom-splines.html
glm::dvec3 catmullRom(double t, const glm::dvec3& p0, const glm::dvec3& p1,
const glm::dvec3& p2, const glm::dvec3& p3, double alpha)
{
glm::dvec3 m01, m02, m23, m13;
double t01 = pow(glm::distance(p0, p1), alpha);
double t12 = pow(glm::distance(p1, p2), alpha);
double t23 = pow(glm::distance(p2, p3), alpha);
m01 = (t01 > Epsilon) ? (p1 - p0) / t01 : glm::dvec3{};
m23 = (t23 > Epsilon) ? (p3 - p2) / t23 : glm::dvec3{};
m02 = (t01 + t12 > Epsilon) ? (p2 - p0) / (t01 + t12) : glm::dvec3{};
m13 = (t12 + t23 > Epsilon) ? (p3 - p1) / (t12 + t23) : glm::dvec3{};
glm::dvec3 m1 = p2 - p1 + t12 * (m01 - m02);
glm::dvec3 m2 = p2 - p1 + t12 * (m23 - m13);
glm::dvec3 a = 2.0 * (p1 - p2) + m1 + m2;
glm::dvec3 b = -3.0 * (p1 - p2) - m1 - m1 - m2;
glm::dvec3 c = m1;
glm::dvec3 d = p1;
return a * t * t * t
+ b * t * t
+ c * t
+ d;
}
glm::dvec3 cubicBezier(double t, const glm::dvec3& cp1, const glm::dvec3& cp2,
const glm::dvec3& cp3, const glm::dvec3& cp4)
{
ghoul_assert(t >= 0 && t <= 1.0, "Interpolation variable out of range [0, 1]");
double a = 1.0 - t;
return cp1 * a * a * a
+ cp2 * t * a * a * 3.0
+ cp3 * t * t * a * 3.0
+ cp4 * t * t * t;
}
glm::dvec3 linear(double t, const glm::dvec3 &cp1, const glm::dvec3 &cp2) {
ghoul_assert(t >= 0 && t <= 1.0, "Interpolation variable out of range [0, 1]");
return cp1 * (1.0 - t) + cp2 * t;
}
glm::dvec3 hermite(double t, const glm::dvec3 &p1, const glm::dvec3 &p2,
const glm::dvec3 &tangent1, const glm::dvec3 &tangent2)
{
ghoul_assert(t >= 0 && t <= 1.0, "Interpolation variable out of range [0, 1]");
if (t <= 0.0) return p1;
if (t >= 1.0) return p2;
const double t2 = t * t;
const double t3 = t2 * t;
// calculate basis functions
double const a0 = (2.0 * t3) - (3.0 * t2) + 1.0;
double const a1 = (-2.0 * t3) + (3.0 * t2);
double const b0 = t3 - (2.0 * t2) + t;
double const b1 = t3 - t2;
return (a0 * p1) + (a1 * p2) + (b0 * tangent1) + (b1 * tangent2);
}
// uniform if tKnots are equally spaced, or else non uniform
glm::dvec3 piecewiseCubicBezier(double t, const std::vector<glm::dvec3>& points,
const std::vector<double>& tKnots)
{
ghoul_assert(points.size() > 4, "Minimum of four control points needed for interpolation!");
ghoul_assert((points.size() - 1) % 3 == 0, "A vector containing 3n + 1 control points must be provided!");
int nrSegments = (points.size() - 1) / 3;
ghoul_assert(nrSegments == (tKnots.size() - 1), "Number of interval times must match number of segments");
if (t <= 0.0) return points.front();
if (t >= 1.0) return points.back();
// compute current segment index
std::vector<double>::const_iterator segmentEndIt =
std::lower_bound(tKnots.begin(), tKnots.end(), t);
unsigned int segmentIdx = (segmentEndIt - 1) - tKnots.begin();
double segmentStart = tKnots[segmentIdx];
double segmentDuration = (tKnots[segmentIdx + 1] - tKnots[segmentIdx]);
double tScaled = (t - segmentStart) / segmentDuration;
unsigned int idx = segmentIdx * 3;
// Interpolate using De Casteljau's algorithm
return interpolation::cubicBezier(
tScaled,
points[idx],
points[idx + 1],
points[idx + 2],
points[idx + 3]
);
}
glm::dvec3 piecewiseLinear(double t, const std::vector<glm::dvec3>& points,
const std::vector<double>& tKnots)
{
ghoul_assert(points.size() == tKnots.size(), "Must have equal number of points and times!");
ghoul_assert(points.size() > 2, "Minimum of two control points needed for interpolation!");
size_t nrSegments = points.size() - 1;
if (t <= 0.0) return points.front();
if (t >= 1.0) return points.back();
// compute current segment index
std::vector<double>::const_iterator segmentEndIt =
std::lower_bound(tKnots.begin(), tKnots.end(), t);
unsigned int idx = (segmentEndIt - 1) - tKnots.begin();
double segmentStart = tKnots[idx];
double segmentDuration = (tKnots[idx + 1] - tKnots[idx]);
double tScaled = (t - segmentStart) / segmentDuration;
return interpolation::linear(tScaled, points[idx], points[idx + 1]);
}
} // interpolation
<commit_msg>Better naming<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* 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 <modules/autonavigation/helperfunctions.h>
#include <ghoul/logging/logmanager.h>
namespace {
constexpr const char* _loggerCat = "Helpers";
const double Epsilon = 1E-7;
} // namespace
namespace openspace::autonavigation::helpers {
// Shift and scale to a subinterval [start,end]
double shiftAndScale(double t, double start, double end) {
ghoul_assert(0.0 < start && start < end&& end < 1.0,
"Values must be 0.0 < start < end < 1.0!");
double tScaled = t / (end - start) - start;
return std::max(0.0, std::min(tScaled, 1.0));
}
glm::dquat getLookAtQuaternion(glm::dvec3 eye, glm::dvec3 center, glm::dvec3 up) {
glm::dmat4 lookAtMat = glm::lookAt(eye, center, up);
return glm::normalize(glm::inverse(glm::quat_cast(lookAtMat)));
}
/*
* Calculate the intersection of a line and a sphere
* The line segment is defined from p1 to p2
* The sphere is of radius r and centered at sc
* There are potentially two points of intersection given by
* p = p1 + mu1 (p2 - p1)
* p = p1 + mu2 (p2 - p1)
* Source: http://paulbourke.net/geometry/circlesphere/raysphere.c
*/
bool lineSphereIntersection(glm::dvec3 p1, glm::dvec3 p2, glm::dvec3 sc,
double r, glm::dvec3& intersectionPoint)
{
long double a, b, c;
glm::dvec3 dp = p2 - p1;
a = dp.x * dp.x + dp.y * dp.y + dp.z * dp.z;
b = 2 * (dp.x * (p1.x - sc.x) + dp.y * (p1.y - sc.y) + dp.z * (p1.z - sc.z));
c = sc.x * sc.x + sc.y * sc.y + sc.z * sc.z;
c += p1.x * p1.x + p1.y * p1.y + p1.z * p1.z;
c -= 2 * (sc.x * p1.x + sc.y * p1.y + sc.z * p1.z);
c -= r * r;
long double intersectionTest = b * b - 4.0 * a * c;
// no intersection
if (std::abs(a) < Epsilon || intersectionTest < 0.0) {
return false;
}
else {
// only care about the first intersection point if we have two
double t = (-b - std::sqrt(intersectionTest)) / (2.0 *a);
if (t <= Epsilon || t >= abs(1.0 - Epsilon)) return false;
intersectionPoint = p1 + t * dp;
return true;
}
}
bool isPointInsideSphere(const glm::dvec3& p, const glm::dvec3& c, double r) {
glm::dvec3 v = c - p;
long double squaredDistance = v.x * v.x + v.y * v.y + v.z * v.z;
long double squaredRadius = r * r;
if (squaredDistance <= squaredRadius) {
return true;
}
return false;
}
double simpsonsRule(double t0, double t1, int n, std::function<double(double)> f) {
double h = (t1 - t0) / n;
double times4 = 0.0;
double times2 = 0.0;
double endpoints = f(t0) + f(t1);
// weight 4
for (int i = 1; i < n; i += 2) {
double t = t0 + i * h;
times4 += f(t);
}
// weight 2
for (int i = 2; i < n; i += 2) {
double t = t0 + i * h;
times2 += f(t);
}
return (h / 3) * (endpoints + 4 * times4 + 2 * times2);
}
/*
* Approximate area under a function using 5-point Gaussian quadrature
* https://en.wikipedia.org/wiki/Gaussian_quadrature
*/
double fivePointGaussianQuadrature(double t0, double t1,
std::function<double(double)> f)
{
struct GaussLengendreCoefficient {
double abscissa; // xi
double weight; // wi
};
static constexpr GaussLengendreCoefficient coefficients[] = {
{ 0.0, 0.5688889 },
{ -0.5384693, 0.47862867 },
{ 0.5384693, 0.47862867 },
{ -0.90617985, 0.23692688 },
{ 0.90617985, 0.23692688 }
};
const double a = t0;
const double b = t1;
double sum = 0.0;
for (auto coefficient : coefficients) {
// change of interval to [a, b] from [-1, 1] (also 0.5 * (b - a) below)
double const t = 0.5 * ((b - a) * coefficient.abscissa + (b + a));
sum += f(t) * coefficient.weight;
}
return 0.5 * (b - a) * sum;
}
} // helpers
namespace openspace::autonavigation::interpolation {
// Based on implementation by Mika Rantanen
// https://qroph.github.io/2018/07/30/smooth-paths-using-catmull-rom-splines.html
glm::dvec3 catmullRom(double t, const glm::dvec3& p0, const glm::dvec3& p1,
const glm::dvec3& p2, const glm::dvec3& p3, double alpha)
{
glm::dvec3 m01, m02, m23, m13;
double t01 = pow(glm::distance(p0, p1), alpha);
double t12 = pow(glm::distance(p1, p2), alpha);
double t23 = pow(glm::distance(p2, p3), alpha);
m01 = (t01 > Epsilon) ? (p1 - p0) / t01 : glm::dvec3{};
m23 = (t23 > Epsilon) ? (p3 - p2) / t23 : glm::dvec3{};
m02 = (t01 + t12 > Epsilon) ? (p2 - p0) / (t01 + t12) : glm::dvec3{};
m13 = (t12 + t23 > Epsilon) ? (p3 - p1) / (t12 + t23) : glm::dvec3{};
glm::dvec3 m1 = p2 - p1 + t12 * (m01 - m02);
glm::dvec3 m2 = p2 - p1 + t12 * (m23 - m13);
glm::dvec3 a = 2.0 * (p1 - p2) + m1 + m2;
glm::dvec3 b = -3.0 * (p1 - p2) - m1 - m1 - m2;
glm::dvec3 c = m1;
glm::dvec3 d = p1;
return a * t * t * t
+ b * t * t
+ c * t
+ d;
}
glm::dvec3 cubicBezier(double t, const glm::dvec3& cp1, const glm::dvec3& cp2,
const glm::dvec3& cp3, const glm::dvec3& cp4)
{
ghoul_assert(t >= 0 && t <= 1.0, "Interpolation variable out of range [0, 1]");
double a = 1.0 - t;
return cp1 * a * a * a
+ cp2 * t * a * a * 3.0
+ cp3 * t * t * a * 3.0
+ cp4 * t * t * t;
}
glm::dvec3 linear(double t, const glm::dvec3 &cp1, const glm::dvec3 &cp2) {
ghoul_assert(t >= 0 && t <= 1.0, "Interpolation variable out of range [0, 1]");
return cp1 * (1.0 - t) + cp2 * t;
}
glm::dvec3 hermite(double t, const glm::dvec3 &p1, const glm::dvec3 &p2,
const glm::dvec3 &tangent1, const glm::dvec3 &tangent2)
{
ghoul_assert(t >= 0 && t <= 1.0, "Interpolation variable out of range [0, 1]");
if (t <= 0.0) return p1;
if (t >= 1.0) return p2;
const double t2 = t * t;
const double t3 = t2 * t;
// calculate basis functions
double const a0 = (2.0 * t3) - (3.0 * t2) + 1.0;
double const a1 = (-2.0 * t3) + (3.0 * t2);
double const b0 = t3 - (2.0 * t2) + t;
double const b1 = t3 - t2;
return (a0 * p1) + (a1 * p2) + (b0 * tangent1) + (b1 * tangent2);
}
// uniform if tKnots are equally spaced, or else non uniform
glm::dvec3 piecewiseCubicBezier(double t, const std::vector<glm::dvec3>& points,
const std::vector<double>& tKnots)
{
ghoul_assert(points.size() > 4, "Minimum of four control points needed for interpolation!");
ghoul_assert((points.size() - 1) % 3 == 0, "A vector containing 3n + 1 control points must be provided!");
int nrSegments = (points.size() - 1) / 3;
ghoul_assert(nrSegments == (tKnots.size() - 1), "Number of interval times must match number of segments");
if (t <= 0.0) return points.front();
if (t >= 1.0) return points.back();
// compute current segment index
std::vector<double>::const_iterator segmentEndIt =
std::lower_bound(tKnots.begin(), tKnots.end(), t);
unsigned int segmentIdx = (segmentEndIt - 1) - tKnots.begin();
double segmentStart = tKnots[segmentIdx];
double segmentDuration = (tKnots[segmentIdx + 1] - tKnots[segmentIdx]);
double tScaled = (t - segmentStart) / segmentDuration;
unsigned int idx = segmentIdx * 3;
// Interpolate using De Casteljau's algorithm
return interpolation::cubicBezier(
tScaled,
points[idx],
points[idx + 1],
points[idx + 2],
points[idx + 3]
);
}
glm::dvec3 piecewiseLinear(double t, const std::vector<glm::dvec3>& points,
const std::vector<double>& tKnots)
{
ghoul_assert(points.size() == tKnots.size(), "Must have equal number of points and times!");
ghoul_assert(points.size() > 2, "Minimum of two control points needed for interpolation!");
size_t nrSegments = points.size() - 1;
if (t <= 0.0) return points.front();
if (t >= 1.0) return points.back();
// compute current segment index
std::vector<double>::const_iterator segmentEndIt =
std::lower_bound(tKnots.begin(), tKnots.end(), t);
unsigned int idx = (segmentEndIt - 1) - tKnots.begin();
double segmentStart = tKnots[idx];
double segmentDuration = (tKnots[idx + 1] - tKnots[idx]);
double tScaled = (t - segmentStart) / segmentDuration;
return interpolation::linear(tScaled, points[idx], points[idx + 1]);
}
} // interpolation
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include "IRPrinter.h"
#include "IROperator.h"
#include "IR.h"
namespace Halide {
using std::ostream;
using std::vector;
using std::string;
using std::ostringstream;
ostream &operator<<(ostream &out, const Type &type) {
switch (type.code) {
case Type::Int:
out << "int";
break;
case Type::UInt:
out << "uint";
break;
case Type::Float:
out << "float";
break;
case Type::Handle:
out << "handle";
break;
}
out << type.bits;
if (type.width > 1) out << 'x' << type.width;
return out;
}
ostream &operator<<(ostream &stream, const Expr &ir) {
if (!ir.defined()) {
stream << "(undefined)";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
namespace Internal {
void IRPrinter::test() {
Type i32 = Int(32);
Type f32 = Float(32);
Expr x = Variable::make(Int(32), "x");
Expr y = Variable::make(Int(32), "y");
ostringstream expr_source;
expr_source << (x + 3) * (y / 2 + 17);
internal_assert(expr_source.str() == "((x + 3)*((y/2) + 17))");
Stmt store = Store::make("buf", (x * 17) / (x - 3), y - 1);
Stmt for_loop = For::make("x", -2, y + 2, For::Parallel, store);
vector<Expr> args(1); args[0] = x % 3;
Expr call = Call::make(i32, "buf", args, Call::Extern);
Stmt store2 = Store::make("out", call + 1, x);
Stmt for_loop2 = For::make("x", 0, y, For::Vectorized , store2);
Stmt pipeline = Pipeline::make("buf", for_loop, Stmt(), for_loop2);
Stmt assertion = AssertStmt::make(y > 3, vec<Expr>(Expr("y is greater than "), 3));
Stmt block = Block::make(assertion, pipeline);
Stmt let_stmt = LetStmt::make("y", 17, block);
Stmt allocate = Allocate::make("buf", f32, vec(Expr(1023)), const_true(), let_stmt);
ostringstream source;
source << allocate;
std::string correct_source = \
"allocate buf[float32 * 1023]\n"
"let y = 17\n"
"assert((y > 3), stringify(\"y is greater than \", 3))\n"
"produce buf {\n"
" parallel (x, -2, (y + 2)) {\n"
" buf[(y - 1)] = ((x*17)/(x - 3))\n"
" }\n"
"}\n"
"vectorized (x, 0, y) {\n"
" out[x] = (buf((x % 3)) + 1)\n"
"}\n";
if (source.str() != correct_source) {
internal_error << "Correct output:\n" << correct_source
<< "Actual output:\n" << source.str();
}
std::cout << "IRPrinter test passed\n";
}
ostream &operator<<(ostream &out, const For::ForType &type) {
switch (type) {
case For::Serial:
out << "for";
break;
case For::Parallel:
out << "parallel";
break;
case For::Unrolled:
out << "unrolled";
break;
case For::Vectorized:
out << "vectorized";
break;
}
return out;
}
ostream &operator<<(ostream &stream, const Stmt &ir) {
if (!ir.defined()) {
stream << "(undefined)\n";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
IRPrinter::IRPrinter(ostream &s) : stream(s), indent(0) {
s.setf(std::ios::fixed, std::ios::floatfield);
}
void IRPrinter::print(Expr ir) {
ir.accept(this);
}
void IRPrinter::print(Stmt ir) {
ir.accept(this);
}
void IRPrinter::do_indent() {
for (int i = 0; i < indent; i++) stream << ' ';
}
void IRPrinter::visit(const IntImm *op) {
stream << op->value;
}
void IRPrinter::visit(const FloatImm *op) {
stream << op->value << 'f';
}
void IRPrinter::visit(const StringImm *op) {
stream << '"';
for (size_t i = 0; i < op->value.size(); i++) {
unsigned char c = op->value[i];
if (c >= ' ' && c <= '~' && c != '\\' && c != '"') {
stream << c;
} else {
stream << '\\';
switch (c) {
case '"':
stream << '"';
break;
case '\\':
stream << '\\';
break;
case '\t':
stream << 't';
break;
case '\r':
stream << 'r';
break;
case '\n':
stream << 'n';
break;
default:
string hex_digits = "0123456789ABCDEF";
stream << 'x' << hex_digits[c >> 4] << hex_digits[c & 0xf];
}
}
}
stream << '"';
}
void IRPrinter::visit(const Cast *op) {
stream << op->type << '(';
print(op->value);
stream << ')';
}
void IRPrinter::visit(const Variable *op) {
// omit the type
// stream << op->name << "." << op->type;
stream << op->name;
}
void IRPrinter::visit(const Add *op) {
stream << '(';
print(op->a);
stream << " + ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Sub *op) {
stream << '(';
print(op->a);
stream << " - ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mul *op) {
stream << '(';
print(op->a);
stream << "*";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Div *op) {
stream << '(';
print(op->a);
stream << "/";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mod *op) {
stream << '(';
print(op->a);
stream << " % ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Min *op) {
stream << "min(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const Max *op) {
stream << "max(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const EQ *op) {
stream << '(';
print(op->a);
stream << " == ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const NE *op) {
stream << '(';
print(op->a);
stream << " != ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LT *op) {
stream << '(';
print(op->a);
stream << " < ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LE *op) {
stream << '(';
print(op->a);
stream << " <= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GT *op) {
stream << '(';
print(op->a);
stream << " > ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GE *op) {
stream << '(';
print(op->a);
stream << " >= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const And *op) {
stream << '(';
print(op->a);
stream << " && ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Or *op) {
stream << '(';
print(op->a);
stream << " || ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Not *op) {
stream << '!';
print(op->a);
}
void IRPrinter::visit(const Select *op) {
stream << "select(";
print(op->condition);
stream << ", ";
print(op->true_value);
stream << ", ";
print(op->false_value);
stream << ")";
}
void IRPrinter::visit(const Load *op) {
stream << op->name << "[";
print(op->index);
stream << "]";
}
void IRPrinter::visit(const Ramp *op) {
stream << "ramp(";
print(op->base);
stream << ", ";
print(op->stride);
stream << ", " << op->width << ")";
}
void IRPrinter::visit(const Broadcast *op) {
stream << "x" << op->width << "(";
print(op->value);
stream << ")";
}
void IRPrinter::visit(const Call *op) {
// Special-case some intrinsics for readability
if (op->call_type == Call::Intrinsic) {
if (op->name == Call::extract_buffer_min) {
print(op->args[0]);
stream << ".min[" << op->args[1] << "]";
return;
} else if (op->name == Call::extract_buffer_max) {
print(op->args[0]);
stream << ".max[" << op->args[1] << "]";
return;
}
}
stream << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) {
stream << ", ";
}
}
stream << ")";
}
void IRPrinter::visit(const Let *op) {
stream << "(let " << op->name << " = ";
print(op->value);
stream << " in ";
print(op->body);
stream << ")";
}
void IRPrinter::visit(const LetStmt *op) {
do_indent();
stream << "let " << op->name << " = ";
print(op->value);
stream << '\n';
print(op->body);
}
void IRPrinter::visit(const AssertStmt *op) {
do_indent();
stream << "assert(";
print(op->condition);
stream << ", ";
print(op->message);
stream << ")\n";
}
void IRPrinter::visit(const Pipeline *op) {
do_indent();
stream << "produce " << op->name << " {\n";
indent += 2;
print(op->produce);
indent -= 2;
if (op->update.defined()) {
do_indent();
stream << "} update " << op->name << " {\n";
indent += 2;
print(op->update);
indent -= 2;
}
do_indent();
stream << "}\n";
print(op->consume);
}
void IRPrinter::visit(const For *op) {
do_indent();
stream << op->for_type << " (" << op->name << ", ";
print(op->min);
stream << ", ";
print(op->extent);
stream << ") {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Store *op) {
do_indent();
stream << op->name << "[";
print(op->index);
stream << "] = ";
print(op->value);
stream << '\n';
}
void IRPrinter::visit(const Provide *op) {
do_indent();
stream << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) stream << ", ";
}
stream << ") = ";
if (op->values.size() > 1) {
stream << "{";
}
for (size_t i = 0; i < op->values.size(); i++) {
if (i > 0) {
stream << ", ";
}
print(op->values[i]);
}
if (op->values.size() > 1) {
stream << "}";
}
stream << '\n';
}
void IRPrinter::visit(const Allocate *op) {
do_indent();
stream << "allocate " << op->name << "[" << op->type;
for (size_t i = 0; i < op->extents.size(); i++) {
stream << " * ";
print(op->extents[i]);
}
stream << "]";
if (!is_one(op->condition)) {
stream << " if ";
print(op->condition);
}
stream << "\n";
print(op->body);
}
void IRPrinter::visit(const Free *op) {
do_indent();
stream << "free " << op->name << '\n';
}
void IRPrinter::visit(const Realize *op) {
do_indent();
stream << "realize " << op->name << "(";
for (size_t i = 0; i < op->bounds.size(); i++) {
stream << "[";
print(op->bounds[i].min);
stream << ", ";
print(op->bounds[i].extent);
stream << "]";
if (i < op->bounds.size() - 1) stream << ", ";
}
stream << ")";
if (!is_one(op->condition)) {
stream << " if ";
print(op->condition);
}
stream << " {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Block *op) {
print(op->first);
if (op->rest.defined()) print(op->rest);
}
void IRPrinter::visit(const IfThenElse *op) {
do_indent();
while (1) {
stream << "if (" << op->condition << ") {\n";
indent += 2;
print(op->then_case);
indent -= 2;
if (!op->else_case.defined()) {
break;
}
if (const IfThenElse *nested_if = op->else_case.as<IfThenElse>()) {
do_indent();
stream << "} else ";
op = nested_if;
} else {
do_indent();
stream << "} else {\n";
indent += 2;
print(op->else_case);
indent -= 2;
break;
}
}
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Evaluate *op) {
do_indent();
print(op->value);
stream << "\n";
}
}}
<commit_msg>Output the type of certain expressions in stmt output for debugging<commit_after>#include <iostream>
#include <sstream>
#include "IRPrinter.h"
#include "IROperator.h"
#include "IR.h"
namespace Halide {
using std::ostream;
using std::vector;
using std::string;
using std::ostringstream;
ostream &operator<<(ostream &out, const Type &type) {
switch (type.code) {
case Type::Int:
out << "int";
break;
case Type::UInt:
out << "uint";
break;
case Type::Float:
out << "float";
break;
case Type::Handle:
out << "handle";
break;
}
out << type.bits;
if (type.width > 1) out << 'x' << type.width;
return out;
}
ostream &operator<<(ostream &stream, const Expr &ir) {
if (!ir.defined()) {
stream << "(undefined)";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
namespace Internal {
void IRPrinter::test() {
Type i32 = Int(32);
Type f32 = Float(32);
Expr x = Variable::make(Int(32), "x");
Expr y = Variable::make(Int(32), "y");
ostringstream expr_source;
expr_source << (x + 3) * (y / 2 + 17);
internal_assert(expr_source.str() == "((x + 3)*((y/2) + 17))");
Stmt store = Store::make("buf", (x * 17) / (x - 3), y - 1);
Stmt for_loop = For::make("x", -2, y + 2, For::Parallel, store);
vector<Expr> args(1); args[0] = x % 3;
Expr call = Call::make(i32, "buf", args, Call::Extern);
Stmt store2 = Store::make("out", call + 1, x);
Stmt for_loop2 = For::make("x", 0, y, For::Vectorized , store2);
Stmt pipeline = Pipeline::make("buf", for_loop, Stmt(), for_loop2);
Stmt assertion = AssertStmt::make(y > 3, vec<Expr>(Expr("y is greater than "), 3));
Stmt block = Block::make(assertion, pipeline);
Stmt let_stmt = LetStmt::make("y", 17, block);
Stmt allocate = Allocate::make("buf", f32, vec(Expr(1023)), const_true(), let_stmt);
ostringstream source;
source << allocate;
std::string correct_source = \
"allocate buf[float32 * 1023]\n"
"let y = 17\n"
"assert((y > 3), stringify(\"y is greater than \", 3))\n"
"produce buf {\n"
" parallel (x, -2, (y + 2)) {\n"
" buf[(y - 1)] = ((x*17)/(x - 3))\n"
" }\n"
"}\n"
"vectorized (x, 0, y) {\n"
" out[x] = (buf((x % 3)) + 1)\n"
"}\n";
if (source.str() != correct_source) {
internal_error << "Correct output:\n" << correct_source
<< "Actual output:\n" << source.str();
}
std::cout << "IRPrinter test passed\n";
}
ostream &operator<<(ostream &out, const For::ForType &type) {
switch (type) {
case For::Serial:
out << "for";
break;
case For::Parallel:
out << "parallel";
break;
case For::Unrolled:
out << "unrolled";
break;
case For::Vectorized:
out << "vectorized";
break;
}
return out;
}
ostream &operator<<(ostream &stream, const Stmt &ir) {
if (!ir.defined()) {
stream << "(undefined)\n";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
IRPrinter::IRPrinter(ostream &s) : stream(s), indent(0) {
s.setf(std::ios::fixed, std::ios::floatfield);
}
void IRPrinter::print(Expr ir) {
ir.accept(this);
}
void IRPrinter::print(Stmt ir) {
ir.accept(this);
}
void IRPrinter::do_indent() {
for (int i = 0; i < indent; i++) stream << ' ';
}
void IRPrinter::visit(const IntImm *op) {
stream << op->value;
}
void IRPrinter::visit(const FloatImm *op) {
stream << op->value << 'f';
}
void IRPrinter::visit(const StringImm *op) {
stream << '"';
for (size_t i = 0; i < op->value.size(); i++) {
unsigned char c = op->value[i];
if (c >= ' ' && c <= '~' && c != '\\' && c != '"') {
stream << c;
} else {
stream << '\\';
switch (c) {
case '"':
stream << '"';
break;
case '\\':
stream << '\\';
break;
case '\t':
stream << 't';
break;
case '\r':
stream << 'r';
break;
case '\n':
stream << 'n';
break;
default:
string hex_digits = "0123456789ABCDEF";
stream << 'x' << hex_digits[c >> 4] << hex_digits[c & 0xf];
}
}
}
stream << '"';
}
void IRPrinter::visit(const Cast *op) {
stream << op->type << '(';
print(op->value);
stream << ')';
}
void IRPrinter::visit(const Variable *op) {
// omit the type
// stream << op->name << "." << op->type;
stream << "<" << op->type << "> " << op->name;
}
void IRPrinter::visit(const Add *op) {
stream << '(';
print(op->a);
stream << " + ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Sub *op) {
stream << '(';
print(op->a);
stream << " - ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mul *op) {
stream << '(';
print(op->a);
stream << "*";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Div *op) {
stream << '(';
print(op->a);
stream << "/";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mod *op) {
stream << '(';
print(op->a);
stream << " % ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Min *op) {
stream << "min(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const Max *op) {
stream << "max(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const EQ *op) {
stream << '(';
print(op->a);
stream << " == ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const NE *op) {
stream << '(';
print(op->a);
stream << " != ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LT *op) {
stream << '(';
print(op->a);
stream << " < ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LE *op) {
stream << '(';
print(op->a);
stream << " <= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GT *op) {
stream << '(';
print(op->a);
stream << " > ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GE *op) {
stream << '(';
print(op->a);
stream << " >= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const And *op) {
stream << '(';
print(op->a);
stream << " && ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Or *op) {
stream << '(';
print(op->a);
stream << " || ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Not *op) {
stream << '!';
print(op->a);
}
void IRPrinter::visit(const Select *op) {
stream << "select(";
print(op->condition);
stream << ", ";
print(op->true_value);
stream << ", ";
print(op->false_value);
stream << ")";
}
void IRPrinter::visit(const Load *op) {
stream << op->name << "[";
print(op->index);
stream << "]";
}
void IRPrinter::visit(const Ramp *op) {
stream << "ramp(";
print(op->base);
stream << ", ";
print(op->stride);
stream << ", " << op->width << ")";
}
void IRPrinter::visit(const Broadcast *op) {
stream << "x" << op->width << "(";
print(op->value);
stream << ")";
}
void IRPrinter::visit(const Call *op) {
// Special-case some intrinsics for readability
if (op->call_type == Call::Intrinsic) {
if (op->name == Call::extract_buffer_min) {
print(op->args[0]);
stream << ".min[" << op->args[1] << "]";
return;
} else if (op->name == Call::extract_buffer_max) {
print(op->args[0]);
stream << ".max[" << op->args[1] << "]";
return;
}
}
stream << "<" << op->type << "> " << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) {
stream << ", ";
}
}
stream << ")";
}
void IRPrinter::visit(const Let *op) {
stream << "<" << op->value.type() << "> ";
stream << "(let " << op->name << " = ";
print(op->value);
stream << " in\n";
print(op->body);
stream << ")";
}
void IRPrinter::visit(const LetStmt *op) {
do_indent();
stream << "let " << op->name << " = ";
print(op->value);
stream << '\n';
print(op->body);
}
void IRPrinter::visit(const AssertStmt *op) {
do_indent();
stream << "assert(";
print(op->condition);
stream << ", ";
print(op->message);
stream << ")\n";
}
void IRPrinter::visit(const Pipeline *op) {
do_indent();
stream << "produce " << op->name << " {\n";
indent += 2;
print(op->produce);
indent -= 2;
if (op->update.defined()) {
do_indent();
stream << "} update " << op->name << " {\n";
indent += 2;
print(op->update);
indent -= 2;
}
do_indent();
stream << "}\n";
print(op->consume);
}
void IRPrinter::visit(const For *op) {
do_indent();
stream << op->for_type << " (" << op->name << ", ";
print(op->min);
stream << ", ";
print(op->extent);
stream << ") {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Store *op) {
do_indent();
stream << op->name << "[";
print(op->index);
stream << "] = ";
print(op->value);
stream << '\n';
}
void IRPrinter::visit(const Provide *op) {
do_indent();
stream << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) stream << ", ";
}
stream << ") = ";
if (op->values.size() > 1) {
stream << "{";
}
for (size_t i = 0; i < op->values.size(); i++) {
if (i > 0) {
stream << ", ";
}
print(op->values[i]);
}
if (op->values.size() > 1) {
stream << "}";
}
stream << '\n';
}
void IRPrinter::visit(const Allocate *op) {
do_indent();
stream << "allocate " << op->name << "[" << op->type;
for (size_t i = 0; i < op->extents.size(); i++) {
stream << " * ";
print(op->extents[i]);
}
stream << "]";
if (!is_one(op->condition)) {
stream << " if ";
print(op->condition);
}
stream << "\n";
print(op->body);
}
void IRPrinter::visit(const Free *op) {
do_indent();
stream << "free " << op->name << '\n';
}
void IRPrinter::visit(const Realize *op) {
do_indent();
stream << "realize " << op->name << "(";
for (size_t i = 0; i < op->bounds.size(); i++) {
stream << "[";
print(op->bounds[i].min);
stream << ", ";
print(op->bounds[i].extent);
stream << "]";
if (i < op->bounds.size() - 1) stream << ", ";
}
stream << ")";
if (!is_one(op->condition)) {
stream << " if ";
print(op->condition);
}
stream << " {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Block *op) {
print(op->first);
if (op->rest.defined()) print(op->rest);
}
void IRPrinter::visit(const IfThenElse *op) {
do_indent();
while (1) {
stream << "if (" << op->condition << ") {\n";
indent += 2;
print(op->then_case);
indent -= 2;
if (!op->else_case.defined()) {
break;
}
if (const IfThenElse *nested_if = op->else_case.as<IfThenElse>()) {
do_indent();
stream << "} else ";
op = nested_if;
} else {
do_indent();
stream << "} else {\n";
indent += 2;
print(op->else_case);
indent -= 2;
break;
}
}
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Evaluate *op) {
do_indent();
print(op->value);
stream << "\n";
}
}}
<|endoftext|> |
<commit_before>// Copyright 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 "chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.h"
#include <string>
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/grit/generated_resources.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest.h"
#include "ui/base/l10n/l10n_util.h"
namespace chromeos {
namespace {
// Apps/extensions explicitly whitelisted for use in public sessions.
const char* const kPublicSessionWhitelist[] = {
// Public sessions in general:
"cbkkbcmdlboombapidmoeolnmdacpkch", // Chrome RDP
"djflhoibgkdhkhhcedjiklpkjnoahfmg", // User Agent Switcher
"iabmpiboiopbgfabjmgeedhcmjenhbla", // VNC Viewer
"haiffjcadagjlijoggckpgfnoeiflnem", // Citrix Receiver
"mfaihdlpglflfgpfjcifdjdjcckigekc", // ARC Runtime
// Libraries:
"aclofikceldphonlfmghmimkodjdmhck", // Ancoris login component
"eilbnahdgoddoedakcmfkcgfoegeloil", // Ancoris proxy component
"ceehlgckkmkaoggdnjhibffkphfnphmg", // Libdata login
// Retail mode:
"bjfeaefhaooblkndnoabbkkkenknkemb", // 500 px demo
"ehcabepphndocfmgbdkbjibfodelmpbb", // Angry Birds demo
"kgimkbnclbekdkabkpjhpakhhalfanda", // Bejeweled demo
"joodangkbfjnajiiifokapkpmhfnpleo", // Calculator
"fpgfohogebplgnamlafljlcidjedbdeb", // Calendar demo
"hfhhnacclhffhdffklopdkcgdhifgngh", // Camera
"cdjikkcakjcdjemakobkmijmikhkegcj", // Chrome Remote Desktop demo
"jkoildpomkimndcphjpffmephmcmkfhn", // Chromebook Demo App
"lbhdhapagjhalobandnbdnmblnmocojh", // Crackle demo
"ielkookhdphmgbipcfmafkaiagademfp", // Custom bookmarks
"kogjlbfgggambihdjcpijgcbmenblimd", // Custom bookmarks
"ogbkmlkceflgpilgbmbcfbifckpkfacf", // Custom bookmarks
"pbbbjjecobhljkkcenlakfnkmkfkfamd", // Custom bookmarks
"jkbfjmnjcdmhlfpephomoiipbhcoiffb", // Custom bookmarks
"dgmblbpgafgcgpkoiilhjifindhinmai", // Custom bookmarks
"iggnealjakkgfofealilhkkclnbnfnmo", // Custom bookmarks
"lplkobnahgbopmpkdapaihnnojkphahc", // Custom bookmarks
"lejnflfhjpcannpaghnahbedlabpmhoh", // Custom bookmarks
"dhjmfhojkfjmfbnbnpichdmcdghdpccg", // Cut the Rope demo
"ebkhfdfghngbimnpgelagnfacdafhaba", // Deezer demo
"npnjdccdffhdndcbeappiamcehbhjibf", // Docs.app demo
"ekgadegabdkcbkodfbgidncffijbghhl", // Duolingo demo
"iddohohhpmajlkbejjjcfednjnhlnenk", // Evernote demo
"bjdhhokmhgelphffoafoejjmlfblpdha", // Gmail demo
"mdhnphfgagkpdhndljccoackjjhghlif", // Google Drive demo
"dondgdlndnpianbklfnehgdhkickdjck", // Google Keep demo
"amfoiggnkefambnaaphodjdmdooiinna", // Google Play Movie and TV demo
"fgjnkhlabjcaajddbaenilcmpcidahll", // Google+ demo
"ifpkhncdnjfipfjlhfidljjffdgklanh", // Google+ Photos demo
"cgmlfbhkckbedohgdepgbkflommbfkep", // Hangouts.app demo
"edhhaiphkklkcfcbnlbpbiepchnkgkpn", // Helper.extension demo
"jckncghadoodfbbbmbpldacojkooophh", // Journal demo
"diehajhcjifpahdplfdkhiboknagmfii", // Kindle demo
"idneggepppginmaklfbaniklagjghpio", // Kingsroad demo
"nhpmmldpbfjofkipjaieeomhnmcgihfm", // Menu.app demo
"kcjbmmhccecjokfmckhddpmghepcnidb", // Mint demo
"onbhgdmifjebcabplolilidlpgeknifi", // Music.app demo
"kkkbcoabfhgekpnddfkaphobhinociem", // Netflix demo
"adlphlfdhhjenpgimjochcpelbijkich", // New York Times demo
"cgefhjmlaifaamhhoojmpcnihlbddeki", // Pandora demo
"kpjjigggmcjinapdeipapdcnmnjealll", // Pixlr demo
"ifnadhpngkodeccijnalokiabanejfgm", // Pixsta demo
"klcojgagjmpgmffcildkgbfmfffncpcd", // Plex demo
"nnikmgjhdlphciaonjmoppfckbpoinnb", // Pocket demo
"khldngaiohpnnoikfmnmfnebecgeobep", // Polarr Photo demo
"aleodiobpjillgfjdkblghiiaegggmcm", // Quickoffice demo
"nifkmgcdokhkjghdlgflonppnefddien", // Sheets demo
"hdmobeajeoanbanmdlabnbnlopepchip", // Slides demo
"dgohlccohkojjgkkfholmobjjoledflp", // Spotify demo
"dhmdaeekeihmajjnmichlhiffffdbpde", // Store.app demo
"onklhlmbpfnmgmelakhgehkfdmkpmekd", // Todoist demo
"jeabmjjifhfcejonjjhccaeigpnnjaak", // TweetDeck demo
"pdckcbpciaaicoomipamcabpdadhofgh", // Weatherbug demo
"biliocemfcghhioihldfdmkkhnofcgmb", // Webcam Toy demo
"bhfoghflalnnjfcfkaelngenjgjjhapk", // Wevideo demo
"pjckdjlmdcofkkkocnmhcbehkiapalho", // Wunderlist demo
"pbdihpaifchmclcmkfdgffnnpfbobefh", // YouTube demo
// Testing extensions:
"ongnjlefhnoajpbodoldndkbkdgfomlp", // Show Managed Storage
};
} // namespace
DeviceLocalAccountManagementPolicyProvider::
DeviceLocalAccountManagementPolicyProvider(
policy::DeviceLocalAccount::Type account_type)
: account_type_(account_type) {
}
DeviceLocalAccountManagementPolicyProvider::
~DeviceLocalAccountManagementPolicyProvider() {
}
std::string DeviceLocalAccountManagementPolicyProvider::
GetDebugPolicyProviderName() const {
#if defined(NDEBUG)
NOTREACHED();
return std::string();
#else
return "whitelist for device-local accounts";
#endif
}
bool DeviceLocalAccountManagementPolicyProvider::UserMayLoad(
const extensions::Extension* extension,
base::string16* error) const {
if (account_type_ == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION) {
// Allow extension if it is an externally hosted component of Chrome.
if (extension->location() ==
extensions::Manifest::EXTERNAL_COMPONENT) {
return true;
}
// Allow extension if its type is whitelisted for use in public sessions.
if (extension->GetType() == extensions::Manifest::TYPE_HOSTED_APP)
return true;
// Allow extension if its specific ID is whitelisted for use in public
// sessions.
for (size_t i = 0; i < arraysize(kPublicSessionWhitelist); ++i) {
if (extension->id() == kPublicSessionWhitelist[i])
return true;
}
} else if (account_type_ == policy::DeviceLocalAccount::TYPE_KIOSK_APP) {
// For single-app kiosk sessions, allow only platform apps.
if (extension->GetType() == extensions::Manifest::TYPE_PLATFORM_APP)
return true;
}
// Disallow all other extensions.
if (error) {
*error = l10n_util::GetStringFUTF16(
IDS_EXTENSION_CANT_INSTALL_IN_DEVICE_LOCAL_ACCOUNT,
base::UTF8ToUTF16(extension->name()),
base::UTF8ToUTF16(extension->id()));
}
return false;
}
} // namespace chromeos
<commit_msg>Demo: Add new extension IDs of demo application to the public session white list.<commit_after>// Copyright 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 "chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.h"
#include <string>
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/grit/generated_resources.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest.h"
#include "ui/base/l10n/l10n_util.h"
namespace chromeos {
namespace {
// Apps/extensions explicitly whitelisted for use in public sessions.
const char* const kPublicSessionWhitelist[] = {
// Public sessions in general:
"cbkkbcmdlboombapidmoeolnmdacpkch", // Chrome RDP
"djflhoibgkdhkhhcedjiklpkjnoahfmg", // User Agent Switcher
"iabmpiboiopbgfabjmgeedhcmjenhbla", // VNC Viewer
"haiffjcadagjlijoggckpgfnoeiflnem", // Citrix Receiver
"mfaihdlpglflfgpfjcifdjdjcckigekc", // ARC Runtime
// Libraries:
"aclofikceldphonlfmghmimkodjdmhck", // Ancoris login component
"eilbnahdgoddoedakcmfkcgfoegeloil", // Ancoris proxy component
"ceehlgckkmkaoggdnjhibffkphfnphmg", // Libdata login
// Retail mode:
"bjfeaefhaooblkndnoabbkkkenknkemb", // 500 px demo
"ehcabepphndocfmgbdkbjibfodelmpbb", // Angry Birds demo
"kgimkbnclbekdkabkpjhpakhhalfanda", // Bejeweled demo
"joodangkbfjnajiiifokapkpmhfnpleo", // Calculator
"fpgfohogebplgnamlafljlcidjedbdeb", // Calendar demo
"hfhhnacclhffhdffklopdkcgdhifgngh", // Camera
"cdjikkcakjcdjemakobkmijmikhkegcj", // Chrome Remote Desktop demo
"jkoildpomkimndcphjpffmephmcmkfhn", // Chromebook Demo App
"lbhdhapagjhalobandnbdnmblnmocojh", // Crackle demo
"ielkookhdphmgbipcfmafkaiagademfp", // Custom bookmarks
"kogjlbfgggambihdjcpijgcbmenblimd", // Custom bookmarks
"ogbkmlkceflgpilgbmbcfbifckpkfacf", // Custom bookmarks
"pbbbjjecobhljkkcenlakfnkmkfkfamd", // Custom bookmarks
"jkbfjmnjcdmhlfpephomoiipbhcoiffb", // Custom bookmarks
"dgmblbpgafgcgpkoiilhjifindhinmai", // Custom bookmarks
"iggnealjakkgfofealilhkkclnbnfnmo", // Custom bookmarks
"lplkobnahgbopmpkdapaihnnojkphahc", // Custom bookmarks
"lejnflfhjpcannpaghnahbedlabpmhoh", // Custom bookmarks
"dhjmfhojkfjmfbnbnpichdmcdghdpccg", // Cut the Rope demo
"ebkhfdfghngbimnpgelagnfacdafhaba", // Deezer demo
"npnjdccdffhdndcbeappiamcehbhjibf", // Docs.app demo
"ekgadegabdkcbkodfbgidncffijbghhl", // Duolingo demo
"iddohohhpmajlkbejjjcfednjnhlnenk", // Evernote demo
"bjdhhokmhgelphffoafoejjmlfblpdha", // Gmail demo
"nldmakcnfaflagmohifhcihkfgcbmhph", // Gmail offline demo
"mdhnphfgagkpdhndljccoackjjhghlif", // Google Drive demo
"dondgdlndnpianbklfnehgdhkickdjck", // Google Keep demo
"amfoiggnkefambnaaphodjdmdooiinna", // Google Play Movie and TV demo
"fgjnkhlabjcaajddbaenilcmpcidahll", // Google+ demo
"ifpkhncdnjfipfjlhfidljjffdgklanh", // Google+ Photos demo
"cgmlfbhkckbedohgdepgbkflommbfkep", // Hangouts.app demo
"ndlgnmfmgpdecjgehbcejboifbbmlkhp", // Hash demo
"edhhaiphkklkcfcbnlbpbiepchnkgkpn", // Helper.extension demo
"jckncghadoodfbbbmbpldacojkooophh", // Journal demo
"diehajhcjifpahdplfdkhiboknagmfii", // Kindle demo
"idneggepppginmaklfbaniklagjghpio", // Kingsroad demo
"nhpmmldpbfjofkipjaieeomhnmcgihfm", // Menu.app demo
"kcjbmmhccecjokfmckhddpmghepcnidb", // Mint demo
"onbhgdmifjebcabplolilidlpgeknifi", // Music.app demo
"kkkbcoabfhgekpnddfkaphobhinociem", // Netflix demo
"adlphlfdhhjenpgimjochcpelbijkich", // New York Times demo
"cgefhjmlaifaamhhoojmpcnihlbddeki", // Pandora demo
"kpjjigggmcjinapdeipapdcnmnjealll", // Pixlr demo
"ifnadhpngkodeccijnalokiabanejfgm", // Pixsta demo
"klcojgagjmpgmffcildkgbfmfffncpcd", // Plex demo
"nnikmgjhdlphciaonjmoppfckbpoinnb", // Pocket demo
"khldngaiohpnnoikfmnmfnebecgeobep", // Polarr Photo demo
"aleodiobpjillgfjdkblghiiaegggmcm", // Quickoffice demo
"nifkmgcdokhkjghdlgflonppnefddien", // Sheets demo
"hdmobeajeoanbanmdlabnbnlopepchip", // Slides demo
"ikmidginfdcbojdbmejkeakncgdbmonc", // Soundtrap demo
"dgohlccohkojjgkkfholmobjjoledflp", // Spotify demo
"dhmdaeekeihmajjnmichlhiffffdbpde", // Store.app demo
"onklhlmbpfnmgmelakhgehkfdmkpmekd", // Todoist demo
"jeabmjjifhfcejonjjhccaeigpnnjaak", // TweetDeck demo
"gnckahkflocidcgjbeheneogeflpjien", // Vine demo
"pdckcbpciaaicoomipamcabpdadhofgh", // Weatherbug demo
"biliocemfcghhioihldfdmkkhnofcgmb", // Webcam Toy demo
"bhfoghflalnnjfcfkaelngenjgjjhapk", // Wevideo demo
"pjckdjlmdcofkkkocnmhcbehkiapalho", // Wunderlist demo
"pbdihpaifchmclcmkfdgffnnpfbobefh", // YouTube demo
// Testing extensions:
"ongnjlefhnoajpbodoldndkbkdgfomlp", // Show Managed Storage
};
} // namespace
DeviceLocalAccountManagementPolicyProvider::
DeviceLocalAccountManagementPolicyProvider(
policy::DeviceLocalAccount::Type account_type)
: account_type_(account_type) {
}
DeviceLocalAccountManagementPolicyProvider::
~DeviceLocalAccountManagementPolicyProvider() {
}
std::string DeviceLocalAccountManagementPolicyProvider::
GetDebugPolicyProviderName() const {
#if defined(NDEBUG)
NOTREACHED();
return std::string();
#else
return "whitelist for device-local accounts";
#endif
}
bool DeviceLocalAccountManagementPolicyProvider::UserMayLoad(
const extensions::Extension* extension,
base::string16* error) const {
if (account_type_ == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION) {
// Allow extension if it is an externally hosted component of Chrome.
if (extension->location() ==
extensions::Manifest::EXTERNAL_COMPONENT) {
return true;
}
// Allow extension if its type is whitelisted for use in public sessions.
if (extension->GetType() == extensions::Manifest::TYPE_HOSTED_APP)
return true;
// Allow extension if its specific ID is whitelisted for use in public
// sessions.
for (size_t i = 0; i < arraysize(kPublicSessionWhitelist); ++i) {
if (extension->id() == kPublicSessionWhitelist[i])
return true;
}
} else if (account_type_ == policy::DeviceLocalAccount::TYPE_KIOSK_APP) {
// For single-app kiosk sessions, allow only platform apps.
if (extension->GetType() == extensions::Manifest::TYPE_PLATFORM_APP)
return true;
}
// Disallow all other extensions.
if (error) {
*error = l10n_util::GetStringFUTF16(
IDS_EXTENSION_CANT_INSTALL_IN_DEVICE_LOCAL_ACCOUNT,
base::UTF8ToUTF16(extension->name()),
base::UTF8ToUTF16(extension->id()));
}
return false;
}
} // namespace chromeos
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.