hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0e5f10d8203116b88b7dd32930174494ebcf9ca5 | 435 | cpp | C++ | src/runnables/checkqrcoderunnable.cpp | hdchieh/xmly-downloader-qt5 | 4c89b866368ba1fd82cf3ada52186751d2d1d85f | [
"MIT"
] | 299 | 2020-05-27T14:04:04.000Z | 2022-03-30T15:09:48.000Z | src/runnables/checkqrcoderunnable.cpp | hdchieh/xmly-downloader-qt5 | 4c89b866368ba1fd82cf3ada52186751d2d1d85f | [
"MIT"
] | 9 | 2020-07-15T06:34:12.000Z | 2020-10-10T01:40:53.000Z | src/runnables/checkqrcoderunnable.cpp | hdchieh/xmly-downloader-qt5 | 4c89b866368ba1fd82cf3ada52186751d2d1d85f | [
"MIT"
] | 103 | 2020-06-23T08:02:46.000Z | 2022-03-20T03:24:59.000Z | #include "checkqrcoderunnable.h"
#include <QThread>
CheckQRCodeRunnable::CheckQRCodeRunnable(const QString& qrID) : qrID_(qrID) {}
void CheckQRCodeRunnable::Stop() { stop_ = true; }
void CheckQRCodeRunnable::run() {
while (!stop_) {
char* cookie =
CgoCheckQRCode(const_cast<char*>(qrID_.toStdString().c_str()));
if (cookie && !stop_) {
emit Succeed(cookie);
return;
}
QThread::sleep(1);
}
}
| 21.75 | 78 | 0.652874 | hdchieh |
0e5f7b7d8d00e7aab2599026cfcb427fe4e75e83 | 8,428 | cpp | C++ | utils/SamToCmpH5.cpp | mchaisso/mcpbblasr | 6c92959ba61adfd234a4f35849490709284105de | [
"BSD-3-Clause-Clear"
] | null | null | null | utils/SamToCmpH5.cpp | mchaisso/mcpbblasr | 6c92959ba61adfd234a4f35849490709284105de | [
"BSD-3-Clause-Clear"
] | null | null | null | utils/SamToCmpH5.cpp | mchaisso/mcpbblasr | 6c92959ba61adfd234a4f35849490709284105de | [
"BSD-3-Clause-Clear"
] | null | null | null | #include <iostream>
#include <datastructures/alignment/AlignmentCandidate.hpp>
#include <sam/SAMReader.hpp>
#include <format/StickAlignmentPrinter.hpp>
#include <HDFCmpFile.hpp>
#include <FASTASequence.hpp>
#include <FASTAReader.hpp>
#include <CommandLineParser.hpp>
#include <datastructures/alignmentset/AlignmentSetToCmpH5Adapter.hpp>
#include <datastructures/alignment/SAMToAlignmentCandidateAdapter.hpp>
#include <ChangeListID.hpp>
#include <utils/TimeUtils.hpp>
char VERSION[] = "v1.0.0";
char PERFORCE_VERSION_STRING[] = "$Change: 141782 $";
int main(int argc, char* argv[]) {
std::string program = "samtoh5";
std::string versionString = VERSION;
AppendPerforceChangelist(PERFORCE_VERSION_STRING, versionString);
std::string samFileName, cmpFileName, refFileName;
bool parseSmrtTitle = false;
bool useShortRefName = false;
bool copyQVs = false;
CommandLineParser clp;
std::string readType = "standard";
int verbosity = 0;
clp.SetProgramName(program);
clp.SetProgramSummary("Converts in.sam file to out.cmp.h5 file.");
clp.SetVersion(versionString);
clp.RegisterStringOption("in.sam", &samFileName,
"Input SAM file.", true);
clp.RegisterStringOption("reference.fasta", &refFileName,
"Reference used to generate reads.", true);
clp.RegisterStringOption("out.cmp.h5", &cmpFileName,
"Output cmp.h5 file.", true);
clp.RegisterPreviousFlagsAsHidden();
clp.RegisterFlagOption("smrtTitle", &parseSmrtTitle,
"Use this option when converting alignments "
"generated from reads produced by the "
"pls2fasta from bas.h5 files by parsing read "
"coordinates from the SMRT read title. The title "
"is in the format /name/hole/coordinates, where "
"coordinates are in the format \\d+_\\d+, and "
"represent the interval of the read that was "
"aligned.");
clp.RegisterStringOption("readType", &readType,
"Set the read type: 'standard', 'strobe', 'CCS', "
"or 'cDNA'");
clp.RegisterIntOption("verbosity", &verbosity,
"Set desired verbosity.",
CommandLineParser::PositiveInteger);
clp.RegisterFlagOption("useShortRefName", &useShortRefName,
"Use abbreviated reference names obtained "
"from file.sam instead of using full names "
"from reference.fasta.");
clp.RegisterFlagOption("copyQVs", ©QVs,
"Copy all QVs available in the SAM file into the "
"cmp.h5 file. This includes things like InsertionQV "
"and DeletionTag.");
std::string description = ("Because SAM has optional tags that have different "
"meanings in different programs, careful usage is required in order to "
"have proper output. The \"xs\" tag in bwa-sw is used to show the "
"suboptimal score, but in PacBio SAM (blasr) it is defined as the start "
"in the query sequence of the alignment.\nWhen \"-smrtTitle\" is "
"specified, the xs tag is ignored, but when it is not specified, the "
"coordinates given by the xs and xe tags are used to define the interval "
"of a read that is aligned. The CIGAR string is relative to this interval.");
clp.SetExamples(description);
clp.ParseCommandLine(argc, argv);
if (readType != "standard" and readType != "strobe" and
readType != "cDNA" and readType != "CCS") {
std::cout << "ERROR. Read type '" << readType
<< "' must be one of either 'standard', 'strobe', 'cDNA' or 'CCS'."
<< std::endl;
std::exit(EXIT_FAILURE);
}
std::cerr << "[INFO] " << GetTimestamp() << " [" << program << "] started." << std::endl;
SAMReader<SAMFullReferenceSequence, SAMReadGroup, SAMPosAlignment> samReader;
FASTAReader fastaReader;
HDFCmpFile<AlignmentCandidate<FASTASequence, FASTASequence> > cmpFile;
//
// Initialize input/output files.
//
samReader.Initialize(samFileName);
fastaReader.Initialize(refFileName);
cmpFile.Create(cmpFileName);
//
// Configure the file log.
//
std::string command;
CommandLineParser::CommandLineToString(argc, argv, command);
std::string log = "Convert sam to cmp.h5";
cmpFile.fileLogGroup.AddEntry(command, log, program, GetTimestamp(), versionString);
//
// Set the readType
//
cmpFile.SetReadType(readType);
//
// Read necessary input.
//
std::vector<FASTASequence> references;
fastaReader.ReadAllSequences(references);
//
// This should probably be handled by the alignmentSetAdapter, but
// time constraints...
//
AlignmentSet<SAMFullReferenceSequence, SAMReadGroup, SAMPosAlignment> alignmentSet;
samReader.ReadHeader(alignmentSet);
//
// The order of references in std::vector<FASTASequence> references and
// AlignmentSet<, , >alignmentSet.references can be different.
// Rearrange alignmentSet.references such that it is ordered in
// exactly the same way as std::vector<FASTASequence> references.
//
alignmentSet.RearrangeReferences(references);
//
// Always recompute the MD5 values even if they exist in the input
// sam file. Because MD5 is defined differently in sam and cmp.h5 files.
// The SAM convention uppercases and normalizes before computing the MD5.
// For cmp.h5, we compute the MD5 on the sequence 'as is'.
//
for(size_t i = 0; i < alignmentSet.references.size(); i++) {
MakeMD5((const char*)&references[i].seq[0],
(unsigned int)references[i].length, alignmentSet.references[i].md5);
}
//
// Map short names for references obtained from file.sam to full names obtained from reference.fasta
//
std::map<std::string, std::string> shortRefNameToFull;
std::map<std::string, std::string>::iterator it;
assert(references.size() == alignmentSet.references.size());
if (!useShortRefName) {
for (size_t i = 0; i < references.size(); i++) {
std::string shortRefName = alignmentSet.references[i].GetSequenceName();
std::string fullRefName(references[i].title);
if (shortRefNameToFull.find(shortRefName) != shortRefNameToFull.end()) {
std::cout << "ERROR, Found more than one reference " << shortRefName << "in sam header" << std::endl;
std::exit(EXIT_FAILURE);
}
shortRefNameToFull[shortRefName] = fullRefName;
alignmentSet.references[i].sequenceName = fullRefName;
}
}
//
// Start setting up the cmp.h5 file.
//
AlignmentSetToCmpH5Adapter<HDFCmpFile<AlignmentCandidate<FASTASequence, FASTASequence> > > alignmentSetAdapter;
alignmentSetAdapter.Initialize();
alignmentSetAdapter.StoreReferenceInfo(alignmentSet.references, cmpFile);
//
// Store the alignments.
//
SAMAlignment samAlignment;
while (samReader.GetNextAlignment(samAlignment)) {
if (samAlignment.rName == "*") {
continue;
}
if (!useShortRefName) {
//convert shortRefName to fullRefName
it = shortRefNameToFull.find(samAlignment.rName);
if (it == shortRefNameToFull.end()) {
std::cout << "ERROR, Could not find " << samAlignment.rName << " in the reference repository." << std::endl;
std::exit(EXIT_FAILURE);
}
samAlignment.rName = (*it).second;
}
std::vector<AlignmentCandidate<> > convertedAlignments;
if (verbosity > 0) {
std::cout << "Storing alignment for " << samAlignment.qName << std::endl;
}
SAMAlignmentsToCandidates(samAlignment,
// Order of references and alignmentSetAdapter.RefInfoGroup
// should be exactly the same.
references, alignmentSetAdapter.refNameToRefInfoIndex,
convertedAlignments, parseSmrtTitle, false,
copyQVs);
// -1: moleculeID will be computed dynamically.
// o.w., the value will be assigned as moleculeID.
alignmentSetAdapter.StoreAlignmentCandidateList(convertedAlignments, cmpFile, -1, copyQVs);
for (size_t a = 0; a < convertedAlignments.size(); a++) {
convertedAlignments[a].FreeSubsequences();
}
}
std::cerr << "[INFO] " << GetTimestamp() << " [" << program << "] ended." << std::endl;
return 0;
}
| 40.325359 | 120 | 0.657333 | mchaisso |
0e62f93dab4109f30f98794df0e24309fb221133 | 16,246 | cpp | C++ | src/blinkit/blink/renderer/core/events/EventPath.cpp | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | 13 | 2020-04-21T13:14:00.000Z | 2021-11-13T14:55:12.000Z | src/blinkit/blink/renderer/core/events/EventPath.cpp | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | null | null | null | src/blinkit/blink/renderer/core/events/EventPath.cpp | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | 4 | 2020-04-21T13:15:43.000Z | 2021-11-13T14:55:00.000Z | // -------------------------------------------------
// BlinKit - BlinKit Library
// -------------------------------------------------
// File Name: EventPath.cpp
// Description: EventPath Class
// Author: Ziming Li
// Created: 2021-07-23
// -------------------------------------------------
// Copyright (C) 2021 MingYang Software Technology.
// -------------------------------------------------
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "core/events/EventPath.h"
#include "core/EventNames.h"
#include "core/dom/Document.h"
#if 0 // BKTODO:
#include "core/dom/Touch.h"
#include "core/dom/TouchList.h"
#endif
#include "core/dom/shadow/InsertionPoint.h"
#include "core/dom/shadow/ShadowRoot.h"
#if 0 // BKTODO:
#include "core/events/TouchEvent.h"
#include "core/events/TouchEventContext.h"
#else
#include "core/events/Event.h"
#endif
using namespace BlinKit;
namespace blink {
EventTarget* EventPath::eventTargetRespectingTargetRules(Node& referenceNode)
{
if (referenceNode.isPseudoElement()) {
ASSERT(referenceNode.parentNode());
return referenceNode.parentNode();
}
return &referenceNode;
}
static inline bool shouldStopAtShadowRoot(Event& event, ShadowRoot& shadowRoot, EventTarget& target)
{
// WebKit never allowed selectstart event to cross the the shadow DOM boundary.
// Changing this breaks existing sites.
// See https://bugs.webkit.org/show_bug.cgi?id=52195 for details.
const AtomicString eventType = event.type();
return target.toNode() && target.toNode()->shadowHost() == shadowRoot.host()
&& (eventType == EventTypeNames::abort
|| eventType == EventTypeNames::change
|| eventType == EventTypeNames::error
|| eventType == EventTypeNames::load
|| eventType == EventTypeNames::reset
|| eventType == EventTypeNames::resize
|| eventType == EventTypeNames::scroll
|| eventType == EventTypeNames::select
|| eventType == EventTypeNames::selectstart);
}
EventPath::EventPath(Node& node, Event* event)
: m_node(&node)
, m_event(event)
{
initialize();
}
void EventPath::initializeWith(Node& node, Event* event)
{
m_node = &node;
m_event = event;
m_windowEventContext = nullptr;
m_nodeEventContexts.clear();
m_treeScopeEventContexts.clear();
initialize();
}
static inline bool eventPathShouldBeEmptyFor(Node& node)
{
return node.isPseudoElement() && !node.parentElement();
}
void EventPath::initialize()
{
if (eventPathShouldBeEmptyFor(*m_node))
return;
calculatePath();
calculateAdjustedTargets();
calculateTreeOrderAndSetNearestAncestorClosedTree();
}
void EventPath::calculatePath()
{
ASSERT(m_node);
ASSERT(m_nodeEventContexts.empty());
m_node->updateDistribution();
// For performance and memory usage reasons we want to store the
// path using as few bytes as possible and with as few allocations
// as possible which is why we gather the data on the stack before
// storing it in a perfectly sized m_nodeEventContexts Vector.
std::vector<Node *> nodesInPath;
Node* current = m_node.get();
nodesInPath.emplace_back(current);
while (current) {
if (m_event && current->keepEventInNode(m_event))
break;
WillBeHeapVector<RawPtrWillBeMember<InsertionPoint>, 8> insertionPoints;
collectDestinationInsertionPoints(*current, insertionPoints);
if (!insertionPoints.isEmpty()) {
for (const auto& insertionPoint : insertionPoints) {
if (insertionPoint->isShadowInsertionPoint()) {
ShadowRoot* containingShadowRoot = insertionPoint->containingShadowRoot();
ASSERT(containingShadowRoot);
if (!containingShadowRoot->isOldest())
nodesInPath.emplace_back(containingShadowRoot->olderShadowRoot());
}
nodesInPath.emplace_back(insertionPoint);
}
current = insertionPoints.last();
continue;
}
if (current->isShadowRoot()) {
if (m_event && shouldStopAtShadowRoot(*m_event, *toShadowRoot(current), *m_node))
break;
current = current->shadowHost();
#if !ENABLE(OILPAN)
// TODO(kochi): crbug.com/507413 This check is necessary when some asynchronous event
// is queued while its shadow host is removed and the shadow root gets the event
// immediately after it. When Oilpan is enabled, this situation does not happen.
// Except this case, shadow root's host is assumed to be non-null.
if (current)
nodesInPath.append(current);
#else
nodesInPath.emplace_back(current);
#endif
} else {
current = current->parentNode();
if (current)
nodesInPath.emplace_back(current);
}
}
m_nodeEventContexts.reserve(nodesInPath.size());
for (Node* nodeInPath : nodesInPath) {
m_nodeEventContexts.emplace_back(NodeEventContext(nodeInPath, eventTargetRespectingTargetRules(*nodeInPath)));
}
}
void EventPath::calculateTreeOrderAndSetNearestAncestorClosedTree()
{
// Precondition:
// - TreeScopes in m_treeScopeEventContexts must be *connected* in the same tree of trees.
// - The root tree must be included.
std::unordered_map<Member<const TreeScope>, Member<TreeScopeEventContext>> treeScopeEventContextMap;
for (const auto& treeScopeEventContext : m_treeScopeEventContexts)
treeScopeEventContextMap.emplace(&treeScopeEventContext->treeScope(), treeScopeEventContext.get());
TreeScopeEventContext* rootTree = nullptr;
for (const auto& treeScopeEventContext : m_treeScopeEventContexts) {
// Use olderShadowRootOrParentTreeScope here for parent-child relationships.
// See the definition of trees of trees in the Shadow DOM spec:
// http://w3c.github.io/webcomponents/spec/shadow/
TreeScope* parent = treeScopeEventContext.get()->treeScope().olderShadowRootOrParentTreeScope();
if (!parent) {
ASSERT(!rootTree);
rootTree = treeScopeEventContext.get();
continue;
}
ASSERT(treeScopeEventContextMap.find(parent) != treeScopeEventContextMap.end());
treeScopeEventContextMap[parent]->addChild(*treeScopeEventContext.get());
}
ASSERT(rootTree);
rootTree->calculateTreeOrderAndSetNearestAncestorClosedTree(0, nullptr);
}
TreeScopeEventContext* EventPath::ensureTreeScopeEventContext(Node* currentTarget, TreeScope* treeScope, TreeScopeEventContextMap& treeScopeEventContextMap)
{
if (!treeScope)
return nullptr;
TreeScopeEventContext* treeScopeEventContext;
bool isNewEntry;
{
GCRefPtr<TreeScopeEventContext> &entry = treeScopeEventContextMap[treeScope];
if (!entry)
{
isNewEntry = true;
entry = TreeScopeEventContext::create(*treeScope);
}
else
{
isNewEntry = false;
}
treeScopeEventContext = entry.get();
}
if (isNewEntry) {
TreeScopeEventContext* parentTreeScopeEventContext = ensureTreeScopeEventContext(0, treeScope->olderShadowRootOrParentTreeScope(), treeScopeEventContextMap);
if (parentTreeScopeEventContext && parentTreeScopeEventContext->target()) {
treeScopeEventContext->setTarget(parentTreeScopeEventContext->target());
} else if (currentTarget) {
treeScopeEventContext->setTarget(eventTargetRespectingTargetRules(*currentTarget));
}
} else if (!treeScopeEventContext->target() && currentTarget) {
treeScopeEventContext->setTarget(eventTargetRespectingTargetRules(*currentTarget));
}
return treeScopeEventContext;
}
void EventPath::calculateAdjustedTargets()
{
const TreeScope* lastTreeScope = nullptr;
TreeScopeEventContextMap treeScopeEventContextMap;
TreeScopeEventContext* lastTreeScopeEventContext = nullptr;
for (size_t i = 0; i < size(); ++i) {
Node* currentNode = at(i).node();
TreeScope& currentTreeScope = currentNode->treeScope();
if (lastTreeScope != ¤tTreeScope) {
lastTreeScopeEventContext = ensureTreeScopeEventContext(currentNode, ¤tTreeScope, treeScopeEventContextMap);
}
ASSERT(lastTreeScopeEventContext);
at(i).setTreeScopeEventContext(lastTreeScopeEventContext);
lastTreeScope = ¤tTreeScope;
}
for (const auto &it : treeScopeEventContextMap)
m_treeScopeEventContexts.emplace_back(it.second);
}
void EventPath::buildRelatedNodeMap(const Node& relatedNode, RelatedTargetMap& relatedTargetMap)
{
std::unique_ptr<EventPath> relatedTargetEventPath = std::make_unique<EventPath>(const_cast<Node&>(relatedNode));
for (size_t i = 0; i < relatedTargetEventPath->m_treeScopeEventContexts.size(); ++i) {
TreeScopeEventContext* treeScopeEventContext = relatedTargetEventPath->m_treeScopeEventContexts[i].get();
relatedTargetMap.emplace(&treeScopeEventContext->treeScope(), treeScopeEventContext->target());
}
#if ENABLE(OILPAN)
// Oilpan: It is important to explicitly clear the vectors to reuse
// the memory in subsequent event dispatchings.
relatedTargetEventPath->clear();
#endif
}
EventTarget* EventPath::findRelatedNode(TreeScope& scope, RelatedTargetMap& relatedTargetMap)
{
WillBeHeapVector<RawPtrWillBeMember<TreeScope>, 32> parentTreeScopes;
EventTarget* relatedNode = nullptr;
for (TreeScope* current = &scope; current; current = current->olderShadowRootOrParentTreeScope()) {
parentTreeScopes.append(current);
RelatedTargetMap::const_iterator iter = relatedTargetMap.find(current);
if (iter != relatedTargetMap.end() && iter->second) {
relatedNode = iter->second;
break;
}
}
ASSERT(relatedNode);
for (const auto& entry : parentTreeScopes)
relatedTargetMap.emplace(entry, relatedNode);
return relatedNode;
}
void EventPath::adjustForRelatedTarget(Node& target, EventTarget* relatedTarget)
{
if (!relatedTarget)
return;
Node* relatedNode = relatedTarget->toNode();
if (!relatedNode)
return;
if (target.document() != relatedNode->document())
return;
if (!target.inDocument() || !relatedNode->inDocument())
return;
RelatedTargetMap relatedNodeMap;
buildRelatedNodeMap(*relatedNode, relatedNodeMap);
for (const auto& treeScopeEventContext : m_treeScopeEventContexts) {
EventTarget* adjustedRelatedTarget = findRelatedNode(treeScopeEventContext->treeScope(), relatedNodeMap);
ASSERT(adjustedRelatedTarget);
treeScopeEventContext.get()->setRelatedTarget(adjustedRelatedTarget);
}
shrinkIfNeeded(target, *relatedTarget);
}
void EventPath::shrinkIfNeeded(const Node& target, const EventTarget& relatedTarget)
{
// Synthetic mouse events can have a relatedTarget which is identical to the target.
bool targetIsIdenticalToToRelatedTarget = (&target == &relatedTarget);
for (size_t i = 0; i < size(); ++i) {
if (targetIsIdenticalToToRelatedTarget) {
if (target.treeScope().rootNode() == at(i).node()) {
shrink(i + 1);
break;
}
} else if (at(i).target() == at(i).relatedTarget()) {
// Event dispatching should be stopped here.
shrink(i);
break;
}
}
}
void EventPath::adjustForTouchEvent(TouchEvent& touchEvent)
{
ASSERT(false); // BKTODO:
#if 0
WillBeHeapVector<RawPtrWillBeMember<TouchList>> adjustedTouches;
WillBeHeapVector<RawPtrWillBeMember<TouchList>> adjustedTargetTouches;
WillBeHeapVector<RawPtrWillBeMember<TouchList>> adjustedChangedTouches;
WillBeHeapVector<RawPtrWillBeMember<TreeScope>> treeScopes;
for (const auto& treeScopeEventContext : m_treeScopeEventContexts) {
TouchEventContext* touchEventContext = treeScopeEventContext->ensureTouchEventContext();
adjustedTouches.append(&touchEventContext->touches());
adjustedTargetTouches.append(&touchEventContext->targetTouches());
adjustedChangedTouches.append(&touchEventContext->changedTouches());
treeScopes.append(&treeScopeEventContext->treeScope());
}
adjustTouchList(touchEvent.touches(), adjustedTouches, treeScopes);
adjustTouchList(touchEvent.targetTouches(), adjustedTargetTouches, treeScopes);
adjustTouchList(touchEvent.changedTouches(), adjustedChangedTouches, treeScopes);
#if ENABLE(ASSERT)
for (const auto& treeScopeEventContext : m_treeScopeEventContexts) {
TreeScope& treeScope = treeScopeEventContext->treeScope();
TouchEventContext* touchEventContext = treeScopeEventContext->touchEventContext();
checkReachability(treeScope, touchEventContext->touches());
checkReachability(treeScope, touchEventContext->targetTouches());
checkReachability(treeScope, touchEventContext->changedTouches());
}
#endif
#endif
}
void EventPath::adjustTouchList(const TouchList* touchList, WillBeHeapVector<RawPtrWillBeMember<TouchList>> adjustedTouchList, const WillBeHeapVector<RawPtrWillBeMember<TreeScope>>& treeScopes)
{
if (!touchList)
return;
ASSERT(false); // BKTODO:
#if 0
for (size_t i = 0; i < touchList->length(); ++i) {
const Touch& touch = *touchList->item(i);
if (!touch.target())
continue;
Node* targetNode = touch.target()->toNode();
if (!targetNode)
continue;
RelatedTargetMap relatedNodeMap;
buildRelatedNodeMap(*targetNode, relatedNodeMap);
for (size_t j = 0; j < treeScopes.size(); ++j) {
adjustedTouchList[j]->append(touch.cloneWithNewTarget(findRelatedNode(*treeScopes[j], relatedNodeMap)));
}
}
#endif
}
const NodeEventContext& EventPath::topNodeEventContext()
{
ASSERT(!isEmpty());
return last();
}
void EventPath::ensureWindowEventContext()
{
ASSERT(m_event);
if (!m_windowEventContext)
m_windowEventContext = std::make_unique<WindowEventContext>(*m_event, topNodeEventContext());
}
#if ENABLE(ASSERT)
void EventPath::checkReachability(TreeScope& treeScope, TouchList& touchList)
{
ASSERT(false); // BKTODO:
#if 0
for (size_t i = 0; i < touchList.length(); ++i)
ASSERT(touchList.item(i)->target()->toNode()->treeScope().isInclusiveOlderSiblingShadowRootOrAncestorTreeScopeOf(treeScope));
#endif
}
#endif
DEFINE_TRACE(EventPath)
{
#if ENABLE(OILPAN)
visitor->trace(m_nodeEventContexts);
visitor->trace(m_node);
// BKTODO: visitor->trace(m_event);
visitor->trace(m_treeScopeEventContexts);
// BKTODO: visitor->trace(m_windowEventContext);
#endif
}
} // namespace
| 38.225882 | 193 | 0.688354 | titilima |
0e6451eb917b212f9f874f509a3d3a83d3479cca | 1,742 | cpp | C++ | ShooterMini/ShooterMini/main.cpp | Floneyyang/ShooterGame | 6cc6fdb52ac75a7fce08d0aa1cd997c55e2ac6d3 | [
"MIT"
] | null | null | null | ShooterMini/ShooterMini/main.cpp | Floneyyang/ShooterGame | 6cc6fdb52ac75a7fce08d0aa1cd997c55e2ac6d3 | [
"MIT"
] | null | null | null | ShooterMini/ShooterMini/main.cpp | Floneyyang/ShooterGame | 6cc6fdb52ac75a7fce08d0aa1cd997c55e2ac6d3 | [
"MIT"
] | null | null | null |
//
// Disclaimer:
// ----------
//
// This code will work only if you selected window, graphics and audio.
//
// Note that the "Run Script" build phase will copy the required frameworks
// or dylibs to your application bundle so you can execute it on any OS X
// computer.
//
// Your resource files (images, sounds, fonts, ...) are also copied to your
// application bundle. To get the path to these resources, use the helper
// function `resourcePath()` from ResourcePath.hpp
//
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
// Here is a small helper for you! Have a look.
#include "ResourcePath.hpp"
#include "Game.hpp"
using namespace sf;
static const int screenWidth = 1600;
static const int screenHeight = 1200;
int main(int, char const**)
{
// Create the main window
sf::RenderWindow window(sf::VideoMode(screenWidth, screenHeight), "Shooter Game By Floney");
Game game(&window);
game.Start(screenWidth,screenHeight);
// Start the game loop
while (window.isOpen())
{
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window: exit
if (event.type == sf::Event::Closed) {
window.close();
}
// Escape pressed: exit
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
window.close();
}
}
//Update
game.Update();
// Clear screen
window.clear(Color(100, 149, 237));
// Draw the sprite
//window.draw();
//Draw
game.Draw();
// Update the window
window.display();
}
return EXIT_SUCCESS;
}
| 23.863014 | 96 | 0.5907 | Floneyyang |
0e6595477a06ba4f121a822a0d2899cff24cf479 | 445 | cpp | C++ | tools/codegen/template/extendedimplol.cpp | tdzl2003/luaqt | 7ebebd39037b906e6fa8a485f94e963e345e107a | [
"BSD-3-Clause"
] | 20 | 2015-04-27T06:45:29.000Z | 2021-08-21T03:51:39.000Z | tools/codegen/template/extendedimplol.cpp | tdzl2003/luaqt | 7ebebd39037b906e6fa8a485f94e963e345e107a | [
"BSD-3-Clause"
] | null | null | null | tools/codegen/template/extendedimplol.cpp | tdzl2003/luaqt | 7ebebd39037b906e6fa8a485f94e963e345e107a | [
"BSD-3-Clause"
] | 8 | 2015-03-02T19:51:36.000Z | 2021-08-21T03:51:40.000Z | explicit /*%return class.classname%*/_Extended_Impl(const QMetaObject * _mo
/*%
local ret = {}
for i,v in ipairs(func.arguments) do
table.insert(ret, ",")
table.insert(ret, v.type.rawName)
table.insert(ret, "arg"..i)
end
return table.concat(ret, " ")
%*/)
: mo(_mo), /*%return class.classname%*/(/*%
local ret = {}
for i = 1, #func.arguments do
table.insert(ret, "arg"..i)
end
return table.concat(ret, ", ")
%*/)
{
}
| 22.25 | 77 | 0.611236 | tdzl2003 |
0e66384c8471c5eec40b1c55991f676444598bef | 8,512 | cxx | C++ | src/ControllerKit.cxx | broken-bytes/ControllerKit | 1045d304c613455f3564d7d225b8a6ed90c8a48a | [
"MIT"
] | null | null | null | src/ControllerKit.cxx | broken-bytes/ControllerKit | 1045d304c613455f3564d7d225b8a6ed90c8a48a | [
"MIT"
] | null | null | null | src/ControllerKit.cxx | broken-bytes/ControllerKit | 1045d304c613455f3564d7d225b8a6ed90c8a48a | [
"MIT"
] | 1 | 2020-12-03T09:55:03.000Z | 2020-12-03T09:55:03.000Z | #include <array>
#include <utility>
#include "ControllerKit.hxx"
#include <minwindef.h>
#include <DualSense.hxx>
#include <Controller.hxx>
#include <DualShock4.hxx>
#ifdef _W10
#include <GamingInputController.hxx>
#else
#include <XInputController.hxx>
#endif
#include <GamingInputController.hxx>
#include <interfaces/IAdaptiveTriggerController.hxx>
#include <interfaces/IGyroscopeController.hxx>
#include <interfaces/IImpulseTriggerController.hxx>
#include <interfaces/ITouchpadController.hxx>
#include "Controller.hxx"
#include "Interface.hxx"
#include "USB.hxx"
#include <Types.h>
using namespace BrokenBytes::ControllerKit;
using namespace Types;
namespace BrokenBytes::ControllerKit {
Controller::Controller(uint8_t player, ControllerKitControllerType type) {
_player = player;
_type = type;
}
[[nodiscard]] auto Controller::Player() const ->uint8_t {
return _player;
}
[[nodiscard]] auto Controller::Type() const ->ControllerKitControllerType {
return _type;
}
[[nodiscard]] auto Controller::HasFeature(
uint8_t controller,
ControllerKitFeature feature
) const -> bool {
auto raw = Interface::GetControllers()[_player];
switch (feature) {
case ControllerKitFeature::Rumble:
return true;
break;
case ControllerKitFeature::Gyroscope:
if (dynamic_cast<Internal::IGyroscopeController*>(raw)) {
return true;
}
break;
case ControllerKitFeature::Lightbar:
if (dynamic_cast<Internal::ILightbarController*>(raw)) {
return true;
}
break;
case ControllerKitFeature::AdaptiveTriggers:
if (dynamic_cast<Internal::IAdaptiveTriggerController*>(raw)) {
return true;
}
break;
case ControllerKitFeature::ImpulseTriggers:
if (dynamic_cast<Internal::IImpulseTriggerController*>(raw)) {
return true;
}
break;
case ControllerKitFeature::Touchpad:
if (dynamic_cast<Internal::ITouchpadController*>(raw)) {
return true;
}
break;
default:
break;
}
return false;
}
[[nodiscard]] auto Controller::GetButtonState(
ControllerKitButton button
) const -> ControllerKitButtonState {
return Interface::GetControllers()[_player]->GetButtonState(button);
}
[[nodiscard]] auto Controller::GetAxis(
ControllerKitAxis axis
) const -> float {
switch (axis) {
case ControllerKitAxis::LeftX:
return Interface::GetControllers()[_player]->GetStick(0).X;
case ControllerKitAxis::LeftY:
return Interface::GetControllers()[_player]->GetStick(0).Y;
case ControllerKitAxis::RightX:
return Interface::GetControllers()[_player]->GetStick(1).X;
case ControllerKitAxis::RightY:
return Interface::GetControllers()[_player]->GetStick(1).Y;
case ControllerKitAxis::LeftTrigger:
return Interface::GetControllers()[_player]->GetTrigger(TriggerLeft);
case ControllerKitAxis::RightTrigger:
return Interface::GetControllers()[_player]->GetTrigger(TriggerRight);
}
return 0;
}
auto Controller::SetTriggerDisabled(ControllerKitTrigger trigger) -> void {
auto* raw = Interface::GetControllers()[Player()];
Internal::IAdaptiveTriggerController::Params params{
0xFF,
0xFF,
0xFF,
{
0xFF,
0xFF,
0xFF
},
false,
0xFF
};
if (Type() == ControllerDualSense) {
dynamic_cast<Internal::DualSense*>(raw)->SetTrigger(
trigger,
ControllerKitAdaptiveTriggerMode::Disabled,
params
);
}
}
auto Controller::SetTriggerContinuous(ControllerKitTrigger trigger, float start, float force) const -> void {
auto* raw = Interface::GetControllers()[Player()];
Internal::IAdaptiveTriggerController::Params params{};
params.ForceOrEnd = Math::ConvertToUnsignedShort(force);
params.Start = Math::ConvertToUnsignedShort(start);
if (Type() == ControllerDualSense) {
dynamic_cast<Internal::DualSense*>(raw)->SetTrigger(
trigger,
ControllerKitAdaptiveTriggerMode::Continuous,
params
);
}
}
auto Controller::SetTriggerSectional(ControllerKitTrigger trigger, float start, float end, float force) const -> void {
auto* raw = Interface::GetControllers()[Player()];
Internal::IAdaptiveTriggerController::Params params{};
params.ForceOrEnd = Math::ConvertToUnsignedShort(end);
params.Start = Math::ConvertToUnsignedShort(start);
params.ForceInRange = Math::ConvertToUnsignedShort(force);
if (Type() == ControllerDualSense) {
dynamic_cast<Internal::DualSense*>(raw)->SetTrigger(
trigger,
ControllerKitAdaptiveTriggerMode::Sectional,
params
);
}
}
auto Controller::SetTriggerAdvanced(ControllerKitTrigger trigger, float extension, float strengthReleased, float strengthMiddle, float strengthPressed, float frequency, bool pauseOnPressed) const -> void {
auto* raw = Interface::GetControllers()[Player()];
Internal::IAdaptiveTriggerController::Params params{};
params.ForceOrEnd = (pauseOnPressed) ? 0x00 : 0x02;
params.Start = Math::ConvertToUnsignedShort(extension);
params.ForceInRange = 0x00;
params.Strength = {
Math::ConvertToUnsignedShort(strengthReleased),
Math::ConvertToUnsignedShort(strengthMiddle),
Math::ConvertToUnsignedShort(strengthPressed)
};
params.Frequency = Math::ConvertToUnsignedShort(frequency);
if (Type() == ControllerDualSense) {
dynamic_cast<Internal::DualSense*>(raw)->SetTrigger(
trigger,
ControllerKitAdaptiveTriggerMode::Advanced,
params
);
}
}
auto Controller::SetLightbarColor(ControllerKitColor color) const -> void {
auto raw = Interface::GetControllers()[Player()];
if (Type() == ControllerDualSense) {
dynamic_cast<Internal::DualSense*>(raw)->SetLightbarColor(color);
}
if (Type() == ControllerDualShock4) {
dynamic_cast<Internal::DualShock4*>(raw)->SetLightbarColor(color);
}
}
[[nodiscard]] auto Controller::GetTouches() const -> std::vector<ControllerKitTouch> {
auto* c = dynamic_cast<Internal::ITouchpadController*>(
Interface::GetControllers()[Player()]
);
auto touches = c->GetTouches();
return {
{ touches[0].X, touches[0].Y, 0 },
{ touches[1].X, touches[1].Y, 1 }
};
}
[[nodiscard]] auto Controller::GetGyroscope(
ControllerKitButton button
) const -> ControllerKitGyroscope {
auto* c = dynamic_cast<Internal::IGyroscopeController*>(
Interface::GetControllers()[Player()]
);
auto gyro = c->ReadGyroscope();
return { gyro.X, gyro.Y, gyro.Z };
}
[[nodiscard]] auto Controller::GetAcceleration(
ControllerKitButton button
) const ->ControllerKitGyroscope {
auto* c = dynamic_cast<Internal::IGyroscopeController*>(
Interface::GetControllers()[Player()]
);
auto gyro = c->ReadGyroscope();
return { gyro.X, gyro.Y, gyro.Z };
}
auto Controller::SetImpulseTrigger(ControllerKitRumble trigger, float strength) -> void {
auto raw = Interface::GetControllers()[Player()];
if (Type() == ControllerXBoxOne ||
Type() == ControllerXBoxSeries
) {
auto motor = (trigger == RumbleTriggerLeft) ?
RumbleTriggerLeft :
RumbleTriggerRight;
reinterpret_cast<Internal::GamingInputController*>(raw)->SetRumble(
motor,
Math::ConvertToUnsignedShort(strength)
);
}
}
void Init() {
Interface::Init();
}
auto Controllers() -> std::vector<Controller> {
std::vector<Controller> list;
auto controllers = Interface::GetControllers();
for (auto item : controllers) {
list.emplace_back(Controller{ item.first, item.second->Type() });
}
return list;
}
auto GetControllerType(int controller) ->ControllerKitControllerType {
return Interface::GetControllers()[controller]->Type();
}
auto Flush() -> void {
Interface::Flush();
}
auto Next() -> void {
Interface::Next();
}
auto OnControllerConnected(std::function<void(uint8_t id, ControllerKitControllerType type)> controller) -> void {
Interface::OnControllerConnected(std::move(controller));
}
auto OnControllerDisconnected(std::function<void(uint8_t id)> controller) -> void {
Interface::OnControllerDisconnected(std::move(controller));
}
}
#ifdef _WIN32
#ifdef _LIB_DYNAMIC
BOOL WINAPI DllMain(
HINSTANCE hinstDLL, // handle to DLL module
DWORD fdwReason, // reason for calling function
LPVOID lpReserved) // reserved
{
// Perform actions based on the reason for calling.
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
Init();
break;
case DLL_THREAD_ATTACH:
// Do thread-specific initialization.
break;
case DLL_THREAD_DETACH:
// Do thread-specific cleanup.
break;
case DLL_PROCESS_DETACH:
// Perform any necessary cleanup.
break;
}
return TRUE; // Successful DLL_PROCESS_ATTACH.
}
#endif
#endif | 28.27907 | 206 | 0.724977 | broken-bytes |
0e66f00dd3c3ab264beb9df5bf49f8bd7f83bb54 | 529 | cpp | C++ | Tree/countLeavesInBinaryTree.cpp | harshallgarg/Diversified-Programming | 7e6fb135c4639dbaa0651b85f98397f994a5b11d | [
"MIT"
] | 2 | 2020-08-09T02:09:50.000Z | 2020-08-09T07:07:47.000Z | Tree/countLeavesInBinaryTree.cpp | harshallgarg/Diversified-Programming | 7e6fb135c4639dbaa0651b85f98397f994a5b11d | [
"MIT"
] | null | null | null | Tree/countLeavesInBinaryTree.cpp | harshallgarg/Diversified-Programming | 7e6fb135c4639dbaa0651b85f98397f994a5b11d | [
"MIT"
] | 5 | 2020-09-21T12:49:07.000Z | 2020-09-29T16:13:09.000Z | //
// Created by Anish Mookherjee on 28/05/20.
//
/* A binary tree node has data, pointer to left child
and a pointer to right child
struct Node
{
int data;
Node* left;
Node* right;
}; */
/* Should return count of leaves. For example, return
value should be 2 for following tree.
10
/ \
20 30 */
int countLeaves(Node* root)
{
if(root==NULL)
return 0;
if(!root->left&&!root->right)
return 1;
return countLeaves(root->left)+countLeaves(root->right);
}
| 18.892857 | 60 | 0.597353 | harshallgarg |
0e6d63f0bb2a3549d5ba99ec208186a4bdec9d96 | 21,535 | cpp | C++ | MILP_Multiview/src/OptimalHorizontalScenario.cpp | xmar/MultiViewpoint360_MMSys18 | 59a9bd17b86b9b287690e059fe43517839add55e | [
"MIT"
] | 8 | 2018-07-02T16:14:07.000Z | 2021-06-29T12:20:11.000Z | MILP_Multiview/src/OptimalHorizontalScenario.cpp | xmar/MultiViewpoint360_MMSys18 | 59a9bd17b86b9b287690e059fe43517839add55e | [
"MIT"
] | 2 | 2019-02-06T19:16:49.000Z | 2021-03-01T15:41:58.000Z | MILP_Multiview/src/OptimalHorizontalScenario.cpp | xmar/MultiViewpoint360_MMSys18 | 59a9bd17b86b9b287690e059fe43517839add55e | [
"MIT"
] | 3 | 2018-04-12T08:05:02.000Z | 2022-01-21T12:09:13.000Z | #include "OptimalHorizontalScenario.hpp"
#include <ilcplex/ilocplex.h>
#include <cmath>
using namespace IMT;
#include <iostream>
void OptimalHorizontalScenario::SetSelectAndDownloadedConstraint(int k, int u, int b)
{
for (int chunkId = 0; chunkId < GetNbProcessedChunk(); ++chunkId)
{
for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
{
for (int tileId = 0; tileId < GetNbTile(); ++tileId)
{
for (int qualityLevel = 0; qualityLevel < GetNbQuality(); ++qualityLevel)
{
IloExpr sum1d(m_env);
for (int chunkLagId = -GetNbLagChunk(); chunkLagId < GetNbProcessedChunk(); ++chunkLagId)
{
sum1d += m_d[GetDId(chunkId, chunkLagId, viewpointId, tileId, qualityLevel)];
}
IloExpr sumX(m_env);
for (int viewpointIdPrime = 0; viewpointIdPrime < GetNbViewpoint(); ++viewpointIdPrime)
{
sumX += m_x[GetXId(chunkId, viewpointIdPrime, tileId, qualityLevel)];
}
IloConstraint ic1d = sum1d == D_MAX*sumX;
m_model.add(ic1d);
}
}
}
}
}
void OptimalHorizontalScenario::Presolve(int k, int u, int b)
{
for (int chunkId = 0; chunkId < GetNbProcessedChunk(); ++chunkId)
{
for (int tileId = 0; tileId < GetNbTile(); ++tileId)
{
IloExpr sum(m_env);
for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
{
for (int qualityLevel = -1; qualityLevel < GetNbQuality(); ++qualityLevel)
{
if(m_users[u].GetTileVisibility(chunkId+k*GetNbProcessedChunk(), tileId)==0)
{
m_x[GetXId(chunkId, viewpointId, tileId, qualityLevel)].setUB(0);
for (int chunkLagId = -GetNbLagChunk(); chunkLagId < GetNbProcessedChunk(); ++chunkLagId)
{
if (qualityLevel != -1)
{
m_d[GetDId(chunkId, chunkLagId, viewpointId, tileId, qualityLevel)].setUB(0);
}
}
}
if (qualityLevel == -1)
{
m_x[GetXId(chunkId, viewpointId, tileId, qualityLevel)].setUB(0);
}
}
}
}
}
for (int chunkId = 0; chunkId < GetNbProcessedChunk(); ++chunkId)
{
for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
{
for (int nbSwitch = 0; nbSwitch < m_users[u].GetNbSwitch(k, GetNbProcessedChunk())+1; ++nbSwitch)
{
if (!m_users[u].IsAtViewpoint(chunkId+k*GetNbProcessedChunk(), viewpointId) || nbSwitch != m_users[u].GetNbSwitchUntil(chunkId, k, GetNbProcessedChunk()))
{
m_y[GetYId(chunkId,viewpointId, nbSwitch, u, k)].setUB(0);
}
else
{
m_y[GetYId(chunkId,viewpointId, nbSwitch, u, k)].setLB(1);
}
}
}
}
}
//void OptimalHorizontalScenario::Run(void)
//{
// float DistortionMax = NOT_DOWNLOADED_DISTORTION;
// //Init the Cplex environment
// IloEnv env;
// IloModel model(env);
//
// //Create the decision variables
// IloArray<IloArray<IloArray<IloIntVarArray>>> x(env, GetNbChunk());
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// x[chunkId] = IloArray<IloArray<IloIntVarArray>>(env, GetNbViewpoint());
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// x[chunkId][viewpointId] = IloArray<IloIntVarArray>(env, GetNbTile());
// for (int tileId = 0; tileId < GetNbTile(); ++tileId)
// {
// x[chunkId][viewpointId][tileId] = IloIntVarArray(env, GetNbQuality()+1, 0, 1);
// for (int qualityLevel = -1; qualityLevel < GetNbQuality(); ++qualityLevel)
// {
// x[chunkId][viewpointId][tileId][qualityLevel+1].setName(("x["+
// std::to_string(chunkId) + "][" +
// std::to_string(viewpointId) + "][" +
// std::to_string(tileId) + "][" +
// std::to_string(qualityLevel) + "]").c_str());
// }
// }
// }
// }
// IloArray<IloIntVarArray> y(env, GetNbChunk());
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// y[chunkId] = IloIntVarArray(env, GetNbViewpoint(), 0, 1);
// }
// IloArray<IloArray<IloArray<IloArray<IloNumVarArray>>>> d(env, GetNbChunk());
// //Create the decision variables
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// d[chunkId] = IloArray<IloArray<IloArray<IloNumVarArray>>>(env, GetNbChunk()+GetNbLagChunk());
// for (int chunkLagId = -GetNbLagChunk(); chunkLagId < GetNbChunk(); ++chunkLagId)
// {
// d[chunkId][chunkLagId+GetNbLagChunk()] = IloArray<IloArray<IloNumVarArray>>(env, GetNbViewpoint());
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// d[chunkId][chunkLagId+GetNbLagChunk()][viewpointId] = IloArray<IloNumVarArray>(env, GetNbTile());
// for (int tileId = 0; tileId < GetNbTile(); ++tileId)
// {
// d[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId] = IloNumVarArray(env, GetNbQuality(), 0, 1, ILOFLOAT);
// for (int qualityLevel = 0; qualityLevel < GetNbQuality(); ++qualityLevel)
// {
// d[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId][qualityLevel].setName(("d["+
// std::to_string(chunkId) + "][" +
// std::to_string(viewpointId) + "][" +
// std::to_string(tileId) + "][" +
// std::to_string(qualityLevel) + "]").c_str());
//
// }
// }
// }
// }
// }
// IloIntVarArray stall(env, GetNbChunk()+GetNbLagChunk(), 0, 25000);
//
// //Contraints
// //Contraints 1a and 1b
// for (int chunkLagId = -GetNbLagChunk(); chunkLagId < GetNbChunk(); ++chunkLagId)
// {
// IloExpr sum1a(env);
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// for (int tileId = 0; tileId < GetNbTile(); ++tileId)
// {
// for (int qualityLevel = 0; qualityLevel < GetNbQuality(); ++qualityLevel)
// {
// if (int(chunkId) <= int(chunkLagId))
// {
// d[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId][qualityLevel].setUB(0);
// }
// else
// {
// sum1a += m_as.GetSeg(chunkId, viewpointId, tileId, qualityLevel).GetBitrate() * d[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId][qualityLevel];
// }
// }
// }
// }
// }
//
//
// IloConstraint ic1a = sum1a <= m_bandwidths[b].GetBandwidth(chunkLagId)*(1+stall[chunkLagId+GetNbLagChunk()]);
// ic1a.setName(("Const1a["+std::to_string(chunkLagId)+"]").c_str());
// model.add(ic1a);
// //if (chunkLagId >= 0)
// //{
// // IloConstraint ic1b = sum1b == IloInt(0);
// // ic1b.setName(("Const1b["+std::to_string(chunkLagId)+"]").c_str());
// // model.add(ic1b);
// //}
// }
// //contraints 1c and 1d
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// for (int tileId = 0; tileId < GetNbTile(); ++tileId)
// {
// for (int qualityLevel = 0; qualityLevel < GetNbQuality(); ++qualityLevel)
// {
// IloExpr sumX(env);
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// sumX += x[chunkId][viewpointId][tileId][qualityLevel+1];
// }
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
//
// IloExpr sum(env);
// for (int chunkLagId = -GetNbLagChunk(); chunkLagId < GetNbChunk(); ++chunkLagId)
// {
// sum += d[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId][qualityLevel];
// }
//
// IloConstraint ic1c = sum <= IloInt(1);
// ic1c.setName(("Const1c[" + std::to_string(chunkId) +
// "][" + std::to_string(viewpointId) + "][" +
// std::to_string(tileId) + "][" +
// std::to_string(qualityLevel) + "]").c_str());
// model.add(ic1c);
// IloConstraint ic1d = sumX == sum; //if this tile at this quality level is selected by on any viewpoint, then it should be downloaded
// ic1d.setName(("Const1d[" + std::to_string(chunkId) +
// "][" + std::to_string(viewpointId) + "][" +
// std::to_string(tileId) + "][" +
// std::to_string(qualityLevel) + "]").c_str());
// model.add(ic1d);
// }
// }
// }
// }
// //contraints 1e
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// for (int tileId = 0; tileId < GetNbTile(); ++tileId)
// {
// IloExpr sum(env);
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// for (int qualityLevel = -1; qualityLevel < GetNbQuality(); ++qualityLevel)
// {
// sum += x[chunkId][viewpointId][tileId][qualityLevel+1];
// }
// }
// IloConstraint ic1e = IloNum(std::ceil(m_user.GetTileVisibility(chunkId, tileId))) == sum;
// ic1e.setName(("Const1e[" + std::to_string(chunkId) +
// "][" +
// std::to_string(tileId) + "]").c_str());
// model.add(ic1e);
// }
// }
// //contraints: exactly one viewpoint displayed
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// model.add(IloSum(y[chunkId]) == 1);
// }
// //contraints: display only one viewpoint
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// for (int tileId = 0; tileId < GetNbTile(); ++tileId)
// {
// for (int qualityLevel = -1; qualityLevel < GetNbQuality(); ++qualityLevel)
// {
// model.add(x[chunkId][viewpointId][tileId][qualityLevel+1] <= y[chunkId][viewpointId]);
// }
// }
// }
// }
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// if (m_user.IsAtViewpoint(0, viewpointId))
// {
// y[0][viewpointId].setLB(1);
// }
// else
// {
// y[0][viewpointId].setUB(0);
// }
// }
// for (int chunkId = 1; chunkId < GetNbChunk(); ++chunkId)
// {
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// model.add( y[chunkId][viewpointId] <= y[chunkId-1][viewpointId] + (m_user.IsAtViewpoint(chunkId, viewpointId) ? 1 : 0));
// }
// }
// //Download segment in display order: ds[chunkLagId][chunkId] == 1 if segment of chunkId was downloaded during chunk chunkLagId
// IloArray<IloIntVarArray> ds(env, GetNbChunk()+GetNbLagChunk());
// for (int chunkId = 0; chunkId < GetNbChunk()+GetNbLagChunk(); ++chunkId)
// {
// ds[chunkId] = IloIntVarArray(env, GetNbChunk(), 0, 1);
// }
// for (int chunkLagId = -GetNbLagChunk(); chunkLagId < GetNbChunk(); ++chunkLagId)
// {
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// IloExpr sum(env);
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// for (int tileId = 0; tileId < GetNbTile(); ++tileId)
// {
// for (int qualityLevel = 0; qualityLevel < GetNbQuality(); ++qualityLevel)
// {
// sum += d[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId][qualityLevel];
// }
// }
// }
// //IloExpr sum2(env);
// //for (int cLagId = chunkLagId + 1; cLagId < GetNbChunk(); ++cLagId)
// //{
// // for (int c = 0; c < chunkId; ++c)
// // {
// // sum2 += ds[cLagId+GetNbLagChunk()][c];
// // }
// //}
// //model.add(IloIfThen(env, ds[chunkLagId+GetNbLagChunk()][chunkId] == 1, sum2 == 0));
// model.add((ds[chunkLagId+GetNbLagChunk()][chunkId] == 0) == (sum == 0));
// }
// }
//
// //Objective function:
// IloExpr obj(env);
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// for (int tileId = 0; tileId < GetNbTile(); ++tileId)
// {
// float tileVisibility = m_user.GetTileVisibility(chunkId, tileId);
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// for (int qualityLevel = -1; qualityLevel < GetNbQuality(); ++qualityLevel)
// {
// if (qualityLevel == -1)
// {
// obj += x[chunkId][viewpointId][tileId][qualityLevel+1]*(DistortionMax+(m_user.IsAtViewpoint(chunkId, viewpointId) ? 0 : LAG_COST))*tileVisibility;
// }
// else
// {
// obj += x[chunkId][viewpointId][tileId][qualityLevel+1]*(m_as.GetSeg(chunkId, viewpointId, tileId, qualityLevel).GetDistortion()+(m_user.IsAtViewpoint(chunkId, viewpointId) ? 0 : LAG_COST))*tileVisibility;
// }
// }
// }
// }
// }
// const float alpha = STALL_QoE_IMPACT;
// model.add(IloMinimize(env, obj/GetNbChunk()+alpha*IloSum(stall)/GetNbChunk()));
//
// std::cout << std::endl << "Ready to run" << std::endl;
//
// IloCplex cplex(model);
// //cplex.setParam(IloCplex::EpGap, m_conf->epGap);
// cplex.setParam(IloCplex::EpGap, m_optimalGap);
// cplex.setParam(IloCplex::TiLim, 600);
// //cplex.setParam(IloCplex::Threads, m_conf->nbThread);
// cplex.setParam(IloCplex::Threads, m_nbThread);
// //cplex.setParam(IloCplex::MIPOrdType, 2);
// cplex.setParam(IloCplex::BrDir, -1);
// cplex.setParam(IloCplex::Probe, 3);
// //cplex.setParam(IloCplex::PolishAfterNode, 2000);
// cplex.setParam(IloCplex::PolishAfterTime, 150);
// cplex.setParam(IloCplex::MIPEmphasis, 1);
// cplex.setParam(IloCplex::RINSHeur, 25);
// cplex.setParam(IloCplex::DisjCuts, 2);
// // cplex.setParam(IloCplex::NodeFileInd,3);
// // cplex.setParam(IloCplex::WorkDir,".");
// // cplex.setParam(IloCplex::MemoryEmphasis,true);
// //cplex.setParam(IloCplex::DataCheck, true);
//
//
// //cplex.exportModel((std::string("model.lp")).c_str());
//
// std::cout << "Start solving" << std::endl;
//
// cplex.solve();
//
// std::cout << "Solving done\n" << std::endl;
//
// std::cout << "Solution status " << cplex.getStatus() << std::endl;
// std::cout << "Objective value " << cplex.getObjValue() << std::endl;
// std::cout << "Solution gap " << cplex.getMIPRelativeGap() << "\n" << std::endl;
//
// m_objectiveValue = cplex.getObjValue();
// m_solutionGap = cplex.getMIPRelativeGap();
// m_solutionStatus = cplex.getStatus() == IloAlgorithm::Optimal ? "Optimal" : (cplex.getStatus() == IloAlgorithm::Infeasible ? "Infeasible" : "Unknown");
//
//
// //Get the results
// IloArray<IloArray<IloArray<IloNumArray>>> x_sol(env, GetNbChunk());
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// x_sol[chunkId] = IloArray<IloArray<IloNumArray>>(env, GetNbViewpoint());
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// x_sol[chunkId][viewpointId] = IloArray<IloNumArray>(env, GetNbTile());
// for (int tileId = 0; tileId < GetNbTile(); ++tileId)
// {
// x_sol[chunkId][viewpointId][tileId] = IloNumArray(env, GetNbQuality()+1);
// cplex.getValues(x_sol[chunkId][viewpointId][tileId], x[chunkId][viewpointId][tileId]);
// for (int qualityLevel = 0; qualityLevel < GetNbQuality(); ++qualityLevel)
// {
// if (x_sol[chunkId][viewpointId][tileId][qualityLevel+1] > 0.5)
// {
// m_as.GetSeg(chunkId, viewpointId, tileId, qualityLevel).SetSelected();
// }
// }
// x_sol[chunkId][viewpointId][tileId].end();
// x[chunkId][viewpointId][tileId].end();
// }
// x_sol[chunkId][viewpointId].end();
// x[chunkId][viewpointId].end();
// }
// x_sol[chunkId].end();
// x[chunkId].end();
// }
// x_sol.end();
// x.end();
// IloArray<IloNumArray> y_sol(env, GetNbChunk());
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// y_sol[chunkId] = IloNumArray(env, GetNbViewpoint());
// cplex.getValues(y_sol[chunkId], y[chunkId]);
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// if (y_sol[chunkId][viewpointId] == 1)
// {
// m_displayedViewpoint[chunkId]= viewpointId;
// break;
// }
// }
// y[chunkId].end();
// }
// y.end();
// IloArray<IloArray<IloArray<IloArray<IloNumArray>>>> d_sol(env, GetNbChunk());
// for (int chunkId = 0; chunkId < GetNbChunk(); ++chunkId)
// {
// d_sol[chunkId] = IloArray<IloArray<IloArray<IloNumArray>>>(env, GetNbChunk()+GetNbLagChunk());
// for (int chunkLagId = -GetNbLagChunk(); chunkLagId < GetNbChunk(); ++chunkLagId)
// {
// d_sol[chunkId][chunkLagId+GetNbLagChunk()] = IloArray<IloArray<IloNumArray>>(env, GetNbViewpoint());
// for (int viewpointId = 0; viewpointId < GetNbViewpoint(); ++viewpointId)
// {
// d_sol[chunkId][chunkLagId+GetNbLagChunk()][viewpointId] = IloArray<IloNumArray>(env, GetNbTile());
// for (int tileId = 0; tileId < GetNbTile(); ++tileId)
// {
// d_sol[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId] = IloNumArray(env, GetNbQuality());
// cplex.getValues(d_sol[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId], d[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId]);
// for (int qualityLevel = 0; qualityLevel < GetNbQuality(); ++qualityLevel)
// {
// SetDownloadRatio(chunkId, chunkLagId, viewpointId, tileId, qualityLevel, d_sol[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId][qualityLevel]);
// }
// d_sol[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId].end();
// d[chunkId][chunkLagId+GetNbLagChunk()][viewpointId][tileId].end();
// }
// d_sol[chunkId][chunkLagId+GetNbLagChunk()][viewpointId].end();
// d[chunkId][chunkLagId+GetNbLagChunk()][viewpointId].end();
// }
// d_sol[chunkId][chunkLagId+GetNbLagChunk()].end();
// d[chunkId][chunkLagId+GetNbLagChunk()].end();
// }
// d_sol[chunkId].end();
// d[chunkId].end();
// }
// d_sol.end();
// d.end();
// IloNumArray stall_sol(env, GetNbChunk()+GetNbLagChunk());
// cplex.getValues(stall_sol, stall);
// for (int chunkLagId = -GetNbLagChunk(); chunkLagId < GetNbChunk(); ++chunkLagId)
// {
// m_nbStall[chunkLagId+GetNbLagChunk()] = stall_sol[chunkLagId+GetNbLagChunk()];
// }
// stall_sol.end();
// stall.end();
// for (int chunkId = 0; chunkId < GetNbChunk()+GetNbLagChunk(); ++chunkId)
// {
// ds[chunkId].end();
// }
// ds.end();
//
// //cleanup
// cplex.end();
// obj.end();
// model.end();
// env.end();
//}
| 45.146751 | 230 | 0.504528 | xmar |
0e6fcc185060efadc1434dd4d405422ea3a79069 | 3,426 | cpp | C++ | apps/myApps/clubProjectionMapping/src/TextDrawer.cpp | nmbakfm/club_projection_mapping | 95dd0d7604fce397fcdf058d09085fb32b184257 | [
"MIT"
] | 1 | 2015-06-16T07:36:55.000Z | 2015-06-16T07:36:55.000Z | apps/myApps/clubProjectionMapping/src/TextDrawer.cpp | nmbakfm/club_projection_mapping | 95dd0d7604fce397fcdf058d09085fb32b184257 | [
"MIT"
] | null | null | null | apps/myApps/clubProjectionMapping/src/TextDrawer.cpp | nmbakfm/club_projection_mapping | 95dd0d7604fce397fcdf058d09085fb32b184257 | [
"MIT"
] | null | null | null | //
// TextDrawer.cpp
// clubProjectionMapping
//
// Created by KamedaKei on 2015/11/22.
//
//
#include "TextDrawer.hpp"
#include "Settings.h"
typedef std::shared_ptr<TextDrawer> d_p;
std::shared_ptr<TextDrawer> TextDrawer::Alloc(){
auto p = std::shared_ptr<TextDrawer>(new TextDrawer());
p->self = p;
p->setPosition(ofPoint(0,0));
return p;
}
shared_ptr<ofTrueTypeFont> TextDrawer::getTrueTypeFont(){
switch (this->fontType){
case NormalFontType:
return Settings::normalFont;
break;
case WeddingFontType:
return Settings::weddingFont;
break;
case BirthdayFontType:
return Settings::birthdayFont;
break;
}
return Settings::normalFont;
}
d_p TextDrawer::setFontType(FontType t){
auto f = getTrueTypeFont();
for(auto it = nodes.begin(); it != nodes.end(); it ++){
it->setFont(f);
}
this->fontType = t;
return self.lock();
}
d_p TextDrawer::setAnimator(shared_ptr<NodeAnimator> a){
this->base_animator = a;
updateAnimator();
return self.lock();
}
void TextDrawer::updateAnimator(){
this->animator_nodes.clear();
int index[nodes.size()];
for(int i = 0; i < nodes.size(); i ++){
index[i] = i;
}
if(base_animator->isRandom()){
for(int i = 0; i < nodes.size() * 3; i ++){
int swap1 = rand() % nodes.size();
int swap2 = rand() % nodes.size();
int buf = index[swap1];
index[swap1] = index[swap2];
index[swap2] = buf;
}
}
for(int i = 0; i< nodes.size(); i ++){
auto a = base_animator->clone();
a->setTimeOffset(index[i] * base_animator->getDiff());
animator_nodes.push_back(a);
}
}
d_p TextDrawer::setMessage(string message){
//make Nodes
nodes.clear();
for(auto it = message.begin(); it != message.end(); it++){
char a = *it;
nodes.push_back(TextNode(string(&a, 1), getTrueTypeFont()));
}
this->message = message;
updateAnimator();
return self.lock();
}
int TextDrawer::getMessageHeight(){
int height = 0;
if(!nodes.empty())height = nodes[0].getHeight();
return height;
}
int TextDrawer::getMessageWidth(){
int width = 0;
for(auto it = nodes.begin(); it != nodes.end(); it++){
width += it->getWidth();
}
return width;
}
void TextDrawer::draw(){
ofPoint pos = position;
auto font = getTrueTypeFont();
int width = getMessageWidth();
int height = getMessageHeight();
int offsetX = 0;
ofTranslate(pos.x - width/2, pos.y + height);
for(int i = 0; i < nodes.size(); i++){
auto n = nodes[i];
auto a = animator_nodes[i];
ofPushMatrix();
ofTranslate(offsetX, 0);
ofPushMatrix();
float w = n.getWidth() / 2;
float h = n.getHeight() / 2;
ofTranslate( w, -h);
a->update(currentFrame);
ofTranslate(-w, h);
n.draw();
ofPopMatrix();
offsetX += n.getWidth();
ofPopMatrix();
}
}
void TextDrawer::update(){
if(!this->isDone())this->currentFrame ++;
}
bool TextDrawer::isDone(){
return this->currentFrame >= this->showEndFrame;
}
void TextDrawer::restart(){
this->currentFrame = 0;
} | 23.958042 | 68 | 0.555458 | nmbakfm |
0e70b7e4b7541b040a273260a7575b3ec8f0cc93 | 5,212 | cpp | C++ | ui/viewmodel/send_view.cpp | coincash/kitap-kabile-hakk-nda | 26616a7d0e8bedc561d031f49190f896faa88233 | [
"Apache-2.0"
] | 1 | 2019-08-02T08:19:45.000Z | 2019-08-02T08:19:45.000Z | ui/viewmodel/send_view.cpp | coincash/kitap-kabile-hakk-nda | 26616a7d0e8bedc561d031f49190f896faa88233 | [
"Apache-2.0"
] | 1 | 2021-07-24T13:50:37.000Z | 2021-07-24T13:50:37.000Z | ui/viewmodel/send_view.cpp | coincash/kitap-kabile-hakk-nda | 26616a7d0e8bedc561d031f49190f896faa88233 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 The Beam Team
//
// 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 "send_view.h"
#include "model/app_model.h"
#include "wallet/common.h"
#include "ui_helpers.h"
#include <QLocale>
namespace
{
const int kDefaultFeeInGroth = 10;
const int kFeeInGroth_Fork1 = 100;
}
SendViewModel::SendViewModel()
: _feeGrothes(0)
, _sendAmount(0.0)
, _change(0)
, _walletModel(*AppModel::getInstance().getWallet())
{
connect(&_walletModel, &WalletModel::changeCalculated, this, &SendViewModel::onChangeCalculated);
connect(&_walletModel, &WalletModel::changeCurrentWalletIDs, this, &SendViewModel::onChangeWalletIDs);
connect(&_walletModel, &WalletModel::sendMoneyVerified, this, &SendViewModel::onSendMoneyVerified);
connect(&_walletModel, &WalletModel::cantSendToExpired, this, &SendViewModel::onCantSendToExpired);
_status.setOnChanged([this]() {
emit availableChanged();
});
_status.refresh();
}
int SendViewModel::getFeeGrothes() const
{
return _feeGrothes;
}
void SendViewModel::setFeeGrothes(int value)
{
if (value != _feeGrothes)
{
_feeGrothes = value;
_walletModel.getAsync()->calcChange(calcTotalAmount());
emit feeGrothesChanged();
}
}
beam::Amount SendViewModel::calcFeeAmount() const
{
return static_cast<beam::Amount>(_feeGrothes);
}
beam::Amount SendViewModel::calcSendAmount() const
{
return std::round(_sendAmount * beam::Rules::Coin);
}
beam::Amount SendViewModel::calcTotalAmount() const
{
return calcSendAmount() + calcFeeAmount();
}
QString SendViewModel::getComment() const
{
return _comment;
}
void SendViewModel::setComment(const QString& value)
{
if (_comment != value)
{
_comment = value;
emit commentChanged();
}
}
double SendViewModel::getSendAmount() const
{
return _sendAmount;
}
void SendViewModel::setSendAmount(double value)
{
if (value != _sendAmount)
{
_sendAmount = value;
_walletModel.getAsync()->calcChange(calcTotalAmount());
emit sendAmountChanged();
}
}
QString SendViewModel::getReceiverAddress() const
{
return _receiverAddr;
}
void SendViewModel::setReceiverAddress(const QString& value)
{
if (_receiverAddr != value)
{
_receiverAddr = value;
emit receiverAddressChanged();
}
}
bool SendViewModel::isValidReceiverAddress(const QString& value)
{
return beam::wallet::check_receiver_address(value.toStdString());
}
int SendViewModel::getDefaultFeeInGroth() const
{
return _walletModel.isFork1() ? kFeeInGroth_Fork1 : kDefaultFeeInGroth;
}
int SendViewModel::getMinFeeInGroth() const
{
return _walletModel.isFork1() ? kFeeInGroth_Fork1 : 0;
}
QString SendViewModel::getAvailable() const
{
return beamui::BeamToString(_status.getAvailable() - calcTotalAmount() - _change);
}
QString SendViewModel::getMissing() const
{
beam::Amount missed = calcTotalAmount() - _status.getAvailable();
if (missed > 99999)
{
//% "BEAM"
return beamui::BeamToString(missed) + " " + qtTrId("tx-curency-name");
}
//% "GROTH"
return QLocale().toString(static_cast<qulonglong>(missed)) + " " + qtTrId("tx-curency-sub-name");
}
bool SendViewModel::isEnough() const
{
return _status.getAvailable() >= calcTotalAmount() + _change;
}
bool SendViewModel::needPassword() const
{
return AppModel::getInstance().getSettings().isPasswordReqiredToSpendMoney();
}
bool SendViewModel::isPasswordValid(const QString& value) const
{
beam::SecString secretPass = value.toStdString();
return AppModel::getInstance().checkWalletPassword(secretPass);
}
void SendViewModel::onChangeCalculated(beam::Amount change)
{
_change = change;
emit availableChanged();
}
QString SendViewModel::getChange() const
{
return beamui::BeamToString(_change);
}
void SendViewModel::onChangeWalletIDs(beam::wallet::WalletID senderID, beam::wallet::WalletID receiverID)
{
setReceiverAddress(beamui::toString(receiverID));
}
void SendViewModel::sendMoney()
{
assert(isValidReceiverAddress(getReceiverAddress()));
if(isValidReceiverAddress(getReceiverAddress()))
{
beam::wallet::WalletID walletID(beam::Zero);
walletID.FromHex(getReceiverAddress().toStdString());
// TODO: show 'operation in process' animation here?
_walletModel.getAsync()->sendMoney(walletID, _comment.toStdString(), calcSendAmount(), calcFeeAmount());
}
}
void SendViewModel::onSendMoneyVerified()
{
// forward to qml
emit sendMoneyVerified();
}
void SendViewModel::onCantSendToExpired()
{
// forward to qml
emit cantSendToExpired();
}
| 25.42439 | 112 | 0.708749 | coincash |
0e735da36f30fb622df813250ee94c75016c2a31 | 3,513 | hpp | C++ | libs/camera/include/sge/camera/spherical/parameters.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/camera/include/sge/camera/spherical/parameters.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/camera/include/sge/camera/spherical/parameters.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// 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)
#ifndef SGE_CAMERA_SPHERICAL_PARAMETERS_HPP_INCLUDED
#define SGE_CAMERA_SPHERICAL_PARAMETERS_HPP_INCLUDED
#include <sge/camera/optional_projection_matrix.hpp>
#include <sge/camera/projection_matrix.hpp>
#include <sge/camera/detail/symbol.hpp>
#include <sge/camera/spherical/acceleration_factor.hpp>
#include <sge/camera/spherical/damping_factor.hpp>
#include <sge/camera/spherical/maximum_radius.hpp>
#include <sge/camera/spherical/minimum_radius.hpp>
#include <sge/camera/spherical/movement_speed.hpp>
#include <sge/camera/spherical/origin.hpp>
#include <sge/camera/spherical/action/mapping.hpp>
#include <sge/camera/spherical/coordinate_system/object.hpp>
namespace sge::camera::spherical
{
class parameters
{
public:
SGE_CAMERA_DETAIL_SYMBOL
parameters(
sge::camera::spherical::coordinate_system::object const &,
sge::camera::spherical::action::mapping const &);
[[nodiscard]] SGE_CAMERA_DETAIL_SYMBOL sge::camera::spherical::coordinate_system::object const &
coordinate_system() const;
[[nodiscard]] SGE_CAMERA_DETAIL_SYMBOL sge::camera::spherical::action::mapping const &
action_mapping() const;
SGE_CAMERA_DETAIL_SYMBOL
parameters &movement_speed(sge::camera::spherical::movement_speed const &);
[[nodiscard]] SGE_CAMERA_DETAIL_SYMBOL sge::camera::spherical::movement_speed const &
movement_speed() const;
SGE_CAMERA_DETAIL_SYMBOL
parameters &origin(sge::camera::spherical::origin const &);
[[nodiscard]] SGE_CAMERA_DETAIL_SYMBOL sge::camera::spherical::origin const &origin() const;
SGE_CAMERA_DETAIL_SYMBOL
parameters &minimum_radius(sge::camera::spherical::minimum_radius);
[[nodiscard]] SGE_CAMERA_DETAIL_SYMBOL sge::camera::spherical::minimum_radius
minimum_radius() const;
SGE_CAMERA_DETAIL_SYMBOL
parameters &maximum_radius(sge::camera::spherical::maximum_radius);
[[nodiscard]] SGE_CAMERA_DETAIL_SYMBOL sge::camera::spherical::maximum_radius
maximum_radius() const;
SGE_CAMERA_DETAIL_SYMBOL
parameters &acceleration_factor(sge::camera::spherical::acceleration_factor const &);
[[nodiscard]] SGE_CAMERA_DETAIL_SYMBOL sge::camera::spherical::acceleration_factor const &
acceleration_factor() const;
SGE_CAMERA_DETAIL_SYMBOL
parameters &damping_factor(sge::camera::spherical::damping_factor const &);
[[nodiscard]] SGE_CAMERA_DETAIL_SYMBOL sge::camera::spherical::damping_factor const &
damping_factor() const;
// Projection is optional on construction, since we might know it only
// after we get a viewport.
SGE_CAMERA_DETAIL_SYMBOL
parameters &projection(sge::camera::projection_matrix const &);
[[nodiscard]] SGE_CAMERA_DETAIL_SYMBOL sge::camera::optional_projection_matrix const &
projection_matrix() const;
private:
sge::camera::spherical::movement_speed movement_speed_;
sge::camera::spherical::coordinate_system::object coordinate_system_;
sge::camera::spherical::action::mapping action_mapping_;
sge::camera::spherical::origin origin_;
sge::camera::spherical::minimum_radius minimum_radius_;
sge::camera::spherical::maximum_radius maximum_radius_;
sge::camera::spherical::acceleration_factor acceleration_factor_;
sge::camera::spherical::damping_factor damping_factor_;
sge::camera::optional_projection_matrix projection_matrix_;
};
}
#endif
| 33.778846 | 98 | 0.785084 | cpreh |
0e74318fad01ed7e5f0d326b93e8b557bc7ec9d5 | 1,199 | cpp | C++ | src/plugins/video/videoplugin.cpp | qtmediahub/qtmediahub-ruins | 844c71dbd7bcbd94a6ba76b952b7d1850e3ddc67 | [
"BSD-3-Clause"
] | null | null | null | src/plugins/video/videoplugin.cpp | qtmediahub/qtmediahub-ruins | 844c71dbd7bcbd94a6ba76b952b7d1850e3ddc67 | [
"BSD-3-Clause"
] | null | null | null | src/plugins/video/videoplugin.cpp | qtmediahub/qtmediahub-ruins | 844c71dbd7bcbd94a6ba76b952b7d1850e3ddc67 | [
"BSD-3-Clause"
] | null | null | null | #include "videoplugin.h"
#include <QtPlugin>
#include "submenuentry.h"
class VideoPluginItem : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
public:
VideoPluginItem(const QString &name, QObject *parent = 0) : QObject(parent), m_name(name) { }
QString name() const {
return m_name;
}
void setName(const QString &name) {
m_name = name;
emit nameChanged();
}
signals:
void nameChanged();
private:
QString m_name;
};
VideoPlugin::VideoPlugin()
{
m_childItems << new VideoPluginItem(tr("Files"), this)
<< new VideoPluginItem(tr("Add-ons"), this)
<< new VideoPluginItem(tr("Library"), this);
m_model = new VideoModel(this);
}
QObject *VideoPlugin::pluginProperties() const
{
return const_cast<VideoPlugin *>(this);
}
void VideoPlugin::registerPlugin(QDeclarativeContext *context)
{
//FIXME: these structures should be suitably disconnected from QML to be usable from html
//Post CES adjustment :)
if (context)
m_model->registerImageProvider(context);
}
Q_EXPORT_PLUGIN2(video, VideoPlugin)
#include "videoplugin.moc"
| 21.410714 | 97 | 0.674729 | qtmediahub |
0e74923f2e661f5971bda9e492c1a994b3025365 | 23,865 | cpp | C++ | src/image/SkImage_GpuBase.cpp | luigi-rosso/skia | 45ecf91884eab043429ba844108772a44dda7253 | [
"BSD-3-Clause"
] | null | null | null | src/image/SkImage_GpuBase.cpp | luigi-rosso/skia | 45ecf91884eab043429ba844108772a44dda7253 | [
"BSD-3-Clause"
] | null | null | null | src/image/SkImage_GpuBase.cpp | luigi-rosso/skia | 45ecf91884eab043429ba844108772a44dda7253 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImage_GpuBase.h"
#include "GrBackendSurface.h"
#include "GrClip.h"
#include "GrContext.h"
#include "GrContextPriv.h"
#include "GrRenderTargetContext.h"
#include "GrTexture.h"
#include "GrTextureAdjuster.h"
#include "SkBitmapCache.h"
#include "SkImage_Gpu.h"
#include "SkPromiseImageTexture.h"
#include "SkReadPixelsRec.h"
#include "SkTLList.h"
#include "effects/GrYUVtoRGBEffect.h"
SkImage_GpuBase::SkImage_GpuBase(sk_sp<GrContext> context, int width, int height, uint32_t uniqueID,
SkAlphaType at, sk_sp<SkColorSpace> cs)
: INHERITED(width, height, uniqueID)
, fContext(std::move(context))
, fAlphaType(at)
, fColorSpace(std::move(cs)) {}
SkImage_GpuBase::~SkImage_GpuBase() {}
//////////////////////////////////////////////////////////////////////////////////////////////////
bool SkImage_GpuBase::ValidateBackendTexture(GrContext* ctx, const GrBackendTexture& tex,
GrPixelConfig* config, SkColorType ct, SkAlphaType at,
sk_sp<SkColorSpace> cs) {
if (!tex.isValid()) {
return false;
}
// TODO: Create a SkImageColorInfo struct for color, alpha, and color space so we don't need to
// create a fake image info here.
SkImageInfo info = SkImageInfo::Make(1, 1, ct, at, cs);
if (!SkImageInfoIsValid(info)) {
return false;
}
GrBackendFormat backendFormat = tex.getBackendFormat();
if (!backendFormat.isValid()) {
return false;
}
*config = ctx->contextPriv().caps()->getConfigFromBackendFormat(backendFormat, ct);
return *config != kUnknown_GrPixelConfig;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
bool SkImage_GpuBase::getROPixels(SkBitmap* dst, CachingHint chint) const {
if (!fContext->contextPriv().resourceProvider()) {
// DDL TODO: buffer up the readback so it occurs when the DDL is drawn?
return false;
}
const auto desc = SkBitmapCacheDesc::Make(this);
if (SkBitmapCache::Find(desc, dst)) {
SkASSERT(dst->isImmutable());
SkASSERT(dst->getPixels());
return true;
}
SkBitmapCache::RecPtr rec = nullptr;
SkPixmap pmap;
if (kAllow_CachingHint == chint) {
rec = SkBitmapCache::Alloc(desc, this->onImageInfo(), &pmap);
if (!rec) {
return false;
}
} else {
if (!dst->tryAllocPixels(this->onImageInfo()) || !dst->peekPixels(&pmap)) {
return false;
}
}
sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext(
this->asTextureProxyRef(),
fColorSpace);
if (!sContext) {
return false;
}
if (!sContext->readPixels(pmap.info(), pmap.writable_addr(), pmap.rowBytes(), 0, 0)) {
return false;
}
if (rec) {
SkBitmapCache::Add(std::move(rec), dst);
this->notifyAddedToRasterCache();
}
return true;
}
sk_sp<SkImage> SkImage_GpuBase::onMakeSubset(const SkIRect& subset) const {
sk_sp<GrSurfaceProxy> proxy = this->asTextureProxyRef();
GrSurfaceDesc desc;
desc.fWidth = subset.width();
desc.fHeight = subset.height();
desc.fConfig = proxy->config();
GrBackendFormat format = proxy->backendFormat().makeTexture2D();
if (!format.isValid()) {
return nullptr;
}
// TODO: Should this inherit our proxy's budgeted status?
sk_sp<GrSurfaceContext> sContext(fContext->contextPriv().makeDeferredSurfaceContext(
format, desc, proxy->origin(), GrMipMapped::kNo, SkBackingFit::kExact,
proxy->isBudgeted()));
if (!sContext) {
return nullptr;
}
if (!sContext->copy(proxy.get(), subset, SkIPoint::Make(0, 0))) {
return nullptr;
}
// MDB: this call is okay bc we know 'sContext' was kExact
return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID, fAlphaType,
sContext->asTextureProxyRef(), fColorSpace);
}
static void apply_premul(const SkImageInfo& info, void* pixels, size_t rowBytes) {
switch (info.colorType()) {
case kRGBA_8888_SkColorType:
case kBGRA_8888_SkColorType:
break;
default:
return; // nothing to do
}
// SkColor is not necessarily RGBA or BGRA, but it is one of them on little-endian,
// and in either case, the alpha-byte is always in the same place, so we can safely call
// SkPreMultiplyColor()
//
SkColor* row = (SkColor*)pixels;
for (int y = 0; y < info.height(); ++y) {
for (int x = 0; x < info.width(); ++x) {
row[x] = SkPreMultiplyColor(row[x]);
}
row = (SkColor*)((char*)(row)+rowBytes);
}
}
bool SkImage_GpuBase::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRB,
int srcX, int srcY, CachingHint) const {
if (!fContext->contextPriv().resourceProvider()) {
// DDL TODO: buffer up the readback so it occurs when the DDL is drawn?
return false;
}
if (!SkImageInfoValidConversion(dstInfo, this->onImageInfo())) {
return false;
}
SkReadPixelsRec rec(dstInfo, dstPixels, dstRB, srcX, srcY);
if (!rec.trim(this->width(), this->height())) {
return false;
}
// TODO: this seems to duplicate code in GrTextureContext::onReadPixels and
// GrRenderTargetContext::onReadPixels
uint32_t flags = 0;
if (kUnpremul_SkAlphaType == rec.fInfo.alphaType() && kPremul_SkAlphaType == fAlphaType) {
// let the GPU perform this transformation for us
flags = GrContextPriv::kUnpremul_PixelOpsFlag;
}
sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext(
this->asTextureProxyRef(), fColorSpace);
if (!sContext) {
return false;
}
if (!sContext->readPixels(rec.fInfo, rec.fPixels, rec.fRowBytes, rec.fX, rec.fY, flags)) {
return false;
}
// do we have to manually fix-up the alpha channel?
// src dst
// unpremul premul fix manually
// premul unpremul done by kUnpremul_PixelOpsFlag
// all other combos need to change.
//
// Should this be handled by Ganesh? todo:?
//
if (kPremul_SkAlphaType == rec.fInfo.alphaType() && kUnpremul_SkAlphaType == fAlphaType) {
apply_premul(rec.fInfo, rec.fPixels, rec.fRowBytes);
}
return true;
}
sk_sp<GrTextureProxy> SkImage_GpuBase::asTextureProxyRef(GrContext* context,
const GrSamplerState& params,
SkScalar scaleAdjust[2]) const {
if (context->uniqueID() != fContext->uniqueID()) {
SkASSERT(0);
return nullptr;
}
GrTextureAdjuster adjuster(fContext.get(), this->asTextureProxyRef(), fAlphaType,
this->uniqueID(), fColorSpace.get());
return adjuster.refTextureProxyForParams(params, scaleAdjust);
}
GrBackendTexture SkImage_GpuBase::onGetBackendTexture(bool flushPendingGrContextIO,
GrSurfaceOrigin* origin) const {
sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef();
SkASSERT(proxy);
if (!fContext->contextPriv().resourceProvider() && !proxy->isInstantiated()) {
// This image was created with a DDL context and cannot be instantiated.
return GrBackendTexture();
}
if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) {
return GrBackendTexture(); // invalid
}
GrTexture* texture = proxy->peekTexture();
if (texture) {
if (flushPendingGrContextIO) {
fContext->contextPriv().prepareSurfaceForExternalIO(proxy.get());
}
if (origin) {
*origin = proxy->origin();
}
return texture->getBackendTexture();
}
return GrBackendTexture(); // invalid
}
GrTexture* SkImage_GpuBase::onGetTexture() const {
GrTextureProxy* proxy = this->peekProxy();
if (!proxy) {
return nullptr;
}
sk_sp<GrTextureProxy> proxyRef = this->asTextureProxyRef();
if (!fContext->contextPriv().resourceProvider() && !proxyRef->isInstantiated()) {
// This image was created with a DDL context and cannot be instantiated.
return nullptr;
}
if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) {
return nullptr;
}
return proxy->peekTexture();
}
bool SkImage_GpuBase::onIsValid(GrContext* context) const {
// The base class has already checked that context isn't abandoned (if it's not nullptr)
if (fContext->abandoned()) {
return false;
}
if (context && context != fContext.get()) {
return false;
}
return true;
}
bool SkImage_GpuBase::MakeTempTextureProxies(GrContext* ctx, const GrBackendTexture yuvaTextures[],
int numTextures, const SkYUVAIndex yuvaIndices[4],
GrSurfaceOrigin imageOrigin,
sk_sp<GrTextureProxy> tempTextureProxies[4]) {
GrProxyProvider* proxyProvider = ctx->contextPriv().proxyProvider();
// We need to make a copy of the input backend textures because we need to preserve the result
// of validate_backend_texture.
GrBackendTexture yuvaTexturesCopy[4];
for (int textureIndex = 0; textureIndex < numTextures; ++textureIndex) {
yuvaTexturesCopy[textureIndex] = yuvaTextures[textureIndex];
GrBackendFormat backendFormat = yuvaTexturesCopy[textureIndex].getBackendFormat();
if (!backendFormat.isValid()) {
return false;
}
yuvaTexturesCopy[textureIndex].fConfig =
ctx->contextPriv().caps()->getYUVAConfigFromBackendFormat(backendFormat);
if (yuvaTexturesCopy[textureIndex].fConfig == kUnknown_GrPixelConfig) {
return false;
}
SkASSERT(yuvaTexturesCopy[textureIndex].isValid());
tempTextureProxies[textureIndex] =
proxyProvider->wrapBackendTexture(yuvaTexturesCopy[textureIndex], imageOrigin,
kBorrow_GrWrapOwnership, kRead_GrIOType);
if (!tempTextureProxies[textureIndex]) {
return false;
}
// Check that each texture contains the channel data for the corresponding YUVA index
GrPixelConfig config = yuvaTexturesCopy[textureIndex].fConfig;
for (int yuvaIndex = 0; yuvaIndex < SkYUVAIndex::kIndexCount; ++yuvaIndex) {
if (yuvaIndices[yuvaIndex].fIndex == textureIndex) {
switch (yuvaIndices[yuvaIndex].fChannel) {
case SkColorChannel::kR:
if (kAlpha_8_as_Alpha_GrPixelConfig == config) {
return false;
}
break;
case SkColorChannel::kG:
case SkColorChannel::kB:
if (kAlpha_8_as_Alpha_GrPixelConfig == config ||
kAlpha_8_as_Red_GrPixelConfig == config) {
return false;
}
break;
case SkColorChannel::kA:
default:
if (kRGB_888_GrPixelConfig == config) {
return false;
}
break;
}
}
}
}
return true;
}
bool SkImage_GpuBase::RenderYUVAToRGBA(GrContext* ctx, GrRenderTargetContext* renderTargetContext,
const SkRect& rect, SkYUVColorSpace yuvColorSpace,
const sk_sp<GrTextureProxy> proxies[4],
const SkYUVAIndex yuvaIndices[4]) {
SkASSERT(renderTargetContext);
if (!renderTargetContext->asSurfaceProxy()) {
return false;
}
GrPaint paint;
paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
paint.addColorFragmentProcessor(GrYUVtoRGBEffect::Make(proxies, yuvaIndices,
yuvColorSpace,
GrSamplerState::Filter::kNearest));
renderTargetContext->drawRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(), rect);
// DDL TODO: in the promise image version we must not flush here
ctx->contextPriv().flushSurfaceWrites(renderTargetContext->asSurfaceProxy());
return true;
}
sk_sp<GrTextureProxy> SkImage_GpuBase::MakePromiseImageLazyProxy(
GrContext* context, int width, int height, GrSurfaceOrigin origin, GrPixelConfig config,
GrBackendFormat backendFormat, GrMipMapped mipMapped,
PromiseImageTextureFulfillProc fulfillProc,
PromiseImageTextureReleaseProc releaseProc,
PromiseImageTextureDoneProc doneProc,
PromiseImageTextureContext textureContext) {
SkASSERT(context);
SkASSERT(width > 0 && height > 0);
SkASSERT(doneProc);
SkASSERT(config != kUnknown_GrPixelConfig);
if (!fulfillProc || !releaseProc) {
doneProc(textureContext);
return nullptr;
}
if (mipMapped == GrMipMapped::kYes &&
GrTextureTypeHasRestrictedSampling(backendFormat.textureType())) {
// It is invalid to have a GL_TEXTURE_EXTERNAL or GL_TEXTURE_RECTANGLE and have mips as
// well.
doneProc(textureContext);
return nullptr;
}
/**
* This class is the lazy instantiation callback for promise images. It manages calling the
* client's Fulfill, Release, and Done procs. It attempts to reuse a GrTexture instance in
* cases where the client provides the same SkPromiseImageTexture for successive Fulfill calls.
* The created GrTexture is given a key based on a unique ID associated with the
* SkPromiseImageTexture. When the texture enters "idle" state (meaning it is not being used by
* the GPU and is at rest in the resource cache) the client's Release proc is called
* using GrTexture's idle proc mechanism. If the same SkPromiseImageTexture is provided for
* another fulfill we find the cached GrTexture. If the proxy, and therefore this object,
* is destroyed, we invalidate the GrTexture's key. Also if the client overwrites or
* destroys their SkPromiseImageTexture we invalidate the key.
*
* Currently a GrTexture is only reused for a given SkPromiseImageTexture if the
* SkPromiseImageTexture is reused in Fulfill for the same promise SkImage. However, we'd
* like to relax that so that a SkPromiseImageTexture can be reused with different promise
* SkImages that will reuse a single GrTexture.
*/
class PromiseLazyInstantiateCallback {
public:
PromiseLazyInstantiateCallback(PromiseImageTextureFulfillProc fulfillProc,
PromiseImageTextureReleaseProc releaseProc,
PromiseImageTextureDoneProc doneProc,
PromiseImageTextureContext context,
GrPixelConfig config)
: fFulfillProc(fulfillProc)
, fConfig(config) {
auto doneHelper = sk_make_sp<GrReleaseProcHelper>(doneProc, context);
fReleaseContext = sk_make_sp<IdleContext::PromiseImageReleaseContext>(
releaseProc, context, std::move(doneHelper));
}
~PromiseLazyInstantiateCallback() = default;
sk_sp<GrSurface> operator()(GrResourceProvider* resourceProvider) {
if (!resourceProvider) {
return nullptr;
}
sk_sp<GrTexture> cachedTexture;
SkASSERT(fLastFulfilledKey.isValid() == (fLastFulfillID > 0));
if (fLastFulfilledKey.isValid()) {
auto surf = resourceProvider->findByUniqueKey<GrSurface>(fLastFulfilledKey);
if (surf) {
cachedTexture = sk_ref_sp(surf->asTexture());
SkASSERT(cachedTexture);
}
}
// If the release callback hasn't been called already by releasing the GrTexture
// then we can be sure that won't happen so long as we have a ref to the texture.
if (cachedTexture && !fReleaseContext->isReleased()) {
return std::move(cachedTexture);
}
GrBackendTexture backendTexture;
sk_sp<SkPromiseImageTexture> promiseTexture =
fFulfillProc(fReleaseContext->textureContext());
fReleaseContext->notifyWasFulfilled();
if (!promiseTexture) {
fReleaseContext->release();
return sk_sp<GrTexture>();
}
bool same = promiseTexture->uniqueID() == fLastFulfillID;
SkASSERT(!same || fLastFulfilledKey.isValid());
if (same && cachedTexture) {
SkASSERT(fReleaseContext->unique());
this->addToIdleContext(cachedTexture.get());
return std::move(cachedTexture);
} else if (cachedTexture) {
cachedTexture->resourcePriv().removeUniqueKey();
}
fLastFulfillID = promiseTexture->uniqueID();
backendTexture = promiseTexture->backendTexture();
backendTexture.fConfig = fConfig;
if (!backendTexture.isValid()) {
// Even though the GrBackendTexture is not valid, we must call the release
// proc to keep our contract of always calling Fulfill and Release in pairs.
fReleaseContext->release();
return sk_sp<GrTexture>();
}
auto tex = resourceProvider->wrapBackendTexture(backendTexture, kBorrow_GrWrapOwnership,
kRead_GrIOType);
if (!tex) {
// Even though we failed to wrap the backend texture, we must call the release
// proc to keep our contract of always calling Fulfill and Release in pairs.
fReleaseContext->release();
return sk_sp<GrTexture>();
}
// The texture gets a ref, which is balanced when the idle callback is called.
this->addToIdleContext(tex.get());
static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
GrUniqueKey::Builder builder(&fLastFulfilledKey, kDomain, 2, "promise");
builder[0] = promiseTexture->uniqueID();
builder[1] = fConfig;
builder.finish();
tex->resourcePriv().setUniqueKey(fLastFulfilledKey);
SkASSERT(fContextID == SK_InvalidUniqueID ||
fContextID == tex->getContext()->uniqueID());
fContextID = tex->getContext()->uniqueID();
promiseTexture->addKeyToInvalidate(fContextID, fLastFulfilledKey);
return std::move(tex);
}
private:
// The GrTexture's idle callback mechanism is used to call the client's Release proc via
// this class. This also owns a ref counted helper that calls the client's ReleaseProc when
// the ref count reaches zero. The callback and any Fulfilled but un-Released texture share
// ownership of the IdleContext. Thus, the IdleContext is destroyed and calls the Done proc
// after the last fulfilled texture goes idle and calls the Release proc or the proxy's
// destructor destroys the lazy callback, whichever comes last.
class IdleContext {
public:
class PromiseImageReleaseContext;
IdleContext() = default;
~IdleContext() = default;
void addImageReleaseContext(sk_sp<PromiseImageReleaseContext> context) {
fReleaseContexts.addToHead(std::move(context));
}
static void IdleProc(void* context) {
IdleContext* idleContext = static_cast<IdleContext*>(context);
for (ReleaseContextList::Iter iter = idleContext->fReleaseContexts.headIter();
iter.get();
iter.next()) {
(*iter.get())->release();
}
idleContext->fReleaseContexts.reset();
delete idleContext;
}
class PromiseImageReleaseContext : public SkNVRefCnt<PromiseImageReleaseContext> {
public:
PromiseImageReleaseContext(PromiseImageTextureReleaseProc releaseProc,
PromiseImageTextureContext textureContext,
sk_sp<GrReleaseProcHelper> doneHelper)
: fReleaseProc(releaseProc)
, fTextureContext(textureContext)
, fDoneHelper(std::move(doneHelper)) {}
~PromiseImageReleaseContext() { SkASSERT(fIsReleased); }
void release() {
SkASSERT(!fIsReleased);
fReleaseProc(fTextureContext);
fIsReleased = true;
}
void notifyWasFulfilled() { fIsReleased = false; }
bool isReleased() const { return fIsReleased; }
PromiseImageTextureContext textureContext() const { return fTextureContext; }
private:
PromiseImageTextureReleaseProc fReleaseProc;
PromiseImageTextureContext fTextureContext;
sk_sp<GrReleaseProcHelper> fDoneHelper;
bool fIsReleased = true;
};
private:
using ReleaseContextList = SkTLList<sk_sp<PromiseImageReleaseContext>, 4>;
ReleaseContextList fReleaseContexts;
};
void addToIdleContext(GrTexture* texture) {
SkASSERT(!fReleaseContext->isReleased());
IdleContext* idleContext = static_cast<IdleContext*>(texture->idleContext());
if (!idleContext) {
idleContext = new IdleContext();
texture->setIdleProc(IdleContext::IdleProc, idleContext);
}
idleContext->addImageReleaseContext(fReleaseContext);
}
sk_sp<IdleContext::PromiseImageReleaseContext> fReleaseContext;
PromiseImageTextureFulfillProc fFulfillProc;
GrPixelConfig fConfig;
// ID of the last SkPromiseImageTexture given to us by the client.
uint32_t fLastFulfillID = 0;
// ID of the GrContext that we are interacting with.
uint32_t fContextID = SK_InvalidUniqueID;
GrUniqueKey fLastFulfilledKey;
} callback(fulfillProc, releaseProc, doneProc, textureContext, config);
GrProxyProvider* proxyProvider = context->contextPriv().proxyProvider();
GrSurfaceDesc desc;
desc.fWidth = width;
desc.fHeight = height;
desc.fConfig = config;
// We pass kReadOnly here since we should treat content of the client's texture as immutable.
return proxyProvider->createLazyProxy(std::move(callback), backendFormat, desc, origin,
mipMapped, GrInternalSurfaceFlags::kReadOnly,
SkBackingFit::kExact, SkBudgeted::kNo,
GrSurfaceProxy::LazyInstantiationType::kDeinstantiate);
}
| 40.93482 | 100 | 0.60352 | luigi-rosso |
0e754647e6ffac51be83aaeb38ed75e23f8b6cb2 | 3,752 | cpp | C++ | src/LiteHtml/gumbo.v110/string_buffer.cpp | BclEx/h3ml | acfcccbdadcffa7b2c1794393a26359ad7c8479b | [
"MIT"
] | null | null | null | src/LiteHtml/gumbo.v110/string_buffer.cpp | BclEx/h3ml | acfcccbdadcffa7b2c1794393a26359ad7c8479b | [
"MIT"
] | null | null | null | src/LiteHtml/gumbo.v110/string_buffer.cpp | BclEx/h3ml | acfcccbdadcffa7b2c1794393a26359ad7c8479b | [
"MIT"
] | null | null | null | // Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: jdtang@google.com (Jonathan Tang)
#include "string_buffer.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "strings.h"
#include "string_piece.h"
#include "util.h"
struct GumboInternalParser;
// Size chosen via statistical analysis of ~60K websites.
// 99% of text nodes and 98% of attribute names/values fit in this initial size.
static const size_t kDefaultStringBufferSize = 5;
static void maybe_resize_string_buffer(struct GumboInternalParser* parser,
size_t additional_chars, GumboStringBuffer* buffer) {
size_t new_length = buffer->length + additional_chars;
size_t new_capacity = buffer->capacity;
while (new_capacity < new_length) {
new_capacity *= 2;
}
if (new_capacity != buffer->capacity) {
char* new_data = (char*)gumbo_parser_allocate(parser, new_capacity);
memcpy(new_data, buffer->data, buffer->length);
gumbo_parser_deallocate(parser, buffer->data);
buffer->data = new_data;
buffer->capacity = new_capacity;
}
}
void gumbo_string_buffer_init(
struct GumboInternalParser* parser, GumboStringBuffer* output) {
output->data = (char*)gumbo_parser_allocate(parser, kDefaultStringBufferSize);
output->length = 0;
output->capacity = kDefaultStringBufferSize;
}
void gumbo_string_buffer_reserve(struct GumboInternalParser* parser,
size_t min_capacity, GumboStringBuffer* output) {
maybe_resize_string_buffer(parser, min_capacity - output->length, output);
}
void gumbo_string_buffer_append_codepoint(
struct GumboInternalParser* parser, int c, GumboStringBuffer* output) {
// num_bytes is actually the number of continuation bytes, 1 less than the
// total number of bytes. This is done to keep the loop below simple and
// should probably change if we unroll it.
int num_bytes, prefix;
if (c <= 0x7f) {
num_bytes = 0;
prefix = 0;
} else if (c <= 0x7ff) {
num_bytes = 1;
prefix = 0xc0;
} else if (c <= 0xffff) {
num_bytes = 2;
prefix = 0xe0;
} else {
num_bytes = 3;
prefix = 0xf0;
}
maybe_resize_string_buffer(parser, num_bytes + 1, output);
output->data[output->length++] = prefix | (c >> (num_bytes * 6));
for (int i = num_bytes - 1; i >= 0; --i) {
output->data[output->length++] = 0x80 | (0x3f & (c >> (i * 6)));
}
}
void gumbo_string_buffer_append_string(struct GumboInternalParser* parser,
GumboStringPiece* str, GumboStringBuffer* output) {
maybe_resize_string_buffer(parser, str->length, output);
memcpy(output->data + output->length, str->data, str->length);
output->length += str->length;
}
char* gumbo_string_buffer_to_string(
struct GumboInternalParser* parser, GumboStringBuffer* input) {
char* buffer = (char*)gumbo_parser_allocate(parser, input->length + 1);
memcpy(buffer, input->data, input->length);
buffer[input->length] = '\0';
return buffer;
}
void gumbo_string_buffer_clear(
struct GumboInternalParser* parser, GumboStringBuffer* input) {
input->length = 0;
}
void gumbo_string_buffer_destroy(
struct GumboInternalParser* parser, GumboStringBuffer* buffer) {
gumbo_parser_deallocate(parser, buffer->data);
}
| 33.801802 | 80 | 0.72468 | BclEx |
0e760a06a3469354a94d3f1f3f418a2226d6b830 | 1,841 | cpp | C++ | GPIO.cpp | Compotes/robocup-2018 | 546e4fab33403866a460d058775f6e619c80649a | [
"MIT"
] | null | null | null | GPIO.cpp | Compotes/robocup-2018 | 546e4fab33403866a460d058775f6e619c80649a | [
"MIT"
] | null | null | null | GPIO.cpp | Compotes/robocup-2018 | 546e4fab33403866a460d058775f6e619c80649a | [
"MIT"
] | null | null | null | #include "GPIO.hpp"
using namespace std;
void init_gpio() {
cout << "STARTING GPIO" << endl;
fstream sys_unexport;
sys_unexport.open(GPIO_DIR + "unexport", ios::out);
sys_unexport << DRIBBLER_READ_GPIO << endl;
sys_unexport << DRIBBLER_WRITE_GPIO << endl;
sys_unexport << COMPASS_RESET_READ_GPIO << endl;
sys_unexport << COMPASS_RESET_WRITE_GPIO;
sys_unexport.close();
fstream sys_export;
sys_export.open(GPIO_DIR + "export", ios::out);
sys_export << DRIBBLER_READ_GPIO << endl;
sys_export << DRIBBLER_WRITE_GPIO << endl;
sys_export << COMPASS_RESET_READ_GPIO << endl;
sys_export << COMPASS_RESET_WRITE_GPIO;
sys_export.close();
fstream sys_gpio_out;
sys_gpio_out.open(GPIO_DIR + "gpio" + to_string(DRIBBLER_WRITE_GPIO) + "/direction", ios::out);
sys_gpio_out << "out" << endl;
sys_gpio_out.close();
sys_gpio_out.open(GPIO_DIR + "gpio" + to_string(COMPASS_RESET_WRITE_GPIO) + "/direction", ios::out);
sys_gpio_out << "out" << endl;
sys_gpio_out.close();
fstream sys_gpio_in;
sys_gpio_in.open(GPIO_DIR + "gpio" + to_string(DRIBBLER_READ_GPIO) + "/direction", ios::out);
sys_gpio_in << "in" << endl;
sys_gpio_in.close();
sys_gpio_in.open(GPIO_DIR + "gpio" + to_string(COMPASS_RESET_READ_GPIO) + "/direction", ios::out);
sys_gpio_in << "in" << endl;
sys_gpio_in.close();
sys_gpio_in.open(GPIO_DIR + "gpio" + to_string(DRIBBLER_READ_GPIO) + "/active_low", ios::out);
sys_gpio_in << "1" << endl;
sys_gpio_in.close();
sys_gpio_in.open(GPIO_DIR + "gpio" + to_string(COMPASS_RESET_READ_GPIO) + "/active_low", ios::out);
sys_gpio_in << "1" << endl;
sys_gpio_in.close();
}
int get_gpio_status(int gpio) {
fstream gpio_file;
gpio_file.open(GPIO_DIR + "gpio" + to_string(gpio) + "/value", ios::in);
string line;
getline(gpio_file, line);
int val = atoi(line.c_str());
gpio_file.close();
return val;
}
| 31.20339 | 101 | 0.716458 | Compotes |
0e7aec567a5d57ddaa9a863d0eeed33a0276724b | 3,387 | cpp | C++ | Timestamp.cpp | matijalukic/subtitly | c7001fd6c70019c6ed745b8726035486bd645dd4 | [
"MIT"
] | null | null | null | Timestamp.cpp | matijalukic/subtitly | c7001fd6c70019c6ed745b8726035486bd645dd4 | [
"MIT"
] | null | null | null | Timestamp.cpp | matijalukic/subtitly | c7001fd6c70019c6ed745b8726035486bd645dd4 | [
"MIT"
] | null | null | null | #include "Timestamp.h"
// Konstruktor na osnovu double-a
Timestamp::Timestamp(double sekundi)
: seconds(sekundi)
{}
double Timestamp::getSeconds() const { return seconds; }
const string& Timestamp::getStringSec() const { return to_string(seconds); }
// ucitavanje na osnovu stringa
Timestamp::Timestamp(const string& newTime) throw(ErrTimeFormatFault) {
regex formatTime("([0-9]{1,3})\:([0-9]{2})\:([0-9]{2})\,([0-9]{3})");
smatch numbers;
regex_match(newTime, numbers, formatTime);
// Provera da li je validan datum
if (numbers.size() < 3) {
throw ErrTimeFormatFault(ErrTimeFormatFault::ErrType::STRERR);
}
// sati
long sati = stoul(numbers[1]);
// minuti
long minuti = stoul(numbers[2]);
// sekundi
long sekundi = stoul(numbers[3]);
// milisekundi
long milisekundi = stoul(numbers[4]);
seconds = sekundi + minuti * 60 + sati * 3600 + milisekundi*0.001;
}
// Ispis vremena
ostream& operator<<(ostream& outputStream, const Timestamp& time) {
return outputStream
<< setfill('0') << setw(2) << ((int)time.seconds) / 3600 << ":"
<< setfill('0') << setw(2) << (((int)time.seconds) / 60) % 60 << ":"
<< setfill('0') << setw(2) << ((int)time.seconds) % 60 << ","
<< setfill('0') << setw(3) << ((int) (time.seconds * 1000)) % 1000;
}
// Ispis u string
string Timestamp::timestampStirng() const{
char toReturn[12];
int hours = ((int)seconds) / 3600;
int minutes = ((int)seconds / 60) % 60;
int secs = (int)seconds % 60;
int miliseconds = ((int)(seconds * 1000)) % 1000;
sprintf(toReturn, "%.2d:%.2d:%.2d,%.3d", hours, minutes, secs, miliseconds);
return string(toReturn);
}
// operator >
bool Timestamp::operator>(const Timestamp& compare) const {
return seconds > compare.seconds;
}
// operator <
bool Timestamp::operator<(const Timestamp& compare) const {
return seconds < compare.seconds;
}
// da li je pre
bool Timestamp::isBefore(const Timestamp& compare) const{
return *this < compare;
}
// da li je posle
bool Timestamp::isAfter(const Timestamp& compare) const{
return *this > compare;
}
// da li su isti
bool Timestamp::operator==(Timestamp& compare){ // ako su do 3 decimale jednake
return ((int) seconds * 1000) == ((int) compare.seconds * 1000);
}
bool Timestamp::operator==(Timestamp& compare) const { // ako su do 3 decimale jednake
return ((int) seconds * 1000) == ((int) compare.seconds * 1000);
}
bool Timestamp::operator==(const Timestamp& compare) const { // ako su do 3 decimale jednake
return ((int) seconds * 1000) == ((int) compare.seconds * 1000);
}
bool Timestamp::operator!=(const Timestamp& compare) const {
return !(*this == compare);
}
// Sabiranje
Timestamp Timestamp::operator+(const Timestamp& add) {
Timestamp result;
result.seconds = seconds + add.seconds;
return result;
}
Timestamp& Timestamp::operator+=(const Timestamp& add) {
*this = *this + add; return *this;
}
// Oduzimanje
Timestamp Timestamp::operator-(const Timestamp& sub) {
Timestamp result;
result.seconds = seconds - sub.seconds;
return result;
}
Timestamp& Timestamp::operator-=(const Timestamp& sub){
*this = *this - sub; return *this; }
// Vraca sredinu izmedju dva vremena
Timestamp middle(const Timestamp& startTime, const Timestamp& endTime) {
double middleSecond = (startTime.seconds + endTime.seconds) / 2;
return Timestamp(middleSecond);
}
| 28.70339 | 92 | 0.667848 | matijalukic |
0e7cb8ae12f41cb208750a8a6617fa9a9a6517ec | 31,374 | cpp | C++ | lib/mayaUsd/render/vp2RenderDelegate/render_delegate.cpp | smithw-adsk/maya-usd | 3a2278111e631423ffa9bae28158a6d2299a200e | [
"Apache-2.0"
] | null | null | null | lib/mayaUsd/render/vp2RenderDelegate/render_delegate.cpp | smithw-adsk/maya-usd | 3a2278111e631423ffa9bae28158a6d2299a200e | [
"Apache-2.0"
] | 4 | 2020-05-04T19:21:26.000Z | 2020-05-08T15:30:38.000Z | lib/mayaUsd/render/vp2RenderDelegate/render_delegate.cpp | smithw-adsk/maya-usd | 3a2278111e631423ffa9bae28158a6d2299a200e | [
"Apache-2.0"
] | 1 | 2020-05-04T22:14:09.000Z | 2020-05-04T22:14:09.000Z | //
// Copyright 2020 Autodesk
//
// 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 "render_delegate.h"
#include "basisCurves.h"
#include "bboxGeom.h"
#include "instancer.h"
#include "material.h"
#include "mesh.h"
#include "render_pass.h"
#include <mayaUsd/render/vp2ShaderFragments/shaderFragments.h>
#include <pxr/imaging/hd/bprim.h>
#include <pxr/imaging/hd/camera.h>
#include <pxr/imaging/hd/instancer.h>
#include <pxr/imaging/hd/resourceRegistry.h>
#include <pxr/imaging/hd/rprim.h>
#include <pxr/imaging/hd/tokens.h>
#include <maya/MProfiler.h>
#include <boost/functional/hash.hpp>
#include <tbb/reader_writer_lock.h>
#include <tbb/spin_rw_mutex.h>
#include <unordered_map>
PXR_NAMESPACE_OPEN_SCOPE
namespace {
/*! \brief List of supported Rprims by VP2 render delegate
*/
inline const TfTokenVector& _SupportedRprimTypes()
{
static const TfTokenVector SUPPORTED_RPRIM_TYPES
= { HdPrimTypeTokens->basisCurves, HdPrimTypeTokens->mesh };
return SUPPORTED_RPRIM_TYPES;
}
/*! \brief List of supported Sprims by VP2 render delegate
*/
inline const TfTokenVector& _SupportedSprimTypes()
{
static const TfTokenVector r { HdPrimTypeTokens->material, HdPrimTypeTokens->camera };
return r;
}
/*! \brief List of supported Bprims by VP2 render delegate
*/
inline const TfTokenVector& _SupportedBprimTypes()
{
static const TfTokenVector r { HdPrimTypeTokens->texture };
return r;
}
const MString _diffuseColorParameterName = "diffuseColor"; //!< Shader parameter name
const MString _solidColorParameterName = "solidColor"; //!< Shader parameter name
const MString _pointSizeParameterName = "pointSize"; //!< Shader parameter name
const MString _curveBasisParameterName = "curveBasis"; //!< Shader parameter name
const MString _structOutputName = "outSurfaceFinal"; //!< Output struct name of the fallback shader
//! Enum class for fallback shader types
enum class FallbackShaderType
{
kCommon = 0,
kBasisCurvesLinear,
kBasisCurvesCubicBezier,
kBasisCurvesCubicBSpline,
kBasisCurvesCubicCatmullRom,
kCount
};
//! Total number of fallback shader types
constexpr size_t FallbackShaderTypeCount = static_cast<size_t>(FallbackShaderType::kCount);
//! Array of constant-color shader fragment names indexed by FallbackShaderType
const MString _fallbackShaderNames[] = { "FallbackShader",
"BasisCurvesLinearFallbackShader",
"BasisCurvesCubicFallbackShader",
"BasisCurvesCubicFallbackShader",
"BasisCurvesCubicFallbackShader" };
//! Array of varying-color shader fragment names indexed by FallbackShaderType
const MString _cpvFallbackShaderNames[] = { "FallbackCPVShader",
"BasisCurvesLinearCPVShader",
"BasisCurvesCubicCPVShader",
"BasisCurvesCubicCPVShader",
"BasisCurvesCubicCPVShader" };
//! "curveBasis" parameter values for three different cubic curves
const std::unordered_map<FallbackShaderType, int> _curveBasisParameterValueMapping
= { { FallbackShaderType::kBasisCurvesCubicBezier, 0 },
{ FallbackShaderType::kBasisCurvesCubicBSpline, 1 },
{ FallbackShaderType::kBasisCurvesCubicCatmullRom, 2 } };
//! Get the shader type needed by the given curveType and curveBasis
FallbackShaderType GetBasisCurvesShaderType(const TfToken& curveType, const TfToken& curveBasis)
{
FallbackShaderType type = FallbackShaderType::kCount;
if (curveType == HdTokens->linear) {
type = FallbackShaderType::kBasisCurvesLinear;
} else if (curveType == HdTokens->cubic) {
if (curveBasis == HdTokens->bezier) {
type = FallbackShaderType::kBasisCurvesCubicBezier;
} else if (curveBasis == HdTokens->bSpline) {
type = FallbackShaderType::kBasisCurvesCubicBSpline;
} else if (curveBasis == HdTokens->catmullRom) {
type = FallbackShaderType::kBasisCurvesCubicCatmullRom;
}
}
return type;
}
/*! \brief Color hash helper class, used by shader registry
*/
struct MColorHash
{
std::size_t operator()(const MColor& color) const
{
std::size_t seed = 0;
boost::hash_combine(seed, color.r);
boost::hash_combine(seed, color.g);
boost::hash_combine(seed, color.b);
boost::hash_combine(seed, color.a);
return seed;
}
};
/*! \brief Color-indexed shader map.
*/
struct MShaderMap
{
//! Shader registry
std::unordered_map<MColor, MHWRender::MShaderInstance*, MColorHash> _map;
//! Synchronization used to protect concurrent read from serial writes
tbb::spin_rw_mutex _mutex;
};
/*! \brief Shader cache.
*/
class MShaderCache final
{
public:
/*! \brief Initialize shaders.
*/
void Initialize()
{
if (_isInitialized)
return;
MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
const MHWRender::MShaderManager* shaderMgr
= renderer ? renderer->getShaderManager() : nullptr;
if (!TF_VERIFY(shaderMgr))
return;
_3dCPVSolidShader = shaderMgr->getStockShader(MHWRender::MShaderManager::k3dCPVSolidShader);
TF_VERIFY(_3dCPVSolidShader);
_3dFatPointShader = shaderMgr->getStockShader(MHWRender::MShaderManager::k3dFatPointShader);
if (TF_VERIFY(_3dFatPointShader)) {
constexpr float white[] = { 1.0f, 1.0f, 1.0f, 1.0f };
constexpr float size[] = { 5.0, 5.0 };
_3dFatPointShader->setParameter(_solidColorParameterName, white);
_3dFatPointShader->setParameter(_pointSizeParameterName, size);
}
for (size_t i = 0; i < FallbackShaderTypeCount; i++) {
MHWRender::MShaderInstance* shader
= shaderMgr->getFragmentShader(_cpvFallbackShaderNames[i], _structOutputName, true);
if (TF_VERIFY(shader)) {
FallbackShaderType type = static_cast<FallbackShaderType>(i);
const auto it = _curveBasisParameterValueMapping.find(type);
if (it != _curveBasisParameterValueMapping.end()) {
shader->setParameter(_curveBasisParameterName, it->second);
}
}
_fallbackCPVShaders[i] = shader;
}
_isInitialized = true;
}
/*! \brief Returns a fallback CPV shader instance when no material is bound.
*/
MHWRender::MShaderInstance* GetFallbackCPVShader(FallbackShaderType type) const
{
if (type >= FallbackShaderType::kCount) {
return nullptr;
}
const size_t index = static_cast<size_t>(type);
return _fallbackCPVShaders[index];
}
/*! \brief Returns a white 3d fat point shader.
*/
MHWRender::MShaderInstance* Get3dFatPointShader() const { return _3dFatPointShader; }
/*! \brief Returns a 3d CPV solid-color shader instance.
*/
MHWRender::MShaderInstance* Get3dCPVSolidShader() const { return _3dCPVSolidShader; }
/*! \brief Returns a 3d solid shader with the specified color.
*/
MHWRender::MShaderInstance* Get3dSolidShader(const MColor& color)
{
// Look for it first with reader lock
tbb::spin_rw_mutex::scoped_lock lock(_3dSolidShaders._mutex, false /*write*/);
auto it = _3dSolidShaders._map.find(color);
if (it != _3dSolidShaders._map.end()) {
return it->second;
}
// Upgrade to writer lock.
lock.upgrade_to_writer();
// Double check that it wasn't inserted by another thread
it = _3dSolidShaders._map.find(color);
if (it != _3dSolidShaders._map.end()) {
return it->second;
}
MHWRender::MShaderInstance* shader = nullptr;
MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
const MHWRender::MShaderManager* shaderMgr
= renderer ? renderer->getShaderManager() : nullptr;
if (TF_VERIFY(shaderMgr)) {
shader = shaderMgr->getStockShader(MHWRender::MShaderManager::k3dSolidShader);
if (TF_VERIFY(shader)) {
const float solidColor[] = { color.r, color.g, color.b, color.a };
shader->setParameter(_solidColorParameterName, solidColor);
// Insert instance we just created
_3dSolidShaders._map[color] = shader;
}
}
return shader;
}
/*! \brief Returns a fallback shader instance when no material is bound.
This method is keeping registry of all fallback shaders generated,
allowing only one instance per color which enables consolidation of
draw calls with same shader instance.
\param color Color to set on given shader instance
\param index Index to the required shader name in _fallbackShaderNames
\return A new or existing copy of shader instance with given color
*/
MHWRender::MShaderInstance* GetFallbackShader(const MColor& color, FallbackShaderType type)
{
if (type >= FallbackShaderType::kCount) {
return nullptr;
}
const size_t index = static_cast<size_t>(type);
auto& shaderMap = _fallbackShaders[index];
// Look for it first with reader lock
tbb::spin_rw_mutex::scoped_lock lock(shaderMap._mutex, false /*write*/);
auto it = shaderMap._map.find(color);
if (it != shaderMap._map.end()) {
return it->second;
}
// Upgrade to writer lock.
lock.upgrade_to_writer();
// Double check that it wasn't inserted by another thread
it = shaderMap._map.find(color);
if (it != shaderMap._map.end()) {
return it->second;
}
MHWRender::MShaderInstance* shader = nullptr;
// If the map is not empty, clone any existing shader instance in the
// map instead of acquiring via MShaderManager::getFragmentShader(),
// which creates new shader fragment graph for each shader instance
// and causes expensive shader compilation and rebinding.
it = shaderMap._map.begin();
if (it != shaderMap._map.end()) {
shader = it->second->clone();
} else {
MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
const MHWRender::MShaderManager* shaderMgr
= renderer ? renderer->getShaderManager() : nullptr;
if (TF_VERIFY(shaderMgr)) {
shader = shaderMgr->getFragmentShader(
_fallbackShaderNames[index], _structOutputName, true);
if (TF_VERIFY(shader)) {
const auto it = _curveBasisParameterValueMapping.find(type);
if (it != _curveBasisParameterValueMapping.end()) {
shader->setParameter(_curveBasisParameterName, it->second);
}
}
}
}
// Insert the new shader instance
if (TF_VERIFY(shader)) {
float diffuseColor[] = { color.r, color.g, color.b, color.a };
shader->setParameter(_diffuseColorParameterName, diffuseColor);
shaderMap._map[color] = shader;
}
return shader;
}
private:
bool _isInitialized { false }; //!< Whether the shader cache is initialized
//! Shader registry used by fallback shaders
MShaderMap _fallbackShaders[FallbackShaderTypeCount];
MShaderMap _3dSolidShaders;
//!< Fallback shaders with CPV support
MHWRender::MShaderInstance* _fallbackCPVShaders[FallbackShaderTypeCount] { nullptr };
MHWRender::MShaderInstance* _3dFatPointShader { nullptr }; //!< 3d shader for points
MHWRender::MShaderInstance* _3dCPVSolidShader { nullptr }; //!< 3d CPV solid-color shader
};
MShaderCache sShaderCache; //!< Global shader cache to minimize the number of unique shaders.
/*! \brief Sampler state desc hash helper class, used by sampler state cache.
*/
struct MSamplerStateDescHash
{
std::size_t operator()(const MHWRender::MSamplerStateDesc& desc) const
{
std::size_t seed = 0;
boost::hash_combine(seed, desc.filter);
boost::hash_combine(seed, desc.comparisonFn);
boost::hash_combine(seed, desc.addressU);
boost::hash_combine(seed, desc.addressV);
boost::hash_combine(seed, desc.addressW);
boost::hash_combine(seed, desc.borderColor[0]);
boost::hash_combine(seed, desc.borderColor[1]);
boost::hash_combine(seed, desc.borderColor[2]);
boost::hash_combine(seed, desc.borderColor[3]);
boost::hash_combine(seed, desc.mipLODBias);
boost::hash_combine(seed, desc.minLOD);
boost::hash_combine(seed, desc.maxLOD);
boost::hash_combine(seed, desc.maxAnisotropy);
boost::hash_combine(seed, desc.coordCount);
boost::hash_combine(seed, desc.elementIndex);
return seed;
}
};
/*! Sampler state desc equality helper class, used by sampler state cache.
*/
struct MSamplerStateDescEquality
{
bool
operator()(const MHWRender::MSamplerStateDesc& a, const MHWRender::MSamplerStateDesc& b) const
{
return (
a.filter == b.filter && a.comparisonFn == b.comparisonFn && a.addressU == b.addressU
&& a.addressV == b.addressV && a.addressW == b.addressW
&& a.borderColor[0] == b.borderColor[0] && a.borderColor[1] == b.borderColor[1]
&& a.borderColor[2] == b.borderColor[2] && a.borderColor[3] == b.borderColor[3]
&& a.mipLODBias == b.mipLODBias && a.minLOD == b.minLOD && a.maxLOD == b.maxLOD
&& a.maxAnisotropy == b.maxAnisotropy && a.coordCount == b.coordCount
&& a.elementIndex == b.elementIndex);
}
};
using MSamplerStateCache = std::unordered_map<
MHWRender::MSamplerStateDesc,
const MHWRender::MSamplerState*,
MSamplerStateDescHash,
MSamplerStateDescEquality>;
MSamplerStateCache sSamplerStates; //!< Sampler state cache
tbb::spin_rw_mutex
sSamplerRWMutex; //!< Synchronization used to protect concurrent read from serial writes
const HdVP2BBoxGeom* sSharedBBoxGeom
= nullptr; //!< Shared geometry for all Rprims to display bounding box
} // namespace
const int HdVP2RenderDelegate::sProfilerCategory = MProfiler::addCategory(
#if MAYA_API_VERSION >= 20190000
"HdVP2RenderDelegate",
"HdVP2RenderDelegate"
#else
"HdVP2RenderDelegate"
#endif
);
std::mutex HdVP2RenderDelegate::_renderDelegateMutex;
std::atomic_int HdVP2RenderDelegate::_renderDelegateCounter;
HdResourceRegistrySharedPtr HdVP2RenderDelegate::_resourceRegistry;
/*! \brief Constructor.
*/
HdVP2RenderDelegate::HdVP2RenderDelegate(ProxyRenderDelegate& drawScene)
{
_id = SdfPath(TfToken(TfStringPrintf("/HdVP2RenderDelegate_%p", this)));
std::lock_guard<std::mutex> guard(_renderDelegateMutex);
if (_renderDelegateCounter.fetch_add(1) == 0) {
_resourceRegistry.reset(new HdResourceRegistry());
// HdVP2BBoxGeom can only be instantiated during the lifetime of VP2
// renderer from main thread. HdVP2RenderDelegate is created from main
// thread currently, if we need to make its creation parallel in the
// future we should move this code out.
if (TF_VERIFY(sSharedBBoxGeom == nullptr)) {
sSharedBBoxGeom = new HdVP2BBoxGeom();
}
}
_renderParam.reset(new HdVP2RenderParam(drawScene));
// Shader fragments can only be registered after VP2 initialization, thus the function cannot
// be called when loading plugin (which can happen before VP2 initialization in the case of
// command-line rendering). The fragments will be deregistered when plugin is unloaded.
HdVP2ShaderFragments::registerFragments();
// The shader cache should be initialized after registration of shader fragments.
sShaderCache.Initialize();
}
/*! \brief Destructor.
*/
HdVP2RenderDelegate::~HdVP2RenderDelegate()
{
std::lock_guard<std::mutex> guard(_renderDelegateMutex);
if (_renderDelegateCounter.fetch_sub(1) == 1) {
_resourceRegistry.reset();
if (TF_VERIFY(sSharedBBoxGeom)) {
delete sSharedBBoxGeom;
sSharedBBoxGeom = nullptr;
}
}
}
/*! \brief Return delegate's HdVP2RenderParam, giving access to things like MPxSubSceneOverride.
*/
HdRenderParam* HdVP2RenderDelegate::GetRenderParam() const { return _renderParam.get(); }
/*! \brief Notification to commit resources to GPU & compute before rendering
This notification sent by HdEngine happens after parallel synchronization of data,
prim's via VP2 resource registry are inserting work to commit. Now is the time
on main thread to commit resources and compute missing streams.
In future we will better leverage evaluation time to perform synchronization
of data and allow main-thread task execution during the compute as it's done
for the rest of VP2 synchronization with DG data.
*/
void HdVP2RenderDelegate::CommitResources(HdChangeTracker* tracker)
{
TF_UNUSED(tracker);
MProfilingScope profilingScope(sProfilerCategory, MProfiler::kColorC_L2, "Commit resources");
// --------------------------------------------------------------------- //
// RESOLVE, COMPUTE & COMMIT PHASE
// --------------------------------------------------------------------- //
// All the required input data is now resident in memory, next we must:
//
// 1) Execute compute as needed for normals, tessellation, etc.
// 2) Commit resources to the GPU.
// 3) Update any scene-level acceleration structures.
_resourceRegistryVP2.Commit();
}
/*! \brief Return a list of which Rprim types can be created by this class's.
*/
const TfTokenVector& HdVP2RenderDelegate::GetSupportedRprimTypes() const
{
return _SupportedRprimTypes();
}
/*! \brief Return a list of which Sprim types can be created by this class's.
*/
const TfTokenVector& HdVP2RenderDelegate::GetSupportedSprimTypes() const
{
return _SupportedSprimTypes();
}
/*! \brief Return a list of which Bprim types can be created by this class's.
*/
const TfTokenVector& HdVP2RenderDelegate::GetSupportedBprimTypes() const
{
return _SupportedBprimTypes();
}
/*! \brief Return unused global resource registry.
*/
HdResourceRegistrySharedPtr HdVP2RenderDelegate::GetResourceRegistry() const
{
return _resourceRegistry;
}
/*! \brief Return VP2 resource registry, holding access to commit execution enqueue.
*/
HdVP2ResourceRegistry& HdVP2RenderDelegate::GetVP2ResourceRegistry()
{
return _resourceRegistryVP2;
}
/*! \brief Create a renderpass for rendering a given collection.
*/
HdRenderPassSharedPtr
HdVP2RenderDelegate::CreateRenderPass(HdRenderIndex* index, const HdRprimCollection& collection)
{
return HdRenderPassSharedPtr(new HdVP2RenderPass(this, index, collection));
}
/*! \brief Request to create a new VP2 instancer.
\param id The unique identifier of this instancer.
\param instancerId The unique identifier for the parent instancer that
uses this instancer as a prototype (may be empty).
\return A pointer to the new instancer or nullptr on error.
*/
HdInstancer* HdVP2RenderDelegate::CreateInstancer(
HdSceneDelegate* delegate,
#if defined(HD_API_VERSION) && HD_API_VERSION >= 36
const SdfPath& id)
{
return new HdVP2Instancer(delegate, id);
#else
const SdfPath& id,
const SdfPath& instancerId)
{
return new HdVP2Instancer(delegate, id, instancerId);
#endif
}
/*! \brief Destroy instancer instance
*/
void HdVP2RenderDelegate::DestroyInstancer(HdInstancer* instancer) { delete instancer; }
/*! \brief Request to Allocate and Construct a new, VP2 specialized Rprim.
\param typeId the type identifier of the prim to allocate
\param rprimId a unique identifier for the prim
\param instancerId the unique identifier for the instancer that uses
the prim (optional: May be empty).
\return A pointer to the new prim or nullptr on error.
*/
HdRprim* HdVP2RenderDelegate::CreateRprim(
const TfToken& typeId,
#if defined(HD_API_VERSION) && HD_API_VERSION >= 36
const SdfPath& rprimId)
#else
const SdfPath& rprimId,
const SdfPath& instancerId)
#endif
{
if (typeId == HdPrimTypeTokens->mesh) {
#if defined(HD_API_VERSION) && HD_API_VERSION >= 36
return new HdVP2Mesh(this, rprimId);
#else
return new HdVP2Mesh(this, rprimId, instancerId);
#endif
}
if (typeId == HdPrimTypeTokens->basisCurves) {
#if defined(HD_API_VERSION) && HD_API_VERSION >= 36
return new HdVP2BasisCurves(this, rprimId);
#else
return new HdVP2BasisCurves(this, rprimId, instancerId);
#endif
}
// if (typeId == HdPrimTypeTokens->volume) {
// #if defined(HD_API_VERSION) && HD_API_VERSION >= 36
// return new HdVP2Volume(this, rprimId);
// #else
// return new HdVP2Volume(this, rprimId, instancerId);
// #endif
//}
TF_CODING_ERROR("Unknown Rprim Type %s", typeId.GetText());
return nullptr;
}
/*! \brief Destroy & deallocate Rprim instance
*/
void HdVP2RenderDelegate::DestroyRprim(HdRprim* rPrim) { delete rPrim; }
/*! \brief Request to Allocate and Construct a new, VP2 specialized Sprim.
\param typeId the type identifier of the prim to allocate
\param sprimId a unique identifier for the prim
\return A pointer to the new prim or nullptr on error.
*/
HdSprim* HdVP2RenderDelegate::CreateSprim(const TfToken& typeId, const SdfPath& sprimId)
{
if (typeId == HdPrimTypeTokens->material) {
return new HdVP2Material(this, sprimId);
}
if (typeId == HdPrimTypeTokens->camera) {
return new HdCamera(sprimId);
}
/*
if (typeId == HdPrimTypeTokens->sphereLight) {
return HdVP2Light::CreatePointLight(this, sprimId);
}
if (typeId == HdPrimTypeTokens->distantLight) {
return HdVP2Light::CreateDistantLight(this, sprimId);
}
if (typeId == HdPrimTypeTokens->diskLight) {
return HdVP2Light::CreateDiskLight(this, sprimId);
}
if (typeId == HdPrimTypeTokens->rectLight) {
return HdVP2Light::CreateRectLight(this, sprimId);
}
if (typeId == HdPrimTypeTokens->cylinderLight) {
return HdVP2Light::CreateCylinderLight(this, sprimId);
}
if (typeId == HdPrimTypeTokens->domeLight) {
return HdVP2Light::CreateDomeLight(this, sprimId);
}
*/
TF_CODING_ERROR("Unknown Sprim Type %s", typeId.GetText());
return nullptr;
}
/*! \brief Request to Allocate and Construct an Sprim to use as a standin, if there
if an error with another another Sprim of the same type.For example,
if another prim references a non - exisiting Sprim, the fallback could
be used.
\param typeId the type identifier of the prim to allocate
\return A pointer to the new prim or nullptr on error.
*/
HdSprim* HdVP2RenderDelegate::CreateFallbackSprim(const TfToken& typeId)
{
if (typeId == HdPrimTypeTokens->material) {
return new HdVP2Material(this, SdfPath::EmptyPath());
}
if (typeId == HdPrimTypeTokens->camera) {
return new HdCamera(SdfPath::EmptyPath());
}
/*
if (typeId == HdPrimTypeTokens->sphereLight) {
return HdVP2Light::CreatePointLight(this, SdfPath::EmptyPath());
}
if (typeId == HdPrimTypeTokens->distantLight) {
return HdVP2Light::CreateDistantLight(this, SdfPath::EmptyPath());
}
if (typeId == HdPrimTypeTokens->diskLight) {
return HdVP2Light::CreateDiskLight(this, SdfPath::EmptyPath());
}
if (typeId == HdPrimTypeTokens->rectLight) {
return HdVP2Light::CreateRectLight(this, SdfPath::EmptyPath());
}
if (typeId == HdPrimTypeTokens->cylinderLight) {
return HdVP2Light::CreateCylinderLight(this, SdfPath::EmptyPath());
}
if (typeId == HdPrimTypeTokens->domeLight) {
return HdVP2Light::CreateDomeLight(this, SdfPath::EmptyPath());
}
*/
TF_CODING_ERROR("Unknown Sprim Type %s", typeId.GetText());
return nullptr;
}
/*! \brief Destroy & deallocate Sprim instance
*/
void HdVP2RenderDelegate::DestroySprim(HdSprim* sPrim) { delete sPrim; }
/*! \brief Request to Allocate and Construct a new, VP2 specialized Bprim.
\param typeId the type identifier of the prim to allocate
\param sprimId a unique identifier for the prim
\return A pointer to the new prim or nullptr on error.
*/
HdBprim* HdVP2RenderDelegate::CreateBprim(const TfToken& typeId, const SdfPath& bprimId)
{
/*
if (typeId == HdPrimTypeTokens->texture) {
return new HdVP2Texture(this, bprimId);
}
if (typeId == HdPrimTypeTokens->renderBuffer) {
return new HdVP2RenderBuffer(bprimId);
}
if (typeId == _tokens->openvdbAsset) {
return new HdVP2OpenvdbAsset(this, bprimId);
}
TF_CODING_ERROR("Unknown Bprim Type %s", typeId.GetText());
*/
return nullptr;
}
/*! \brief Request to Allocate and Construct a Bprim to use as a standin, if there
if an error with another another Bprim of the same type. For example,
if another prim references a non-exisiting Bprim, the fallback could
be used.
\param typeId the type identifier of the prim to allocate
\return A pointer to the new prim or nullptr on error.
*/
HdBprim* HdVP2RenderDelegate::CreateFallbackBprim(const TfToken& typeId)
{
/*
if (typeId == HdPrimTypeTokens->texture) {
return new HdVP2Texture(this, SdfPath::EmptyPath());
}
if (typeId == HdPrimTypeTokens->renderBuffer) {
return new HdVP2RenderBuffer(SdfPath::EmptyPath());
}
if (typeId == _tokens->openvdbAsset) {
return new HdVP2OpenvdbAsset(this, SdfPath::EmptyPath());
}
TF_CODING_ERROR("Unknown Bprim Type %s", typeId.GetText());
*/
return nullptr;
}
/*! \brief Destroy & deallocate Bprim instance
*/
void HdVP2RenderDelegate::DestroyBprim(HdBprim* bPrim) { delete bPrim; }
/*! \brief Returns a token that indicates material bindings purpose.
The full material purpose is suggested according to
https://github.com/PixarAnimationStudios/USD/pull/853
*/
TfToken HdVP2RenderDelegate::GetMaterialBindingPurpose() const { return HdTokens->full; }
/*! \brief Returns a node name made as a child of delegate's id.
*/
MString HdVP2RenderDelegate::GetLocalNodeName(const MString& name) const
{
return MString(_id.AppendChild(TfToken(name.asChar())).GetText());
}
/*! \brief Returns a fallback shader instance when no material is bound.
This method is keeping registry of all fallback shaders generated, allowing only
one instance per color which enables consolidation of render calls with same shader
instance.
\param color Color to set on given shader instance
\return A new or existing copy of shader instance with given color parameter set
*/
MHWRender::MShaderInstance* HdVP2RenderDelegate::GetFallbackShader(const MColor& color) const
{
return sShaderCache.GetFallbackShader(color, FallbackShaderType::kCommon);
}
/*! \brief Returns a constant-color fallback shader instance for basisCurves when no material is
bound.
This method is keeping registry of all fallback shaders generated, keeping minimal number of
shader instances.
\param curveType The curve type
\param curveBasis The curve basis
\param color Color to set on given shader instance
\return A new or existing copy of shader instance with given color parameter set
*/
MHWRender::MShaderInstance* HdVP2RenderDelegate::GetBasisCurvesFallbackShader(
const TfToken& curveType,
const TfToken& curveBasis,
const MColor& color) const
{
FallbackShaderType type = GetBasisCurvesShaderType(curveType, curveBasis);
return sShaderCache.GetFallbackShader(color, type);
}
/*! \brief Returns a varying-color fallback shader instance for basisCurves when no material is
bound.
This method is keeping registry of all fallback shaders generated, keeping minimal number of
shader instances.
\param curveType The curve type
\param curveBasis The curve basis
\return A new or existing copy of shader instance with given color parameter set
*/
MHWRender::MShaderInstance* HdVP2RenderDelegate::GetBasisCurvesCPVShader(
const TfToken& curveType,
const TfToken& curveBasis) const
{
FallbackShaderType type = GetBasisCurvesShaderType(curveType, curveBasis);
return sShaderCache.GetFallbackCPVShader(type);
}
/*! \brief Returns a fallback CPV shader instance when no material is bound.
*/
MHWRender::MShaderInstance* HdVP2RenderDelegate::GetFallbackCPVShader() const
{
return sShaderCache.GetFallbackCPVShader(FallbackShaderType::kCommon);
}
/*! \brief Returns a 3d solid-color shader.
*/
MHWRender::MShaderInstance* HdVP2RenderDelegate::Get3dSolidShader(const MColor& color) const
{
return sShaderCache.Get3dSolidShader(color);
}
/*! \brief Returns a 3d CPV solid-color shader.
*/
MHWRender::MShaderInstance* HdVP2RenderDelegate::Get3dCPVSolidShader() const
{
return sShaderCache.Get3dCPVSolidShader();
}
/*! \brief Returns a white 3d fat point shader.
*/
MHWRender::MShaderInstance* HdVP2RenderDelegate::Get3dFatPointShader() const
{
return sShaderCache.Get3dFatPointShader();
}
/*! \brief Returns a sampler state as specified by the description.
*/
const MHWRender::MSamplerState*
HdVP2RenderDelegate::GetSamplerState(const MHWRender::MSamplerStateDesc& desc) const
{
// Look for it first with reader lock
tbb::spin_rw_mutex::scoped_lock lock(sSamplerRWMutex, false /*write*/);
auto it = sSamplerStates.find(desc);
if (it != sSamplerStates.end()) {
return it->second;
}
// Upgrade to writer lock.
lock.upgrade_to_writer();
// Double check that it wasn't inserted by another thread
it = sSamplerStates.find(desc);
if (it != sSamplerStates.end()) {
return it->second;
}
// Create and cache.
const MHWRender::MSamplerState* samplerState
= MHWRender::MStateManager::acquireSamplerState(desc);
sSamplerStates[desc] = samplerState;
return samplerState;
}
/*! \brief Returns the shared bbox geometry.
*/
const HdVP2BBoxGeom& HdVP2RenderDelegate::GetSharedBBoxGeom() const { return *sSharedBBoxGeom; }
PXR_NAMESPACE_CLOSE_SCOPE
| 35.331081 | 100 | 0.679767 | smithw-adsk |
0e82d78345fe92aae8799aa67bdcf118cedca4a3 | 1,055 | cc | C++ | 3rdparty/voro++-0.4.6/examples/walls/cylinder.cc | wgq-iapcm/Parvoro- | 9459e1081ff948628358c59207d5fcd8ce60ef8f | [
"BSD-3-Clause"
] | 51 | 2015-03-14T16:53:50.000Z | 2021-12-26T13:44:57.000Z | 3rdparty/voro++-0.4.6/examples/walls/cylinder.cc | wgq-iapcm/Parvoro- | 9459e1081ff948628358c59207d5fcd8ce60ef8f | [
"BSD-3-Clause"
] | 10 | 2015-11-11T23:12:56.000Z | 2020-11-20T20:23:01.000Z | 3rdparty/voro++-0.4.6/examples/walls/cylinder.cc | wgq-iapcm/Parvoro- | 9459e1081ff948628358c59207d5fcd8ce60ef8f | [
"BSD-3-Clause"
] | 21 | 2016-08-24T14:39:00.000Z | 2022-02-20T01:58:40.000Z | // Cylindrical wall example code
//
// Author : Chris H. Rycroft (LBL / UC Berkeley)
// Email : chr@alum.mit.edu
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-6.5,x_max=6.5;
const double y_min=-6.5,y_max=6.5;
const double z_min=0,z_max=18.5;
// Set the computational grid size
const int n_x=7,n_y=7,n_z=14;
int main() {
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block.
container con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
false,false,false,8);
// Add a cylindrical wall to the container
wall_cylinder cyl(0,0,0,0,0,1,6);
con.add_wall(cyl);
// Import the particles from a file
con.import("pack_cylinder");
// Output the particle positions in POV-Ray format
con.draw_particles_pov("cylinder_p.pov");
// Output the Voronoi cells in POV-Ray format
con.draw_cells_pov("cylinder_v.pov");
}
| 27.763158 | 69 | 0.723223 | wgq-iapcm |
0e85045f6321976fd3c0605d054f9f46c45b9f8e | 424 | hpp | C++ | src/windows/scene_tree.hpp | seigtm/meov | 2aeb87961df0602c2d36192d8589776463531059 | [
"MIT"
] | 1 | 2022-03-05T10:28:23.000Z | 2022-03-05T10:28:23.000Z | src/windows/scene_tree.hpp | seigtm/meov | 2aeb87961df0602c2d36192d8589776463531059 | [
"MIT"
] | 9 | 2022-01-25T07:44:34.000Z | 2022-03-15T07:09:16.000Z | src/windows/scene_tree.hpp | seigtm/meov | 2aeb87961df0602c2d36192d8589776463531059 | [
"MIT"
] | null | null | null | #pragma once
#include "base_window.hpp"
namespace meov::core {
class Scene;
} // namespace meov::core
namespace meov::Window {
class SceneTree final : public Base {
public:
explicit SceneTree() noexcept;
~SceneTree() override = default;
void Select(std::weak_ptr<core::Scene> &&scene);
private:
std::weak_ptr<core::Scene> mWrappedScene;
void DrawImpl() override;
};
} // namespace meov::Window
| 16.96 | 52 | 0.688679 | seigtm |
0e89458a372814d5436e5d6377fc90f9c44f65f1 | 1,551 | hpp | C++ | source/physics/physics_define.hpp | Paul-Wortmann/Grume | 0ffdd8f98e0b7d7857cc6a3e0f971f9a74651d17 | [
"Intel"
] | 3 | 2021-12-19T12:00:34.000Z | 2021-12-30T08:36:58.000Z | source/physics/physics_define.hpp | Paul-Wortmann/Grume | 0ffdd8f98e0b7d7857cc6a3e0f971f9a74651d17 | [
"Intel"
] | 2 | 2021-11-02T05:30:53.000Z | 2021-11-30T00:11:16.000Z | source/physics/physics_define.hpp | Paul-Wortmann/Grume | 0ffdd8f98e0b7d7857cc6a3e0f971f9a74651d17 | [
"Intel"
] | null | null | null | /**
* Copyright (C) Paul Wortmann
* This file is part of "Grume"
*
* "Grume" is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 only.
*
* "Grume" is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with "Grume" If not, see <http://www.gnu.org/licenses/>.
*
* @author Paul Wortmann
* @email physhex@gmail.com
* @website www.physhexgames.com
* @license GPL V2
* @date 2011-11-11
*/
#ifndef PHYISCS_DEFINE_HPP
#define PHYISCS_DEFINE_HPP
#include "../core/includes.hpp"
#include "physics_collision.hpp"
#include "physics_resolution.hpp"
// Event type enum
enum ePhysicsEventType : std::uint32_t { physicsEventType_none = 0, // null event
physicsEventType_collision = 1, // collision event
physicsEventType_objectClick = 2, // object click event
physicsEventType_tileClick = 3 }; // tile click event
// Event struct
struct sPhysicsEvent
{
sPhysicsEvent* next = nullptr;
ePhysicsEventType type = ePhysicsEventType::physicsEventType_none;
std::uint32_t data = 0;
};
#endif //PHYISCS_DEFINE_HPP
| 33 | 99 | 0.667311 | Paul-Wortmann |
0e92d4b9924a80bc2268c03ff4f02358b80b10d4 | 4,588 | cpp | C++ | src/ert/host/mmapfs.cpp | edgelesssys/edgelessrt | 848fb902d1da7c0adde5dfe61677cbb8ed8bd6de | [
"MIT"
] | 101 | 2020-06-19T09:14:41.000Z | 2022-03-28T03:14:09.000Z | src/ert/host/mmapfs.cpp | edgelesssys/edgelessrt | 848fb902d1da7c0adde5dfe61677cbb8ed8bd6de | [
"MIT"
] | 24 | 2020-07-20T09:45:44.000Z | 2022-01-10T09:56:46.000Z | src/ert/host/mmapfs.cpp | edgelesssys/edgelessrt | 848fb902d1da7c0adde5dfe61677cbb8ed8bd6de | [
"MIT"
] | 14 | 2020-07-18T17:17:35.000Z | 2022-01-06T03:29:06.000Z | // Copyright (c) Edgeless Systems GmbH.
// Licensed under the MIT License.
#include "../common/mmapfs.h"
#include <fcntl.h>
#include <openenclave/internal/syscall/types.h>
#include <openenclave/internal/trace.h>
#include <openenclave/internal/utils.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <cstddef>
#include <string_view>
#include "fd.h"
#include "syscall_u.h"
using namespace std;
using namespace ert;
static bool _writable(int flags)
{
return (flags & O_ACCMODE) == O_RDWR;
}
oe_host_fd_t ert_mmapfs_open_ocall(
const char* pathname,
int flags,
oe_mode_t mode,
void** addr,
size_t* file_size)
{
errno = 0;
FileDescriptor fd = open(pathname, flags, mode);
if (!fd)
return fd;
struct stat file_stat;
if (fstat(fd, &file_stat) == -1)
return -1;
*file_size = static_cast<size_t>(file_stat.st_size);
constexpr string_view file_size_tag = "EDG_SIZE";
static_assert(sizeof ert_mmapfs_file_size_t::tag == file_size_tag.size());
// recover real file size from appended ert_mmapfs_file_size_t if file has
// not been closed properly
if (*file_size >= sizeof(ert_mmapfs_file_size_t))
{
if (lseek(
fd,
-static_cast<off_t>(sizeof(ert_mmapfs_file_size_t)),
SEEK_END) < 0)
return -1;
ert_mmapfs_file_size_t stored_file_size{};
if (read(fd, &stored_file_size, sizeof stored_file_size) !=
sizeof stored_file_size)
return -1;
if (file_size_tag.compare(
0,
file_size_tag.size(),
stored_file_size.tag,
file_size_tag.size()) == 0)
{
if (stored_file_size.size > *file_size - sizeof stored_file_size)
return -1;
*file_size = stored_file_size.size;
}
}
// calculate map length
size_t len = *file_size;
if (len == 0)
len = OE_MMAP_FILE_CHUNK_SIZE;
len = oe_round_up_to_multiple(len, OE_MMAP_FILE_CHUNK_SIZE);
const size_t pos_file_size = len;
int mmap_prot = PROT_READ;
// extend file in case we want to write/append
// fd needs ~O_TRUNC & O_RDWR
if (_writable(flags))
{
len += sizeof(ert_mmapfs_file_size_t);
if (ftruncate(fd, (ssize_t)len) == -1)
return -1;
mmap_prot |= PROT_WRITE;
}
*addr = mmap(NULL, len, mmap_prot, MAP_SHARED, fd, 0);
if (*addr == MAP_FAILED)
return -1;
if (_writable(flags))
{
// append file size, which will be kept up-to-date by the enclave
auto& stored_file_size = *reinterpret_cast<ert_mmapfs_file_size_t*>(
static_cast<byte*>(*addr) + pos_file_size);
memcpy(
stored_file_size.tag, file_size_tag.data(), file_size_tag.size());
stored_file_size.size = *file_size;
}
return fd.release();
}
bool ert_mmapfs_close_ocall(
oe_host_fd_t fd,
int flags,
void* region,
size_t file_size)
{
errno = 0;
size_t region_size = OE_MMAP_FILE_CHUNK_SIZE;
if (file_size != 0)
region_size =
oe_round_up_to_multiple(file_size, OE_MMAP_FILE_CHUNK_SIZE);
if (_writable(flags))
region_size += sizeof(ert_mmapfs_file_size_t);
if (munmap(region, region_size) == -1)
return false;
if (_writable(flags))
{
if (ftruncate((int)fd, (off_t)file_size) == -1)
{
// file size stays aligned to MMAP_FILE_CHUNK_SIZE
OE_TRACE_ERROR("ftruncate host fd failed");
}
}
if (close((int)fd) == -1)
OE_TRACE_ERROR("close on host fd failed");
return true;
}
void* ert_mmapfs_extend_ocall(
oe_host_fd_t fd,
void* region,
size_t file_size,
size_t new_region_size)
{
errno = 0;
size_t cur_region_size =
oe_round_up_to_multiple(file_size, OE_MMAP_FILE_CHUNK_SIZE);
new_region_size += sizeof(ert_mmapfs_file_size_t);
// make sure we extend the file on disk appropriately
if (ftruncate((int)fd, (off_t)new_region_size) == -1)
return NULL;
const auto result =
mremap(region, cur_region_size, new_region_size, MREMAP_MAYMOVE);
if (result == MAP_FAILED)
return result;
// copy the appended file size to the new end
const auto p = static_cast<byte*>(result);
memcpy(
p + new_region_size - sizeof(ert_mmapfs_file_size_t),
p + cur_region_size,
sizeof(ert_mmapfs_file_size_t));
return result;
}
| 26.830409 | 78 | 0.62816 | edgelesssys |
0e94d0e5a3439d810d31e1f15f974b74ddbe961b | 1,785 | cpp | C++ | source/bsys/pad/pad_list.cpp | bluebackblue/brownie | 917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917 | [
"MIT"
] | null | null | null | source/bsys/pad/pad_list.cpp | bluebackblue/brownie | 917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917 | [
"MIT"
] | null | null | null | source/bsys/pad/pad_list.cpp | bluebackblue/brownie | 917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917 | [
"MIT"
] | null | null | null |
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief パッド。
*/
/** include
*/
#include <bsys_pch.h>
/** include
*/
#pragma warning(push)
#pragma warning(disable:4464)
#include "../types/types.h"
#pragma warning(pop)
/** include
*/
#include "./pad_list.h"
/** warning
4710 : この関数はインライン展開のために選択されましたが、コンパイラはインライン展開を実行しませんでした。
*/
#pragma warning(disable:4710)
/** NBsys::NPad
*/
#if(BSYS_PAD_ENABLE)
namespace NBsys{namespace NPad
{
/** constructor
*/
Pad_List::Pad_List(s32 a_virtualpad_max)
{
for(int ii=0;ii<a_virtualpad_max;ii++){
sharedptr<Pad_Virtual> t_virtual_pad(new Pad_Virtual(ii));
this->virtual_list.push_back(t_virtual_pad);
}
}
/** destructor
*/
Pad_List::~Pad_List()
{
}
/** デバイス追加。
*/
void Pad_List::AddDevice(sharedptr<Pad_Device_Base> a_device_instance)
{
this->device_list.push_back(a_device_instance);
}
/** 仮想パッド取得。
*/
sharedptr<Pad_Virtual>& Pad_List::GetVirtualPad(s32 a_virtualpad_index)
{
return this->virtual_list[static_cast<u32>(a_virtualpad_index)];
}
/** 更新。
*/
void Pad_List::Update(bool a_device_update)
{
//デバイスの更新。
if(a_device_update == true){
auto t_it_end = this->device_list.end();
for(auto t_it = this->device_list.begin();t_it!=t_it_end;++t_it){
if(*t_it != nullptr){
(*t_it)->DeviceUpdate();
}
}
}
//仮想パッド更新。
{
auto t_it_end = this->virtual_list.end();
for(auto t_it = this->virtual_list.begin();t_it!=t_it_end;++t_it){
if(*t_it != nullptr){
(*t_it)->Update();
}
}
}
}
}}
#endif
| 16.839623 | 73 | 0.626331 | bluebackblue |
0e970185d83b144d81f17a0485dac073493ff635 | 2,660 | cpp | C++ | Wavelength/src/Rendering/Renderer.cpp | RyanAlterman/Light | 68b5e740e1d960671866675834e29ec2196dd437 | [
"MIT"
] | null | null | null | Wavelength/src/Rendering/Renderer.cpp | RyanAlterman/Light | 68b5e740e1d960671866675834e29ec2196dd437 | [
"MIT"
] | null | null | null | Wavelength/src/Rendering/Renderer.cpp | RyanAlterman/Light | 68b5e740e1d960671866675834e29ec2196dd437 | [
"MIT"
] | null | null | null | #include "Renderer.hpp"
#include "glad/glad.h"
Renderer::Renderer() {
}
Renderer ::~Renderer() {
}
Renderer& Renderer::getInstance() {
static Renderer instance;
return instance;
}
void Renderer::initRenderer() {
const char* vertexSource =
"#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"layout (location = 1) in vec2 aTexCoord;\n"
"out vec2 TexCoord;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos, 1.0);\n"
" TexCoord = aTexCoord;\n"
"}\0";
const char* fragmentSource =
"#version 330 core\n"
"out vec4 FragColor;\n"
"in vec2 TexCoord;\n"
"uniform sampler2D ourTexture;\n"
"void main()\n"
"{\n"
" FragColor = texture(ourTexture, TexCoord);\n"
"}\n";
float vertices[]{
1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 0.0f, 1.0f};
unsigned int indices[]{
0, 1, 3,
1, 2, 3};
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
unsigned int VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
unsigned int EBO;
glGenBuffers(1, &EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// Shader work
unsigned int vertShader;
vertShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertShader, 1, &vertexSource, NULL);
glCompileShader(vertShader);
unsigned int fragShader;
fragShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragShader, 1, &fragmentSource, NULL);
glCompileShader(fragShader);
shader = glCreateProgram();
glAttachShader(shader, vertShader);
glAttachShader(shader, fragShader);
glLinkProgram(shader);
glDeleteShader(vertShader);
glDeleteShader(fragShader);
// Position Attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// Texture Attribute
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
}
void Renderer::shutdownRenderer() {
glDeleteVertexArrays(1, &VAO);
}
void Renderer::render() {
glUseProgram(shader);
glBindTexture(GL_TEXTURE_2D, texture.getTexture());
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
} | 27.142857 | 99 | 0.635338 | RyanAlterman |
0e9cb517eec5c20b03eb05ec367d15de16b19c04 | 815 | cpp | C++ | samples/snippets/cpp/VS_Snippets_Winforms/DataFormats_GetFormat/CPP/dataformats_getformat.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_Winforms/DataFormats_GetFormat/CPP/dataformats_getformat.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_Winforms/DataFormats_GetFormat/CPP/dataformats_getformat.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z |
// System::Windows::Forms::DataFormats::GetFormat(int)
/*
The following example demonstrates the 'GetFormat(int)' method of 'DataFormats'
class. It creates a 'DataFormats' Object* using a integer into the 'GetFormat' method.
By using the 'DatFormats' Object* it displays the format name with respective the id.
*/
#using <System.dll>
#using <System.Windows.Forms.dll>
// <Snippet1>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
// Create a DataFormats::Format for the Unicode data format.
DataFormats::Format^ myFormat = DataFormats::GetFormat( 13 );
// Display the contents of myFormat.
Console::WriteLine( "The Format Name corresponding to the ID {0} is :", myFormat->Id );
Console::WriteLine( myFormat->Name );
}
// </Snippet1>
| 30.185185 | 91 | 0.696933 | hamarb123 |
0e9efbb1a402f20d499a1c2a2d36187d55b9f35d | 5,158 | cc | C++ | cyber/transport/transceiver/rtps_transceiver_test.cc | aurora12344/project | f904643843c7c41d422b92fb53279475b4b0b1bd | [
"Apache-2.0"
] | 2 | 2019-01-15T08:34:59.000Z | 2019-01-15T08:35:00.000Z | cyber/transport/transceiver/rtps_transceiver_test.cc | aurora12344/project | f904643843c7c41d422b92fb53279475b4b0b1bd | [
"Apache-2.0"
] | null | null | null | cyber/transport/transceiver/rtps_transceiver_test.cc | aurora12344/project | f904643843c7c41d422b92fb53279475b4b0b1bd | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <gtest/gtest.h>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include "cyber/common/util.h"
#include "cyber/proto/unit_test.pb.h"
#include "cyber/transport/receiver/rtps_receiver.h"
#include "cyber/transport/transmitter/rtps_transmitter.h"
#include "cyber/transport/transport.h"
namespace apollo {
namespace cyber {
namespace transport {
class RtpsTransceiverTest : public ::testing::Test {
protected:
using TransmitterPtr = std::shared_ptr<Transmitter<proto::UnitTest>>;
using ReceiverPtr = std::shared_ptr<Receiver<proto::UnitTest>>;
RtpsTransceiverTest() : channel_name_("rtps_channel") {}
virtual ~RtpsTransceiverTest() {}
virtual void SetUp() {
RoleAttributes attr;
attr.set_channel_name(channel_name_);
attr.set_channel_id(common::Hash(channel_name_));
transmitter_a_ = std::make_shared<RtpsTransmitter<proto::UnitTest>>(
attr, Transport::Instance()->participant());
transmitter_b_ = std::make_shared<RtpsTransmitter<proto::UnitTest>>(
attr, Transport::Instance()->participant());
transmitter_a_->Enable();
transmitter_b_->Enable();
}
virtual void TearDown() {
transmitter_a_ = nullptr;
transmitter_b_ = nullptr;
}
std::string channel_name_;
TransmitterPtr transmitter_a_ = nullptr;
TransmitterPtr transmitter_b_ = nullptr;
};
TEST_F(RtpsTransceiverTest, constructor) {
RoleAttributes attr;
TransmitterPtr transmitter =
std::make_shared<RtpsTransmitter<proto::UnitTest>>(
attr, Transport::Instance()->participant());
ReceiverPtr receiver =
std::make_shared<RtpsReceiver<proto::UnitTest>>(attr, nullptr);
EXPECT_EQ(transmitter->seq_num(), 0);
auto& transmitter_id = transmitter->id();
auto& receiver_id = receiver->id();
EXPECT_NE(transmitter_id.ToString(), receiver_id.ToString());
}
TEST_F(RtpsTransceiverTest, enable_and_disable) {
// repeated call
transmitter_a_->Enable();
std::vector<proto::UnitTest> msgs;
RoleAttributes attr;
attr.set_channel_name(channel_name_);
attr.set_channel_id(common::Hash(channel_name_));
ReceiverPtr receiver = std::make_shared<RtpsReceiver<proto::UnitTest>>(
attr, [&msgs](const std::shared_ptr<proto::UnitTest>& msg,
const MessageInfo& msg_info, const RoleAttributes& attr) {
(void)msg_info;
(void)attr;
msgs.emplace_back(*msg);
});
receiver->Enable();
// repeated call
receiver->Enable();
ReceiverPtr receiver_null_cb =
std::make_shared<RtpsReceiver<proto::UnitTest>>(attr, nullptr);
receiver_null_cb->Enable();
auto msg = std::make_shared<proto::UnitTest>();
msg->set_class_name("RtpsTransceiverTest");
msg->set_case_name("enable_and_disable");
EXPECT_TRUE(transmitter_a_->Transmit(msg));
std::this_thread::sleep_for(std::chrono::milliseconds(200));
EXPECT_EQ(msgs.size(), 1);
EXPECT_TRUE(transmitter_b_->Transmit(msg));
std::this_thread::sleep_for(std::chrono::milliseconds(200));
EXPECT_EQ(msgs.size(), 2);
for (auto& item : msgs) {
EXPECT_EQ(item.class_name(), "RtpsTransceiverTest");
EXPECT_EQ(item.case_name(), "enable_and_disable");
}
transmitter_b_->Disable(receiver->attributes());
EXPECT_FALSE(transmitter_b_->Transmit(msg));
transmitter_b_->Enable(receiver->attributes());
auto& transmitter_b_attr = transmitter_b_->attributes();
receiver->Disable();
receiver->Enable(transmitter_b_attr);
msgs.clear();
EXPECT_TRUE(transmitter_a_->Transmit(msg));
std::this_thread::sleep_for(std::chrono::milliseconds(200));
EXPECT_EQ(msgs.size(), 0);
EXPECT_TRUE(transmitter_b_->Transmit(msg));
std::this_thread::sleep_for(std::chrono::milliseconds(200));
EXPECT_EQ(msgs.size(), 1);
for (auto& item : msgs) {
EXPECT_EQ(item.class_name(), "RtpsTransceiverTest");
EXPECT_EQ(item.case_name(), "enable_and_disable");
}
receiver->Disable(transmitter_b_attr);
msgs.clear();
EXPECT_TRUE(transmitter_b_->Transmit(msg));
std::this_thread::sleep_for(std::chrono::milliseconds(200));
EXPECT_EQ(msgs.size(), 0);
}
} // namespace transport
} // namespace cyber
} // namespace apollo
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
apollo::cyber::transport::Transport::Instance();
auto res = RUN_ALL_TESTS();
apollo::cyber::transport::Transport::Instance()->Shutdown();
return res;
}
| 31.839506 | 79 | 0.698139 | aurora12344 |
0ea105d8f065cab06ba34a4b2aa5b4c689c37b5b | 2,194 | cpp | C++ | src/main/cpp/wee/engine/achievement.cpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2019-02-11T12:18:39.000Z | 2019-02-11T12:18:39.000Z | src/main/cpp/wee/engine/achievement.cpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2021-11-11T07:27:58.000Z | 2021-11-11T07:27:58.000Z | src/main/cpp/wee/engine/achievement.cpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2021-11-11T07:22:12.000Z | 2021-11-11T07:22:12.000Z | #include <engine/achievement.hpp>
using nlohmann::json;
namespace wee {
void to_json(json& j, const condition& c) {
j = {
{ "key", c._key },
{ "activation_value", c._activationValue },
{ "condition", achievement::get_compare_string(c._cond) }
};
}
void from_json(const json& j, condition& c) {
c._key = j.at("key").get<std::string>();
c._activationValue = j.at("activation_value").get<std::string>();
c._cond = achievement::get_compare_func(j.at("condition").get<std::string>());
}
void to_json(json& j, const achievement& a) {
j = {
{ "name", a._name },
{ "text", a._text },
{ "unlocked", a._unlocked },
{ "conditions", a._cond }
};
/*cJSON* json = cJSON_CreateObject();
cJSON* arr = nullptr;
{
cJSON_AddStringToObject(json, "name", _name.c_str());//cJSON_AddStringToObject(json, "key", _key);
cJSON_AddStringToObject(json, "text", _text.c_str());
cJSON_AddBoolToObject(json, "unlocked", _unlocked);
cJSON_AddItemToObject(json, "conditions", arr = cJSON_CreateArray());
for(auto& c : _cond)
cJSON_AddItemToArray(arr, c.serialize());
}
return json;*/
}
void from_json(const json& j, achievement& a) {
a._name = j.at("name").get<std::string>();
a._text = j.at("text").get<std::string>();
a._unlocked = j.at("unlocked").get<bool>();
a._cond = j.at("conditions").get<std::vector<condition> >();
/*
*
cJSON* ptr = json->child;
while(ptr) {
if(!strcmp(ptr->string, "name")) _name=ptr->valuestring;
if(!strcmp(ptr->string, "text")) _text=ptr->valuestring;
if(!strcmp(ptr->string, "unlocked")) _unlocked = ptr->valueint;
if(!strcmp(ptr->string, "conditions")) {
int n = cJSON_GetArraySize(ptr);
for(int i=0; i < n; i++) {
condition c;
c.deserialize(cJSON_GetArrayItem(ptr, i));
_cond.push_back(c);
}
}
ptr = ptr->next;
*/
}
void to_json(json&, const achieve&) {
}
void from_json(const json&, achieve&) {
}
}
| 29.253333 | 102 | 0.557885 | emdavoca |
0ea2d6f9d23acb40982ed688b94199cd8b8e1228 | 2,761 | hpp | C++ | source/dynarithmic/twain/options/general_options.hpp | dynarithmic/twainsave-opensource | 9aa0d43572ffd68ba28311e237c33f1ec4557534 | [
"Apache-2.0"
] | null | null | null | source/dynarithmic/twain/options/general_options.hpp | dynarithmic/twainsave-opensource | 9aa0d43572ffd68ba28311e237c33f1ec4557534 | [
"Apache-2.0"
] | null | null | null | source/dynarithmic/twain/options/general_options.hpp | dynarithmic/twainsave-opensource | 9aa0d43572ffd68ba28311e237c33f1ec4557534 | [
"Apache-2.0"
] | null | null | null | /*
This file is part of the Dynarithmic TWAIN Library (DTWAIN).
Copyright (c) 2002-2020 Dynarithmic Software.
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.
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
DYNARITHMIC SOFTWARE. DYNARITHMIC SOFTWARE DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS.
*/
#ifndef DTWAIN_GENERAL_OPTIONS_HPP
#define DTWAIN_GENERAL_OPTIONS_HPP
#include <limits>
#include <cstdint>
#include <dynarithmic/twain/twain_values.hpp>
namespace dynarithmic
{
namespace twain
{
class general_options
{
public:
static constexpr double default_val = (std::numeric_limits<double>::min)();
static constexpr uint16_t default_int = (std::numeric_limits<uint16_t>::min)();
private:
transfer_type m_transfer_type;
int m_nMaxPageCount;
int m_nMaxAcquisitions;
sourceaction_type m_SourceAction;
public:
general_options() :
m_nMaxPageCount(DTWAIN_MAXACQUIRE),
m_nMaxAcquisitions(default_int),
m_transfer_type(transfer_type::file_using_native),
m_SourceAction(sourceaction_type::openafteracquire)
{}
general_options& set_transfer_type(transfer_type t)
{ m_transfer_type = t; return *this; }
general_options& set_max_pages(int numPages)
{ m_nMaxPageCount = numPages; return *this; }
general_options& set_max_acquisitions(int numAcqs)
{ m_nMaxAcquisitions = numAcqs; return *this; }
general_options& set_source_action(sourceaction_type sa)
{ m_SourceAction = sa; return *this; }
transfer_type get_transfer_type() const
{ return m_transfer_type; }
int get_max_pages() const
{ return m_nMaxPageCount; }
int get_max_acquisitions() const
{ return m_nMaxAcquisitions; }
sourceaction_type get_source_action() const
{ return m_SourceAction; }
};
}
}
#endif
| 34.5125 | 95 | 0.634191 | dynarithmic |
0ea38050d1b0b2267f568aea2b557c21be5620ac | 9,858 | cpp | C++ | beelzebub/arc/amd64/src/_print/paging.cpp | vercas/Beelzebub | 9d0e4790060b313c6681ca7e478d08d3910332b0 | [
"NCSA"
] | 32 | 2015-09-02T22:56:22.000Z | 2021-02-24T17:15:50.000Z | beelzebub/arc/amd64/src/_print/paging.cpp | vercas/Beelzebub | 9d0e4790060b313c6681ca7e478d08d3910332b0 | [
"NCSA"
] | 30 | 2015-04-26T18:35:07.000Z | 2021-06-06T09:57:02.000Z | beelzebub/arc/amd64/src/_print/paging.cpp | vercas/Beelzebub | 9d0e4790060b313c6681ca7e478d08d3910332b0 | [
"NCSA"
] | 11 | 2015-09-03T20:47:41.000Z | 2021-06-25T17:00:01.000Z | /*
Copyright (c) 2015 Alexandru-Mihai Maftei. All rights reserved.
Developed by: Alexandru-Mihai Maftei
aka Vercas
http://vercas.com | https://github.com/vercas/Beelzebub
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal with 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:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimers.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimers in the
documentation and/or other materials provided with the distribution.
* Neither the names of Alexandru-Mihai Maftei, Vercas, nor the names of
its contributors may be used to endorse or promote products derived from
this Software without specific prior written permission.
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
CONTRIBUTORS 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
WITH THE SOFTWARE.
---
You may also find the text of this license in "LICENSE.md", along with a more
thorough explanation regarding other files.
*/
#include <_print/paging.hpp>
#include <debug.hpp>
using namespace Beelzebub;
using namespace Beelzebub::Debug;
using namespace Beelzebub::Memory;
using namespace Beelzebub::Terminals;
/***********************
Pml1Entry Struct
***********************/
TerminalWriteResult PrintToTerminal(TerminalBase * const term, Pml1Entry const val)
{
char str[58] = " | | | | | | | | | | |\r\n";
//str[60] = '\r'; str[61] = '\n'; str[62] = 0;
// Address writing.
uint64_t adr = (uint64_t)val.GetAddress();
for (size_t i = 0; i < 16; ++i)
{
uint8_t nib = (adr >> (i * 4)) & 0xF;
str[15 - i] = (nib > 9 ? '7' : '0') + nib;
}
if (val.GetPresent())
str[17] = 'P';
if (val.GetXd())
{ str[19] = 'E'; str[20] = 'X'; str[21] = 'D'; }
if (val.GetWritable())
{ str[23] = 'R'; str[24] = '/'; str[25] = 'W'; }
else
str[24] = 'R';
if (val.GetUserland())
{ str[27] = 'U'; str[28] = '/'; str[29] = 'S'; }
else
str[28] = 'S';
if (val.GetPwt())
{ str[31] = 'P'; str[32] = 'W'; str[33] = 'T'; }
if (val.GetPcd())
{ str[35] = 'P'; str[36] = 'C'; str[37] = 'D'; }
if (val.GetAccessed())
{ str[39] = 'A'; str[40] = 'C'; str[41] = 'C'; }
if (val.GetGlobal())
{ str[43] = 'G'; str[44] = 'L'; str[45] = 'B'; }
if (val.GetDirty())
{ str[47] = 'D'; str[48] = 'R'; str[49] = 'T'; }
if (val.GetPat1())
{ str[51] = 'P'; str[52] = 'A'; str[53] = 'T'; }
return term->Write(str);
}
TerminalWriteResult PrintToDebugTerminal(Pml1Entry const val)
{
return PrintToTerminal(DebugTerminal, val);
}
/******************
Pml1 Struct
******************/
TerminalWriteResult PrintToTerminal(TerminalBase * const term, Pml1 const & val)
{
TerminalWriteResult tret;
TERMTRY0(term->WriteLine("IND |PML1: Address |T|NXB|R/W|U/S|PWT|PCD|ACC|GLB|DRT|PAT|"), tret);
uint32_t cnt;
for (size_t i = 0; i < 512; ++i)
{
TERMTRY1(term->WriteHex16((uint16_t)i), tret, cnt);
TERMTRY1(term->Write("|"), tret, cnt);
TERMTRY1(PrintToTerminal(term, val.Entries[i]), tret, cnt);
}
return tret;
}
TerminalWriteResult PrintToDebugTerminal(Pml1 const & val)
{
return PrintToTerminal(DebugTerminal, val);
}
/***********************
Pml2Entry Struct
***********************/
TerminalWriteResult PrintToTerminal(TerminalBase * const term, Pml2Entry const val)
{
char str[58] = " | | | | | | | | | | |\r\n";
//str[60] = '\r'; str[61] = '\n'; str[62] = 0;
// Address writing.
uint64_t adr = (uint64_t)val.GetPml1Ptr();
for (size_t i = 0; i < 16; ++i)
{
uint8_t nib = (adr >> (i * 4)) & 0xF;
str[15 - i] = (nib > 9 ? '7' : '0') + nib;
}
if (val.GetPresent())
{
if (val.GetPageSize())
str[17] = 'P';
else
str[17] = 'T';
}
if (val.GetXd())
{ str[19] = 'E'; str[20] = 'X'; str[21] = 'D'; }
if (val.GetWritable())
{ str[23] = 'R'; str[24] = '/'; str[25] = 'W'; }
else
str[24] = 'R';
if (val.GetUserland())
{ str[27] = 'U'; str[28] = '/'; str[29] = 'S'; }
else
str[28] = 'S';
if (val.GetPwt())
{ str[31] = 'P'; str[32] = 'W'; str[33] = 'T'; }
if (val.GetPcd())
{ str[35] = 'P'; str[36] = 'C'; str[37] = 'D'; }
if (val.GetAccessed())
{ str[39] = 'A'; str[40] = 'C'; str[41] = 'C'; }
if (val.GetGlobal())
{ str[43] = 'G'; str[44] = 'L'; str[45] = 'B'; }
if (val.GetDirty())
{ str[47] = 'D'; str[48] = 'R'; str[49] = 'T'; }
if (val.GetPat1())
{ str[51] = 'P'; str[52] = 'A'; str[53] = 'T'; }
return term->Write(str);
}
TerminalWriteResult PrintToDebugTerminal(Pml2Entry const val)
{
return PrintToTerminal(DebugTerminal, val);
}
/******************
Pml2 Struct
******************/
TerminalWriteResult PrintToTerminal(TerminalBase * const term, Pml2 const & val)
{
TerminalWriteResult tret;
TERMTRY0(term->WriteLine("IND |PML2: Address |T|NXB|R/W|U/S|PWT|PCD|ACC|GLB|DRT|PAT|"), tret);
uint32_t cnt;
for (size_t i = 0; i < 512; ++i)
{
TERMTRY1(term->WriteHex16((uint16_t)i), tret, cnt);
TERMTRY1(term->Write("|"), tret, cnt);
TERMTRY1(PrintToTerminal(term, val.Entries[i]), tret, cnt);
}
return tret;
}
TerminalWriteResult PrintToDebugTerminal(Pml2 const & val)
{
return PrintToTerminal(DebugTerminal, val);
}
/***********************
Pml3Entry Struct
***********************/
TerminalWriteResult PrintToTerminal(TerminalBase * const term, Pml3Entry const val)
{
char str[58] = " | | | | | | | | | | |\r\n";
//str[60] = '\r'; str[61] = '\n'; str[62] = 0;
// Address writing.
uint64_t adr = (uint64_t)val.GetPml2Ptr();
for (size_t i = 0; i < 16; ++i)
{
uint8_t nib = (adr >> (i * 4)) & 0xF;
str[15 - i] = (nib > 9 ? '7' : '0') + nib;
}
if (val.GetPresent())
{
if (val.GetPageSize())
str[17] = 'P';
else
str[17] = 'T';
}
if (val.GetXd())
{ str[19] = 'E'; str[20] = 'X'; str[21] = 'D'; }
if (val.GetWritable())
{ str[23] = 'R'; str[24] = '/'; str[25] = 'W'; }
else
str[24] = 'R';
if (val.GetUserland())
{ str[27] = 'U'; str[28] = '/'; str[29] = 'S'; }
else
str[28] = 'S';
if (val.GetPwt())
{ str[31] = 'P'; str[32] = 'W'; str[33] = 'T'; }
if (val.GetPcd())
{ str[35] = 'P'; str[36] = 'C'; str[37] = 'D'; }
if (val.GetAccessed())
{ str[39] = 'A'; str[40] = 'C'; str[41] = 'C'; }
if (val.GetGlobal())
{ str[43] = 'G'; str[44] = 'L'; str[45] = 'B'; }
if (val.GetDirty())
{ str[47] = 'D'; str[48] = 'R'; str[49] = 'T'; }
if (val.GetPat1())
{ str[51] = 'P'; str[52] = 'A'; str[53] = 'T'; }
return term->Write(str);
}
TerminalWriteResult PrintToDebugTerminal(Pml3Entry const val)
{
return PrintToTerminal(DebugTerminal, val);
}
/******************
Pml3 Struct
******************/
TerminalWriteResult PrintToTerminal(TerminalBase * const term, Pml3 const & val)
{
TerminalWriteResult tret;
TERMTRY0(term->WriteLine("IND |PML3: Address |T|NXB|R/W|U/S|PWT|PCD|ACC|GLB|DRT|PAT|"), tret);
uint32_t cnt;
for (size_t i = 0; i < 512; ++i)
{
TERMTRY1(term->WriteHex16((uint16_t)i), tret, cnt);
TERMTRY1(term->Write("|"), tret, cnt);
TERMTRY1(PrintToTerminal(term, val.Entries[i]), tret, cnt);
}
return tret;
}
TerminalWriteResult PrintToDebugTerminal(Pml3 const & val)
{
return PrintToTerminal(DebugTerminal, val);
}
/***********************
Pml4Entry Struct
***********************/
TerminalWriteResult PrintToTerminal(TerminalBase * const term, Pml4Entry const val)
{
char str[58] = " | | | | | | | |\r\n";
//str[60] = '\r'; str[61] = '\n'; str[62] = 0;
// Address writing.
uint64_t adr = (uint64_t)val.GetPml3Ptr();
for (size_t i = 0; i < 16; ++i)
{
uint8_t nib = (adr >> (i * 4)) & 0xF;
str[15 - i] = (nib > 9 ? '7' : '0') + nib;
}
if (val.GetPresent())
str[17] = 'T';
if (val.GetXd())
{ str[19] = 'E'; str[20] = 'X'; str[21] = 'D'; }
if (val.GetWritable())
{ str[23] = 'R'; str[24] = '/'; str[25] = 'W'; }
else
str[24] = 'R';
if (val.GetUserland())
{ str[27] = 'U'; str[28] = '/'; str[29] = 'S'; }
else
str[28] = 'S';
if (val.GetPwt())
{ str[31] = 'P'; str[32] = 'W'; str[33] = 'T'; }
if (val.GetPcd())
{ str[35] = 'P'; str[36] = 'C'; str[37] = 'D'; }
if (val.GetAccessed())
{ str[39] = 'A'; str[40] = 'C'; str[41] = 'C'; }
return term->Write(str);
}
TerminalWriteResult PrintToDebugTerminal(Pml4Entry const val)
{
return PrintToTerminal(DebugTerminal, val);
}
/******************
Pml4 Struct
******************/
TerminalWriteResult PrintToTerminal(TerminalBase * const term, Pml4 const & val)
{
TerminalWriteResult tret;
TERMTRY0(term->WriteLine("IND |PML4: Address |T|NXB|R/W|U/S|PWT|PCD|ACC|"), tret);
uint32_t cnt;
for (size_t i = 0; i < 512; ++i)
{
TERMTRY1(term->WriteHex16((uint16_t)i), tret, cnt);
TERMTRY1(term->Write("|"), tret, cnt);
TERMTRY1(PrintToTerminal(term, val.Entries[i]), tret, cnt);
}
return tret;
}
TerminalWriteResult PrintToDebugTerminal(Pml4 const & val)
{
return PrintToTerminal(DebugTerminal, val);
}
| 25.212276 | 97 | 0.573646 | vercas |
0eae1b638337a7c2c090fd3599888359affe74f0 | 18,475 | hpp | C++ | rocprim/include/rocprim/device/device_merge.hpp | lamikr/rocPRIM | aef6c8b58b8bf597e17ee19e70759e7467a8ffb6 | [
"MIT"
] | null | null | null | rocprim/include/rocprim/device/device_merge.hpp | lamikr/rocPRIM | aef6c8b58b8bf597e17ee19e70759e7467a8ffb6 | [
"MIT"
] | null | null | null | rocprim/include/rocprim/device/device_merge.hpp | lamikr/rocPRIM | aef6c8b58b8bf597e17ee19e70759e7467a8ffb6 | [
"MIT"
] | null | null | null | // Copyright (c) 2017-2019 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef ROCPRIM_DEVICE_DEVICE_MERGE_HPP_
#define ROCPRIM_DEVICE_DEVICE_MERGE_HPP_
#include <type_traits>
#include <iterator>
#include "../config.hpp"
#include "../detail/various.hpp"
#include "device_merge_config.hpp"
#include "detail/device_merge.hpp"
BEGIN_ROCPRIM_NAMESPACE
/// \addtogroup devicemodule
/// @{
namespace detail
{
template<
class IndexIterator,
class KeysInputIterator1,
class KeysInputIterator2,
class BinaryFunction
>
__global__
void partition_kernel(IndexIterator index,
KeysInputIterator1 keys_input1,
KeysInputIterator2 keys_input2,
const size_t input1_size,
const size_t input2_size,
const unsigned int spacing,
BinaryFunction compare_function)
{
partition_kernel_impl(
index, keys_input1, keys_input2, input1_size, input2_size,
spacing, compare_function
);
}
template<
unsigned int BlockSize,
unsigned int ItemsPerThread,
class IndexIterator,
class KeysInputIterator1,
class KeysInputIterator2,
class KeysOutputIterator,
class ValuesInputIterator1,
class ValuesInputIterator2,
class ValuesOutputIterator,
class BinaryFunction
>
__global__
void merge_kernel(IndexIterator index,
KeysInputIterator1 keys_input1,
KeysInputIterator2 keys_input2,
KeysOutputIterator keys_output,
ValuesInputIterator1 values_input1,
ValuesInputIterator2 values_input2,
ValuesOutputIterator values_output,
const size_t input1_size,
const size_t input2_size,
BinaryFunction compare_function)
{
merge_kernel_impl<BlockSize, ItemsPerThread>(
index, keys_input1, keys_input2, keys_output,
values_input1, values_input2, values_output,
input1_size, input2_size, compare_function
);
}
#define ROCPRIM_DETAIL_HIP_SYNC_AND_RETURN_ON_ERROR(name, size, start) \
{ \
auto error = hipPeekAtLastError(); \
if(error != hipSuccess) return error; \
if(debug_synchronous) \
{ \
std::cout << name << "(" << size << ")"; \
auto error = hipStreamSynchronize(stream); \
if(error != hipSuccess) return error; \
auto end = std::chrono::high_resolution_clock::now(); \
auto d = std::chrono::duration_cast<std::chrono::duration<double>>(end - start); \
std::cout << " " << d.count() * 1000 << " ms" << '\n'; \
} \
}
template<
class Config,
class KeysInputIterator1,
class KeysInputIterator2,
class KeysOutputIterator,
class ValuesInputIterator1,
class ValuesInputIterator2,
class ValuesOutputIterator,
class BinaryFunction
>
inline
hipError_t merge_impl(void * temporary_storage,
size_t& storage_size,
KeysInputIterator1 keys_input1,
KeysInputIterator2 keys_input2,
KeysOutputIterator keys_output,
ValuesInputIterator1 values_input1,
ValuesInputIterator2 values_input2,
ValuesOutputIterator values_output,
const size_t input1_size,
const size_t input2_size,
BinaryFunction compare_function,
const hipStream_t stream,
bool debug_synchronous)
{
using key_type = typename std::iterator_traits<KeysInputIterator1>::value_type;
using value_type = typename std::iterator_traits<ValuesInputIterator1>::value_type;
// Get default config if Config is default_config
using config = detail::default_or_custom_config<
Config,
detail::default_merge_config<ROCPRIM_TARGET_ARCH, key_type, value_type>
>;
constexpr unsigned int block_size = config::block_size;
constexpr unsigned int half_block = block_size / 2;
constexpr unsigned int items_per_thread = config::items_per_thread;
constexpr auto items_per_block = block_size * items_per_thread;
const unsigned int partitions = ((input1_size + input2_size) + items_per_block - 1) / items_per_block;
const size_t partition_bytes = (partitions + 1) * sizeof(unsigned int);
if(temporary_storage == nullptr)
{
// storage_size is never zero
storage_size = partition_bytes;
return hipSuccess;
}
// Start point for time measurements
std::chrono::high_resolution_clock::time_point start;
auto number_of_blocks = partitions;
if(debug_synchronous)
{
std::cout << "block_size " << block_size << '\n';
std::cout << "number of blocks " << number_of_blocks << '\n';
std::cout << "items_per_block " << items_per_block << '\n';
}
unsigned int * index = reinterpret_cast<unsigned int *>(temporary_storage);
const unsigned partition_blocks = ((partitions + 1) + half_block - 1) / half_block;
if(debug_synchronous) start = std::chrono::high_resolution_clock::now();
hipLaunchKernelGGL(
HIP_KERNEL_NAME(detail::partition_kernel),
dim3(partition_blocks), dim3(half_block), 0, stream,
index, keys_input1, keys_input2, input1_size, input2_size,
items_per_block, compare_function
);
ROCPRIM_DETAIL_HIP_SYNC_AND_RETURN_ON_ERROR("partition_kernel", input1_size, start);
if(debug_synchronous) start = std::chrono::high_resolution_clock::now();
hipLaunchKernelGGL(
HIP_KERNEL_NAME(detail::merge_kernel<block_size, items_per_thread>),
dim3(number_of_blocks), dim3(block_size), 0, stream,
index, keys_input1, keys_input2, keys_output,
values_input1, values_input2, values_output,
input1_size, input2_size, compare_function
);
ROCPRIM_DETAIL_HIP_SYNC_AND_RETURN_ON_ERROR("merge_kernel", input1_size, start);
return hipSuccess;
}
#undef ROCPRIM_DETAIL_HIP_SYNC_AND_RETURN_ON_ERROR
} // end of detail namespace
/// \brief Parallel merge primitive for device level.
///
/// \p merge function performs a device-wide merge.
/// Function merges two ordered sets of input values based on comparison function.
///
/// \par Overview
/// * The contents of the inputs are not altered by the merging function.
/// * Returns the required size of \p temporary_storage in \p storage_size
/// if \p temporary_storage in a null pointer.
/// * Accepts custom compare_functions for merging across the device.
///
/// \tparam Config - [optional] configuration of the primitive. It can be \p merge_config or
/// a custom class with the same members.
/// \tparam InputIterator1 - random-access iterator type of the first input range. Must meet the
/// requirements of a C++ InputIterator concept. It can be a simple pointer type.
/// \tparam InputIterator2 - random-access iterator type of the second input range. Must meet the
/// requirements of a C++ InputIterator concept. It can be a simple pointer type.
/// \tparam OutputIterator - random-access iterator type of the output range. Must meet the
/// requirements of a C++ OutputIterator concept. It can be a simple pointer type.
///
/// \param [in] temporary_storage - pointer to a device-accessible temporary storage. When
/// a null pointer is passed, the required allocation size (in bytes) is written to
/// \p storage_size and function returns without performing the sort operation.
/// \param [in,out] storage_size - reference to a size (in bytes) of \p temporary_storage.
/// \param [in] input1 - iterator to the first element in the first range to merge.
/// \param [in] input2 - iterator to the first element in the second range to merge.
/// \param [out] output - iterator to the first element in the output range.
/// \param [in] input1_size - number of element in the first input range.
/// \param [in] input2_size - number of element in the second input range.
/// \param [in] compare_function - binary operation function object that will be used for comparison.
/// The signature of the function should be equivalent to the following:
/// <tt>bool f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
/// The default value is \p BinaryFunction().
/// \param [in] stream - [optional] HIP stream object. Default is \p 0 (default stream).
/// \param [in] debug_synchronous - [optional] If true, synchronization after every kernel
/// launch is forced in order to check for errors. Default value is \p false.
///
/// \returns \p hipSuccess (\p 0) after successful sort; otherwise a HIP runtime error of
/// type \p hipError_t.
///
/// \par Example
/// \parblock
/// In this example a device-level ascending merge is performed on an array of
/// \p int values.
///
/// \code{.cpp}
/// #include <rocprim/rocprim.hpp>
///
/// // Prepare input and output (declare pointers, allocate device memory etc.)
/// size_t input_size1; // e.g., 4
/// size_t input_size2; // e.g., 4
/// int * input1; // e.g., [0, 1, 2, 3]
/// int * input2; // e.g., [0, 1, 2, 3]
/// int * output; // empty array of 8 elements
///
/// size_t temporary_storage_size_bytes;
/// void * temporary_storage_ptr = nullptr;
/// // Get required size of the temporary storage
/// rocprim::merge(
/// temporary_storage_ptr, temporary_storage_size_bytes,
/// input1, input2, output, input_size1, input_size2
/// );
///
/// // allocate temporary storage
/// hipMalloc(&temporary_storage_ptr, temporary_storage_size_bytes);
///
/// // perform merge
/// rocprim::merge(
/// temporary_storage_ptr, temporary_storage_size_bytes,
/// input1, input2, output, input_size1, input_size2
/// );
/// // output: [0, 0, 1, 1, 2, 2, 3, 3]
/// \endcode
/// \endparblock
template<
class Config = default_config,
class InputIterator1,
class InputIterator2,
class OutputIterator,
class BinaryFunction = ::rocprim::less<typename std::iterator_traits<InputIterator1>::value_type>
>
inline
hipError_t merge(void * temporary_storage,
size_t& storage_size,
InputIterator1 input1,
InputIterator2 input2,
OutputIterator output,
const size_t input1_size,
const size_t input2_size,
BinaryFunction compare_function = BinaryFunction(),
const hipStream_t stream = 0,
bool debug_synchronous = false)
{
empty_type * values = nullptr;
return detail::merge_impl<Config>(
temporary_storage, storage_size,
input1, input2, output,
values, values, values,
input1_size, input2_size, compare_function,
stream, debug_synchronous
);
}
/// \brief Parallel merge primitive for device level.
///
/// \p merge function performs a device-wide merge of (key, value) pairs.
/// Function merges two ordered sets of input keys and corresponding values
/// based on key comparison function.
///
/// \par Overview
/// * The contents of the inputs are not altered by the merging function.
/// * Returns the required size of \p temporary_storage in \p storage_size
/// if \p temporary_storage in a null pointer.
/// * Accepts custom compare_functions for merging across the device.
///
/// \tparam Config - [optional] configuration of the primitive. It can be \p merge_config or
/// a custom class with the same members.
/// \tparam KeysInputIterator1 - random-access iterator type of the first keys input range. Must meet the
/// requirements of a C++ InputIterator concept. It can be a simple pointer type.
/// \tparam KeysInputIterator2 - random-access iterator type of the second keys input range. Must meet the
/// requirements of a C++ InputIterator concept. It can be a simple pointer type.
/// \tparam KeysOutputIterator - random-access iterator type of the keys output range. Must meet the
/// requirements of a C++ OutputIterator concept. It can be a simple pointer type.
/// \tparam ValuesInputIterator1 - random-access iterator type of the first values input range. Must meet the
/// requirements of a C++ InputIterator concept. It can be a simple pointer type.
/// \tparam ValuesInputIterator2 - random-access iterator type of the second values input range. Must meet the
/// requirements of a C++ InputIterator concept. It can be a simple pointer type.
/// \tparam ValuesOutputIterator - random-access iterator type of the values output range. Must meet the
/// requirements of a C++ OutputIterator concept. It can be a simple pointer type.
///
/// \param [in] temporary_storage - pointer to a device-accessible temporary storage. When
/// a null pointer is passed, the required allocation size (in bytes) is written to
/// \p storage_size and function returns without performing the sort operation.
/// \param [in,out] storage_size - reference to a size (in bytes) of \p temporary_storage.
/// \param [in] keys_input1 - iterator to the first key in the first range to merge.
/// \param [in] keys_input2 - iterator to the first key in the second range to merge.
/// \param [out] keys_output - iterator to the first key in the output range.
/// \param [in] values_input1 - iterator to the first value in the first range to merge.
/// \param [in] values_input2 - iterator to the first value in the second range to merge.
/// \param [out] values_output - iterator to the first value in the output range.
/// \param [in] input1_size - number of element in the first input range.
/// \param [in] input2_size - number of element in the second input range.
/// \param [in] compare_function - binary operation function object that will be used for key comparison.
/// The signature of the function should be equivalent to the following:
/// <tt>bool f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
/// The default value is \p BinaryFunction().
/// \param [in] stream - [optional] HIP stream object. Default is \p 0 (default stream).
/// \param [in] debug_synchronous - [optional] If true, synchronization after every kernel
/// launch is forced in order to check for errors. Default value is \p false.
///
/// \returns \p hipSuccess (\p 0) after successful sort; otherwise a HIP runtime error of
/// type \p hipError_t.
///
/// \par Example
/// \parblock
/// In this example a device-level ascending merge is performed on an array of
/// \p int values.
///
/// \code{.cpp}
/// #include <rocprim/rocprim.hpp>
///
/// // Prepare input and output (declare pointers, allocate device memory etc.)
/// size_t input_size1; // e.g., 4
/// size_t input_size2; // e.g., 4
/// int * keys_input1; // e.g., [0, 1, 2, 3]
/// int * keys_input2; // e.g., [0, 1, 2, 3]
/// int * keys_output; // empty array of 8 elements
/// int * values_input1; // e.g., [10, 11, 12, 13]
/// int * values_input2; // e.g., [20, 21, 22, 23]
/// int * values_output; // empty array of 8 elements
///
/// size_t temporary_storage_size_bytes;
/// void * temporary_storage_ptr = nullptr;
/// // Get required size of the temporary storage
/// rocprim::merge(
/// temporary_storage_ptr, temporary_storage_size_bytes,
/// keys_input1, keys_input2, keys_output,
/// values_input1, values_input2, values_output,
// input_size1, input_size2
/// );
///
/// // allocate temporary storage
/// hipMalloc(&temporary_storage_ptr, temporary_storage_size_bytes);
///
/// // perform merge
/// rocprim::merge(
/// temporary_storage_ptr, temporary_storage_size_bytes,
/// keys_input1, keys_input2, keys_output,
/// values_input1, values_input2, values_output,
// input_size1, input_size2
/// );
/// // keys_output: [0, 0, 1, 1, 2, 2, 3, 3]
/// // values_output: [10, 20, 11, 21, 12, 22, 13, 23]
/// \endcode
/// \endparblock
template<
class Config = default_config,
class KeysInputIterator1,
class KeysInputIterator2,
class KeysOutputIterator,
class ValuesInputIterator1,
class ValuesInputIterator2,
class ValuesOutputIterator,
class BinaryFunction = ::rocprim::less<typename std::iterator_traits<KeysInputIterator1>::value_type>
>
inline
hipError_t merge(void * temporary_storage,
size_t& storage_size,
KeysInputIterator1 keys_input1,
KeysInputIterator2 keys_input2,
KeysOutputIterator keys_output,
ValuesInputIterator1 values_input1,
ValuesInputIterator2 values_input2,
ValuesOutputIterator values_output,
const size_t input1_size,
const size_t input2_size,
BinaryFunction compare_function = BinaryFunction(),
const hipStream_t stream = 0,
bool debug_synchronous = false)
{
return detail::merge_impl<Config>(
temporary_storage, storage_size,
keys_input1, keys_input2, keys_output,
values_input1, values_input2, values_output,
input1_size, input2_size, compare_function,
stream, debug_synchronous
);
}
/// @}
// end of group devicemodule
END_ROCPRIM_NAMESPACE
#endif // ROCPRIM_DEVICE_DEVICE_MERGE_HPP_
| 42.373853 | 110 | 0.688119 | lamikr |
0eae9ae643dd0f4a51eaed42059d09b27f259c45 | 327 | cpp | C++ | test/point.cpp | rlichtenwalter/kdtree | c5aa357604cb856700f2be2c4850c55a280c341a | [
"MIT"
] | 1 | 2020-12-10T08:13:23.000Z | 2020-12-10T08:13:23.000Z | test/point.cpp | rlichtenwalter/kdtree | c5aa357604cb856700f2be2c4850c55a280c341a | [
"MIT"
] | null | null | null | test/point.cpp | rlichtenwalter/kdtree | c5aa357604cb856700f2be2c4850c55a280c341a | [
"MIT"
] | 1 | 2020-11-23T13:26:55.000Z | 2020-11-23T13:26:55.000Z | #include <sstream>
#include "../include/point.hpp"
int main( int argc, char* argv[] ) {
(void)argc;
(void)argv;
using coordinate = float;
using point = kdtree::point<coordinate,2>;
point p = {1.0f,2.0f};
std::cout << p << '\n';
std::stringstream ss( "(4.2,-3.7)" );
ss >> p;
std::cout << p << '\n';
return 0;
}
| 15.571429 | 43 | 0.571865 | rlichtenwalter |
0eb197476f8342666323130ab20b13e2dc321b5c | 4,684 | cpp | C++ | firmware/src/network-messaging-task.cpp | clegg89/temperature-monitor | 5928db28f3493b620085de623806d7c3441fe07f | [
"MIT"
] | null | null | null | firmware/src/network-messaging-task.cpp | clegg89/temperature-monitor | 5928db28f3493b620085de623806d7c3441fe07f | [
"MIT"
] | null | null | null | firmware/src/network-messaging-task.cpp | clegg89/temperature-monitor | 5928db28f3493b620085de623806d7c3441fe07f | [
"MIT"
] | null | null | null | /*
* @file network-messaging-task.cpp
*
* @author C. Smith
*/
#include "network-messaging-task.hpp"
#include <Crypto.h>
#include <AES.h>
#include <CBC.h>
#include <SHA256.h>
#include <ESP8266TrueRandom.h>
#include <cassert>
#include <array>
#include <vector>
#include <algorithm>
#include "security-information.hpp"
namespace app
{
static std::vector<uint8_t> performEncryption(const std::vector<uint8_t>& key,
const std::vector<uint8_t>& iv,
const std::vector<uint8_t>& data);
static std::vector<uint8_t> sign(const std::vector<uint8_t>& key,
const std::vector<uint8_t>& data);
template <typename T>
static String hexify(const T& data);
static std::vector<uint8_t> padData(const std::vector<uint8_t>& data);
NetworkMessagingTask::NetworkMessagingTask(
const std::shared_ptr<MqttClient>& client,
const std::shared_ptr<NetworkQueue>& queue,
const uint32_t timeInterval)
: Task(timeInterval), m_client(client), m_queue(queue)
{
}
bool NetworkMessagingTask::OnStart()
{
return true;
}
void NetworkMessagingTask::OnStop()
{
}
void NetworkMessagingTask::OnUpdate(uint32_t deltaTime)
{
if(m_client->isConnected())
{
String msgString = m_queue->dequeue();
if(msgString != "")
{
MqttClient::Message message;
MqttClient::Error::type rc;
Serial.print("Received Message: ");
Serial.println(msgString);
msgString = encrypt(msgString);
Serial.print("Encrypted Message: ");
Serial.println(msgString);
message.qos = MqttClient::QOS0;
message.retained = false;
message.dup = false;
message.payload = reinterpret_cast<void*>(
const_cast<char*>(msgString.c_str()));
message.payloadLen = msgString.length();
rc = m_client->publish("monitor", message);
if(rc != MqttClient::Error::SUCCESS)
{
Serial.print("Error sending message: ");
Serial.println(rc);
}
}
}
}
String NetworkMessagingTask::encrypt(const String& message) const
{
const SecurityInformation& info = g_securityInformation;
std::vector<uint8_t> iv(16, 0);
std::vector<uint8_t> encryptedIv;
std::vector<uint8_t> cipherText;
std::vector<uint8_t> signature;
std::vector<uint8_t> fullMessage;
std::vector<uint8_t> plainText = padData(std::vector<uint8_t>(message.c_str(), message.c_str() + message.length()));
String result;
ESP8266TrueRandom.memfill(reinterpret_cast<char*>(iv.data()), iv.size());
encryptedIv = performEncryption(
std::vector<uint8_t>(info.ivKey.begin(), info.ivKey.end()),
std::vector<uint8_t>(info.staticIv.begin(), info.staticIv.end()),
iv);
cipherText = performEncryption(
std::vector<uint8_t>(info.dataKey.begin(), info.dataKey.end()),
iv,
plainText);
fullMessage.reserve(iv.size() + plainText.size());
fullMessage = iv;
fullMessage.insert(fullMessage.end(), plainText.begin(), plainText.end());
signature = sign(info.hashKey, fullMessage);
result = hexify(encryptedIv);
result += ',';
result += hexify(cipherText);
result += ',';
result += hexify(signature);
return result;
}
static std::vector<uint8_t> performEncryption(const std::vector<uint8_t>& key,
const std::vector<uint8_t>& iv,
const std::vector<uint8_t>& data)
{
CBC<AES128> cipher;
std::vector<uint8_t> cipherText(data.size(), 0);;
cipher.clear();
assert(cipher.setKey(key.data(), key.size()));
assert(cipher.setIV(iv.data(), iv.size()));
assert(data.size() % 16 == 0);
cipher.encrypt(cipherText.data(), data.data(), data.size());
return cipherText;
}
static std::vector<uint8_t> sign(const std::vector<uint8_t>& key,
const std::vector<uint8_t>& data)
{
SHA256 hmac;
std::vector<uint8_t> signature;
signature.resize(hmac.hashSize());
hmac.resetHMAC(key.data(), key.size());
hmac.update(data.data(), data.size());
hmac.finalizeHMAC(key.data(), key.size(), signature.data(), hmac.hashSize());
return signature;
}
template <typename T>
static String hexify(const T& data)
{
const char hexLookup[] = "0123456789ABCDEF";
String result = "";
for(auto x : data)
{
result += hexLookup[(x >> 4) & 0x0F];
result += hexLookup[(x & 0x0F)];
}
return result;
}
static std::vector<uint8_t> padData(const std::vector<uint8_t>& data)
{
std::vector<uint8_t> padded(data);
while(padded.size() % 16 != 0)
{
padded.push_back(static_cast<uint8_t>(' '));
}
return padded;
}
}
| 25.736264 | 118 | 0.63877 | clegg89 |
0ebb5c02b6ee2d3fbf1b62d04a93b1e58cced7ef | 899 | hxx | C++ | source/Engine/include/Core.Rendering/Sampler.hxx | selmentdev/recr-game-native-cxx-shooter | c924477cb2adb1500bed2a2958aaf4f1ee96391b | [
"Apache-2.0"
] | null | null | null | source/Engine/include/Core.Rendering/Sampler.hxx | selmentdev/recr-game-native-cxx-shooter | c924477cb2adb1500bed2a2958aaf4f1ee96391b | [
"Apache-2.0"
] | null | null | null | source/Engine/include/Core.Rendering/Sampler.hxx | selmentdev/recr-game-native-cxx-shooter | c924477cb2adb1500bed2a2958aaf4f1ee96391b | [
"Apache-2.0"
] | null | null | null | #ifndef INCLUDED_CORE_RENDERING_SAMPLER_HXX
#define INCLUDED_CORE_RENDERING_SAMPLER_HXX
//
// Copyright (C) Selmentdev, 2017
//
// See LICENSE file in the project root for full license information.
//
#include <Core/Common.hxx>
#include <Core.Rendering/Common.hxx>
#include <Core.Rendering/Resource.hxx>
namespace Core::Rendering
{
class RenderSystem;
struct SamplerDesc final
{
D3D11_SAMPLER_DESC Desc;
};
using SamplerRef = Reference<class Sampler>;
class Sampler : public Resource
{
friend class RenderSystem;
friend class CommandList;
private:
RenderSystem* m_RenderSystem;
Microsoft::WRL::ComPtr<ID3D11SamplerState> m_Sampler;
public:
Sampler(RenderSystem* renderSystem, const SamplerDesc& desc) noexcept;
virtual ~Sampler() noexcept;
};
}
#endif // INCLUDED_CORE_RENDERING_SAMPLER_HXX | 23.051282 | 78 | 0.707453 | selmentdev |
0ebbce746dae3cfd5fc274e2520fc41a2049d0bb | 5,890 | cpp | C++ | frameworks/qt/plugins/osg/dmzQtPluginViewerOSG.cpp | ashok/dmz | 2f8d4bced646f25abf2e98bdc0d378dafb4b32ed | [
"MIT"
] | 1 | 2015-11-05T03:03:31.000Z | 2015-11-05T03:03:31.000Z | frameworks/qt/plugins/osg/dmzQtPluginViewerOSG.cpp | ashok/dmz | 2f8d4bced646f25abf2e98bdc0d378dafb4b32ed | [
"MIT"
] | null | null | null | frameworks/qt/plugins/osg/dmzQtPluginViewerOSG.cpp | ashok/dmz | 2f8d4bced646f25abf2e98bdc0d378dafb4b32ed | [
"MIT"
] | null | null | null | // Note due to compiler issues on Linux, this header must go first.
#include <dmzRenderEventHandlerOSG.h>
#include "dmzQtPluginViewerOSG.h"
#include <dmzInputModule.h>
#include <dmzRenderModuleCoreOSG.h>
#include <dmzRenderCameraManipulatorOSG.h>
#include <dmzRuntimeConfig.h>
#include <dmzRuntimeConfigToTypesBase.h>
#include <dmzRuntimeDefinitions.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzRuntimePluginInfo.h>
#include <dmzTypesVector.h>
#include <dmzTypesMatrix.h>
dmz::QtPluginViewerOSG::QtPluginViewerOSG (
const PluginInfo &Info,
Config &local) :
Plugin (Info),
TimeSlice (Info),
QtWidget (Info),
_log (Info),
_core (0),
_channels (0),
_portalName (DefaultPortalNameOSG),
_camera (0),
_cameraManipulator (0),
_eventHandler (0),
_viewer (0) {
_viewer = new ViewerQOSG;
_viewer->setThreadingModel (osgViewer::Viewer::SingleThreaded);
_cameraManipulator = new RenderCameraManipulatorOSG;
_eventHandler = new RenderEventHandlerOSG (get_plugin_runtime_context ());
osgViewer::StatsHandler *stats = new osgViewer::StatsHandler;
stats->setKeyEventTogglesOnScreenStats (osgGA::GUIEventAdapter::KEY_F1);
stats->setKeyEventPrintsOutStats (osgGA::GUIEventAdapter::KEY_F2);
_viewer->addEventHandler (stats);
_viewer->setCameraManipulator (_cameraManipulator.get ());
_viewer->addEventHandler (_eventHandler.get ());
_viewer->setKeyEventSetsDone (0);
_init (local);
_camera = _viewer->getCamera ();
}
dmz::QtPluginViewerOSG::~QtPluginViewerOSG () {
_eventHandler = 0;
}
// Plugin Interface
void
dmz::QtPluginViewerOSG::update_plugin_state (
const PluginStateEnum State,
const UInt32 Level) {
if (State == PluginStateStart) {
}
}
void
dmz::QtPluginViewerOSG::discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr) {
if (Mode == PluginDiscoverAdd) {
if (!_core) {
_core = RenderModuleCoreOSG::cast (PluginPtr);
if (_core) {
osg::ref_ptr<osg::Group> scene = _core->get_scene ();
if (scene.valid ()) { _viewer->setSceneData (scene.get ()); }
if (_cameraManipulator.valid ()) {
_core->add_camera_manipulator (_portalName, _cameraManipulator.get ());
}
if (_camera.valid ()) {
_core->add_camera (_portalName, _camera.get ());
}
}
}
if (!_channels) {
_channels = InputModule::cast (PluginPtr);
if (_channels) {
Definitions defs (get_plugin_runtime_context (), &_log);
const Handle SourceHandle = defs.create_named_handle (_portalName);
_eventHandler->set_input_module_channels (_channels, SourceHandle);
}
}
}
else if (Mode == PluginDiscoverRemove) {
if (_core && (_core == RenderModuleCoreOSG::cast (PluginPtr))) {
_viewer->setCameraManipulator (0);
_core->remove_camera (_portalName);
_core->remove_camera_manipulator (_portalName);
osg::ref_ptr<osg::Group> scene = new osg::Group;
if (scene.valid ()) { _viewer->setSceneData (scene.get ()); }
_viewer.release ();
_core = 0;
}
if (_channels && (_channels == InputModule::cast (PluginPtr))) {
_eventHandler->set_input_module_channels (0, 0);
_channels = 0;
}
}
}
void
dmz::QtPluginViewerOSG::update_time_slice (const Float64 TimeDelta) {
if (_viewer.valid ()) {
_viewer->frame (); // Render a complete new frame
}
}
// QtWidget Interface
QWidget *
dmz::QtPluginViewerOSG::get_qt_widget () { return _viewer.get (); }
void
dmz::QtPluginViewerOSG::_init (const Config &Local) {
_portalName = config_to_string ("portal.name", Local, DefaultPortalNameOSG);
#if 0
Config windowData;
if (Local.lookup_all_config ("window", windowData)) {
ConfigIterator it;
Config cd;
Boolean found (windowData.get_first_config (it, cd));
if (found) {
UInt32 windowLeft = config_to_uint32 ("left", cd);
UInt32 windowTop = config_to_uint32 ("top", cd);
UInt32 windowWidth = config_to_uint32 ("width", cd);
UInt32 windowHeight = config_to_uint32 ("height", cd);
UInt32 screen = config_to_uint32 ("screen", cd);
__init_viewer_window (windowLeft, windowTop, windowWidth, windowHeight, screen);
}
_log.info << "Loading viewer windowed" << endl;
}
else if (Local.lookup_all_config ("fullscreen", windowData)) {
ConfigIterator it;
Config cd;
Boolean found (windowData.get_first_config (it, cd));
if (found) {
UInt32 screen = config_to_uint32 ("screen", cd);
__init_viewer_fullscreen (screen);
}
_log.info << "Loading viewer full-screen" << endl;
}
else {
__init_viewer_window (100, 100, 800, 600, 0);
_log.info << "Loading viewer windowed with defaults" << endl;
}
#endif
}
void
dmz::QtPluginViewerOSG::__init_viewer_window (
UInt32 windowLeft,
UInt32 windowTop,
UInt32 windowWidth,
UInt32 windowHeight,
UInt32 screen) {
if (_viewer.valid ()) {
_viewer->setUpViewInWindow (
windowLeft,
windowTop,
windowWidth,
windowHeight,
screen);
}
}
void
dmz::QtPluginViewerOSG::__init_viewer_fullscreen (UInt32 screen) {
if (_viewer.valid ()) {
_viewer->setUpViewOnSingleScreen (screen);
if (_viewer->done ()) { _log.error << "The viewer thinks it is done?" << endl; }
}
}
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzQtPluginViewerOSG (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::QtPluginViewerOSG (Info, local);
}
};
| 24.957627 | 89 | 0.645671 | ashok |
0ebbe8f10530b20e009f0180cce4529f7593e890 | 319 | cpp | C++ | src/c++/tests/src/unit-init.cpp | vnepogodin/Toy-Neural-Network-C | 3fb540050ec6e4010069dbe7a3abe4ccba457f2c | [
"MIT"
] | 4 | 2021-03-26T20:04:52.000Z | 2021-10-30T22:15:42.000Z | src/c++/tests/src/unit-init.cpp | vnepogodin/Toy-Neural-Network-C | 3fb540050ec6e4010069dbe7a3abe4ccba457f2c | [
"MIT"
] | 1 | 2020-06-01T19:37:43.000Z | 2020-06-01T20:16:03.000Z | src/c++/tests/src/unit-init.cpp | vnepogodin/Toy-Neural-Network-C | 3fb540050ec6e4010069dbe7a3abe4ccba457f2c | [
"MIT"
] | 1 | 2020-05-23T22:31:02.000Z | 2020-05-23T22:31:02.000Z | #include <doctest_compatibility.h>
#include <vnepogodin/nn.hpp> // class NeuralNetwork
using vnepogodin::NeuralNetwork;
TEST_CASE("constructor 1")
{
SECTION("basic behavior")
{
const std::unique_ptr<NeuralNetwork> nn = std::make_unique<NeuralNetwork>(2, 4, 1);
CHECK(nn != nullptr);
}
}
| 21.266667 | 91 | 0.673981 | vnepogodin |
0ec0430d2752c5954a19d5eb9a50b248ab8fafad | 1,563 | cpp | C++ | src/services/pcn-loadbalancer-rp/src/default-src/ServiceDefaultImpl.cpp | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-07-16T04:49:29.000Z | 2020-07-16T04:49:29.000Z | src/services/pcn-loadbalancer-rp/src/default-src/ServiceDefaultImpl.cpp | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/services/pcn-loadbalancer-rp/src/default-src/ServiceDefaultImpl.cpp | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /**
* lbrp API
* LoadBalancer Reverse-Proxy Service
*
* OpenAPI spec version: 2.0.0
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/polycube-network/swagger-codegen.git
* branch polycube
*/
// These methods have a default implementation. Your are free to keep it or add your own
#include "../Service.h"
nlohmann::fifo_map<std::string, std::string> Service::getKeys() {
nlohmann::fifo_map<std::string, std::string> r;
r["vip"] = getVip();
r["vport"] = getVport();
r["proto"] = ServiceJsonObject::ServiceProtoEnum_to_string(getProto());
return r;
}
std::shared_ptr<ServiceBackend> Service::getBackend(const std::string &ip){
return ServiceBackend::getEntry(*this, ip);
}
std::vector<std::shared_ptr<ServiceBackend>> Service::getBackendList(){
return ServiceBackend::get(*this);
}
void Service::addBackend(const std::string &ip, const ServiceBackendJsonObject &conf){
ServiceBackend::create(*this, ip, conf);
}
void Service::addBackendList(const std::vector<ServiceBackendJsonObject> &conf){
for(auto &i : conf){
std::string ip_ = i.getIp();
ServiceBackend::create(*this, ip_, i);
}
}
void Service::replaceBackend(const std::string &ip, const ServiceBackendJsonObject &conf){
ServiceBackend::removeEntry(*this, ip);
std::string ip_ = conf.getIp();
ServiceBackend::create(*this, ip_, conf);
}
void Service::delBackend(const std::string &ip){
ServiceBackend::removeEntry(*this, ip);
}
void Service::delBackendList(){
ServiceBackend::remove(*this);
}
| 21.708333 | 90 | 0.710813 | mbertrone |
b1be4bb21931aeb3d96fc1326c539bf1b2390248 | 7,830 | cpp | C++ | src/overlay/Tracker.cpp | V5DF8/stellar-core | 3fb2dc6bea41ed9160313f856e57451897f68cd9 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | 10 | 2017-09-23T08:25:40.000Z | 2022-01-04T10:28:02.000Z | src/overlay/Tracker.cpp | V5DF8/stellar-core | 3fb2dc6bea41ed9160313f856e57451897f68cd9 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | 1 | 2021-12-09T04:33:19.000Z | 2021-12-09T04:33:19.000Z | src/overlay/Tracker.cpp | V5DF8/stellar-core | 3fb2dc6bea41ed9160313f856e57451897f68cd9 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | 2 | 2021-10-21T20:34:04.000Z | 2021-11-21T14:13:54.000Z | // Copyright 2016 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "Tracker.h"
#include "OverlayMetrics.h"
#include "crypto/BLAKE2.h"
#include "crypto/Hex.h"
#include "herder/Herder.h"
#include "main/Application.h"
#include "medida/medida.h"
#include "overlay/OverlayManager.h"
#include "util/GlobalChecks.h"
#include "util/Logging.h"
#include "util/Math.h"
#include "util/XDROperators.h"
#include "xdrpp/marshal.h"
#include <Tracy.hpp>
namespace stellar
{
static std::chrono::milliseconds const MS_TO_WAIT_FOR_FETCH_REPLY{1500};
static int const MAX_REBUILD_FETCH_LIST = 10;
Tracker::Tracker(Application& app, Hash const& hash, AskPeer& askPeer)
: mAskPeer(askPeer)
, mApp(app)
, mNumListRebuild(0)
, mTimer(app)
, mItemHash(hash)
, mTryNextPeer(
app.getOverlayManager().getOverlayMetrics().mItemFetcherNextPeer)
, mFetchTime("fetch-" + hexAbbrev(hash), LogSlowExecution::Mode::MANUAL)
{
releaseAssert(mAskPeer);
}
Tracker::~Tracker()
{
cancel();
}
SCPEnvelope
Tracker::pop()
{
auto env = mWaitingEnvelopes.back().second;
mWaitingEnvelopes.pop_back();
return env;
}
// returns false if no one cares about this guy anymore
bool
Tracker::clearEnvelopesBelow(uint64 slotIndex)
{
ZoneScoped;
for (auto iter = mWaitingEnvelopes.begin();
iter != mWaitingEnvelopes.end();)
{
if (iter->second.statement.slotIndex < slotIndex)
{
iter = mWaitingEnvelopes.erase(iter);
}
else
{
iter++;
}
}
if (!mWaitingEnvelopes.empty())
{
return true;
}
mTimer.cancel();
mLastAskedPeer = nullptr;
return false;
}
void
Tracker::doesntHave(Peer::pointer peer)
{
if (mLastAskedPeer == peer)
{
CLOG_TRACE(Overlay, "Does not have {}", hexAbbrev(mItemHash));
tryNextPeer();
}
}
void
Tracker::tryNextPeer()
{
ZoneScoped;
// will be called by some timer or when we get a
// response saying they don't have it
CLOG_TRACE(Overlay, "tryNextPeer {} last: {}", hexAbbrev(mItemHash),
(mLastAskedPeer ? mLastAskedPeer->toString() : "<none>"));
if (mLastAskedPeer)
{
mTryNextPeer.Mark();
mLastAskedPeer.reset();
}
auto canAskPeer = [&](Peer::pointer const& p, bool peerHas) {
auto it = mPeersAsked.find(p);
return (p->isAuthenticated() &&
(it == mPeersAsked.end() || (peerHas && !it->second)));
};
// Helper function to populate "candidates" with a set of peers, which we're
// going to randomly select a candidate from to ask for the item.
//
// We want to bias the candidates set towards peers that are close to us in
// terms of network latency, so we repeatedly lower a "nearness threshold"
// in units of 500ms (1/3 of the MS_TO_WAIT_FOR_FETCH_REPLY) until we have a
// "closest peers" bucket that we have at least one peer for, and keep all
// the peers in that bucket, and then (later) randomly select from it.
//
// if the map of peers passed in is for peers that claim to have the data we
// need, `peersHave` is also set to true. in this case, the candidate list
// will also be populated with peers that we asked before but that since
// then received the data that we need
std::vector<Peer::pointer> candidates;
int64 curBest = INT64_MAX;
auto procPeers = [&](std::map<NodeID, Peer::pointer> const& peerMap,
bool peersHave) {
for (auto& mp : peerMap)
{
auto& p = mp.second;
if (canAskPeer(p, peersHave))
{
int64 GROUPSIZE_MS = (MS_TO_WAIT_FOR_FETCH_REPLY.count() / 3);
int64 plat = p->getPing().count() / GROUPSIZE_MS;
if (plat < curBest)
{
candidates.clear();
curBest = plat;
candidates.emplace_back(p);
}
else if (curBest == plat)
{
candidates.emplace_back(p);
}
}
}
};
// build the set of peers we didn't ask yet that have this envelope
std::map<NodeID, Peer::pointer> newPeersWithEnvelope;
for (auto const& e : mWaitingEnvelopes)
{
auto const& s = mApp.getOverlayManager().getPeersKnows(e.first);
for (auto pit = s.begin(); pit != s.end(); ++pit)
{
auto& p = *pit;
if (canAskPeer(p, true))
{
newPeersWithEnvelope.emplace(p->getPeerID(), *pit);
}
}
}
bool peerWithEnvelopeSelected = !newPeersWithEnvelope.empty();
if (peerWithEnvelopeSelected)
{
procPeers(newPeersWithEnvelope, true);
}
else
{
auto& inPeers = mApp.getOverlayManager().getInboundAuthenticatedPeers();
auto& outPeers =
mApp.getOverlayManager().getOutboundAuthenticatedPeers();
procPeers(inPeers, false);
procPeers(outPeers, false);
}
// pick a random element from the candidate list
if (!candidates.empty())
{
mLastAskedPeer = rand_element(candidates);
}
std::chrono::milliseconds nextTry;
if (!mLastAskedPeer)
{
// we have asked all our peers, reset the list and try again after a
// pause
mNumListRebuild++;
mPeersAsked.clear();
CLOG_TRACE(Overlay, "tryNextPeer {} restarting fetch #{}",
hexAbbrev(mItemHash), mNumListRebuild);
nextTry = MS_TO_WAIT_FOR_FETCH_REPLY *
std::min(MAX_REBUILD_FETCH_LIST, mNumListRebuild);
}
else
{
mPeersAsked[mLastAskedPeer] = peerWithEnvelopeSelected;
CLOG_TRACE(Overlay, "Asking for {} to {}", hexAbbrev(mItemHash),
mLastAskedPeer->toString());
mAskPeer(mLastAskedPeer, mItemHash);
nextTry = MS_TO_WAIT_FOR_FETCH_REPLY;
}
mTimer.expires_from_now(nextTry);
mTimer.async_wait([this]() { this->tryNextPeer(); },
VirtualTimer::onFailureNoop);
}
static std::function<bool(std::pair<Hash, SCPEnvelope> const&)>
matchEnvelope(SCPEnvelope const& env)
{
return [&env](std::pair<Hash, SCPEnvelope> const& x) {
return x.second == env;
};
}
void
Tracker::listen(const SCPEnvelope& env)
{
ZoneScoped;
mLastSeenSlotIndex = std::max(env.statement.slotIndex, mLastSeenSlotIndex);
// don't track the same envelope twice
auto matcher = matchEnvelope(env);
auto it = std::find_if(mWaitingEnvelopes.begin(), mWaitingEnvelopes.end(),
matcher);
if (it != mWaitingEnvelopes.end())
{
return;
}
StellarMessage m;
m.type(SCP_MESSAGE);
m.envelope() = env;
// NB: hash here is BLAKE2 of StellarMessage because that is
// what the floodmap is keyed by, and we're storing its keys
// in mWaitingEnvelopes, not the mItemHash that is the SHA256
// of the item being tracked.
mWaitingEnvelopes.push_back(std::make_pair(xdrBlake2(m), env));
}
void
Tracker::discard(const SCPEnvelope& env)
{
ZoneScoped;
auto matcher = matchEnvelope(env);
mWaitingEnvelopes.erase(std::remove_if(std::begin(mWaitingEnvelopes),
std::end(mWaitingEnvelopes),
matcher),
std::end(mWaitingEnvelopes));
}
void
Tracker::cancel()
{
mTimer.cancel();
mLastSeenSlotIndex = 0;
}
std::chrono::milliseconds
Tracker::getDuration()
{
return mFetchTime.checkElapsedTime();
}
}
| 28.786765 | 80 | 0.613282 | V5DF8 |
b1c07f9c601c38719cf322fdfb8a428da56c6f3a | 454 | cpp | C++ | 0800/20/825a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | 1 | 2020-07-03T15:55:52.000Z | 2020-07-03T15:55:52.000Z | 0800/20/825a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | null | null | null | 0800/20/825a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | 3 | 2020-10-01T14:55:28.000Z | 2021-07-11T11:33:58.000Z | #include <iostream>
#include <string>
void answer(unsigned v)
{
std::cout << v << '\n';
}
void solve(const std::string& s)
{
unsigned v = 0, k = 0;
for (const char c : s) {
if (c == '0') {
v = v * 10 + k;
k = 0;
} else {
++k;
}
}
answer(v * 10 + k);
}
int main()
{
size_t n;
std::cin >> n;
std::string s;
std::cin >> s;
solve(s);
return 0;
}
| 12.27027 | 32 | 0.403084 | actium |
b1c58044096de9c6c5533d65f5cef4bce10f3528 | 10,660 | cpp | C++ | modules/face/samples/facemark_demo_aam.cpp | onearrow/opencv_calib | c6f1922adec976b565aba4b4a54d8790bdce2cfa | [
"BSD-3-Clause"
] | 17 | 2020-03-13T00:10:28.000Z | 2021-09-06T17:13:17.000Z | opencv_contrib-3.4.1/modules/face/samples/facemark_demo_aam.cpp | luoyongheng/opencv_add_contrib | 99fc5c28f5e39ebb1a2b76c592ef72d598c429cb | [
"BSD-3-Clause"
] | 1 | 2020-03-12T08:10:07.000Z | 2020-03-12T08:10:07.000Z | opencv_contrib-3.4.1/modules/face/samples/facemark_demo_aam.cpp | luoyongheng/opencv_add_contrib | 99fc5c28f5e39ebb1a2b76c592ef72d598c429cb | [
"BSD-3-Clause"
] | 3 | 2018-02-26T06:43:33.000Z | 2021-03-18T09:13:30.000Z | /*
This file was part of GSoC Project: Facemark API for OpenCV
Final report: https://gist.github.com/kurnianggoro/74de9121e122ad0bd825176751d47ecc
Student: Laksono Kurnianggoro
Mentor: Delia Passalacqua
*/
/*----------------------------------------------
* Usage:
* facemark_demo_aam <face_cascade_model> <eyes_cascade_model> <training_images> <annotation_files> [test_files]
*
* Example:
* facemark_demo_aam ../face_cascade.xml ../eyes_cascade.xml ../images_train.txt ../points_train.txt ../test.txt
*
* Notes:
* the user should provides the list of training images_train
* accompanied by their corresponding landmarks location in separated files.
* example of contents for images_train.txt:
* ../trainset/image_0001.png
* ../trainset/image_0002.png
* example of contents for points_train.txt:
* ../trainset/image_0001.pts
* ../trainset/image_0002.pts
* where the image_xxxx.pts contains the position of each face landmark.
* example of the contents:
* version: 1
* n_points: 68
* {
* 115.167660 220.807529
* 116.164839 245.721357
* 120.208690 270.389841
* ...
* }
* example of the dataset is available at https://ibug.doc.ic.ac.uk/download/annotations/lfpw.zip
*--------------------------------------------------*/
#include <stdio.h>
#include <fstream>
#include <sstream>
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/face.hpp"
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
using namespace cv;
using namespace cv::face;
bool myDetector( InputArray image, OutputArray ROIs, CascadeClassifier *face_cascade);
bool getInitialFitting(Mat image, Rect face, std::vector<Point2f> s0,
CascadeClassifier eyes_cascade, Mat & R, Point2f & Trans, float & scale);
bool parseArguments(int argc, char** argv, CommandLineParser & , String & cascade,
String & model, String & images, String & annotations, String & testImages
);
int main(int argc, char** argv )
{
CommandLineParser parser(argc, argv,"");
String cascade_path,eyes_cascade_path,images_path, annotations_path, test_images_path;
if(!parseArguments(argc, argv, parser,cascade_path,eyes_cascade_path,images_path, annotations_path, test_images_path))
return -1;
//! [instance_creation]
/*create the facemark instance*/
FacemarkAAM::Params params;
params.scales.push_back(2.0);
params.scales.push_back(4.0);
params.model_filename = "AAM.yaml";
Ptr<FacemarkAAM> facemark = FacemarkAAM::create(params);
//! [instance_creation]
//! [load_dataset]
/*Loads the dataset*/
std::vector<String> images_train;
std::vector<String> landmarks_train;
loadDatasetList(images_path,annotations_path,images_train,landmarks_train);
//! [load_dataset]
//! [add_samples]
Mat image;
std::vector<Point2f> facial_points;
for(size_t i=0;i<images_train.size();i++){
image = imread(images_train[i].c_str());
loadFacePoints(landmarks_train[i],facial_points);
facemark->addTrainingSample(image, facial_points);
}
//! [add_samples]
//! [training]
/* trained model will be saved to AAM.yml */
facemark->training();
//! [training]
//! [load_test_images]
/*test using some images*/
String testFiles(images_path), testPts(annotations_path);
if(!test_images_path.empty()){
testFiles = test_images_path;
testPts = test_images_path; //unused
}
std::vector<String> images;
std::vector<String> facePoints;
loadDatasetList(testFiles, testPts, images, facePoints);
//! [load_test_images]
//! [trainsformation_variables]
float scale ;
Point2f T;
Mat R;
//! [trainsformation_variables]
//! [base_shape]
FacemarkAAM::Data data;
facemark->getData(&data);
std::vector<Point2f> s0 = data.s0;
//! [base_shape]
//! [fitting]
/*fitting process*/
std::vector<Rect> faces;
//! [load_cascade_models]
CascadeClassifier face_cascade(cascade_path);
CascadeClassifier eyes_cascade(eyes_cascade_path);
//! [load_cascade_models]
for(int i=0;i<(int)images.size();i++){
printf("image #%i ", i);
//! [detect_face]
image = imread(images[i]);
myDetector(image, faces, &face_cascade);
//! [detect_face]
if(faces.size()>0){
//! [get_initialization]
std::vector<FacemarkAAM::Config> conf;
std::vector<Rect> faces_eyes;
for(unsigned j=0;j<faces.size();j++){
if(getInitialFitting(image,faces[j],s0,eyes_cascade, R,T,scale)){
conf.push_back(FacemarkAAM::Config(R,T,scale,(int)params.scales.size()-1));
faces_eyes.push_back(faces[j]);
}
}
//! [get_initialization]
//! [fitting_process]
if(conf.size()>0){
printf(" - face with eyes found %i ", (int)conf.size());
std::vector<std::vector<Point2f> > landmarks;
double newtime = (double)getTickCount();
facemark->fit(image, faces_eyes, landmarks, (void*)&conf);
double fittime = ((getTickCount() - newtime)/getTickFrequency());
for(unsigned j=0;j<landmarks.size();j++){
drawFacemarks(image, landmarks[j],Scalar(0,255,0));
}
printf("%f ms\n",fittime*1000);
imshow("fitting", image);
waitKey(0);
}else{
printf("initialization cannot be computed - skipping\n");
}
//! [fitting_process]
}
} //for
//! [fitting]
}
bool myDetector(InputArray image, OutputArray faces, CascadeClassifier *face_cascade)
{
Mat gray;
if (image.channels() > 1)
cvtColor(image, gray, COLOR_BGR2GRAY);
else
gray = image.getMat().clone();
equalizeHist(gray, gray);
std::vector<Rect> faces_;
face_cascade->detectMultiScale(gray, faces_, 1.4, 2, CASCADE_SCALE_IMAGE, Size(30, 30));
Mat(faces_).copyTo(faces);
return true;
}
bool getInitialFitting(Mat image, Rect face, std::vector<Point2f> s0 ,CascadeClassifier eyes_cascade, Mat & R, Point2f & Trans, float & scale){
std::vector<Point2f> mybase;
std::vector<Point2f> T;
std::vector<Point2f> base = Mat(Mat(s0)+Scalar(image.cols/2,image.rows/2)).reshape(2);
std::vector<Point2f> base_shape,base_shape2 ;
Point2f e1 = Point2f((float)((base[39].x+base[36].x)/2.0),(float)((base[39].y+base[36].y)/2.0)); //eye1
Point2f e2 = Point2f((float)((base[45].x+base[42].x)/2.0),(float)((base[45].y+base[42].y)/2.0)); //eye2
if(face.width==0 || face.height==0) return false;
std::vector<Point2f> eye;
bool found=false;
Mat faceROI = image( face);
std::vector<Rect> eyes;
//-- In each face, detect eyes
eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, CASCADE_SCALE_IMAGE, Size(20, 20) );
if(eyes.size()==2){
found = true;
int j=0;
Point2f c1( (float)(face.x + eyes[j].x + eyes[j].width*0.5), (float)(face.y + eyes[j].y + eyes[j].height*0.5));
j=1;
Point2f c2( (float)(face.x + eyes[j].x + eyes[j].width*0.5), (float)(face.y + eyes[j].y + eyes[j].height*0.5));
Point2f pivot;
double a0,a1;
if(c1.x<c2.x){
pivot = c1;
a0 = atan2(c2.y-c1.y, c2.x-c1.x);
}else{
pivot = c2;
a0 = atan2(c1.y-c2.y, c1.x-c2.x);
}
scale = (float)(norm(Mat(c1)-Mat(c2))/norm(Mat(e1)-Mat(e2)));
mybase= Mat(Mat(s0)*scale).reshape(2);
Point2f ey1 = Point2f((float)((mybase[39].x+mybase[36].x)/2.0),(float)((mybase[39].y+mybase[36].y)/2.0));
Point2f ey2 = Point2f((float)((mybase[45].x+mybase[42].x)/2.0),(float)((mybase[45].y+mybase[42].y)/2.0));
#define TO_DEGREE 180.0/3.14159265
a1 = atan2(ey2.y-ey1.y, ey2.x-ey1.x);
Mat rot = getRotationMatrix2D(Point2f(0,0), (a1-a0)*TO_DEGREE, 1.0);
rot(Rect(0,0,2,2)).convertTo(R, CV_32F);
base_shape = Mat(Mat(R*scale*Mat(Mat(s0).reshape(1)).t()).t()).reshape(2);
ey1 = Point2f((float)((base_shape[39].x+base_shape[36].x)/2.0),(float)((base_shape[39].y+base_shape[36].y)/2.0));
ey2 = Point2f((float)((base_shape[45].x+base_shape[42].x)/2.0),(float)((base_shape[45].y+base_shape[42].y)/2.0));
T.push_back(Point2f(pivot.x-ey1.x,pivot.y-ey1.y));
Trans = Point2f(pivot.x-ey1.x,pivot.y-ey1.y);
return true;
}else{
Trans = Point2f( (float)(face.x + face.width*0.5),(float)(face.y + face.height*0.5));
}
return found;
}
bool parseArguments(int argc, char** argv, CommandLineParser & parser,
String & cascade,
String & model,
String & images,
String & annotations,
String & test_images
){
const String keys =
"{ @f face-cascade | | (required) path to the cascade model file for the face detector }"
"{ @e eyes-cascade | | (required) path to the cascade model file for the eyes detector }"
"{ @i images | | (required) path of a text file contains the list of paths to all training images}"
"{ @a annotations | | (required) Path of a text file contains the list of paths to all annotations files}"
"{ @t test-images | | Path of a text file contains the list of paths to the test images}"
"{ help h usage ? | | facemark_demo_aam -face-cascade -eyes-cascade -images -annotations [-t]\n"
" example: facemark_demo_aam ../face_cascade.xml ../eyes_cascade.xml ../images_train.txt ../points_train.txt ../test.txt}"
;
parser = CommandLineParser(argc, argv,keys);
parser.about("hello");
if (parser.has("help")){
parser.printMessage();
return false;
}
cascade = String(parser.get<String>("face-cascade"));
model = String(parser.get<string>("eyes-cascade"));
images = String(parser.get<string>("images"));
annotations = String(parser.get<string>("annotations"));
test_images = String(parser.get<string>("test-images"));
if(cascade.empty() || model.empty() || images.empty() || annotations.empty()){
std::cerr << "one or more required arguments are not found" << '\n';
cout<<"face-cascade : "<<cascade.c_str()<<endl;
cout<<"eyes-cascade : "<<model.c_str()<<endl;
cout<<"images : "<<images.c_str()<<endl;
cout<<"annotations : "<<annotations.c_str()<<endl;
parser.printMessage();
return false;
}
return true;
}
| 36.632302 | 143 | 0.616229 | onearrow |
b1c935fdde5fc26ef741a1d4d758ee471fe3a900 | 1,344 | cpp | C++ | problems/chapter05/tokuma/003.cpp | tokuma09/algorithm_problems | 58534620df73b230afbeb12de126174362625a78 | [
"CC0-1.0"
] | 1 | 2021-07-07T15:46:58.000Z | 2021-07-07T15:46:58.000Z | problems/chapter05/tokuma/003.cpp | tokuma09/algorithm_problems | 58534620df73b230afbeb12de126174362625a78 | [
"CC0-1.0"
] | 5 | 2021-06-05T14:16:41.000Z | 2021-07-10T07:08:28.000Z | problems/chapter05/tokuma/003.cpp | tokuma09/algorithm_problems | 58534620df73b230afbeb12de126174362625a78 | [
"CC0-1.0"
] | null | null | null | // https://atcoder.jp/contests/tdpc/tasks/tdpc_contest
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// サイズ
int N;
cin >> N;
// 重さx
vector<int> a(N);
for (int i = 0; i < N; ++i)
{
cin >> a[i];
}
// 合計
int W = 100 * 100;
// メモ
vector<vector<int>> memo(N + 1, vector<int>(W + 1, -1));
//初期条件
memo[0] = vector<int>(W + 1, 0);
memo[0][0] = 1;
// 重さに関するループ, i番目までの候補で考える
for (int i = 1; i < N + 1; ++i)
{
// ここで合計に対してのループ
for (int w = 0; w < W + 1; ++w)
{
// i番目を使う場合
// 添字対応のため-1しておく
if (0 <= w - a[i - 1])
{
// メモでtrueを返すなら1を入れる
if (memo[i - 1][w - a[i - 1]] == 1)
{
memo[i][w] = 1;
}
}
// i番目を使わない場合でtrueなら入れる
if (memo[i - 1][w] == 1)
{
memo[i][w] = 1;
}
// メモ化されていなくて、かつだめだったら0を入れる
if (memo[i][w] == -1)
{
memo[i][w] = 0;
}
}
}
// N個使ったときにいくつまでの組ができるのかチェック
int res = 0;
for (int w = 0; w <= W; ++w)
{
if (memo[N][w] == 1)
{
++res;
}
}
cout << res << endl;
}
| 17.92 | 60 | 0.353423 | tokuma09 |
b1cc36ae2b2a73ac0eab4271fa65d25ad9e60b0a | 7,387 | hpp | C++ | sdsl-local-install/include/sdsl/louds_tree.hpp | juakotorres/ParallelRelativeLempel-Ziv | fb6cbd59183b22c6d9530a2db22fbfb93aabd8b7 | [
"MIT"
] | null | null | null | sdsl-local-install/include/sdsl/louds_tree.hpp | juakotorres/ParallelRelativeLempel-Ziv | fb6cbd59183b22c6d9530a2db22fbfb93aabd8b7 | [
"MIT"
] | null | null | null | sdsl-local-install/include/sdsl/louds_tree.hpp | juakotorres/ParallelRelativeLempel-Ziv | fb6cbd59183b22c6d9530a2db22fbfb93aabd8b7 | [
"MIT"
] | null | null | null | /* sdsl - succinct data structures library
Copyright (C) 2012 Simon Gog
*/
/*! \file louds_tree.hpp
\brief louds_tree.hpp contains a classes for the succinct tree representation LOUDS (level order unary degree sequence).
\author Simon Gog
*/
#ifndef INCLUDED_SDSL_LOUDS_TREE
#define INCLUDED_SDSL_LOUDS_TREE
#include "int_vector.hpp"
#include "util.hpp"
#include <ostream>
//! Namespace for the succinct data structure library.
namespace sdsl
{
//! A class for the node representation of louds_tree
class louds_node
{
public:
typedef bit_vector::size_type size_type;
private:
size_type m_nr; // node number
size_type m_pos; // position in the LOUDS
public:
const size_type& nr;
const size_type& pos;
louds_node(size_type f_nr=0, size_type f_pos=0):m_nr(f_nr), m_pos(f_pos),nr(m_nr),pos(m_pos) {}
bool operator==(const louds_node& v)const {
return m_nr == v.m_nr and m_pos ==v.m_pos;
}
bool operator!=(const louds_node& v)const {
return !(v==*this);
}
};
std::ostream& operator<<(std::ostream& os, const louds_node& v);
//! A tree class based on the level order unary degree sequence (LOUDS) representation.
/*!
* \tparam bit_vec_t The bit vector representation used for LOUDS.
* \tparam select_1_t A select_support on 1-bits required for the child(v,i) operation.
* \tparam select_0_t A select_support on 0-bits required for the parent operation.
*
* Example of the structure: A tree with balanced parentheses representation (()()(()()))
* is translated into 10001110011. Traverse the tree in breadth-first order an write
* for each node a 1-bit followed by as many 0-bits as the node has children.
*
* Disadvantages of louds: No efficient support for subtree size.
*/
template<class bit_vec_t = bit_vector, class select_1_t = typename bit_vec_t::select_1_type, class select_0_t = typename bit_vec_t::select_0_type>
class louds_tree
{
public:
typedef bit_vector::size_type size_type;
typedef louds_node node_type;
typedef bit_vec_t bit_vector_type;
typedef select_1_t select_1_type;
typedef select_0_t select_0_type;
private:
bit_vector_type m_bv; // bit vector for the LOUDS sequence
select_1_type m_bv_select1; // select support for 1-bits on m_bv
select_0_type m_bv_select0; // select support for 0-bits on m_bv
public:
const bit_vector_type& bv; // const reference to the LOUDS sequence
//! Constructor for a cst and a root node for the traversal
template<class Cst, class CstBfsIterator>
louds_tree(const Cst& cst, const CstBfsIterator begin, const CstBfsIterator end):m_bv(), m_bv_select1(), m_bv_select0(), bv(m_bv) {
bit_vector tmp_bv(4*cst.size(*begin) , 0); // resize the bit_vector to the maximal
// possible size 2*2*#leaves in the tree
size_type pos = 0;
for (CstBfsIterator it = begin; it != end;) {
tmp_bv[pos++] = 1;
size_type size = it.size();
++it;
pos += it.size()+1-size;
}
tmp_bv.resize(pos);
m_bv = bit_vector_type(std::move(tmp_bv));
util::init_support(m_bv_select1, &m_bv);
util::init_support(m_bv_select0, &m_bv);
}
louds_tree(const louds_tree& lt) : bv(m_bv) {
*this = lt;
}
louds_tree(louds_tree&& lt) : bv(m_bv) {
*this = std::move(lt);
}
louds_tree& operator=(const louds_tree& lt) {
if (this != <) {
m_bv = lt.m_bv;
m_bv_select1 = lt.m_bv_select1;
m_bv_select1.set_vector(&m_bv);
m_bv_select0 = lt.m_bv_select0;
m_bv_select0.set_vector(&m_bv);
}
return *this;
}
louds_tree& operator=(louds_tree&& lt) {
if (this != <) {
m_bv = std::move(lt.m_bv);
m_bv_select1 = std::move(lt.m_bv_select1);
m_bv_select1.set_vector(&m_bv);
m_bv_select0 = std::move(lt.m_bv_select0);
m_bv_select0.set_vector(&m_bv);
}
return *this;
}
//! Returns the root node
node_type root() const {
return louds_node(0, 0);
}
//! Returns the number of nodes in the tree.
size_type nodes()const {
return m_bv.size()+1/2;
}
//! Indicates if a node is a leaf.
/*! \param v A node.
*/
bool is_leaf(const node_type& v) const {
// node is the last leaf or has no children, so m_bv[v.pos]==1
return (v.pos+1 == m_bv.size()) or m_bv[v.pos+1];
}
//! Returns the number of children of a node.
/*!
* \param v A node.
*/
size_type degree(const node_type& v) const {
if (is_leaf(v)) { // handles boundary cases
return 0;
}
// position of the next node - node position - 1
return m_bv_select1(v.nr+2) - v.pos - 1;
}
//! Returns the i-child of a node.
/*!
* \param v The parent node.
* \param i Index of the child. Indexing starts at 1.
* \pre \f$ i \in [1..degree(v)] \f$
*/
node_type child(const node_type& v, size_type i)const {
size_type pos = v.pos+i; // go to the position of the child's zero
// (#bits = pos+1) - (#1-bits = v.nr+1)
size_type zeros = pos+1 - (v.nr+1);
return louds_node(zeros, m_bv_select1(zeros+1));
}
//! Returns the parent of a node v or root() if v==root().
node_type parent(const node_type& v)const {
if (v == root()) {
return root();
}
size_type zero_pos = m_bv_select0(v.nr);
size_type parent_nr = (zero_pos+1) - v.nr - 1;
return node_type(parent_nr, m_bv_select1(parent_nr+1));
}
//! Returns an unique id for each node in [0..size()-1]
size_type id(const node_type& v)const {
return v.nr;
}
void swap(louds_tree& tree) {
m_bv.swap(tree.m_bv);
util::swap_support(m_bv_select1, tree.m_select1, &m_bv, &(tree.m_bv));
util::swap_support(m_bv_select0, tree.m_select0, &m_bv, &(tree.m_bv));
}
size_type serialize(std::ostream& out, structure_tree_node* v=nullptr, std::string name="")const {
structure_tree_node* child = structure_tree::add_child(v, name, util::class_name(*this));
size_type written_bytes = 0;
m_bv.serialize(out, child, "bitvector");
m_bv_select1(out, child, "select1");
m_bv_select0(out, child, "select0");
structure_tree::add_size(child, written_bytes);
return written_bytes;
}
void load(std::istream& in) {
m_bv.load(in);
m_bv_select1.load(in);
m_bv_select1.set_vector(&m_bv);
m_bv_select0.load(in);
m_bv_select0.set_vector(&m_bv);
}
};
}// end namespace sdsl
#endif
| 35.68599 | 146 | 0.575335 | juakotorres |
b1d0f67a24af9a40a3d2900d23ee5208b8b2a1d5 | 2,337 | cpp | C++ | leetcode-cn/cplusplus/0048.cpp | illx10000/relax | 602937ff0c6ba24c9cc58da8f81b56a5834e3934 | [
"MIT"
] | null | null | null | leetcode-cn/cplusplus/0048.cpp | illx10000/relax | 602937ff0c6ba24c9cc58da8f81b56a5834e3934 | [
"MIT"
] | 1 | 2020-04-04T13:49:59.000Z | 2020-04-04T13:49:59.000Z | leetcode-cn/cplusplus/0048.cpp | illx10000/relax | 602937ff0c6ba24c9cc58da8f81b56a5834e3934 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <cstdint>
#include <set>
#include <string>
using namespace std;
#include <set>
#include <string>
#include <sstream>
template<typename T>
void printVector(vector<T> &arr)
{
cout << "[";
for (int i = 0; i < arr.size(); i++)
{
if (i)
{
cout << ",";
}
cout << arr[i] ;
}
cout << "]" << endl;
}
void printT( vector< vector<int> > &arr)
{
for (size_t i = 0; i < arr.size(); i++)
{
printVector(arr[i]);
}
//cout << endl;
}
class Solution {
public:
void rotate(vector<vector<int> >& matrix) {
if(matrix.size() <= 1) return;
int max_rotate_size = matrix.size() / 2;
int n = matrix.size() - 1;
for(int i = 0; i < max_rotate_size; i++)
{
int inner_size = matrix.size() - i * 2 - 1;
for(int j = i; j < inner_size + i ; j++)
{
/* code */
int LL = matrix[i][j]; //保存左上角的数据
matrix[i][j] = matrix[n-j][i];
matrix[n-j][i] = matrix[n-i][n-j];
matrix[n-i][n-j] = matrix[j][n-i];
matrix[j][n-i] = LL;
}
}
}
};
int main(int argc,char** argv)
{
/*Solution a;
string s = "busvutpwmu";
cout << a.lengthOfLongestSubstring(s) << endl;*/
//int a[]={1,8,6,2,5,4,8,3,7};
//int a[]={-1, 0, 1, 2, -1, -4};
int a[]={2,3,0,1,4};
//int b[]={2,3,4}1
vector<int> va(a,a+sizeof(a)/sizeof(a[0]));
//vector<int> vb(b,b+sizeof(b)/sizeof(b[0]));
vector<vector<int> > vvResult;
Solution sssss;
vector< vector<int> > ss ;
const int N = 3;
for(int i = 0; i < N; i++)
{
vector<int> vvvv;
for(int j = 0; j < N; j++)
{
vvvv.push_back( i * N + j + 1);
}
ss.push_back(vvvv);
}
printT(ss);
cout << endl;
sssss.rotate(ss);
printT(ss);
//cout << (
//va.clear(); for(int i = 10; i >=1 ;i--) va.push_back(i); va.push_back(1); va.push_back(0);
//cout << sssss.rotate(va) << endl;
//) << endl;
//printVector(va);
//printT(sssss.removeDuplicates(va));
}
| 19.475 | 96 | 0.450578 | illx10000 |
b1d1dab2bf65100839ef40cdff7a7ab98eb4ecc3 | 1,346 | cpp | C++ | bytecode/serializer/src/Serializer/Config/LoggerSerializer.cpp | Scorbutics/skalang | c8d1869a2f0c7857ee05ef45bd3aa4e537d39558 | [
"MIT"
] | 3 | 2019-04-08T17:34:19.000Z | 2020-01-03T04:47:06.000Z | bytecode/serializer/src/Serializer/Config/LoggerSerializer.cpp | Scorbutics/skalang | c8d1869a2f0c7857ee05ef45bd3aa4e537d39558 | [
"MIT"
] | 4 | 2020-04-19T22:09:06.000Z | 2020-11-06T15:47:08.000Z | bytecode/serializer/src/Serializer/Config/LoggerSerializer.cpp | Scorbutics/skalang | c8d1869a2f0c7857ee05ef45bd3aa4e537d39558 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include "LoggerSerializer.h"
#include <Signal/SignalHandler.h>
#define SKALANG_SERIALIZER_LOGGING
ska::detail::SkaLangSerializerLogger& ska::detail::LangSerializerLogger() {
static auto logger = ska::detail::BuildLangSerializerLogger("SerializerLog.log");
return logger;
}
namespace ska {
namespace detail {
template<class T>
void UpdatePatterns(T& logger) {
logger.setPattern(ska::LogLevel::Debug, "(%m:%s)%10c[D]%8c(%25F l.%3l) %07c%v");
logger.setPattern(ska::LogLevel::Info, "(%m:%s)%11c[I]%8c(%25F l.%3l) %07c%v");
logger.setPattern(ska::LogLevel::Warn, "(%m:%s)%14c[W]%8c(%25F l.%3l) %07c%v");
logger.setPattern(ska::LogLevel::Error, "(%m:%s)%12c[E]%8c(%25F l.%3l) %07c%v");
logger.enableComplexLogging();
}
}
}
ska::detail::SkaLangSerializerLogger ska::detail::BuildLangSerializerLogger(const char * filename) {
static auto LogFileOutput = std::ofstream { filename };
auto logger = SkaLangSerializerLogger{};
#ifdef SKALANG_SERIALIZER_LOGGING
logger.get<0>().addOutputTarget(LogFileOutput);
logger.get<1>().addOutputTarget(std::cout);
UpdatePatterns(logger.get<0>());
UpdatePatterns(logger.get<1>());
#endif
ska::process::SignalHandlerAddAction([](int signalCode) {
detail::LangSerializerLogger().terminate();
LogFileOutput.close();
});
return logger;
}
| 32.047619 | 100 | 0.715453 | Scorbutics |
b1d41b1f58046eeb1a876aafd4306bcf76337c63 | 35,526 | cpp | C++ | Source/IO/Plotfile.cpp | etpalmer63/ERF | 88a3969ae93aae5b9d1416217df9051da476114e | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/IO/Plotfile.cpp | etpalmer63/ERF | 88a3969ae93aae5b9d1416217df9051da476114e | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/IO/Plotfile.cpp | etpalmer63/ERF | 88a3969ae93aae5b9d1416217df9051da476114e | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include <EOS.H>
#include <ERF.H>
#include "AMReX_Interp_3D_C.H"
#include "AMReX_PlotFileUtil.H"
#ifdef ERF_USE_TERRAIN
#include "TerrainMetrics.H"
#endif
using namespace amrex;
// get plotfile name
std::string
ERF::PlotFileName (int lev) const
{
return Concatenate(plot_file, lev, 5);
}
void
ERF::setPlotVariables ()
{
ParmParse pp("amr");
if (pp.contains("plot_vars"))
{
std::string nm;
int nPltVars = pp.countval("plot_vars");
for (int i = 0; i < nPltVars; i++)
{
pp.get("plot_vars", nm, i);
if (nm == "ALL") {
// put all conserved state variables in the plot variables list
plot_state_names = cons_names;
// put all velocity components in the plot variables list
plot_state_names.insert(plot_state_names.end(), velocity_names.begin(), velocity_names.end());
} else if (nm == "NONE" || nm == "None") {
// put no state variables in the plot variable list
plot_state_names.clear();
} else {
// add the named variable to our list of plot variables
// if it is not already in the list
if (!containerHasElement(plot_state_names, nm)) {
plot_state_names.push_back(nm);
}
}
}
}
else
{
//
// The default is to add all state conserved and velocity variables to the plot variables list
//
plot_state_names = cons_names;
plot_state_names.insert(plot_state_names.end(), velocity_names.begin(), velocity_names.end());
}
// Get state variables in the same order as we define them,
// since they may be in any order in the input list
Vector<std::string> tmp_plot_names;
for (int i = 0; i < Cons::NumVars; ++i) {
if (containerHasElement(plot_state_names, cons_names[i])) {
tmp_plot_names.push_back(cons_names[i]);
}
}
// check for velocity since it's not in cons_names
// if we are asked for any velocity component, we will need them all
if (containerHasElement(plot_state_names, "x_velocity") ||
containerHasElement(plot_state_names, "y_velocity") ||
containerHasElement(plot_state_names, "z_velocity")) {
tmp_plot_names.push_back("x_velocity");
tmp_plot_names.push_back("y_velocity");
tmp_plot_names.push_back("z_velocity");
}
// check to see if we found all the requested vairables
for (auto plot_name : plot_state_names) {
if (!containerHasElement(tmp_plot_names, plot_name)) {
Warning("\nWARNING: Requested to plot variable '" + plot_name + "' but it is not available");
}
}
plot_state_names = tmp_plot_names;
if (pp.contains("derive_plot_vars"))
{
std::string nm;
int nDrvPltVars = pp.countval("derive_plot_vars");
for (int i = 0; i < nDrvPltVars; i++)
{
pp.get("derive_plot_vars", nm, i);
if (nm == "ALL") {
// put all diagnostic variables in the plot variables list
plot_deriv_names = derived_names;
} else if (nm == "NONE" || nm == "None") {
// put no diagnostic variables in the plot variable list
plot_deriv_names.clear();
} else {
// add the named variable to our list of plot variables
// if it is not already in the list
if (!containerHasElement(plot_deriv_names, nm)) {
plot_deriv_names.push_back(nm);
}
}
}
}
else
{
//
// The default is to add none of the diagnostic variables to the plot variables list
//
plot_deriv_names.clear();
}
// Get derived variables in the same order as we define them,
// since they may be in any order in the input list
Vector<std::string> tmp_deriv_names;
for (int i = 0; i < derived_names.size(); ++i) {
if (containerHasElement(plot_deriv_names, derived_names[i])) {
tmp_deriv_names.push_back(derived_names[i]);
}
}
// check to see if we found all the requested vairables
for (auto plot_name : plot_deriv_names) {
if (!containerHasElement(tmp_deriv_names, plot_name)) {
Warning("\nWARNING: Requested to plot derived variable '" + plot_name + "' but it is not available");
}
}
plot_deriv_names = tmp_deriv_names;
}
// set plotfile variable names
Vector<std::string>
ERF::PlotFileVarNames () const
{
Vector<std::string> names;
names.insert(names.end(), plot_state_names.begin(), plot_state_names.end());
names.insert(names.end(), plot_deriv_names.begin(), plot_deriv_names.end());
return names;
}
// write plotfile to disk
void
ERF::WritePlotFile ()
{
const Vector<std::string> varnames = PlotFileVarNames();
const int ncomp_mf = varnames.size();
// We fillpatch here because some of the derived quantities require derivatives
// which require ghost cells to be filled
for (int lev = 0; lev <= finest_level; ++lev) {
FillPatch(lev, t_new[lev], vars_new[lev]);
}
if (ncomp_mf == 0)
return;
Vector<MultiFab> mf(finest_level+1);
for (int lev = 0; lev <= finest_level; ++lev) {
mf[lev].define(grids[lev], dmap[lev], ncomp_mf, 0);
}
#ifdef ERF_USE_TERRAIN
Vector<MultiFab> mf_nd(finest_level+1);
for (int lev = 0; lev <= finest_level; ++lev) {
BoxArray nodal_grids(grids[lev]); nodal_grids.surroundingNodes();
mf_nd[lev].define(nodal_grids, dmap[lev], ncomp_mf, 0);
mf_nd[lev].setVal(0.);
}
#endif
for (int lev = 0; lev <= finest_level; ++lev) {
int mf_comp = 0;
// First, copy any of the conserved state variables into the output plotfile
AMREX_ALWAYS_ASSERT(cons_names.size() == Cons::NumVars);
for (int i = 0; i < Cons::NumVars; ++i) {
if (containerHasElement(plot_state_names, cons_names[i])) {
MultiFab::Copy(mf[lev],vars_new[lev][Vars::cons],i,mf_comp,1,0);
mf_comp++;
}
}
// Next, check for velocities and if desired, output them
if (containerHasElement(plot_state_names, "x_velocity") ||
containerHasElement(plot_state_names, "y_velocity") ||
containerHasElement(plot_state_names, "z_velocity")) {
average_face_to_cellcenter(mf[lev],mf_comp,
Array<const MultiFab*,3>{&vars_new[lev][Vars::xvel],&vars_new[lev][Vars::yvel],&vars_new[lev][Vars::zvel]});
mf_comp += AMREX_SPACEDIM;
}
// Finally, check for any derived quantities and compute them, inserting
// them into our output multifab
auto calculate_derived = [&](const std::string der_name,
const decltype(derived::erf_dernull)& der_function)
{
if (containerHasElement(plot_deriv_names, der_name)) {
MultiFab dmf(mf[lev], make_alias, mf_comp, 1);
for (MFIter mfi(dmf, TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
auto& dfab = dmf[mfi];
auto& sfab = vars_new[lev][Vars::cons][mfi];
der_function(bx, dfab, 0, 1, sfab, Geom(lev), t_new[0], nullptr, lev);
}
mf_comp++;
}
};
// Note: All derived variables must be computed in order of "derived_names" defined in ERF.H
calculate_derived("pressure", derived::erf_derpres);
calculate_derived("soundspeed", derived::erf_dersoundspeed);
calculate_derived("temp", derived::erf_dertemp);
calculate_derived("theta", derived::erf_dertheta);
calculate_derived("KE", derived::erf_derKE);
calculate_derived("QKE", derived::erf_derQKE);
calculate_derived("scalar", derived::erf_derscalar);
if (containerHasElement(plot_deriv_names, "pres_hse"))
{
#ifdef ERF_USE_TERRAIN
MultiFab::Copy(mf[lev],pres_hse[lev],0,mf_comp,1,0);
#else
auto d_pres_hse_lev = d_pres_hse[lev].dataPtr();
for ( MFIter mfi(mf[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
const Array4<Real>& derdat = mf[lev].array(mfi);
ParallelFor(bx, [=, ng_pres_hse=ng_pres_hse] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
derdat(i, j, k, mf_comp) = d_pres_hse_lev[k+ng_pres_hse];
});
}
#endif
mf_comp += 1;
}
if (containerHasElement(plot_deriv_names, "dens_hse"))
{
#ifdef ERF_USE_TERRAIN
MultiFab::Copy(mf[lev],dens_hse[lev],0,mf_comp,1,0);
#else
auto d_dens_hse_lev = d_dens_hse[lev].dataPtr();
for ( MFIter mfi(mf[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi)
{ const Box& bx = mfi.tilebox();
const Array4<Real>& derdat = mf[lev].array(mfi);
ParallelFor(bx, [=, ng_dens_hse=ng_dens_hse] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
derdat(i, j, k, mf_comp) = d_dens_hse_lev[k+ng_dens_hse];
});
}
#endif
mf_comp ++;
}
if (containerHasElement(plot_deriv_names, "pert_pres"))
{
#ifndef ERF_USE_TERRAIN
auto d_pres_hse_lev = d_pres_hse[lev].dataPtr();
#endif
for ( MFIter mfi(mf[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
const Array4<Real>& derdat = mf[lev].array(mfi);
#ifdef ERF_USE_TERRAIN
const Array4<Real const>& p0_arr = pres_hse[lev].const_array(mfi);
#endif
const Array4<Real const>& S_arr = vars_new[lev][Vars::cons].const_array(mfi);
ParallelFor(bx, [=, ng_pres_hse=ng_pres_hse] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
const Real rhotheta = S_arr(i,j,k,RhoTheta_comp);
#ifdef ERF_USE_TERRAIN
derdat(i, j, k, mf_comp) = getPgivenRTh(rhotheta) - p0_arr(i,j,k);
#else
derdat(i, j, k, mf_comp) = getPgivenRTh(rhotheta) - d_pres_hse_lev[k+ng_pres_hse];
#endif
});
}
mf_comp ++;
}
if (containerHasElement(plot_deriv_names, "pert_dens"))
{
#ifndef ERF_USE_TERRAIN
auto d_dens_hse_lev = d_dens_hse[lev].dataPtr();
#endif
for ( MFIter mfi(mf[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
const Array4<Real>& derdat = mf[lev].array(mfi);
const Array4<Real const>& S_arr = vars_new[lev][Vars::cons].const_array(mfi);
#ifdef ERF_USE_TERRAIN
const Array4<Real const>& r0_arr = dens_hse[lev].const_array(mfi);
#endif
ParallelFor(bx, [=, ng_dens_hse=ng_dens_hse] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
#ifdef ERF_USE_TERRAIN
derdat(i, j, k, mf_comp) = S_arr(i,j,k,Rho_comp) - r0_arr(i,j,k);
#else
derdat(i, j, k, mf_comp) = S_arr(i,j,k,Rho_comp) - d_dens_hse_lev[k+ng_dens_hse];
#endif
});
}
mf_comp ++;
}
if (containerHasElement(plot_deriv_names, "dpdx"))
{
auto dxInv = geom[lev].InvCellSizeArray();
MultiFab pres(vars_new[lev][Vars::cons].boxArray(), vars_new[lev][Vars::cons].DistributionMap(), 1, 1);
for ( MFIter mfi(mf[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
// First define pressure on grown box
const Box& gbx = mfi.growntilebox(1);
const Array4<Real> & p_arr = pres.array(mfi);
const Array4<Real const>& S_arr = vars_new[lev][Vars::cons].const_array(mfi);
amrex::ParallelFor(gbx, [=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept {
p_arr(i,j,k) = getPgivenRTh(S_arr(i,j,k,RhoTheta_comp));
});
}
pres.FillBoundary(geom[lev].periodicity());
for ( MFIter mfi(mf[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
// Now compute pressure gradient on valid box
const Box& bx = mfi.tilebox();
const Array4<Real>& derdat = mf[lev].array(mfi);
const Array4<Real> & p_arr = pres.array(mfi);
#ifdef ERF_USE_TERRAIN
const Array4<Real const>& z_nd = z_phys_nd[lev].const_array(mfi);
#endif
ParallelFor(bx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
#ifdef ERF_USE_TERRAIN
// Pgrad at lower I face
Real met_h_xi_lo,met_h_eta_lo,met_h_zeta_lo;
ComputeMetricAtIface(i,j,k,met_h_xi_lo,met_h_eta_lo,met_h_zeta_lo,dxInv,z_nd,TerrainMet::h_xi_zeta);
Real gp_xi_lo = dxInv[0] * (p_arr(i,j,k) - p_arr(i-1,j,k));
Real gp_zeta_on_iface_lo;
if(k==0) {
gp_zeta_on_iface_lo = 0.5 * dxInv[2] * (
p_arr(i-1,j,k+1) + p_arr(i,j,k+1)
- p_arr(i-1,j,k ) - p_arr(i,j,k ) );
} else if(k==bx.bigEnd(2)) {
gp_zeta_on_iface_lo = 0.5 * dxInv[2] * (
p_arr(i-1,j,k ) + p_arr(i,j,k )
- p_arr(i-1,j,k-1) - p_arr(i,j,k-1) );
} else {
gp_zeta_on_iface_lo = 0.25 * dxInv[2] * (
p_arr(i-1,j,k+1) + p_arr(i,j,k+1)
- p_arr(i-1,j,k-1) - p_arr(i,j,k-1) );
}
amrex::Real gpx_lo = gp_xi_lo - (met_h_xi_lo/ met_h_zeta_lo) * gp_zeta_on_iface_lo;
// Pgrad at higher I face
Real met_h_xi_hi,met_h_eta_hi,met_h_zeta_hi;
ComputeMetricAtIface(i+1,j,k,met_h_xi_hi,met_h_eta_hi,met_h_zeta_hi,dxInv,z_nd,TerrainMet::h_xi_zeta);
Real gp_xi_hi = dxInv[0] * (p_arr(i+1,j,k) - p_arr(i,j,k));
Real gp_zeta_on_iface_hi;
if(k==0) {
gp_zeta_on_iface_hi = 0.5 * dxInv[2] * (
p_arr(i+1,j,k+1) + p_arr(i,j,k+1)
- p_arr(i+1,j,k ) - p_arr(i,j,k ) );
} else if(k==bx.bigEnd(2)) {
gp_zeta_on_iface_hi = 0.5 * dxInv[2] * (
p_arr(i+1,j,k ) + p_arr(i,j,k )
- p_arr(i+1,j,k-1) - p_arr(i,j,k-1) );
} else {
gp_zeta_on_iface_hi = 0.25 * dxInv[2] * (
p_arr(i+1,j,k+1) + p_arr(i,j,k+1)
- p_arr(i+1,j,k-1) - p_arr(i,j,k-1) );
}
amrex::Real gpx_hi = gp_xi_hi - (met_h_xi_hi/ met_h_zeta_hi) * gp_zeta_on_iface_hi;
// Average P grad to CC
derdat(i ,j ,k, mf_comp) = 0.5 * (gpx_lo + gpx_hi);
#else
derdat(i ,j ,k, mf_comp) = 0.5 * (p_arr(i+1,j,k) - p_arr(i-1,j,k)) * dxInv[0];
#endif
});
}
mf_comp ++;
}
if (containerHasElement(plot_deriv_names, "dpdy"))
{
auto dxInv = geom[lev].InvCellSizeArray();
MultiFab pres(vars_new[lev][Vars::cons].boxArray(), vars_new[lev][Vars::cons].DistributionMap(), 1, 1);
for ( MFIter mfi(mf[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
// First define pressure on grown box
const Box& gbx = mfi.growntilebox(1);
const Array4<Real> & p_arr = pres.array(mfi);
const Array4<Real const>& S_arr = vars_new[lev][Vars::cons].const_array(mfi);
amrex::ParallelFor(gbx, [=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept {
p_arr(i,j,k) = getPgivenRTh(S_arr(i,j,k,RhoTheta_comp));
});
}
pres.FillBoundary(geom[lev].periodicity());
for ( MFIter mfi(mf[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
// Now compute pressure gradient on valid box
const Box& bx = mfi.tilebox();
const Array4<Real>& derdat = mf[lev].array(mfi);
const Array4<Real> & p_arr = pres.array(mfi);
#ifdef ERF_USE_TERRAIN
const Array4<Real const>& z_nd = z_phys_nd[lev].const_array(mfi);
#endif
ParallelFor(bx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
#ifdef ERF_USE_TERRAIN
Real met_h_xi_lo,met_h_eta_lo,met_h_zeta_lo;
ComputeMetricAtJface(i,j,k,met_h_xi_lo,met_h_eta_lo,met_h_zeta_lo,dxInv,z_nd,TerrainMet::h_eta_zeta);
Real gp_eta_lo = dxInv[1] * (p_arr(i,j,k) - p_arr(i,j-1,k));
Real gp_zeta_on_jface_lo = (k == 0) ?
0.5 * dxInv[2] * (
p_arr(i,j,k+1) + p_arr(i,j-1,k+1) - p_arr(i,j,k) - p_arr(i,j-1,k)):
0.25 * dxInv[2] * (
p_arr(i,j,k+1) + p_arr(i,j-1,k+1) - p_arr(i,j,k-1) - p_arr(i,j-1,k-1));
amrex::Real gpy_lo = gp_eta_lo - (met_h_eta_lo / met_h_zeta_lo) * gp_zeta_on_jface_lo;
Real met_h_xi_hi,met_h_eta_hi,met_h_zeta_hi;
ComputeMetricAtJface(i,j+1,k,met_h_xi_hi,met_h_eta_hi,met_h_zeta_hi,dxInv,z_nd,TerrainMet::h_eta_zeta);
Real gp_eta_hi = dxInv[1] * (p_arr(i,j+1,k) - p_arr(i,j,k));
Real gp_zeta_on_jface_hi = (k == 0) ?
0.5 * dxInv[2] * (
p_arr(i,j+1,k+1) + p_arr(i,j,k+1) - p_arr(i,j+1,k) - p_arr(i,j,k)):
0.25 * dxInv[2] * (
p_arr(i,j+1,k+1) + p_arr(i,j,k+1) - p_arr(i,j+1,k-1) - p_arr(i,j,k-1));
amrex::Real gpy_hi = gp_eta_hi - (met_h_eta_hi / met_h_zeta_hi) * gp_zeta_on_jface_hi;
derdat(i ,j ,k, mf_comp) = 0.5 * (gpy_lo + gpy_hi);
#else
derdat(i ,j ,k, mf_comp) = 0.5 * (p_arr(i,j+1,k) - p_arr(i,j-1,k)) * dxInv[1];
#endif
});
}
mf_comp ++;
}
#ifdef ERF_USE_TERRAIN
if (containerHasElement(plot_deriv_names, "pres_hse_x"))
{
auto dxInv = geom[lev].InvCellSizeArray();
for ( MFIter mfi(mf[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
const Array4<Real >& derdat = mf[lev].array(mfi);
const Array4<Real const>& p_arr = pres_hse[lev].const_array(mfi);
const Array4<Real const>& z_nd = z_phys_nd[lev].const_array(mfi);
ParallelFor(bx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
Real met_h_xi_lo,met_h_eta_lo,met_h_zeta_lo;
ComputeMetricAtIface(i,j,k,met_h_xi_lo,met_h_eta_lo,met_h_zeta_lo,dxInv,z_nd,TerrainMet::h_xi_zeta);
Real gp_xi_lo = dxInv[0] * (p_arr(i,j,k) - p_arr(i-1,j,k));
Real gp_zeta_on_iface_lo = (k == 0) ?
0.5 * dxInv[2] * (
p_arr(i,j,k+1) + p_arr(i-1,j,k+1) - p_arr(i,j,k) - p_arr(i-1,j,k)):
0.25 * dxInv[2] * (
p_arr(i,j,k+1) + p_arr(i-1,j,k+1) - p_arr(i,j,k-1) - p_arr(i-1,j,k-1));
amrex::Real gpx_lo = gp_xi_lo - (met_h_xi_lo/ met_h_zeta_lo) * gp_zeta_on_iface_lo;
Real met_h_xi_hi,met_h_eta_hi,met_h_zeta_hi;
ComputeMetricAtIface(i+1,j,k,met_h_xi_hi,met_h_eta_hi,met_h_zeta_hi,dxInv,z_nd,TerrainMet::h_xi_zeta);
Real gp_xi_hi = dxInv[0] * (p_arr(i+1,j,k) - p_arr(i,j,k));
Real gp_zeta_on_iface_hi = (k == 0) ?
0.5 * dxInv[2] * (
p_arr(i+1,j,k+1) + p_arr(i,j,k+1) - p_arr(i+1,j,k) - p_arr(i,j,k)):
0.25 * dxInv[2] * (
p_arr(i+1,j,k+1) + p_arr(i,j,k+1) - p_arr(i+1,j,k-1) - p_arr(i,j,k-1));
amrex::Real gpx_hi = gp_xi_hi - (met_h_xi_hi/ met_h_zeta_hi) * gp_zeta_on_iface_hi;
derdat(i ,j ,k, mf_comp) = 0.5 * (gpx_lo + gpx_hi);
});
}
mf_comp += 1;
}
if (containerHasElement(plot_deriv_names, "pres_hse_y"))
{
auto dxInv = geom[lev].InvCellSizeArray();
for ( MFIter mfi(mf[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
const Array4<Real >& derdat = mf[lev].array(mfi);
const Array4<Real const>& p_arr = pres_hse[lev].const_array(mfi);
const Array4<Real const>& z_nd = z_phys_nd[lev].const_array(mfi);
ParallelFor(bx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
Real met_h_xi_lo,met_h_eta_lo,met_h_zeta_lo;
ComputeMetricAtJface(i,j,k,met_h_xi_lo,met_h_eta_lo,met_h_zeta_lo,dxInv,z_nd,TerrainMet::h_eta_zeta);
Real gp_eta_lo = dxInv[1] * (p_arr(i,j,k) - p_arr(i,j-1,k));
Real gp_zeta_on_jface_lo = (k == 0) ?
0.5 * dxInv[2] * (
p_arr(i,j,k+1) + p_arr(i,j-1,k+1) - p_arr(i,j,k) - p_arr(i,j-1,k)):
0.25 * dxInv[2] * (
p_arr(i,j,k+1) + p_arr(i,j-1,k+1) - p_arr(i,j,k-1) - p_arr(i,j-1,k-1));
amrex::Real gpy_lo = gp_eta_lo - (met_h_eta_lo / met_h_zeta_lo) * gp_zeta_on_jface_lo;
Real met_h_xi_hi,met_h_eta_hi,met_h_zeta_hi;
ComputeMetricAtJface(i,j+1,k,met_h_xi_hi,met_h_eta_hi,met_h_zeta_hi,dxInv,z_nd,TerrainMet::h_eta_zeta);
Real gp_eta_hi = dxInv[1] * (p_arr(i,j+1,k) - p_arr(i,j,k));
Real gp_zeta_on_jface_hi = (k == 0) ?
0.5 * dxInv[2] * (
p_arr(i,j+1,k+1) + p_arr(i,j,k+1) - p_arr(i,j+1,k) - p_arr(i,j,k)):
0.25 * dxInv[2] * (
p_arr(i,j+1,k+1) + p_arr(i,j,k+1) - p_arr(i,j+1,k-1) - p_arr(i,j,k-1));
amrex::Real gpy_hi = gp_eta_hi - (met_h_eta_hi / met_h_zeta_hi) * gp_zeta_on_jface_hi;
derdat(i ,j ,k, mf_comp) = 0.5 * (gpy_lo + gpy_hi);
});
}
mf_comp += 1;
}
if (containerHasElement(plot_deriv_names, "z_phys"))
{
MultiFab::Copy(mf[lev],z_phys_cc[lev],0,mf_comp,1,0);
mf_comp ++;
}
if (containerHasElement(plot_deriv_names, "detJ"))
{
MultiFab::Copy(mf[lev],detJ_cc[lev],0,mf_comp,1,0);
mf_comp ++;
}
#endif
}
const std::string& plotfilename = PlotFileName(istep[0]);
amrex::Print() << "Writing plotfile " << plotfilename << "\n";
if (finest_level == 0)
{
if (plotfile_type == "amrex") {
#ifdef ERF_USE_TERRAIN
// We started with mf_nd holding 0 in every component; here we fill only the offset in z
int lev = 0;
MultiFab::Copy(mf_nd[lev],z_phys_nd[lev],0,2,1,0);
Real dz = Geom()[lev].CellSizeArray()[2];
for (MFIter mfi(mf_nd[lev], TilingIfNotGPU()); mfi.isValid(); ++mfi) {
const Box& bx = mfi.tilebox();
Array4< Real> mf_arr = mf_nd[lev].array(mfi);
ParallelFor(bx, [=] AMREX_GPU_DEVICE (int i, int j, int k) {
mf_arr(i,j,k,2) -= k * dz;
});
}
WriteMultiLevelPlotfileWithTerrain(plotfilename, finest_level+1,
GetVecOfConstPtrs(mf),
GetVecOfConstPtrs(mf_nd),
varnames,
t_new[0], istep, refRatio());
#else
WriteMultiLevelPlotfile(plotfilename, finest_level+1,
GetVecOfConstPtrs(mf),
varnames,
Geom(), t_new[0], istep, refRatio());
#endif
writeJobInfo(plotfilename);
#ifdef ERF_USE_NETCDF
} else {
writeNCPlotFile(plotfilename, GetVecOfConstPtrs(mf), varnames, istep, t_new[0]);
#endif
}
} else {
Vector<IntVect> r2(finest_level);
Vector<Geometry> g2(finest_level+1);
Vector<MultiFab> mf2(finest_level+1);
mf2[0].define(grids[0], dmap[0], ncomp_mf, 0);
// Copy level 0 as is
MultiFab::Copy(mf2[0],mf[0],0,0,mf[0].nComp(),0);
// Define a new multi-level array of Geometry's so that we pass the new "domain" at lev > 0
Array<int,AMREX_SPACEDIM> periodicity =
{Geom()[0].isPeriodic(0),Geom()[0].isPeriodic(1),Geom()[0].isPeriodic(2)};
g2[0].define(Geom()[0].Domain(),&(Geom()[0].ProbDomain()),0,periodicity.data());
r2[0] = IntVect(1,1,ref_ratio[0][0]);
for (int lev = 1; lev <= finest_level; ++lev) {
if (lev > 1) {
r2[lev-1][0] = 1;
r2[lev-1][1] = 1;
r2[lev-1][2] = r2[lev-2][2] * ref_ratio[lev-1][0];
}
mf2[lev].define(refine(grids[lev],r2[lev-1]), dmap[lev], ncomp_mf, 0);
// Set the new problem domain
Box d2(Geom()[lev].Domain());
d2.refine(r2[lev-1]);
g2[lev].define(d2,&(Geom()[lev].ProbDomain()),0,periodicity.data());
}
// Do piecewise interpolation of mf into mf2
for (int lev = 1; lev <= finest_level; ++lev) {
for (MFIter mfi(mf2[lev], TilingIfNotGPU()); mfi.isValid(); ++mfi) {
const Box& bx = mfi.tilebox();
pcinterp_interp(bx,mf2[lev].array(mfi), 0, mf[lev].nComp(), mf[lev].const_array(mfi),0,r2[lev-1]);
}
}
// Define an effective ref_ratio which is isotropic to be passed into WriteMultiLevelPlotfile
Vector<IntVect> rr(finest_level);
for (int lev = 0; lev < finest_level; ++lev) {
rr[lev] = IntVect(ref_ratio[lev][0],ref_ratio[lev][1],ref_ratio[lev][0]);
}
if (plotfile_type == "amrex") {
WriteMultiLevelPlotfile(plotfilename, finest_level+1, GetVecOfConstPtrs(mf2), varnames,
g2, t_new[0], istep, rr);
writeJobInfo(plotfilename);
#ifdef ERF_USE_NETCDF
} else {
writeNCPlotFile(plotfilename, GetVecOfConstPtrs(mf2), varnames, istep, t_new[0]);
#endif
}
} // end multi-level
}
#ifdef ERF_USE_TERRAIN
void
ERF::WriteMultiLevelPlotfileWithTerrain (const std::string& plotfilename, int nlevels,
const Vector<const MultiFab*>& mf,
const Vector<const MultiFab*>& mf_nd,
const Vector<std::string>& varnames,
Real time,
const Vector<int>& level_steps,
const Vector<IntVect>& ref_ratio,
const std::string &versionName,
const std::string &levelPrefix,
const std::string &mfPrefix,
const Vector<std::string>& extra_dirs) const
{
BL_PROFILE("WriteMultiLevelPlotfileWithTerrain()");
BL_ASSERT(nlevels <= mf.size());
BL_ASSERT(nlevels <= ref_ratio.size()+1);
BL_ASSERT(nlevels <= level_steps.size());
BL_ASSERT(mf[0]->nComp() == varnames.size());
bool callBarrier(false);
PreBuildDirectorHierarchy(plotfilename, levelPrefix, nlevels, callBarrier);
if (!extra_dirs.empty()) {
for (const auto& d : extra_dirs) {
const std::string ed = plotfilename+"/"+d;
PreBuildDirectorHierarchy(ed, levelPrefix, nlevels, callBarrier);
}
}
ParallelDescriptor::Barrier();
if (ParallelDescriptor::MyProc() == ParallelDescriptor::NProcs()-1) {
Vector<BoxArray> boxArrays(nlevels);
for(int level(0); level < boxArrays.size(); ++level) {
boxArrays[level] = mf[level]->boxArray();
}
auto f = [=]() {
VisMF::IO_Buffer io_buffer(VisMF::IO_Buffer_Size);
std::string HeaderFileName(plotfilename + "/Header");
std::ofstream HeaderFile;
HeaderFile.rdbuf()->pubsetbuf(io_buffer.dataPtr(), io_buffer.size());
HeaderFile.open(HeaderFileName.c_str(), std::ofstream::out |
std::ofstream::trunc |
std::ofstream::binary);
if( ! HeaderFile.good()) FileOpenFailed(HeaderFileName);
WriteGenericPlotfileHeaderWithTerrain(HeaderFile, nlevels, boxArrays, varnames,
time, level_steps, ref_ratio, versionName,
levelPrefix, mfPrefix);
};
if (AsyncOut::UseAsyncOut()) {
AsyncOut::Submit(std::move(f));
} else {
f();
}
}
std::string mf_nodal_prefix = "Nu_nd";
for (int level = 0; level <= finest_level; ++level)
{
if (AsyncOut::UseAsyncOut()) {
VisMF::AsyncWrite(*mf[level],
MultiFabFileFullPrefix(level, plotfilename, levelPrefix, mfPrefix),
true);
VisMF::AsyncWrite(*mf_nd[level],
MultiFabFileFullPrefix(level, plotfilename, levelPrefix, mf_nodal_prefix),
true);
} else {
const MultiFab* data;
std::unique_ptr<MultiFab> mf_tmp;
if (mf[level]->nGrowVect() != 0) {
mf_tmp = std::make_unique<MultiFab>(mf[level]->boxArray(),
mf[level]->DistributionMap(),
mf[level]->nComp(), 0, MFInfo(),
mf[level]->Factory());
MultiFab::Copy(*mf_tmp, *mf[level], 0, 0, mf[level]->nComp(), 0);
data = mf_tmp.get();
} else {
data = mf[level];
}
VisMF::Write(*data , MultiFabFileFullPrefix(level, plotfilename, levelPrefix, mfPrefix));
VisMF::Write(*mf_nd[level], MultiFabFileFullPrefix(level, plotfilename, levelPrefix, mf_nodal_prefix));
}
}
}
void
ERF::WriteGenericPlotfileHeaderWithTerrain (std::ostream &HeaderFile,
int nlevels,
const Vector<BoxArray> &bArray,
const Vector<std::string> &varnames,
Real time,
const Vector<int> &level_steps,
const Vector<IntVect> &ref_ratio,
const std::string &versionName,
const std::string &levelPrefix,
const std::string &mfPrefix) const
{
BL_ASSERT(nlevels <= bArray.size());
BL_ASSERT(nlevels <= ref_ratio.size()+1);
BL_ASSERT(nlevels <= level_steps.size());
HeaderFile.precision(17);
// ---- this is the generic plot file type name
HeaderFile << versionName << '\n';
HeaderFile << varnames.size() << '\n';
for (int ivar = 0; ivar < varnames.size(); ++ivar) {
HeaderFile << varnames[ivar] << "\n";
}
HeaderFile << AMREX_SPACEDIM << '\n';
HeaderFile << time << '\n';
HeaderFile << finest_level << '\n';
for (int i = 0; i < AMREX_SPACEDIM; ++i) {
HeaderFile << geom[0].ProbLo(i) << ' ';
}
HeaderFile << '\n';
for (int i = 0; i < AMREX_SPACEDIM; ++i) {
HeaderFile << geom[0].ProbHi(i) << ' ';
}
HeaderFile << '\n';
for (int i = 0; i < finest_level; ++i) {
HeaderFile << ref_ratio[i][0] << ' ';
}
HeaderFile << '\n';
for (int i = 0; i <= finest_level; ++i) {
HeaderFile << geom[i].Domain() << ' ';
}
HeaderFile << '\n';
for (int i = 0; i <= finest_level; ++i) {
HeaderFile << level_steps[i] << ' ';
}
HeaderFile << '\n';
for (int i = 0; i <= finest_level; ++i) {
for (int k = 0; k < AMREX_SPACEDIM; ++k) {
HeaderFile << geom[i].CellSize()[k] << ' ';
}
HeaderFile << '\n';
}
HeaderFile << (int) geom[0].Coord() << '\n';
HeaderFile << "0\n";
for (int level = 0; level <= finest_level; ++level) {
HeaderFile << level << ' ' << bArray[level].size() << ' ' << time << '\n';
HeaderFile << level_steps[level] << '\n';
const IntVect& domain_lo = geom[level].Domain().smallEnd();
for (int i = 0; i < bArray[level].size(); ++i)
{
// Need to shift because the RealBox ctor we call takes the
// physical location of index (0,0,0). This does not affect
// the usual cases where the domain index starts with 0.
const Box& b = shift(bArray[level][i], -domain_lo);
RealBox loc = RealBox(b, geom[level].CellSize(), geom[level].ProbLo());
for (int n = 0; n < AMREX_SPACEDIM; ++n) {
HeaderFile << loc.lo(n) << ' ' << loc.hi(n) << '\n';
}
}
HeaderFile << MultiFabHeaderPath(level, levelPrefix, mfPrefix) << '\n';
}
HeaderFile << "1" << "\n";
HeaderFile << "3" << "\n";
HeaderFile << "amrexvec_nu_x" << "\n";
HeaderFile << "amrexvec_nu_y" << "\n";
HeaderFile << "amrexvec_nu_z" << "\n";
std::string mf_nodal_prefix = "Nu_nd";
for (int level = 0; level <= finest_level; ++level) {
HeaderFile << MultiFabHeaderPath(level, levelPrefix, mf_nodal_prefix) << '\n';
}
}
#endif
| 44.131677 | 124 | 0.509739 | etpalmer63 |
b1dba94ddb9a84ea1dc27808a38b819536f7346b | 17,755 | cpp | C++ | 2006/samples/database/ARXDBG/Snoop/ArxDbgUiDlgObjState.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | 1 | 2021-06-25T02:58:47.000Z | 2021-06-25T02:58:47.000Z | 2004/samples/database/ARXDBG/Snoop/ArxDbgUiDlgObjState.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | null | null | null | 2004/samples/database/ARXDBG/Snoop/ArxDbgUiDlgObjState.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | 3 | 2020-05-23T02:47:44.000Z | 2020-10-27T01:26:53.000Z | //
// (C) Copyright 1998-2002 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
//
#include "stdafx.h"
#include "ArxDbgUiDlgObjState.h"
#include "ArxDbgUtils.h"
#include "ArxDbgApp.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/****************************************************************************
**
** ArxDbgUiDlgObjState::ArxDbgUiDlgObjState
**
** **jma
**
*************************************/
ArxDbgUiDlgObjState::ArxDbgUiDlgObjState(CWnd* parent, const AcDbObjectId& objId, LPCTSTR dboxTitle)
: CAcUiDialog(ArxDbgUiDlgObjState::IDD, parent, ArxDbgApp::getApp()->dllInstance()),
m_obj(NULL),
m_objId(objId),
m_wasOpenOnConstruct(false),
m_dboxTitle(dboxTitle),
m_bUpgradedFromNotify(false)
{
//{{AFX_DATA_INIT(ArxDbgUiDlgObjState)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
SetPersistency(FALSE);
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::ArxDbgUiDlgObjState
**
** **jma
**
*************************************/
ArxDbgUiDlgObjState::ArxDbgUiDlgObjState(CWnd* parent, AcDbObject* obj, LPCTSTR dboxTitle)
: CAcUiDialog(ArxDbgUiDlgObjState::IDD, parent, ArxDbgApp::getApp()->dllInstance()),
m_obj(obj),
m_objId(obj->objectId()),
m_wasOpenOnConstruct(true),
m_dboxTitle(dboxTitle)
{
//{{AFX_DATA_INIT(ArxDbgUiDlgObjState)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::~ArxDbgUiDlgObjState
**
** **jma
**
*************************************/
ArxDbgUiDlgObjState::~ArxDbgUiDlgObjState()
{
if (m_wasOpenOnConstruct == false) {
// if left open, the next person to try to access it
// fails miserably, so try to close it all the way
if (m_obj != NULL) {
Acad::ErrorStatus es = Acad::eOk;
while (!m_obj->isReallyClosing()) {
es = m_obj->cancel();
if (es == Acad::eCloseWasNotifying)
return;
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else
acutPrintf("\nCalling obj->cancel().");
}
es = m_obj->cancel();
if (es == Acad::eCloseWasNotifying)
return;
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else
acutPrintf("\nCalling obj->cancel().");
}
}
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::DoDataExchange
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::DoDataExchange(CDataExchange* pDX)
{
CAcUiDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(ArxDbgUiDlgObjState)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
/////////////////////////////////////////////////////////////////////////////
// ArxDbgUiDlgObjState message map
BEGIN_MESSAGE_MAP(ArxDbgUiDlgObjState, CAcUiDialog)
//{{AFX_MSG_MAP(ArxDbgUiDlgObjState)
ON_BN_CLICKED(ARXDBG_BN_CLOSE, OnCloseObj)
ON_BN_CLICKED(ARXDBG_BN_CANCEL, OnCancelObj)
ON_BN_CLICKED(ARXDBG_BN_CLOSE_PAGE, OnCloseAndPageObj)
ON_BN_CLICKED(ARXDBG_BN_DOWNGRADE_TO_N, OnDowngradeToNotify)
ON_BN_CLICKED(ARXDBG_BN_DOWNGRADE_W, OnDowngradeWrite)
ON_BN_CLICKED(ARXDBG_BN_ERASE, OnEraseObj)
ON_BN_CLICKED(ARXDBG_BN_UNERASE, OnUneraseObj)
ON_BN_CLICKED(ARXDBG_BN_MODIFY, OnModifyObj)
ON_BN_CLICKED(ARXDBG_BN_NOTIFY, OnOpenForNotify)
ON_BN_CLICKED(ARXDBG_BN_READ, OnOpenForRead)
ON_BN_CLICKED(ARXDBG_BN_UPGRADE_FROM_N, OnUpgradeFromNotify)
ON_BN_CLICKED(ARXDBG_BN_UPGRADE_TO_W, OnUpgradeToWrite)
ON_BN_CLICKED(ARXDBG_BN_WRITE, OnOpenForWrite)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// ArxDbgUiDlgObjState message handlers
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnInitDialog
**
** **jma
**
*************************************/
BOOL
ArxDbgUiDlgObjState::OnInitDialog()
{
CAcUiDialog::OnInitDialog();
if (m_dboxTitle)
SetWindowText(m_dboxTitle);
display();
return TRUE;
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::objIsOpen
**
** **jma
**
*************************************/
bool
ArxDbgUiDlgObjState::objIsOpen()
{
if (m_obj == NULL) {
ArxDbgUtils::stopAlertBox(_T("The object is not open."));
return false;
}
else
return true;
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::objIsOpenForWrite
**
** **jma
**
*************************************/
bool
ArxDbgUiDlgObjState::objIsOpenForWrite()
{
if (!objIsOpen())
return false;
if (m_obj->isWriteEnabled())
return true;
else {
ArxDbgUtils::stopAlertBox(_T("The object must be open for write."));
return false;
}
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::open
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::open(AcDb::OpenMode openMode)
{
Acad::ErrorStatus es;
es = acdbOpenObject(m_obj, m_objId, openMode);
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else {
if (openMode == AcDb::kForRead)
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Opened For Read"));
else if (openMode == AcDb::kForWrite)
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Opened For Write"));
else
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Opened For Notify"));
}
display();
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::doErase
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::doErase(bool reallyErase)
{
if (!objIsOpenForWrite())
return;
Acad::ErrorStatus es;
es = m_obj->erase(reallyErase);
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else {
if (reallyErase == Adesk::kTrue)
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Erased"));
else
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Un-Erased"));
}
display();
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::display
** display the current state of the entity
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::display()
{
CString str;
LPCTSTR unknown = _T("N/A");
if ((m_obj != NULL) && m_obj->isReadEnabled()){
SetDlgItemText(ARXDBG_TXT_CLASS, ArxDbgUtils::objToClassStr(m_obj));
SetDlgItemText(ARXDBG_TXT_NEWOBJ, ArxDbgUtils::booleanToStr(m_obj->isNewObject(), str));
SetDlgItemText(ARXDBG_TXT_READ_ENABLED, ArxDbgUtils::booleanToStr(m_obj->isReadEnabled(), str));
SetDlgItemText(ARXDBG_TXT_WRITE_ENABLED, ArxDbgUtils::booleanToStr(m_obj->isWriteEnabled(), str));
SetDlgItemText(ARXDBG_TXT_NOTIFY_ENABLED, ArxDbgUtils::booleanToStr(m_obj->isNotifyEnabled(), str));
SetDlgItemText(ARXDBG_TXT_MODIFIED, ArxDbgUtils::booleanToStr(m_obj->isModified(), str));
SetDlgItemText(ARXDBG_TXT_MOD_XDATA, ArxDbgUtils::booleanToStr(m_obj->isModifiedXData(), str));
SetDlgItemText(ARXDBG_TXT_MOD_GRAPHICS, ArxDbgUtils::booleanToStr(m_obj->isModifiedGraphics(), str));
SetDlgItemText(ARXDBG_TXT_PROXY, ArxDbgUtils::booleanToStr(m_obj->isAProxy(), str));
SetDlgItemText(ARXDBG_TXT_TRANS_RESIDENT, ArxDbgUtils::booleanToStr(m_obj->isTransactionResident(), str));
SetDlgItemText(ARXDBG_TXT_ERASED, ArxDbgUtils::booleanToStr(m_obj->isErased(), str));
SetDlgItemText(ARXDBG_TXT_ERASE_TOGGLED, ArxDbgUtils::booleanToStr(m_obj->isEraseStatusToggled(), str));
SetDlgItemText(ARXDBG_TXT_NOTIFYING, ArxDbgUtils::booleanToStr(m_obj->isNotifying(), str));
SetDlgItemText(ARXDBG_TXT_UNDOING, ArxDbgUtils::booleanToStr(m_obj->isUndoing(), str));
SetDlgItemText(ARXDBG_TXT_CANCELLING, ArxDbgUtils::booleanToStr(m_obj->isCancelling(), str));
SetDlgItemText(ARXDBG_TXT_REALLY_CLOSING, ArxDbgUtils::booleanToStr(m_obj->isReallyClosing(), str));
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Object pointer is valid"));
}
else {
SetDlgItemText(ARXDBG_TXT_CLASS, unknown);
SetDlgItemText(ARXDBG_TXT_NEWOBJ, unknown);
SetDlgItemText(ARXDBG_TXT_READ_ENABLED, unknown);
SetDlgItemText(ARXDBG_TXT_WRITE_ENABLED, unknown);
SetDlgItemText(ARXDBG_TXT_NOTIFY_ENABLED, unknown);
SetDlgItemText(ARXDBG_TXT_MODIFIED, unknown);
SetDlgItemText(ARXDBG_TXT_MOD_XDATA, unknown);
SetDlgItemText(ARXDBG_TXT_MOD_GRAPHICS, unknown);
SetDlgItemText(ARXDBG_TXT_PROXY, unknown);
SetDlgItemText(ARXDBG_TXT_TRANS_RESIDENT, unknown);
SetDlgItemText(ARXDBG_TXT_ERASED, unknown);
SetDlgItemText(ARXDBG_TXT_ERASE_TOGGLED, unknown);
SetDlgItemText(ARXDBG_TXT_NOTIFYING, unknown);
SetDlgItemText(ARXDBG_TXT_UNDOING, unknown);
SetDlgItemText(ARXDBG_TXT_CANCELLING, unknown);
SetDlgItemText(ARXDBG_TXT_REALLY_CLOSING, unknown);
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Object pointer not valid, use object Id"));
}
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnOpenForRead
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnOpenForRead()
{
open(AcDb::kForRead);
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnOpenForWrite
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnOpenForWrite()
{
open(AcDb::kForWrite);
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnOpenForNotify
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnOpenForNotify()
{
open(AcDb::kForNotify);
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnModifyObj
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnModifyObj()
{
if (!objIsOpenForWrite())
return;
AcDbEntity* entPtr;
if ((entPtr = AcDbEntity::cast(m_obj)) == NULL) {
ArxDbgUtils::stopAlertBox(_T("This test requires an AcDbEntity."));
return;
}
Acad::ErrorStatus es;
int color = entPtr->colorIndex();
if (color >= 255)
es = entPtr->setColorIndex(1);
else
es = entPtr->setColorIndex(color+1);
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else
ArxDbgUtils::alertBox(_T("The color index was incremented as a test for modification."));
display();
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnUpgradeToWrite
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnUpgradeToWrite()
{
if (!objIsOpen())
return;
Acad::ErrorStatus es;
es = m_obj->upgradeOpen();
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Upgraded To Write"));
display();
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnDowngradeWrite
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnDowngradeWrite()
{
if (!objIsOpen())
return;
Acad::ErrorStatus es;
es = m_obj->downgradeOpen();
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Downgraded From Write"));
display();
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnUpgradeFromNotify
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnUpgradeFromNotify()
{
if (!objIsOpen())
return;
Acad::ErrorStatus es;
es = m_obj->upgradeFromNotify(m_bWasWritable);
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else {
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Upgraded From Notify"));
m_bUpgradedFromNotify =true ;
}
display();
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnDowngradeToNotify
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnDowngradeToNotify()
{
if (!objIsOpen())
return;
if (!m_bUpgradedFromNotify)
{
ArxDbgUtils::alertBox(_T("This function must have been preceded by a call to upgradeFromNotify()."));
return ;
}
m_bUpgradedFromNotify =false ;
Acad::ErrorStatus es;
es = m_obj->downgradeToNotify(m_bWasWritable);
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Downgraded To Notify"));
display();
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnCancelObj
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnCancelObj()
{
if (!objIsOpen())
return;
Adesk::Boolean totallyClosed = m_obj->isReallyClosing();
Adesk::Boolean wasModified = m_obj->isModified();
Acad::ErrorStatus es;
es = m_obj->cancel();
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else {
if (wasModified)
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Cancelled, modifications ignored"));
else
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Cancelled"));
}
if (totallyClosed)
m_obj = NULL;
display();
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnCloseObj
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnCloseObj()
{
if (!objIsOpen())
return;
Adesk::Boolean totallyClosed = m_obj->isReallyClosing();
Adesk::Boolean wasModified = m_obj->isModified();
Acad::ErrorStatus es;
es = m_obj->close();
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else {
if (wasModified)
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Closed, modifications written to database"));
else
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Closed"));
}
if (totallyClosed)
m_obj = NULL;
display();
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnCloseAndPageObj
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnCloseAndPageObj()
{
if (!objIsOpen())
return;
Adesk::Boolean totallyClosed = m_obj->isReallyClosing();
Adesk::Boolean wasModified = m_obj->isModified();
Acad::ErrorStatus es;
es = m_obj->closeAndPage();
if (es != Acad::eOk)
ArxDbgUtils::rxErrorAlert(es);
else {
if (wasModified)
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Closed, modifications written to database"));
else
SetDlgItemText(ARXDBG_TXT_ERRMSG, _T("Closed"));
}
if (totallyClosed)
m_obj = NULL;
display();
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnEraseObj
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnEraseObj()
{
doErase(true);
}
/****************************************************************************
**
** ArxDbgUiDlgObjState::OnUneraseObj
**
** **jma
**
*************************************/
void
ArxDbgUiDlgObjState::OnUneraseObj()
{
doErase(false);
}
| 27.829154 | 115 | 0.536131 | kevinzhwl |
b1dc27479c4daa8ca976e576ff0332ff92bffb3f | 731 | cpp | C++ | Source/Engine/ING/Source/ING/Coder/Coder.cpp | ING-Game-Devs/ing-engine | 7379e96433f47c005fb677cb303686e628d41bfe | [
"MIT"
] | 12 | 2022-01-17T13:25:03.000Z | 2022-03-19T08:53:56.000Z | Source/Engine/ING/Source/ING/Coder/Coder.cpp | ING-Game-Devs/ing | 829611b16a324d1ba0f8fbbd5fdc418e2b9d6aa4 | [
"MIT"
] | null | null | null | Source/Engine/ING/Source/ING/Coder/Coder.cpp | ING-Game-Devs/ing | 829611b16a324d1ba0f8fbbd5fdc418e2b9d6aa4 | [
"MIT"
] | 7 | 2022-01-21T03:50:09.000Z | 2022-03-25T14:30:29.000Z |
/**
* Include Header
*/
#include "Coder.h"
/**
* Include Utils
*/
#include <ING/Utils/Utils.h>
using namespace ING::Utils;
namespace ING {
/**
* Constructors And Destructor
*/
Coder::Coder() {
}
Coder::~Coder() {
}
/**
* Release Method
*/
void Coder::Release() {
delete this;
}
/**
* Encode, Decode, Check Methods
*/
WString Coder::Encode(const WString& content, const WString& key) {
WString result = content;
return result;
}
WString Coder::Decode(const WString& content, const WString& key) {
WString result = content;
return result;
}
bool Coder::Check(const WString& content, const WString& key) {
bool result = false;
return result;
}
} | 9.024691 | 68 | 0.607387 | ING-Game-Devs |
b1dda0e81ffc0f4a55df30cc0231f5a18336521f | 2,080 | cpp | C++ | Raymarcher/src/UI/ColorModsUI/ColorModsUI.cpp | conholo/Raymarcher | 880a268a1ca11161df52462a2b2908a402408227 | [
"Apache-2.0"
] | null | null | null | Raymarcher/src/UI/ColorModsUI/ColorModsUI.cpp | conholo/Raymarcher | 880a268a1ca11161df52462a2b2908a402408227 | [
"Apache-2.0"
] | null | null | null | Raymarcher/src/UI/ColorModsUI/ColorModsUI.cpp | conholo/Raymarcher | 880a268a1ca11161df52462a2b2908a402408227 | [
"Apache-2.0"
] | null | null | null | #include "rmpch.h"
#include "UI/ColorModsUI/ColorModsUI.h"
#include <imgui/imgui.h>
namespace RM
{
namespace UI
{
static void DrawColorModWindow(const std::string& fractalName, const std::string& title, float* dragFloatA, float* dragFloatB)
{
std::string originID = "Origin##" + fractalName + title;
std::string scaleID = "Scale##" + fractalName + title;
ImGui::PushID(originID.c_str());
ImGui::PushID(scaleID.c_str());
ImGui::DragFloat3(originID.c_str(), dragFloatA);
ImGui::DragFloat3(scaleID.c_str(), dragFloatB);
ImGui::PopID();
ImGui::PopID();
}
void ColorModSumUI::DrawEditor(const std::string& fractalName)
{
std::string title = "Color Mod Sum " + std::to_string(m_ID);
DrawColorModWindow(fractalName, title, &m_ColorModSum->GetOrigin().x, &m_ColorModSum->GetScale().x);
}
void ColorModSumAbsUI::DrawEditor(const std::string& fractalName)
{
std::string title = "Color Mod Sum Abs " + std::to_string(m_ID);
DrawColorModWindow(fractalName, title, &m_ColorModSumAbs->GetOrigin().x, &m_ColorModSumAbs->GetScale().x);
}
void ColorModMinUI::DrawEditor(const std::string& fractalName)
{
std::string title = "Color Mod Min " + std::to_string(m_ID);
DrawColorModWindow(fractalName, title, &m_ColorModMin->GetOrigin().x, &m_ColorModMin->GetScale().x);
}
void ColorModMinAbsUI::DrawEditor(const std::string& fractalName)
{
std::string title = "Color Mod Min Abs " + std::to_string(m_ID);
DrawColorModWindow(fractalName, title, &m_ColorModMinAbs->GetOrigin().x, &m_ColorModMinAbs->GetScale().x);
}
void ColorModMaxUI::DrawEditor(const std::string& fractalName)
{
std::string title = "Color Mod Max " + std::to_string(m_ID);
DrawColorModWindow(fractalName, title, &m_ColorModMax->GetOrigin().x, &m_ColorModMax->GetScale().x);
}
void ColorModMaxAbsUI::DrawEditor(const std::string& fractalName)
{
std::string title = "Color Mod Max Abs " + std::to_string(m_ID);
DrawColorModWindow(fractalName, title, &m_ColorModMaxAbs->GetOrigin().x, &m_ColorModMaxAbs->GetScale().x);
}
}
} | 35.862069 | 128 | 0.708173 | conholo |
b1e09603a3103c5638d26cc3f71fd3ea7e5ac015 | 35,379 | cpp | C++ | edge_tree.cpp | tstullich/redner | aaae9f1dee97173fc409ceb0941966d3c2d2feb2 | [
"MIT"
] | 1,146 | 2018-11-11T01:47:18.000Z | 2022-03-31T14:11:03.000Z | edge_tree.cpp | Awcrr/redner | b4f57037af26b720d916bbaf26103a3499101a9f | [
"MIT"
] | 177 | 2018-11-13T22:48:25.000Z | 2022-03-30T07:19:29.000Z | edge_tree.cpp | Awcrr/redner | b4f57037af26b720d916bbaf26103a3499101a9f | [
"MIT"
] | 127 | 2018-11-11T02:32:17.000Z | 2022-03-31T07:24:03.000Z | #include "edge_tree.h"
#include "vector.h"
#include "cuda_utils.h"
#include "atomic.h"
#include "edge.h"
#include "parallel.h"
#include "thrust_utils.h"
#include <thrust/transform_reduce.h>
#include <thrust/sequence.h>
#include <thrust/fill.h>
#include <thrust/partition.h>
struct edge_partitioner {
DEVICE bool operator()(int edge_id) const {
bool result = is_silhouette(shapes, cam_org, edges[edge_id]);
return result;
}
const Shape *shapes;
Vector3 cam_org;
const Edge *edges;
};
struct edge_6d_bounds_computer {
DEVICE void operator()(int idx) {
const auto &edge = edges[idx];
// Compute position bound
auto v0 = get_v0(shapes, edge);
auto v1 = get_v1(shapes, edge);
auto p_min = Vector3{0, 0, 0};
auto p_max = Vector3{0, 0, 0};
for (int i = 0; i < 3; i++) {
p_min[i] = min(v0[i], v1[i]);
p_max[i] = max(v0[i], v1[i]);
}
edge_aabbs[idx].p_min = p_min;
edge_aabbs[idx].p_max = p_max;
assert(isfinite(p_min));
assert(isfinite(p_max));
// Compute directional bound
auto n0 = get_n0(shapes, edge);
auto n1 = Vector3{0, 0, 0};
if (edge.f1 == -1) {
n1 = -n0;
} else {
n1 = get_n1(shapes, edge);
}
auto p = 0.5f * (v0 + v1) - cam_org;
// plane 0 is n0.x * x + n0.y * y + n0.z * z = dot(p, n0)
auto p0d = dot(p, n0);
auto p1d = dot(p, n1);
// 3D Hough transform, see "Silhouette extraction in hough space",
// Olson and Zhang
auto h0 = Vector3{n0.x * p0d, n0.y * p0d, n0.z * p0d};
auto h1 = Vector3{n1.x * p1d, n1.y * p1d, n1.z * p1d};
auto d_min = Vector3{0, 0, 0};
auto d_max = Vector3{0, 0, 0};
for (int i = 0; i < 3; i++) {
d_min[i] = min(h0[i], h1[i]);
d_max[i] = max(h0[i], h1[i]);
}
assert(isfinite(d_min));
assert(isfinite(d_max));
edge_aabbs[idx].d_min = d_min;
edge_aabbs[idx].d_max = d_max;
}
const Shape *shapes;
const Edge *edges;
const Vector3 cam_org;
AABB6 *edge_aabbs;
};
void compute_edge_bounds(const Shape *shapes,
const BufferView<Edge> &edges,
const Vector3 cam_org,
BufferView<AABB6> edge_aabbs,
bool use_gpu) {
parallel_for(edge_6d_bounds_computer{
shapes, edges.begin(), cam_org, edge_aabbs.begin()},
edges.size(),
use_gpu);
}
struct id_to_edge_pt_sum {
DEVICE Vector3 operator()(int id) const {
auto v0 = get_v0(shapes, edges[id]);
auto v1 = get_v1(shapes, edges[id]);
return v0 + v1;
}
const Shape *shapes;
const Edge *edges;
};
struct id_to_edge_pt_abs {
DEVICE Vector3 operator()(int id) const {
auto v0 = get_v0(shapes, edges[id]);
auto v1 = get_v1(shapes, edges[id]);
auto v0_abs = Vector3{}, v1_abs = Vector3{};
for (int i = 0; i < 3; i++) {
v0_abs[i] = fabs(v0[i] - mean[i]);
v1_abs[i] = fabs(v1[i] - mean[i]);
}
return v0_abs + v1_abs;
}
const Shape *shapes;
const Edge *edges;
Vector3 mean;
};
struct id_to_aabb3 {
DEVICE AABB3 operator()(int id) const {
auto b = bounds[id];
return AABB3{b.p_min, b.p_max};
}
const AABB6 *bounds;
};
struct id_to_aabb6 {
DEVICE AABB6 operator()(int id) const {
return bounds[id];
}
const AABB6 *bounds;
};
struct union_bounding_box {
DEVICE AABB6 operator()(const AABB6 &b0, const AABB6 &b1) const {
auto p_min = Vector3{min(b0.p_min[0], b1.p_min[0]),
min(b0.p_min[1], b1.p_min[1]),
min(b0.p_min[2], b1.p_min[2])};
auto d_min = Vector3{min(b0.d_min[0], b1.d_min[0]),
min(b0.d_min[1], b1.d_min[1]),
min(b0.d_min[2], b1.d_min[2])};
auto p_max = Vector3{max(b0.p_max[0], b1.p_max[0]),
max(b0.p_max[1], b1.p_max[1]),
max(b0.p_max[2], b1.p_max[2])};
auto d_max = Vector3{max(b0.d_max[0], b1.d_max[0]),
max(b0.d_max[1], b1.d_max[1]),
max(b0.d_max[2], b1.d_max[2])};
return AABB6{p_min, d_min, p_max, d_max};
}
DEVICE AABB3 operator()(const AABB3 &b0, const AABB3 &b1) const {
auto p_min = Vector3{min(b0.p_min[0], b1.p_min[0]),
min(b0.p_min[1], b1.p_min[1]),
min(b0.p_min[2], b1.p_min[2])};
auto p_max = Vector3{max(b0.p_max[0], b1.p_max[0]),
max(b0.p_max[1], b1.p_max[1]),
max(b0.p_max[2], b1.p_max[2])};
return AABB3{p_min, p_max};
}
};
struct sum_vec3 {
DEVICE Vector3 operator()(const Vector3 &v0, const Vector3 &v1) const {
return v0 + v1;
}
};
struct morton_code_3d_computer {
DEVICE uint64_t expand_bits(uint64_t x) {
// Insert two zero after every bit given a 21-bit integer
// https://github.com/leonardo-domingues/atrbvh/blob/master/BVHRT-Core/src/Commons.cuh#L599
uint64_t expanded = x;
expanded &= 0x1fffff;
expanded = (expanded | expanded << 32) & 0x1f00000000ffff;
expanded = (expanded | expanded << 16) & 0x1f0000ff0000ff;
expanded = (expanded | expanded << 8) & 0x100f00f00f00f00f;
expanded = (expanded | expanded << 4) & 0x10c30c30c30c30c3;
expanded = (expanded | expanded << 2) & 0x1249249249249249;
return expanded;
}
DEVICE uint64_t morton3D(const Vector3 &p) {
auto pp = (p - scene_bounds.p_min) / (scene_bounds.p_max - scene_bounds.p_min);
for (int i = 0; i < 3; i++) {
if (scene_bounds.p_max[i] - scene_bounds.p_min[i] <= 0.f) {
pp[i] = 0.5f;
}
}
auto scale = (1 << 21) - 1;
TVector3<uint64_t> pp_i{pp.x * scale, pp.y * scale, pp.z * scale};
return (expand_bits(pp_i.x) << 2u) |
(expand_bits(pp_i.y) << 1u) |
(expand_bits(pp_i.z) << 0u);
}
DEVICE void operator()(int idx) {
// This might be suboptimal -- should probably use raw edge information directly
auto box = convert_aabb<AABB3>(edge_aabbs[edge_ids[idx]]);
morton_codes[idx] = morton3D(0.5f * (box.p_min + box.p_max));
}
const AABB3 scene_bounds;
const AABB6 *edge_aabbs;
const int *edge_ids;
uint64_t *morton_codes;
};
void compute_morton_codes(const AABB3 &scene_bounds,
const BufferView<AABB6> &edge_bounds,
const BufferView<int> &edge_ids,
BufferView<uint64_t> morton_codes,
bool use_gpu) {
parallel_for(morton_code_3d_computer{
scene_bounds, edge_bounds.begin(), edge_ids.begin(), morton_codes.begin()},
morton_codes.size(),
use_gpu);
}
struct morton_code_6d_computer {
// For 6D Morton code, insert 5 zeros before each bit of a 10-bit integer
// I'm doing this in a very slow way by manipulating each bit.
// This is not the bottleneck anyway and I want readability.
DEVICE uint64_t expand_bits(uint64_t x) {
constexpr uint64_t mask = 0x1u;
// We start from LSB (bit 63)
auto result = (x & (mask << 0u));
result |= ((x & (mask << 1u)) << 5u);
result |= ((x & (mask << 2u)) << 10u);
result |= ((x & (mask << 3u)) << 15u);
result |= ((x & (mask << 4u)) << 20u);
result |= ((x & (mask << 5u)) << 25u);
result |= ((x & (mask << 6u)) << 30u);
result |= ((x & (mask << 7u)) << 35u);
result |= ((x & (mask << 8u)) << 40u);
result |= ((x & (mask << 9u)) << 45u);
return result;
}
DEVICE uint64_t morton6D(const Vector3 &p, const Vector3 &d) {
Vector3 pp = (p - scene_bounds.p_min) / (scene_bounds.p_max - scene_bounds.p_min);
Vector3 dd = (d - scene_bounds.d_min) / (scene_bounds.d_max - scene_bounds.d_min);
for (int i = 0; i < 3; i++) {
if (scene_bounds.p_max[i] - scene_bounds.p_min[i] <= 0.f) {
pp[i] = 0.5f;
}
if (scene_bounds.d_max[i] - scene_bounds.d_min[i] <= 0.f) {
dd[i] = 0.5f;
}
}
TVector3<uint64_t> pp_i{pp.x * 1023, pp.y * 1023, pp.z * 1023};
TVector3<uint64_t> dd_i{dd.x * 1023, dd.y * 1023, dd.z * 1023};
return (expand_bits(pp_i.x) << 5u) |
(expand_bits(pp_i.y) << 4u) |
(expand_bits(pp_i.z) << 3u) |
(expand_bits(dd_i.x) << 2u) |
(expand_bits(dd_i.y) << 1u) |
(expand_bits(dd_i.z) << 0u);
}
DEVICE void operator()(int idx) {
// This might be suboptimal -- should probably use raw edge information directly
const auto &box = edge_aabbs[edge_ids[idx]];
morton_codes[idx] = morton6D(0.5f * (box.p_min + box.p_max),
0.5f * (box.d_min + box.d_max));
}
const AABB6 scene_bounds;
const AABB6 *edge_aabbs;
const int *edge_ids;
uint64_t *morton_codes;
};
void compute_morton_codes(const AABB6 &scene_bounds,
const BufferView<AABB6> &edge_aabbs,
const BufferView<int> &edge_ids,
BufferView<uint64_t> morton_codes,
bool use_gpu) {
parallel_for(morton_code_6d_computer{
scene_bounds, edge_aabbs.begin(), edge_ids.begin(), morton_codes.begin()},
morton_codes.size(),
use_gpu);
}
template <typename BVHNodeType>
struct radix_tree_builder {
// https://github.com/henrikdahlberg/GPUPathTracer/blob/master/Source/Core/BVHConstruction.cu#L62
DEVICE int longest_common_prefix(int idx0, int idx1) {
if (idx0 < 0 || idx0 >= num_primitives || idx1 < 0 || idx1 >= num_primitives) {
return -1;
}
auto mc0 = morton_codes[idx0];
auto mc1 = morton_codes[idx1];
if (mc0 == mc1) {
// Break even when the Morton codes are the same
auto id0 = (uint64_t)edge_ids[idx0];
auto id1 = (uint64_t)edge_ids[idx1];
return clz(mc0 ^ mc1) + clz(id0 ^ id1);
}
else {
return clz(mc0 ^ mc1);
}
}
DEVICE void operator()(int idx) {
// Mostly adapted from
// https://github.com/henrikdahlberg/GPUPathTracer/blob/master/Source/Core/BVHConstruction.cu#L161
// Also see Figure 4 in
// https://devblogs.nvidia.com/wp-content/uploads/2012/11/karras2012hpg_paper.pdf
if (idx >= num_primitives - 1) {
if (num_primitives == 1) {
// Special case: if there is only one primitive, set it as the root
nodes[0] = leaves[0];
}
return;
}
// Compute upper bound for the length of the range
auto d = longest_common_prefix(idx, idx + 1) -
longest_common_prefix(idx, idx - 1) >= 0 ? 1 : -1;
auto delta_min = longest_common_prefix(idx, idx - d);
auto lmax = 2;
while (longest_common_prefix(idx, idx + lmax * d) > delta_min) {
lmax *= 2;
}
// Find the other end using binary search
auto l = 0;
auto divider = 2;
for (int t = lmax / divider; t >= 1;) {
if (longest_common_prefix(idx, idx + (l + t) * d) > delta_min) {
l += t;
}
if (t == 1) {
break;
}
divider *= 2;
t = lmax / divider;
}
auto j = idx + l * d;
// Find the split position using binary search
auto delta_node = longest_common_prefix(idx, j);
auto s = 0;
divider = 2;
for (int t = (l + (divider - 1)) / divider; t >= 1;) {
if (longest_common_prefix(idx, idx + (s + t) * d) > delta_node) {
s += t;
}
if (t == 1) {
break;
}
divider *= 2;
t = (l + (divider - 1)) / divider;
}
auto gamma = idx + s * d + min(d, 0);
assert(gamma >= 0 && gamma + 1 < num_primitives);
auto &node = nodes[idx];
if (min(idx, j) == gamma) {
node.children[0] = &leaves[gamma];
leaves[gamma].parent = &node;
} else {
node.children[0] = &nodes[gamma];
nodes[gamma].parent = &node;
}
if (max(idx, j) == gamma + 1) {
node.children[1] = &leaves[gamma + 1];
leaves[gamma + 1].parent = &node;
} else {
node.children[1] = &nodes[gamma + 1];
nodes[gamma + 1].parent = &node;
}
}
const uint64_t *morton_codes;
const int *edge_ids;
const int num_primitives;
BVHNodeType *nodes;
BVHNodeType *leaves;
};
template <typename BVHNodeType>
void build_radix_tree(const BufferView<uint64_t> &morton_codes,
const BufferView<int> &edge_ids,
BufferView<BVHNodeType> nodes,
BufferView<BVHNodeType> leaves,
bool use_gpu) {
parallel_for(radix_tree_builder<BVHNodeType>{
morton_codes.begin(), edge_ids.begin(),
morton_codes.size(), nodes.begin(), leaves.begin()},
morton_codes.size(),
use_gpu);
}
template <typename BVHNodeType>
struct bvh_computer {
DEVICE void operator()(int idx) {
auto edge_id = edge_ids[idx];
assert(edge_id >= 0 && edge_id < num_edges);
const auto &edge = edges[edge_id];
auto leaf = &leaves[idx];
leaf->bounds = convert_aabb<decltype(BVHNodeType::bounds)>(bounds[edge_id]);
// length * (pi - dihedral angle)
auto v0 = get_v0(shapes, edge);
auto v1 = get_v1(shapes, edge);
auto exterior_dihedral = compute_exterior_dihedral_angle(shapes, edge);
leaf->weighted_total_length = distance(v0, v1) * exterior_dihedral;
leaf->edge_id = edge_ids[idx];
// Trace from leaf to root and merge bounding boxes & length
auto current = leaf->parent;
auto node_idx = current - nodes;
if (current != nullptr) {
while(true) {
assert(node_idx >= 0 && node_idx < num_leaves);
auto res = atomic_increment(node_counters + node_idx);
if (res == 1) {
// Terminate the first thread entering this node to avoid duplicate computation
// It is important to terminate the first not the second so we ensure all children
// are processed
return;
}
auto bbox = current->children[0]->bounds;
auto weighted_length = current->children[0]->weighted_total_length;
for (int i = 1; i < 2; i++) {
bbox = merge(bbox, current->children[i]->bounds);
weighted_length += current->children[i]->weighted_total_length;
}
current->bounds = bbox;
current->weighted_total_length = weighted_length;
if (current->parent == nullptr) {
return;
}
current = current->parent;
node_idx = current - nodes;
}
}
}
const Shape *shapes;
const Edge *edges;
const int num_edges;
const int *edge_ids;
const AABB6 *bounds;
const int num_leaves;
int *node_counters;
BVHNodeType *nodes;
BVHNodeType *leaves;
};
template <typename BVHNodeType>
void compute_bvh(const BufferView<Shape> &shapes,
const BufferView<Edge> &edges,
const BufferView<int> &edge_ids,
const BufferView<AABB6> &bounds,
BufferView<int> node_counters,
BufferView<BVHNodeType> nodes,
BufferView<BVHNodeType> leaves,
bool use_gpu) {
assert(leaves.size() == edge_ids.size());
parallel_for(bvh_computer<BVHNodeType>{
shapes.begin(), edges.begin(), edges.size(), edge_ids.begin(), bounds.begin(), leaves.size(),
node_counters.begin(), nodes.begin(), leaves.begin()},
leaves.size(),
use_gpu);
}
template <typename BVHNodeType>
struct bvh_optimizer {
// Adapted from
// https://github.com/andrewwuan/smallpt-parallel-bvh-gpu/blob/master/gpu.cu
// SAH constants
static constexpr auto Ci = Real(1);
static constexpr auto Ct = Real(1);
DEVICE Real surface_area(const AABB3 &bounds) {
auto d = bounds.p_max - bounds.p_min;
return 2 * (d.x * d.y + d.x * d.z + d.y * d.z);
}
DEVICE Real surface_area(const AABB6 &bounds) {
auto dp = bounds.p_max - bounds.p_min;
auto dd = bounds.d_max - bounds.d_min;
return 2 * ((dp.x * dp.y + dp.x * dp.z + dp.y * dp.z) +
(dd.x * dd.y + dd.x * dd.z + dd.y * dd.z));
}
DEVICE Real compute_total_area(int n,
BVHNodeType **leaves,
uint32_t s) {
decltype(BVHNodeType::bounds) bounds = leaves[0]->bounds;
for (int i = 1; i < n; i++) {
if (((s >> i) & 1) == 1) {
bounds = merge(bounds, leaves[i]->bounds);
}
}
return surface_area(bounds);
}
DEVICE void calculate_optimal_treelet(int n,
BVHNodeType **leaves,
uint8_t *p_opt) {
// Algorithm 2 in Karras et al.
auto num_subsets = (0x1 << n) - 1;
assert(num_subsets < 128);
// TODO: move the following two arrays into shared memory
Real a[128];
Real c_opt[128];
// Total cost of each subset
for (uint32_t s = 1; s <= (uint32_t)num_subsets; s++) {
a[s] = compute_total_area(n, leaves, s);
}
// Costs of leaves
for (uint32_t i = 0; i < (uint32_t)n; i++) {
c_opt[(0x1 << i)] = leaves[i]->cost;
}
// Optimize every subsets of leaves
for (uint32_t k = 2; k <= (uint32_t)n; k++) {
for (uint32_t s = 1; s <= (uint32_t)num_subsets; s++) {
if (popc(s) == (int)k) {
// Try each way of partitioning the leaves
auto c_s = infinity<Real>();
auto p_s = uint32_t(0);
auto d = (s - 1u) & s;
auto p = (-d) & s;
do {
auto c = c_opt[p] + c_opt[s ^ p];
if (c < c_s) {
c_s = c;
p_s = p;
}
p = (p - d) & s;
} while (p != 0);
// SAH
c_opt[s] = Ci * a[s] + c_s;
p_opt[s] = p_s;
}
}
}
}
DEVICE void propagate_cost(BVHNodeType *root,
BVHNodeType **leaves,
int num_leaves) {
for (int i = 0; i < num_leaves; i++) {
auto current = leaves[i];
while (current != root) {
if (current->cost < 0) {
if (current->children[0]->cost >= 0 &&
current->children[1]->cost >= 0) {
current->bounds =
merge(current->children[0]->bounds,
current->children[1]->bounds);
current->weighted_total_length =
current->children[0]->weighted_total_length +
current->children[1]->weighted_total_length;
current->cost = Ci * surface_area(current->bounds) +
current->children[0]->cost + current->children[1]->cost;
} else {
break;
}
}
current = current->parent;
}
}
root->bounds = merge(root->children[0]->bounds, root->children[1]->bounds);
root->weighted_total_length =
root->children[0]->weighted_total_length +
root->children[1]->weighted_total_length;
root->cost = Ci * surface_area(root->bounds) +
root->children[0]->cost + root->children[1]->cost;
}
struct PartitionEntry {
uint8_t partition;
uint8_t child_index;
BVHNodeType *parent;
};
template <int child_index>
DEVICE void restruct_tree(BVHNodeType *parent,
BVHNodeType **leaves,
BVHNodeType **nodes,
uint8_t partition,
uint8_t *optimal,
int &index,
int num_leaves) {
PartitionEntry stack[8];
auto stack_ptr = &stack[0];
*stack_ptr++ = PartitionEntry{partition, child_index, parent};
while (stack_ptr != &stack[0]) {
assert(stack_ptr >= stack && stack_ptr < stack + 8);
auto &entry = *--stack_ptr;
auto partition = entry.partition;
auto child_id = entry.child_index;
auto parent = entry.parent;
if (popc(partition) == 1) {
// Leaf
auto leaf_index = ffs(partition) - 1;
auto leaf = leaves[leaf_index];
parent->children[child_id] = leaf;
leaf->parent = parent;
} else {
// Internal
assert(index < 5);
auto node = nodes[index++];
node->cost = -1;
parent->children[child_id] = node;
node->parent = parent;
auto left_partition = optimal[partition];
auto right_partition = uint8_t((~left_partition) & partition);
*stack_ptr++ = PartitionEntry{left_partition, 0, node};
*stack_ptr++ = PartitionEntry{right_partition, 1, node};
}
}
propagate_cost(parent, leaves, num_leaves);
}
DEVICE void treelet_optimize(BVHNodeType *root) {
if (root->edge_id != -1) {
return;
}
// Form a treelet with max number of leaves being 7
BVHNodeType *leaves[7];
auto counter = 0;
leaves[counter++] = root->children[0];
leaves[counter++] = root->children[1];
// Also remember the internal nodes
// Max 7 (leaves) - 1 (root doesn't count) - 1
BVHNodeType *nodes[5];
auto nodes_counter = 0;
auto max_area = Real(0);
auto max_idx = 0;
while (counter < 7 && max_idx != -1) {
max_idx = -1;
max_area = Real(-1);
// Find the node with largest area and expand it
for (int i = 0; i < counter; i++) {
if (leaves[i]->edge_id == -1) {
auto area = surface_area(leaves[i]->bounds);
if (area > max_area) {
max_area = area;
max_idx = i;
}
}
}
if (max_idx != -1) {
BVHNodeType *tmp = leaves[max_idx];
assert(nodes_counter < 5);
nodes[nodes_counter++] = tmp;
leaves[max_idx] = leaves[counter - 1];
leaves[counter - 1] = tmp->children[0];
leaves[counter] = tmp->children[1];
counter++;
}
}
unsigned char optimal[128];
calculate_optimal_treelet(counter, leaves, optimal);
// Use complement on right tree, and use original on left tree
auto mask = (unsigned char)((1u << counter) - 1);
auto index = 0;
auto left_index = mask;
auto left = optimal[left_index];
restruct_tree<0>(root, leaves, nodes, left, optimal, index, counter);
auto right = (~left) & mask;
restruct_tree<1>(root, leaves, nodes, right, optimal, index, counter);
// Compute bounds & cost
root->bounds = merge(root->children[0]->bounds, root->children[1]->bounds);
root->weighted_total_length =
root->children[0]->weighted_total_length +
root->children[1]->weighted_total_length;
root->cost = Ci * surface_area(root->bounds) +
root->children[0]->cost + root->children[1]->cost;
}
DEVICE void operator()(int idx) {
auto leaf = &leaves[idx];
leaf->cost = Ci * surface_area(leaf->bounds);
assert(isfinite(leaf->cost));
auto current = leaf->parent;
auto node_idx = current - nodes;
if (current != nullptr) {
while(true) {
auto res = atomic_increment(node_counters + node_idx);
if (res == 1) {
// Terminate the first thread entering this node to avoid duplicate computation
// It is important to terminate the first not the second so we ensure all children
// are processed
return;
}
treelet_optimize(current);
if (current == &nodes[0]) {
return;
}
current = current->parent;
node_idx = current - &nodes[0];
}
}
}
int *node_counters;
BVHNodeType *nodes;
BVHNodeType *leaves;
};
template <typename BVHNodeType>
void optimize_bvh(BufferView<int> node_counters,
BufferView<BVHNodeType> nodes,
BufferView<BVHNodeType> leaves,
bool use_gpu) {
parallel_for(bvh_optimizer<BVHNodeType>{
node_counters.begin(), nodes.begin(), leaves.begin()},
leaves.size(),
use_gpu);
}
EdgeTree::EdgeTree(bool use_gpu,
const Camera &camera,
const BufferView<Shape> &shapes,
const BufferView<Edge> &edges) {
if (edges.size() == 0) {
return;
}
// We construct a 6D LBVH for the edges using AABB, where the first 3 dimensions are the
// spatial dimensions and the rest are the 3D hough space as described in
// "Silhouette extraction in Hough space", Olson and Zhang
// We use the camera position as the origin for the 3D Hough transform.
// First, we split the edges into two sets.
// 1) The edges that are silhouette when looking from the camera
// 2) The rest
//
// According to Olson and Zhang, set 1 is a small set (and it includes all
// "boundary" edges that are always silhouettes), and set 2 is a silhouette iff
// it has exactly one point inside the "v-sphere" (the sphere whose center is at the query
// point and the radius is the distance between the query point and the origin)
// in Hough space.
// This means we can build a BVH over set 2 and discard edges whose two endpoints
// are both not inside the v-sphere during traversal.
Buffer<int> edge_ids(use_gpu, edges.size());
DISPATCH(use_gpu, thrust::sequence, edge_ids.begin(), edge_ids.end());
auto cam_org = xfm_point(camera.cam_to_world, Vector3{0, 0, 0});
auto partition_result = DISPATCH(use_gpu,
thrust::stable_partition, edge_ids.begin(), edge_ids.end(),
edge_partitioner{shapes.begin(), cam_org, edges.begin()});
// We call the set of edges in 1) "cs_edges" and the set 2) "ncs_edges"
BufferView<int> cs_edge_ids(edge_ids.begin(), partition_result - edge_ids.begin());
BufferView<int> ncs_edge_ids(partition_result, edge_ids.end() - partition_result);
Buffer<int> node_counters(use_gpu, edges.size());
Buffer<AABB6> edge_bounds(use_gpu, edges.size());
compute_edge_bounds(shapes.begin(),
edges,
cam_org,
edge_bounds.view(0, edge_ids.size()),
use_gpu);
auto edge_pt_mean = DISPATCH(use_gpu,
thrust::transform_reduce, edge_ids.begin(), edge_ids.end(),
id_to_edge_pt_sum{shapes.begin(), edges.begin()},
Vector3{0, 0, 0}, sum_vec3{});
edge_pt_mean /= Real(edge_ids.size());
auto edge_pt_mad = DISPATCH(use_gpu,
thrust::transform_reduce, edge_ids.begin(), edge_ids.end(),
id_to_edge_pt_abs{shapes.begin(), edges.begin(), edge_pt_mean},
Vector3{0, 0, 0}, sum_vec3{});
edge_pt_mad /= Real(edge_ids.size());
edge_bounds_expand = 0.01f * length(edge_pt_mad);
// We build a 3D BVH over the camera silhouette edges, and build
// a 6D BVH over the non camera silhouette edges
// camera silhouette edges
if (cs_edge_ids.size() > 0) {
// Compute scene bounding box for BVH
AABB3 cs_scene_bounds = DISPATCH(use_gpu,
thrust::transform_reduce, cs_edge_ids.begin(), cs_edge_ids.end(),
id_to_aabb3{edge_bounds.begin()}, AABB3(), union_bounding_box{});
assert(cs_scene_bounds.p_max.x - cs_scene_bounds.p_min.x >= 0.f &&
cs_scene_bounds.p_max.y - cs_scene_bounds.p_min.y >= 0.f &&
cs_scene_bounds.p_max.z - cs_scene_bounds.p_min.z >= 0.f);
// Compute Morton code for LBVH
Buffer<uint64_t> cs_morton_codes(use_gpu, cs_edge_ids.size());
compute_morton_codes(cs_scene_bounds,
edge_bounds.view(0, edge_bounds.size()),
cs_edge_ids,
cs_morton_codes.view(0, cs_edge_ids.size()),
use_gpu);
// Sort by Morton code
DISPATCH(use_gpu, thrust::stable_sort_by_key,
cs_morton_codes.begin(), cs_morton_codes.end(), cs_edge_ids.begin());
cs_bvh_nodes = Buffer<BVHNode3>(use_gpu, max(cs_morton_codes.size() - 1, 1));
cs_bvh_leaves = Buffer<BVHNode3>(use_gpu, cs_morton_codes.size());
// Initialize nodes
BVHNode3 init_node{AABB3(), Real(0), nullptr, {nullptr, nullptr}, -1};
DISPATCH(use_gpu, thrust::fill, cs_bvh_nodes.begin(), cs_bvh_nodes.end(), init_node);
DISPATCH(use_gpu, thrust::fill, cs_bvh_leaves.begin(), cs_bvh_leaves.end(), init_node);
// Build tree (see
// "Maximizing Parallelism in the Construction of BVHs, Octrees, and k-d Trees")
build_radix_tree(cs_morton_codes.view(0, cs_morton_codes.size()),
cs_edge_ids,
cs_bvh_nodes.view(0, cs_bvh_nodes.size()),
cs_bvh_leaves.view(0, cs_bvh_leaves.size()),
use_gpu);
// Compute BVH node information (bounding box, length of edges, etc)
DISPATCH(use_gpu, thrust::fill,
node_counters.begin(), node_counters.begin() + cs_bvh_leaves.size(), 0);
compute_bvh(shapes,
edges,
cs_edge_ids,
edge_bounds.view(0, edge_bounds.size()),
node_counters.view(0, cs_bvh_leaves.size()),
cs_bvh_nodes.view(0, cs_bvh_nodes.size()),
cs_bvh_leaves.view(0, cs_bvh_leaves.size()),
use_gpu);
DISPATCH(use_gpu, thrust::fill,
node_counters.begin(), node_counters.begin() + cs_bvh_leaves.size(), 0);
optimize_bvh(node_counters.view(0, cs_bvh_leaves.size()),
cs_bvh_nodes.view(0, cs_bvh_nodes.size()),
cs_bvh_leaves.view(0, cs_bvh_leaves.size()),
use_gpu);
}
// Do the same thing for non camera silhouette edges
if (ncs_edge_ids.size() > 0) {
// Compute scene bounding box for BVH
AABB6 ncs_scene_bounds = DISPATCH(use_gpu,
thrust::transform_reduce, ncs_edge_ids.begin(), ncs_edge_ids.end(),
id_to_aabb6{edge_bounds.begin()}, AABB6(), union_bounding_box{});
assert(ncs_scene_bounds.p_max.x - ncs_scene_bounds.p_min.x >= 0.f &&
ncs_scene_bounds.p_max.y - ncs_scene_bounds.p_min.y >= 0.f &&
ncs_scene_bounds.p_max.z - ncs_scene_bounds.p_min.z >= 0.f);
assert(ncs_scene_bounds.d_max.x - ncs_scene_bounds.d_min.x >= 0.f &&
ncs_scene_bounds.d_max.y - ncs_scene_bounds.d_min.y >= 0.f &&
ncs_scene_bounds.d_max.z - ncs_scene_bounds.d_min.z >= 0.f);
// Compute Morton code for LBVH
Buffer<uint64_t> ncs_morton_codes(use_gpu, ncs_edge_ids.size());
compute_morton_codes(ncs_scene_bounds,
edge_bounds.view(0, edge_bounds.size()),
ncs_edge_ids,
ncs_morton_codes.view(0, ncs_edge_ids.size()),
use_gpu);
// Sort by Morton code
DISPATCH(use_gpu, thrust::stable_sort_by_key,
ncs_morton_codes.begin(), ncs_morton_codes.end(), ncs_edge_ids.begin());
ncs_bvh_nodes = Buffer<BVHNode6>(use_gpu, max(ncs_morton_codes.size() - 1, 1));
ncs_bvh_leaves = Buffer<BVHNode6>(use_gpu, ncs_morton_codes.size());
// Initialize nodes
BVHNode6 init_node{AABB6(), Real(0), nullptr, {nullptr, nullptr}, -1};
DISPATCH(use_gpu, thrust::fill, ncs_bvh_nodes.begin(), ncs_bvh_nodes.end(), init_node);
DISPATCH(use_gpu, thrust::fill, ncs_bvh_leaves.begin(), ncs_bvh_leaves.end(), init_node);
// Build tree (see
// "Maximizing Parallelism in the Construction of BVHs, Octrees, and k-d Trees")
build_radix_tree(ncs_morton_codes.view(0, ncs_morton_codes.size()),
ncs_edge_ids,
ncs_bvh_nodes.view(0, ncs_bvh_nodes.size()),
ncs_bvh_leaves.view(0, ncs_bvh_leaves.size()),
use_gpu);
// Compute BVH node information (bounding box, length of edges, etc)
DISPATCH(use_gpu, thrust::fill,
node_counters.begin(), node_counters.begin() + ncs_bvh_leaves.size(), 0);
compute_bvh(shapes,
edges,
ncs_edge_ids,
edge_bounds.view(0, edge_bounds.size()),
node_counters.view(0, ncs_bvh_leaves.size()),
ncs_bvh_nodes.view(0, ncs_bvh_nodes.size()),
ncs_bvh_leaves.view(0, ncs_bvh_leaves.size()),
use_gpu);
DISPATCH(use_gpu, thrust::fill,
node_counters.begin(), node_counters.begin() + ncs_bvh_leaves.size(), 0);
optimize_bvh(node_counters.view(0, ncs_bvh_leaves.size()),
ncs_bvh_nodes.view(0, ncs_bvh_nodes.size()),
ncs_bvh_leaves.view(0, ncs_bvh_leaves.size()),
use_gpu);
}
}
| 40.066818 | 106 | 0.533876 | tstullich |
b1e0baa1ec211815a0481d94415debb4040dcb2b | 158 | hpp | C++ | include/crucible/IBL.hpp | pianoman373/crucible | fa03ca471fef56cf2def029a14bcc6a467996dfa | [
"MIT"
] | 2 | 2019-02-17T02:55:38.000Z | 2019-04-19T04:57:39.000Z | include/crucible/IBL.hpp | pianoman373/crucible | fa03ca471fef56cf2def029a14bcc6a467996dfa | [
"MIT"
] | null | null | null | include/crucible/IBL.hpp | pianoman373/crucible | fa03ca471fef56cf2def029a14bcc6a467996dfa | [
"MIT"
] | 1 | 2018-12-03T22:39:44.000Z | 2018-12-03T22:39:44.000Z | #pragma once
#include <crucible/Texture.hpp>
namespace IBL {
void generateIBLmaps(const vec3 &position, Cubemap &irradiance, Cubemap &specular);
} | 22.571429 | 88 | 0.727848 | pianoman373 |
b1e0cf346615d859b919c0c03c7858f7fcde0004 | 410 | cpp | C++ | registry/tables/response.cpp | EOSIO-HACKATHON2020/registry-smart-contract | a0cc7cffc5cafb6fd4f4251474f9b09635d44bb0 | [
"CC0-1.0"
] | null | null | null | registry/tables/response.cpp | EOSIO-HACKATHON2020/registry-smart-contract | a0cc7cffc5cafb6fd4f4251474f9b09635d44bb0 | [
"CC0-1.0"
] | null | null | null | registry/tables/response.cpp | EOSIO-HACKATHON2020/registry-smart-contract | a0cc7cffc5cafb6fd4f4251474f9b09635d44bb0 | [
"CC0-1.0"
] | null | null | null | #include "response.hpp"
response::response()
{
}
response::response(const uint64_t &_key, const std::vector<std::string> &_answers)
: key(_key), answers(_answers)
{
}
uint64_t response::primary_key() const
{
return key;
}
std::vector<std::string> response::get_answers() const
{
return answers;
}
void response::set_answers(const std::vector<std::string> &_answers)
{
answers = _answers;
} | 16.4 | 82 | 0.695122 | EOSIO-HACKATHON2020 |
b1e11325423130d0aece319fbcae984a79351a43 | 14,704 | cpp | C++ | example/asio-example.cpp | mkaranki/sdbusplus | a4c9edc12a4f705eedd18f70d33ea0b70211fe2e | [
"Apache-2.0"
] | 14 | 2021-11-04T07:47:37.000Z | 2022-03-21T10:10:30.000Z | example/asio-example.cpp | mkaranki/sdbusplus | a4c9edc12a4f705eedd18f70d33ea0b70211fe2e | [
"Apache-2.0"
] | null | null | null | example/asio-example.cpp | mkaranki/sdbusplus | a4c9edc12a4f705eedd18f70d33ea0b70211fe2e | [
"Apache-2.0"
] | 6 | 2021-11-02T10:56:19.000Z | 2022-03-06T11:58:20.000Z | #include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <sdbusplus/asio/connection.hpp>
#include <sdbusplus/asio/object_server.hpp>
#include <sdbusplus/asio/sd_event.hpp>
#include <sdbusplus/bus.hpp>
#include <sdbusplus/exception.hpp>
#include <sdbusplus/server.hpp>
#include <sdbusplus/timer.hpp>
#include <chrono>
#include <ctime>
#include <iostream>
#include <variant>
using variant = std::variant<int, std::string>;
int foo(int test)
{
std::cout << "foo(" << test << ") -> " << (test + 1) << "\n";
return ++test;
}
// called from coroutine context, can make yielding dbus calls
int fooYield(boost::asio::yield_context yield,
std::shared_ptr<sdbusplus::asio::connection> conn, int test)
{
// fetch the real value from testFunction
boost::system::error_code ec;
std::cout << "fooYield(yield, " << test << ")...\n";
int testCount = conn->yield_method_call<int>(
yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
"xyz.openbmc_project.test", "TestFunction", test);
if (ec || testCount != (test + 1))
{
std::cout << "call to foo failed: ec = " << ec << '\n';
return -1;
}
std::cout << "yielding call to foo OK! (-> " << testCount << ")\n";
return testCount;
}
int methodWithMessage(sdbusplus::message::message& /*m*/, int test)
{
std::cout << "methodWithMessage(m, " << test << ") -> " << (test + 1)
<< "\n";
return ++test;
}
int voidBar(void)
{
std::cout << "voidBar() -> 42\n";
return 42;
}
void do_start_async_method_call_one(
std::shared_ptr<sdbusplus::asio::connection> conn,
boost::asio::yield_context yield)
{
boost::system::error_code ec;
variant testValue;
conn->yield_method_call<>(yield, ec, "xyz.openbmc_project.asio-test",
"/xyz/openbmc_project/test",
"org.freedesktop.DBus.Properties", "Set",
"xyz.openbmc_project.test", "int", variant(24));
testValue = conn->yield_method_call<variant>(
yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
"org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.test",
"int");
if (!ec && std::get<int>(testValue) == 24)
{
std::cout << "async call to Properties.Get serialized via yield OK!\n";
}
else
{
std::cout << "ec = " << ec << ": " << std::get<int>(testValue) << "\n";
}
conn->yield_method_call<void>(
yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
"org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.test",
"int", variant(42));
testValue = conn->yield_method_call<variant>(
yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
"org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.test",
"int");
if (!ec && std::get<int>(testValue) == 42)
{
std::cout << "async call to Properties.Get serialized via yield OK!\n";
}
else
{
std::cout << "ec = " << ec << ": " << std::get<int>(testValue) << "\n";
}
}
void do_start_async_ipmi_call(std::shared_ptr<sdbusplus::asio::connection> conn,
boost::asio::yield_context yield)
{
auto method = conn->new_method_call("xyz.openbmc_project.asio-test",
"/xyz/openbmc_project/test",
"xyz.openbmc_project.test", "execute");
constexpr uint8_t netFn = 6;
constexpr uint8_t lun = 0;
constexpr uint8_t cmd = 1;
std::map<std::string, variant> options = {{"username", variant("admin")},
{"privilege", variant(4)}};
std::vector<uint8_t> commandData = {4, 3, 2, 1};
method.append(netFn, lun, cmd, commandData, options);
boost::system::error_code ec;
sdbusplus::message::message reply = conn->async_send(method, yield[ec]);
std::tuple<uint8_t, uint8_t, uint8_t, uint8_t, std::vector<uint8_t>>
tupleOut;
try
{
reply.read(tupleOut);
}
catch (const sdbusplus::exception::SdBusError& e)
{
std::cerr << "failed to unpack; sig is " << reply.get_signature()
<< "\n";
}
auto& [rnetFn, rlun, rcmd, cc, responseData] = tupleOut;
std::vector<uint8_t> expRsp = {1, 2, 3, 4};
if (rnetFn == uint8_t(netFn + 1) && rlun == lun && rcmd == cmd && cc == 0 &&
responseData == expRsp)
{
std::cerr << "ipmi call returns OK!\n";
}
else
{
std::cerr << "ipmi call returns unexpected response\n";
}
}
auto ipmiInterface(boost::asio::yield_context /*yield*/, uint8_t netFn,
uint8_t lun, uint8_t cmd, std::vector<uint8_t>& /*data*/,
const std::map<std::string, variant>& /*options*/)
{
std::vector<uint8_t> reply = {1, 2, 3, 4};
uint8_t cc = 0;
std::cerr << "ipmiInterface:execute(" << int(netFn) << int(cmd) << ")\n";
return std::make_tuple(uint8_t(netFn + 1), lun, cmd, cc, reply);
}
void do_start_async_to_yield(std::shared_ptr<sdbusplus::asio::connection> conn,
boost::asio::yield_context yield)
{
boost::system::error_code ec;
int testValue = 0;
testValue = conn->yield_method_call<int>(
yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
"xyz.openbmc_project.test", "TestYieldFunction", int(41));
if (!ec && testValue == 42)
{
std::cout
<< "yielding call to TestYieldFunction serialized via yield OK!\n";
}
else
{
std::cout << "ec = " << ec << ": " << testValue << "\n";
}
ec.clear();
auto badValue = conn->yield_method_call<std::string>(
yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
"xyz.openbmc_project.test", "TestYieldFunction", int(41));
if (!ec)
{
std::cout
<< "yielding call to TestYieldFunction returned the wrong type\n";
}
else
{
std::cout << "TestYieldFunction expected error: " << ec << "\n";
}
ec.clear();
auto unUsedValue = conn->yield_method_call<std::string>(
yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
"xyz.openbmc_project.test", "TestYieldFunctionNotExits", int(41));
if (!ec)
{
std::cout << "TestYieldFunctionNotExists returned unexpectedly\n";
}
else
{
std::cout << "TestYieldFunctionNotExits expected error: " << ec << "\n";
}
}
int server()
{
// setup connection to dbus
boost::asio::io_context io;
auto conn = std::make_shared<sdbusplus::asio::connection>(io);
// test object server
conn->request_name("xyz.openbmc_project.asio-test");
auto server = sdbusplus::asio::object_server(conn);
std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
server.add_interface("/xyz/openbmc_project/test",
"xyz.openbmc_project.test");
// test generic properties
iface->register_property("int", 33,
sdbusplus::asio::PropertyPermission::readWrite);
std::vector<std::string> myStringVec = {"some", "test", "data"};
std::vector<std::string> myStringVec2 = {"more", "test", "data"};
iface->register_property("myStringVec", myStringVec,
sdbusplus::asio::PropertyPermission::readWrite);
iface->register_property("myStringVec2", myStringVec2);
// test properties with specialized callbacks
iface->register_property("lessThan50", 23,
// custom set
[](const int& req, int& propertyValue) {
if (req >= 50)
{
return -EINVAL;
}
propertyValue = req;
return 1; // success
});
iface->register_property(
"TrailTime", std::string("foo"),
// custom set
[](const std::string& req, std::string& propertyValue) {
propertyValue = req;
return 1; // success
},
// custom get
[](const std::string& property) {
auto now = std::chrono::system_clock::now();
auto timePoint = std::chrono::system_clock::to_time_t(now);
return property + std::ctime(&timePoint);
});
// test method creation
iface->register_method("TestMethod", [](const int32_t& callCount) {
return std::make_tuple(callCount,
"success: " + std::to_string(callCount));
});
iface->register_method("TestFunction", foo);
// fooYield has boost::asio::yield_context as first argument
// so will be executed in coroutine context if called
iface->register_method("TestYieldFunction",
[conn](boost::asio::yield_context yield, int val) {
return fooYield(yield, conn, val);
});
iface->register_method("TestMethodWithMessage", methodWithMessage);
iface->register_method("VoidFunctionReturnsInt", voidBar);
iface->register_method("execute", ipmiInterface);
iface->initialize();
io.run();
return 0;
}
int client()
{
using GetSubTreeType = std::vector<std::pair<
std::string,
std::vector<std::pair<std::string, std::vector<std::string>>>>>;
using message = sdbusplus::message::message;
// setup connection to dbus
boost::asio::io_context io;
auto conn = std::make_shared<sdbusplus::asio::connection>(io);
int ready = 0;
while (!ready)
{
auto readyMsg = conn->new_method_call(
"xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
"xyz.openbmc_project.test", "VoidFunctionReturnsInt");
try
{
message intMsg = conn->call(readyMsg);
intMsg.read(ready);
}
catch (sdbusplus::exception::SdBusError& e)
{
ready = 0;
// pause to give the server a chance to start up
usleep(10000);
}
}
// test async method call and async send
auto mesg =
conn->new_method_call("xyz.openbmc_project.ObjectMapper",
"/xyz/openbmc_project/object_mapper",
"xyz.openbmc_project.ObjectMapper", "GetSubTree");
static const auto depth = 2;
static const std::vector<std::string> interfaces = {
"xyz.openbmc_project.Sensor.Value"};
mesg.append("/xyz/openbmc_project/Sensors", depth, interfaces);
conn->async_send(mesg, [](boost::system::error_code ec, message& ret) {
std::cout << "async_send callback\n";
if (ec || ret.is_method_error())
{
std::cerr << "error with async_send\n";
return;
}
GetSubTreeType data;
ret.read(data);
for (auto& item : data)
{
std::cout << item.first << "\n";
}
});
conn->async_method_call(
[](boost::system::error_code ec, GetSubTreeType& subtree) {
std::cout << "async_method_call callback\n";
if (ec)
{
std::cerr << "error with async_method_call\n";
return;
}
for (auto& item : subtree)
{
std::cout << item.first << "\n";
}
},
"xyz.openbmc_project.ObjectMapper",
"/xyz/openbmc_project/object_mapper",
"xyz.openbmc_project.ObjectMapper", "GetSubTree",
"/org/openbmc/control", 2, std::vector<std::string>());
std::string nonConstCapture = "lalalala";
conn->async_method_call(
[nonConstCapture = std::move(nonConstCapture)](
boost::system::error_code ec,
const std::vector<std::string>& /*things*/) mutable {
std::cout << "async_method_call callback\n";
nonConstCapture += " stuff";
if (ec)
{
std::cerr << "async_method_call expected failure: " << ec
<< "\n";
}
else
{
std::cerr << "async_method_call should have failed!\n";
}
},
"xyz.openbmc_project.ObjectMapper",
"/xyz/openbmc_project/object_mapper",
"xyz.openbmc_project.ObjectMapper", "GetSubTree",
"/xyz/openbmc_project/sensors", depth, interfaces);
// sd_events work too using the default event loop
phosphor::Timer t1([]() { std::cerr << "*** tock ***\n"; });
t1.start(std::chrono::microseconds(1000000));
phosphor::Timer t2([]() { std::cerr << "*** tick ***\n"; });
t2.start(std::chrono::microseconds(500000), true);
// add the sd_event wrapper to the io object
sdbusplus::asio::sd_event_wrapper sdEvents(io);
// set up a client to make an async call to the server
// using coroutines (userspace cooperative multitasking)
boost::asio::spawn(io, [conn](boost::asio::yield_context yield) {
do_start_async_method_call_one(conn, yield);
});
boost::asio::spawn(io, [conn](boost::asio::yield_context yield) {
do_start_async_ipmi_call(conn, yield);
});
boost::asio::spawn(io, [conn](boost::asio::yield_context yield) {
do_start_async_to_yield(conn, yield);
});
conn->async_method_call(
[](boost::system::error_code ec, int32_t testValue) {
if (ec)
{
std::cerr << "TestYieldFunction returned error with "
"async_method_call (ec = "
<< ec << ")\n";
return;
}
std::cout << "TestYieldFunction return " << testValue << "\n";
},
"xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
"xyz.openbmc_project.test", "TestYieldFunction", int32_t(41));
io.run();
return 0;
}
int main(int argc, const char* argv[])
{
if (argc == 1)
{
int pid = fork();
if (pid == 0)
{
return client();
}
else if (pid > 0)
{
return server();
}
return pid;
}
if (std::string(argv[1]) == "--server")
{
return server();
}
if (std::string(argv[1]) == "--client")
{
return client();
}
std::cout << "usage: " << argv[0] << " [--server | --client]\n";
return -1;
}
| 34.275058 | 80 | 0.557807 | mkaranki |
b1e28d7ed70f0a489d6f7c370ce8a0a018b4e72a | 653 | cpp | C++ | LeetCode/cpp/841.cpp | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 279 | 2019-02-19T16:00:32.000Z | 2022-03-23T12:16:30.000Z | LeetCode/cpp/841.cpp | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 2 | 2019-03-31T08:03:06.000Z | 2021-03-07T04:54:32.000Z | LeetCode/cpp/841.cpp | ZintrulCre/LeetCode_Crawler | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 12 | 2019-01-29T11:45:32.000Z | 2019-02-04T16:31:46.000Z | class Solution {
public:
bool canVisitAllRooms(vector<vector<int>>& rooms) {
vector<int> locked;
int size = rooms.size();
locked.push_back(0);
for (int i = 1; i < size; ++i)
locked.push_back(1);
for (int i = 0; i < rooms[0].size(); ++i) {
locked[rooms[0][i]] = 0;
unlock(rooms[0][i], rooms, locked);
}
for (int i = 0; i < size; ++i)
if (locked[i] == 1)
return false;
return true;
}
void unlock(int k, vector<vector<int>>& rooms, vector<int>& locked) {
for (int i = 0; i < rooms[k].size(); ++i) {
if (locked[rooms[k][i]] == 1) {
locked[rooms[k][i]] = 0;
unlock(rooms[k][i], rooms, locked);
}
}
}
};
| 23.321429 | 70 | 0.554364 | ZintrulCre |
b1e399ecd9e39b2c0f8b037022ea4b25b9a4b8b4 | 9,814 | cpp | C++ | meeting-qt/setup/src/base/encrypt/encrypt_unittest.cpp | GrowthEase/- | 5cc7cab95fc309049de8023ff618219dff22d773 | [
"MIT"
] | 48 | 2022-03-02T07:15:08.000Z | 2022-03-31T08:37:33.000Z | meeting-qt/setup/src/base/encrypt/encrypt_unittest.cpp | chandarlee/Meeting | 9350fdea97eb2cdda28b8bffd9c4199de15460d9 | [
"MIT"
] | 1 | 2022-02-16T01:54:05.000Z | 2022-02-16T01:54:05.000Z | meeting-qt/setup/src/base/encrypt/encrypt_unittest.cpp | chandarlee/Meeting | 9350fdea97eb2cdda28b8bffd9c4199de15460d9 | [
"MIT"
] | 9 | 2022-03-01T13:41:37.000Z | 2022-03-10T06:05:23.000Z | /**
* @copyright Copyright (c) 2021 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
// Copyright (c) 2011, NetEase Inc. All rights reserved.
//
// Author: Ruan Liang <ruanliang@corp.netease.com>
// Date: 2011/6/23
//
// Encrypt Unittest
#include "base/encrypt/encrypt_impl.h"
#include "gtest/gtest.h"
#if defined(WITH_UNITTEST)
#if defined(WITH_ENCRYPT)
TEST(EncryptTest, MD5)
{
std::string string_ori = "I love this product";
std::string string_md5 = "c075917e5681d9379eb5c9278f83f8d2";
std::string string_dst;
nbase::Md5((const unsigned char *)string_ori.data(), string_ori.size(), string_dst);
EXPECT_STREQ(string_md5.c_str(), nbase::BinaryToHexString(string_dst).c_str());
nbase::EncryptInterface_var encrypt = new nbase::Encrypt_Impl();
encrypt->SetMethod(nbase::ENC_MD5);
encrypt->Encrypt(string_ori, string_dst);
EXPECT_STREQ(string_md5.c_str(), nbase::BinaryToHexString(string_dst).c_str());
}
TEST(EncryptTest, MD2)
{
std::string string_ori = "I love this product";
std::string string_md2 = "03a4fe1c2321204cbd2f029fbdb451da";
std::string string_dst;
nbase::EncryptInterface_var encrypt = new nbase::Encrypt_Impl();
encrypt->SetMethod(nbase::ENC_MD2);
encrypt->Encrypt(string_ori, string_dst);
EXPECT_STREQ(string_md2.c_str(), nbase::BinaryToHexString(string_dst).c_str());
}
TEST(EncryptTest, MD4)
{
std::string string_ori = "I love this product";
std::string string_md4 = "29a35e7a7373deaf252269f679293749";
std::string string_dst;
nbase::EncryptInterface_var encrypt = new nbase::Encrypt_Impl();
encrypt->SetMethod(nbase::ENC_MD4);
encrypt->Encrypt(string_ori, string_dst);
EXPECT_STREQ(string_md4.c_str(), nbase::BinaryToHexString(string_dst).c_str());
}
TEST(EncryptTest, SHA)
{
std::string string_ori = "I love this product";
std::string string_sha = "2241bf2032e8218a293412adcbf08aaa4389f69c";
std::string string_dst;
nbase::EncryptInterface_var encrypt = new nbase::Encrypt_Impl();
encrypt->SetMethod(nbase::ENC_SHA);
encrypt->Encrypt(string_ori, string_dst);
EXPECT_STREQ(string_sha.c_str(), nbase::BinaryToHexString(string_dst).c_str());
}
TEST(EncryptTest, SHA1)
{
std::string string_ori = "I love this product";
std::string string_sha1 = "8e5458e9dd8b31bbc32cdb4ab4e9de7f86452a8f";
std::string string_dst;
nbase::EncryptInterface_var encrypt = new nbase::Encrypt_Impl();
encrypt->SetMethod(nbase::ENC_SHA1);
encrypt->Encrypt(string_ori, string_dst);
EXPECT_STREQ(string_sha1.c_str(), nbase::BinaryToHexString(string_dst).c_str());
}
TEST(EncryptTest, DSS)
{
std::string string_ori = "I love this product";
std::string string_dss = "8e5458e9dd8b31bbc32cdb4ab4e9de7f86452a8f";
std::string string_dst;
nbase::EncryptInterface_var encrypt = new nbase::Encrypt_Impl();
encrypt->SetMethod(nbase::ENC_DSS);
encrypt->Encrypt(string_ori, string_dst);
EXPECT_STREQ(string_dss.c_str(), nbase::BinaryToHexString(string_dst).c_str());
}
TEST(EncryptTest, DSS1)
{
std::string string_ori = "I love this product";
std::string string_dss1 = "8e5458e9dd8b31bbc32cdb4ab4e9de7f86452a8f";
std::string string_dst;
nbase::EncryptInterface_var encrypt = new nbase::Encrypt_Impl();
encrypt->SetMethod(nbase::ENC_DSS1);
encrypt->Encrypt(string_ori, string_dst);
EXPECT_STREQ(string_dss1.c_str(), nbase::BinaryToHexString(string_dst).c_str());
}
TEST(EncryptTest, RC2)
{
std::string string_ori = "I love this product";
std::string string_key = "skyruan";
std::string string_rc2 = "c968e2752079b6edbf2d63e9752c25328aa637f8d563ddb2";
std::string enc_dst;
std::string dec_dst;
nbase::EncryptInterface_var encrypt_enc = new nbase::Encrypt_Impl();
encrypt_enc->SetMethod(nbase::ENC_RC2);
encrypt_enc->SetEncryptKey(string_key);
encrypt_enc->Encrypt(string_ori, enc_dst);
EXPECT_STREQ(string_rc2.c_str(), nbase::BinaryToHexString(enc_dst).c_str());
nbase::EncryptInterface_var encrypt_dec = new nbase::Encrypt_Impl();
encrypt_dec->SetMethod(nbase::ENC_RC2);
encrypt_dec->SetDecryptKey(string_key);
encrypt_dec->Decrypt(enc_dst, dec_dst);
EXPECT_STREQ(string_ori.c_str(), dec_dst.c_str());
}
TEST(EncryptTest, CAST)
{
std::string string_ori = "I love this product";
std::string string_key = "skyruan";
std::string string_cast = "b55a914a751af57fd99984a10b6f52c90c879755f6bd2040";
std::string enc_dst;
std::string dec_dst;
nbase::EncryptInterface_var encrypt_enc = new nbase::Encrypt_Impl();
encrypt_enc->SetMethod(nbase::ENC_CAST);
encrypt_enc->SetEncryptKey(string_key);
encrypt_enc->Encrypt(string_ori, enc_dst);
EXPECT_STREQ(string_cast.c_str(), nbase::BinaryToHexString(enc_dst).c_str());
nbase::EncryptInterface_var encrypt_dec = new nbase::Encrypt_Impl();
encrypt_dec->SetMethod(nbase::ENC_CAST);
encrypt_dec->SetDecryptKey(string_key);
encrypt_dec->Decrypt(enc_dst, dec_dst);
EXPECT_STREQ(string_ori.c_str(), dec_dst.c_str());
}
TEST(EncryptTest, AES128)
{
std::string string_ori = "I love this product";
std::string string_key = "skyruan";
std::string string_cast = "1f3413f82b60a2d2b7e69093787cca8275a3e3b409a6a18f9d4f416a41d32fdb";
std::string enc_dst;
std::string dec_dst;
nbase::EncryptInterface_var encrypt_enc = new nbase::Encrypt_Impl();
encrypt_enc->SetMethod(nbase::ENC_AES128);
encrypt_enc->SetEncryptKey(string_key);
encrypt_enc->Encrypt(string_ori, enc_dst);
EXPECT_STREQ(string_cast.c_str(), nbase::BinaryToHexString(enc_dst).c_str());
nbase::EncryptInterface_var encrypt_dec = new nbase::Encrypt_Impl();
encrypt_dec->SetMethod(nbase::ENC_AES128);
encrypt_dec->SetDecryptKey(string_key);
encrypt_dec->Decrypt(enc_dst, dec_dst);
EXPECT_STREQ(string_ori.c_str(), dec_dst.c_str());
}
TEST(EncryptTest, AES192)
{
std::string string_ori = "I love this product";
std::string string_key = "skyruan";
std::string string_aes = "1115f75334d099d93ccc6b7eb18b02792f4924093fd30817229b795f4635530c";
std::string enc_dst;
std::string dec_dst;
nbase::EncryptInterface_var encrypt_enc = new nbase::Encrypt_Impl();
encrypt_enc->SetMethod(nbase::ENC_AES192);
encrypt_enc->SetEncryptKey(string_key);
encrypt_enc->Encrypt(string_ori, enc_dst);
EXPECT_STREQ(string_aes.c_str(), nbase::BinaryToHexString(enc_dst).c_str());
nbase::EncryptInterface_var encrypt_dec = new nbase::Encrypt_Impl();
encrypt_dec->SetMethod(nbase::ENC_AES192);
encrypt_dec->SetDecryptKey(string_key);
encrypt_dec->Decrypt(enc_dst, dec_dst);
EXPECT_STREQ(string_ori.c_str(), dec_dst.c_str());
}
TEST(EncryptTest, AES256)
{
std::string string_ori = "I love this product";
std::string string_key = "skyruan";
std::string string_aes = "ef8ae9fff271dd0328e292c069ffd6d7cd7cb4aa9c6cd13d8a369c7c622e15cc";
std::string enc_dst;
std::string dec_dst;
nbase::EncryptInterface_var encrypt_enc = new nbase::Encrypt_Impl();
encrypt_enc->SetMethod(nbase::ENC_AES256);
encrypt_enc->SetEncryptKey(string_key);
encrypt_enc->Encrypt(string_ori, enc_dst);
EXPECT_STREQ(string_aes.c_str(), nbase::BinaryToHexString(enc_dst).c_str());
nbase::EncryptInterface_var encrypt_dec = new nbase::Encrypt_Impl();
encrypt_dec->SetMethod(nbase::ENC_AES256);
encrypt_dec->SetDecryptKey(string_key);
encrypt_dec->Decrypt(enc_dst, dec_dst);
EXPECT_STREQ(string_ori.c_str(), dec_dst.c_str());
}
TEST(EncryptTest, DES64)
{
std::string string_ori = "I love this product";
std::string string_key = "skyruan";
std::string string_des = "043f58be9970d4f60a1705bb34646b879710d4fb144cd865";
std::string enc_dst;
std::string dec_dst;
nbase::EncryptInterface_var encrypt_enc = new nbase::Encrypt_Impl();
encrypt_enc->SetMethod(nbase::ENC_DES64);
encrypt_enc->SetEncryptKey(string_key);
encrypt_enc->Encrypt(string_ori, enc_dst);
EXPECT_STREQ(string_des.c_str(), nbase::BinaryToHexString(enc_dst).c_str());
nbase::EncryptInterface_var encrypt_dec = new nbase::Encrypt_Impl();
encrypt_dec->SetMethod(nbase::ENC_DES64);
encrypt_dec->SetDecryptKey(string_key);
encrypt_dec->Decrypt(enc_dst, dec_dst);
EXPECT_STREQ(string_ori.c_str(), dec_dst.c_str());
}
TEST(EncryptTest, ARC4)
{
std::string string_ori = "I love this product";
std::string string_key = "skyruan";
std::string string_rc4 = "45e58f9cd88516f8dbcc4358ac86935adc5030";
std::string enc_dst;
std::string dec_dst;
nbase::EncryptInterface_var encrypt_enc = new nbase::Encrypt_Impl();
encrypt_enc->SetMethod(nbase::ENC_ARC4);
encrypt_enc->SetEncryptKey(string_key);
encrypt_enc->Encrypt(string_ori, enc_dst);
EXPECT_STREQ(string_rc4.c_str(), nbase::BinaryToHexString(enc_dst).c_str());
nbase::EncryptInterface_var encrypt_dec = new nbase::Encrypt_Impl();
encrypt_dec->SetMethod(nbase::ENC_ARC4);
encrypt_dec->SetDecryptKey(string_key);
encrypt_dec->Decrypt(enc_dst, dec_dst);
EXPECT_STREQ(string_ori.c_str(), dec_dst.c_str());
}
TEST(EncryptTest, RSA)
{
std::string string_ori = "I love this product";
std::string enc_dst;
std::string dec_dst;
for (int padding = RSA_PKCS1_PADDING; padding <= RSA_X931_PADDING; ++padding)
{
nbase::EncryptInterface_var encrypt_enc = new nbase::Encrypt_Impl();
encrypt_enc->SetMethod(nbase::ENC_RSA);
std::string key_private;
std::string key_public;
encrypt_enc->CreateKey(key_public, key_private);
encrypt_enc->SetPaddingMode(padding);
encrypt_enc->SetEncryptKey(key_public);
encrypt_enc->Encrypt(string_ori, enc_dst);
nbase::EncryptInterface_var encrypt_dec = new nbase::Encrypt_Impl();
encrypt_dec->SetMethod(nbase::ENC_RSA);
encrypt_dec->SetPaddingMode(padding);
encrypt_dec->SetDecryptKey(key_private);
encrypt_dec->Decrypt(enc_dst, dec_dst);
EXPECT_STREQ(string_ori.c_str(), dec_dst.c_str());
}
}
#endif // WITH_ENCRYPT
#endif // WITH_UNITTEST
| 34.801418 | 105 | 0.761361 | GrowthEase |
b1ea15aa6695b45959e226aab856109ab9cdb1d9 | 3,713 | cpp | C++ | Utilities/Poco/Foundation/testsuite/src/TaskTest.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | Utilities/Poco/Foundation/testsuite/src/TaskTest.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | Utilities/Poco/Foundation/testsuite/src/TaskTest.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | //
// TaskTest.cpp
//
// $Id$
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "TaskTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Task.h"
#include "Poco/Thread.h"
#include "Poco/Event.h"
#include "Poco/AutoPtr.h"
using Poco::Task;
using Poco::Thread;
using Poco::Event;
using Poco::AutoPtr;
namespace
{
class TestTask: public Task
{
public:
TestTask(): Task("TestTask")
{
}
void runTask()
{
_event.wait();
if (sleep(10))
return;
setProgress(0.5);
_event.wait();
if (isCancelled())
return;
setProgress(1.0);
_event.wait();
}
void cont()
{
_event.set();
}
private:
Event _event;
};
}
TaskTest::TaskTest(const std::string& name): CppUnit::TestCase(name)
{
}
TaskTest::~TaskTest()
{
}
void TaskTest::testFinish()
{
AutoPtr<TestTask> pTT = new TestTask;
assert (pTT->state() == Task::TASK_IDLE);
Thread thr;
thr.start(*pTT);
assert (pTT->progress() == 0);
pTT->cont();
while (pTT->progress() != 0.5) Thread::sleep(50);
assert (pTT->state() == Task::TASK_RUNNING);
pTT->cont();
while (pTT->progress() != 1.0) Thread::sleep(50);
pTT->cont();
thr.join();
assert (pTT->state() == Task::TASK_FINISHED);
}
void TaskTest::testCancel1()
{
AutoPtr<TestTask> pTT = new TestTask;
assert (pTT->state() == Task::TASK_IDLE);
Thread thr;
thr.start(*pTT);
assert (pTT->progress() == 0);
pTT->cont();
while (pTT->progress() != 0.5) Thread::sleep(50);
assert (pTT->state() == Task::TASK_RUNNING);
pTT->cancel();
assert (pTT->state() == Task::TASK_CANCELLING);
pTT->cont();
thr.join();
assert (pTT->state() == Task::TASK_FINISHED);
}
void TaskTest::testCancel2()
{
AutoPtr<TestTask> pTT = new TestTask;
assert (pTT->state() == Task::TASK_IDLE);
Thread thr;
thr.start(*pTT);
assert (pTT->progress() == 0);
pTT->cancel();
assert (pTT->state() == Task::TASK_CANCELLING);
pTT->cont();
thr.join();
assert (pTT->state() == Task::TASK_FINISHED);
}
void TaskTest::setUp()
{
}
void TaskTest::tearDown()
{
}
CppUnit::Test* TaskTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TaskTest");
CppUnit_addTest(pSuite, TaskTest, testFinish);
CppUnit_addTest(pSuite, TaskTest, testCancel1);
CppUnit_addTest(pSuite, TaskTest, testCancel2);
return pSuite;
}
| 22.919753 | 78 | 0.690816 | nocnokneo |
b1eae36d514f7a8c0103b1470887d00b93076f27 | 616 | cpp | C++ | RealmLib/Packets/Client/CreateGuild.cpp | SometimesRain/realmnet | 76ead08b4a0163a05b65389e512942a620331256 | [
"MIT"
] | 10 | 2018-11-25T21:59:43.000Z | 2022-01-09T22:41:52.000Z | RealmLib/Packets/Client/CreateGuild.cpp | SometimesRain/realmnet | 76ead08b4a0163a05b65389e512942a620331256 | [
"MIT"
] | 1 | 2018-11-28T12:59:59.000Z | 2018-11-28T12:59:59.000Z | RealmLib/Packets/Client/CreateGuild.cpp | SometimesRain/realmnet | 76ead08b4a0163a05b65389e512942a620331256 | [
"MIT"
] | 6 | 2018-12-28T22:34:13.000Z | 2021-10-16T10:17:17.000Z | #include "stdafx.h"
#include <GameData/Constants.h>
#include <GameData/TypeManager.h>
#include "Packets/PacketWriter.h"
#include "Packets/PacketReader.h"
#include <Packets/CreateGuild.h>
CreateGuild::CreateGuild(const String& name)
: name(name)
{
}
CreateGuild::CreateGuild(byte* data)
{
PacketReader r(data);
r.read(name);
}
void CreateGuild::emplace(byte* buffer) const
{
PacketWriter w(buffer, size(), TypeManager::typeToId[PacketType::CreateGuild]);
w.write(name);
}
int CreateGuild::size() const
{
return 7 + name.length;
}
String CreateGuild::toString() const
{
return String("CREATEGUILD");
} | 16.210526 | 80 | 0.730519 | SometimesRain |
b1ef3b34bf746795f986acb63211d1d98bd28e48 | 1,622 | cpp | C++ | regression/icosahedral/div.cpp | aurianer/gridtools | 5f99471bf36215e2a53317d2c7844bf057231ffa | [
"BSD-3-Clause"
] | null | null | null | regression/icosahedral/div.cpp | aurianer/gridtools | 5f99471bf36215e2a53317d2c7844bf057231ffa | [
"BSD-3-Clause"
] | null | null | null | regression/icosahedral/div.cpp | aurianer/gridtools | 5f99471bf36215e2a53317d2c7844bf057231ffa | [
"BSD-3-Clause"
] | null | null | null | /*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <gtest/gtest.h>
#include <gridtools/stencil_composition/icosahedral.hpp>
#include <gridtools/tools/icosahedral_regression_fixture.hpp>
#include "div_functors.hpp"
#include "operators_repository.hpp"
using namespace gridtools;
using namespace ico_operators;
struct div : regression_fixture<2> {
operators_repository repo = {d(0), d(1)};
};
TEST_F(div, reduction_into_scalar) {
auto spec = [](auto in_edges, auto edge_length, auto cell_area_reciprocal, auto out) {
GT_DECLARE_ICO_TMP((array<float_type, 3>), cells, weights);
return execute_parallel()
.ij_cached(weights)
.stage(div_prep_functor(), edge_length, cell_area_reciprocal, weights)
.stage(div_functor_reduction_into_scalar(), in_edges, weights, out);
};
auto out = make_storage<cells>();
run(spec,
backend_t(),
make_grid(),
make_storage<edges>(repo.u),
make_storage<edges>(repo.edge_length),
make_storage<cells>(repo.cell_area_reciprocal),
out);
verify(repo.div_u, out);
}
TEST_F(div, flow_convention) {
auto out = make_storage<cells>();
run_single_stage(div_functor_flow_convention_connectivity(),
backend_t(),
make_grid(),
make_storage<edges>(repo.u),
make_storage<edges>(repo.edge_length),
make_storage<cells>(repo.cell_area_reciprocal),
out);
verify(repo.div_u, out);
}
| 28.964286 | 90 | 0.681874 | aurianer |
b1f032c4b4788243c58a4ca7f5d373ae82adcf37 | 2,924 | cpp | C++ | TEvtGen/EvtGen/EvtGenModels/EvtVtoSll.cpp | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | TEvtGen/EvtGen/EvtGenModels/EvtVtoSll.cpp | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | TEvtGen/EvtGen/EvtGenModels/EvtVtoSll.cpp | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | //--------------------------------------------------------------------------
//
// Environment:
// This software is part of the EvtGen package developed jointly
// for the BaBar and CLEO collaborations. If you use all or part
// of it, please give an appropriate acknowledgement.
//
// Copyright Information: See EvtGen/COPYRIGHT
// Copyright (C) 1998 Caltech, UCSB
//
// Module: EvtVll.cc
//
// Description: The decay of a vector meson to a scalar and a
// lepton pair. E.g. D_s*+ -> D_s+ e+ e-
//
//
// Modification history:
//
// RYD February 28, 2009 Module created
//
//------------------------------------------------------------------------
//
#include "EvtGenBase/EvtPatches.hh"
#include <stdlib.h>
#include <iostream>
#include <string>
#include "EvtGenBase/EvtParticle.hh"
#include "EvtGenBase/EvtPDL.hh"
#include "EvtGenBase/EvtGenKine.hh"
#include "EvtGenModels/EvtVtoSll.hh"
#include "EvtGenBase/EvtDiracSpinor.hh"
#include "EvtGenBase/EvtReport.hh"
#include "EvtGenBase/EvtVector4C.hh"
#include "EvtGenBase/EvtTensor4C.hh"
EvtVtoSll::~EvtVtoSll() {}
std::string EvtVtoSll::getName(){
return "VTOSLL";
}
EvtDecayBase* EvtVtoSll::clone(){
return new EvtVtoSll;
}
void EvtVtoSll::init(){
// check that there are 0 arguments
checkNArg(0);
checkNDaug(3);
checkSpinParent(EvtSpinType::VECTOR);
checkSpinDaughter(0,EvtSpinType::SCALAR);
checkSpinDaughter(1,EvtSpinType::DIRAC);
checkSpinDaughter(2,EvtSpinType::DIRAC);
}
void EvtVtoSll::initProbMax(){
//setProbMax(1.0);
}
void EvtVtoSll::decay(EvtParticle *p){
p->initializePhaseSpace(getNDaug(),getDaugs());
EvtParticle *l1, *l2;
l1 = p->getDaug(1);
l2 = p->getDaug(2);
EvtVector4C l11, l12, l21, l22;
l11=EvtLeptonVCurrent(l1->spParent(0),l2->spParent(0));
l12=EvtLeptonVCurrent(l1->spParent(0),l2->spParent(1));
l21=EvtLeptonVCurrent(l1->spParent(1),l2->spParent(0));
l22=EvtLeptonVCurrent(l1->spParent(1),l2->spParent(1));
EvtVector4C eps0=p->eps(0);
EvtVector4C eps1=p->eps(1);
EvtVector4C eps2=p->eps(2);
EvtVector4R P=p->getP4Restframe();
EvtVector4R k=l1->getP4()+l2->getP4();
double k2=k*k;
EvtTensor4C T(dual(EvtGenFunctions::directProd(P,(1.0/k2)*k)));
double M2=p->mass();
M2*=M2;
double m2=l1->mass();
m2*=m2;
double norm=1.0/sqrt(2*M2+4*m2-4*m2*m2/M2);
vertex(0,0,0,norm*(eps0*T.cont2(l11)));
vertex(0,0,1,norm*(eps0*T.cont2(l12)));
vertex(0,1,0,norm*(eps0*T.cont2(l21)));
vertex(0,1,1,norm*(eps0*T.cont2(l22)));
vertex(1,0,0,norm*(eps1*T.cont2(l11)));
vertex(1,0,1,norm*(eps1*T.cont2(l12)));
vertex(1,1,0,norm*(eps1*T.cont2(l21)));
vertex(1,1,1,norm*(eps1*T.cont2(l22)));
vertex(2,0,0,norm*(eps2*T.cont2(l11)));
vertex(2,0,1,norm*(eps2*T.cont2(l12)));
vertex(2,1,0,norm*(eps2*T.cont2(l21)));
vertex(2,1,1,norm*(eps2*T.cont2(l22)));
return;
}
| 21.984962 | 76 | 0.627223 | AllaMaevskaya |
b1f0b8a27b91264dba6421d942bc7f4b244f09db | 6,870 | cpp | C++ | Sources/simdlib/SimdAvx2Float16.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | 6 | 2017-10-13T04:29:38.000Z | 2018-05-10T13:52:20.000Z | Sources/simdlib/SimdAvx2Float16.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | null | null | null | Sources/simdlib/SimdAvx2Float16.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | null | null | null | /*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2017 Yermalayeu Ihar.
*
* 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 "Simd/SimdMemory.h"
#include "Simd/SimdExtract.h"
#include "Simd/SimdStore.h"
namespace Simd
{
#ifdef SIMD_AVX2_ENABLE
namespace Avx2
{
template<bool align> SIMD_INLINE void Float32ToFloat16(const float * src, uint16_t * dst)
{
Sse2::Store<align>((__m128i*)dst, _mm256_cvtps_ph(Avx::Load<align>(src), 0));
}
template <bool align> void Float32ToFloat16(const float * src, size_t size, uint16_t * dst)
{
assert(size >= F);
if (align)
assert(Aligned(src) && Aligned(dst));
size_t fullAlignedSize = Simd::AlignLo(size, QF);
size_t partialAlignedSize = Simd::AlignLo(size, F);
size_t i = 0;
for (; i < fullAlignedSize; i += QF)
{
Float32ToFloat16<align>(src + i + F * 0, dst + i + F * 0);
Float32ToFloat16<align>(src + i + F * 1, dst + i + F * 1);
Float32ToFloat16<align>(src + i + F * 2, dst + i + F * 2);
Float32ToFloat16<align>(src + i + F * 3, dst + i + F * 3);
}
for (; i < partialAlignedSize; i += F)
Float32ToFloat16<align>(src + i, dst + i);
if(partialAlignedSize != size)
Float32ToFloat16<false>(src + size - F, dst + size - F);
}
void Float32ToFloat16(const float * src, size_t size, uint16_t * dst)
{
if (Aligned(src) && Aligned(dst))
Float32ToFloat16<true>(src, size, dst);
else
Float32ToFloat16<false>(src, size, dst);
}
template<bool align> SIMD_INLINE void Float16ToFloat32(const uint16_t * src, float * dst)
{
Avx::Store<align>(dst, _mm256_cvtph_ps(Sse2::Load<align>((__m128i*)src)));
}
template <bool align> void Float16ToFloat32(const uint16_t * src, size_t size, float * dst)
{
assert(size >= F);
if (align)
assert(Aligned(src) && Aligned(dst));
size_t fullAlignedSize = Simd::AlignLo(size, QF);
size_t partialAlignedSize = Simd::AlignLo(size, F);
size_t i = 0;
for (; i < fullAlignedSize; i += QF)
{
Float16ToFloat32<align>(src + i + F * 0, dst + i + F * 0);
Float16ToFloat32<align>(src + i + F * 1, dst + i + F * 1);
Float16ToFloat32<align>(src + i + F * 2, dst + i + F * 2);
Float16ToFloat32<align>(src + i + F * 3, dst + i + F * 3);
}
for (; i < partialAlignedSize; i += F)
Float16ToFloat32<align>(src + i, dst + i);
if (partialAlignedSize != size)
Float16ToFloat32<false>(src + size - F, dst + size - F);
}
void Float16ToFloat32(const uint16_t * src, size_t size, float * dst)
{
if (Aligned(src) && Aligned(dst))
Float16ToFloat32<true>(src, size, dst);
else
Float16ToFloat32<false>(src, size, dst);
}
template <bool align> SIMD_INLINE void SquaredDifferenceSum16f(const uint16_t * a, const uint16_t * b, size_t offset, __m256 & sum)
{
__m256 _a = _mm256_cvtph_ps(Sse2::Load<align>((__m128i*)(a + offset)));
__m256 _b = _mm256_cvtph_ps(Sse2::Load<align>((__m128i*)(b + offset)));
__m256 _d = _mm256_sub_ps(_a, _b);
sum = _mm256_fmadd_ps(_d, _d, sum);
}
template <bool align> SIMD_INLINE void SquaredDifferenceSum16f(const uint16_t * a, const uint16_t * b, size_t size, float * sum)
{
assert(size >= F);
if (align)
assert(Aligned(a) && Aligned(b));
size_t partialAlignedSize = AlignLo(size, F);
size_t fullAlignedSize = AlignLo(size, QF);
size_t i = 0;
__m256 sums[4] = { _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps() };
if (fullAlignedSize)
{
for (; i < fullAlignedSize; i += QF)
{
SquaredDifferenceSum16f<align>(a, b, i + F*0, sums[0]);
SquaredDifferenceSum16f<align>(a, b, i + F*1, sums[1]);
SquaredDifferenceSum16f<align>(a, b, i + F*2, sums[2]);
SquaredDifferenceSum16f<align>(a, b, i + F*3, sums[3]);
}
sums[0] = _mm256_add_ps(_mm256_add_ps(sums[0], sums[1]), _mm256_add_ps(sums[2], sums[3]));
}
for (; i < partialAlignedSize; i += F)
SquaredDifferenceSum16f<align>(a, b, i, sums[0]);
if (partialAlignedSize != size)
{
__m256 mask = RightNotZero(size - partialAlignedSize);
__m256 _a = _mm256_cvtph_ps(Sse2::Load<false>((__m128i*)(a + size - F)));
__m256 _b = _mm256_cvtph_ps(Sse2::Load<false>((__m128i*)(b + size - F)));
__m256 _d = _mm256_and_ps(_mm256_sub_ps(_a, _b), mask);
sums[0] = _mm256_fmadd_ps(_d, _d, sums[0]);
}
*sum = Avx::ExtractSum(sums[0]);
}
void SquaredDifferenceSum16f(const uint16_t * a, const uint16_t * b, size_t size, float * sum)
{
if (Aligned(a) && Aligned(b))
SquaredDifferenceSum16f<true>(a, b, size, sum);
else
SquaredDifferenceSum16f<false>(a, b, size, sum);
}
}
#endif// SIMD_AVX2_ENABLE
}
| 43.757962 | 140 | 0.552256 | aestesis |
b1f1ded04ec793af538577cd5d3c09c191b6f515 | 2,356 | cxx | C++ | BehaviroalPatterns/mediator/Mediator.cxx | enuguru/design_patterns | 7b5a70d65811c39d15cbfa8b7a0603a16a851265 | [
"MIT"
] | 12 | 2020-03-01T21:05:28.000Z | 2022-03-25T22:25:34.000Z | BehaviroalPatterns/mediator/Mediator.cxx | swarajsomala/design-patterns | 5302a899b391d7c01446ab1e5bb9c8f8235e0038 | [
"MIT"
] | null | null | null | BehaviroalPatterns/mediator/Mediator.cxx | swarajsomala/design-patterns | 5302a899b391d7c01446ab1e5bb9c8f8235e0038 | [
"MIT"
] | 6 | 2020-03-17T22:26:16.000Z | 2022-01-16T12:54:38.000Z | /*
* C++ Design Patterns:
* Author: Junzhuo Du [github.com/Junzhuodu]
* 2020
*
*/
#include <iostream>
#include <string>
#include <vector>
class Mediator;
class Colleague {
public:
Colleague(Mediator* const m, unsigned int i)
: mediator_(m), id_(i) {}
virtual ~Colleague() = default;
unsigned int getId() {
return id_;
}
virtual void sendMsg(std::string) = 0;
virtual void receiveMsg(std::string) = 0;
protected:
Mediator* mediator_;
unsigned int id_;
};
class ConcreteColleague : public Colleague {
public:
ConcreteColleague(Mediator* const m, unsigned int i)
: Colleague(m, i) {}
~ConcreteColleague() = default;
void sendMsg(std::string msg) override;
void receiveMsg(std::string msg) override {
std::cout << "Message: " << msg << " is received by Colleague(id=" << this->getId() << ")" << std::endl;
}
};
class Mediator {
public:
virtual ~Mediator() = default;
virtual void add(Colleague* const c) = 0;
virtual void distribute(Colleague* const sender, const std::string& msg) = 0;
};
class ConcreteMediator : public Mediator {
public:
~ConcreteMediator() {
for (unsigned int i = 0; i < colleagues_.size(); ++i) {
delete colleagues_[i];
}
colleagues_.clear();
}
void add(Colleague* const c) {
colleagues_.push_back(c);
}
void distribute(Colleague* const sender, const std::string& msg) {
for (auto colleague : colleagues_) {
if (colleague->getId() != sender->getId()) {
colleague->receiveMsg(msg);
}
}
}
private:
std::vector<Colleague*> colleagues_;
};
void ConcreteColleague::sendMsg(std::string msg) {
std::cout << "Message: " << msg << " is sent by Colleague(id=" << this->getId() << ")" << std::endl;
mediator_->distribute(this, msg);
}
int main() {
Mediator *mediator = new ConcreteMediator();
Colleague *colleague1 = new ConcreteColleague(mediator, 1);
Colleague *colleague2 = new ConcreteColleague(mediator, 2);
Colleague *colleague3 = new ConcreteColleague(mediator, 3);
mediator->add(colleague1);
mediator->add(colleague2);
mediator->add(colleague3);
colleague1->sendMsg("Hello");
colleague2->sendMsg("World");
colleague3->sendMsg("Mediator Pattern");
}
| 23.326733 | 112 | 0.622666 | enuguru |
b1f2b5e69e668d51ec9e406f5215163f56a9a4ac | 1,155 | hpp | C++ | ReactNativeFrontend/ios/Pods/boost/boost/geometry/core/make.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 326 | 2015-02-08T13:47:49.000Z | 2022-03-16T02:13:59.000Z | ReactNativeFrontend/ios/Pods/boost/boost/geometry/core/make.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 623 | 2015-01-02T23:45:23.000Z | 2022-03-09T11:15:23.000Z | ReactNativeFrontend/ios/Pods/boost/boost/geometry/core/make.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 215 | 2015-01-14T15:50:38.000Z | 2022-02-23T03:58:36.000Z | // Boost.Geometry
// Copyright (c) 2020, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Use, modification and distribution is subject to 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)
#ifndef BOOST_GEOMETRY_CORE_MAKE_HPP
#define BOOST_GEOMETRY_CORE_MAKE_HPP
namespace boost { namespace geometry
{
namespace traits
{
/*!
\brief Traits class to create an object of Geometry type.
\details This trait is optional and allows to define efficient way of creating Geometries.
\ingroup traits
\par Geometries:
- points
- boxes
- segments
\par Specializations should provide:
- static const bool is_specialized = true;
- static member function apply() taking:
- N coordinates (points)
- 2 points, min and max (boxes)
- 2 points, first and second (segments)
\tparam Geometry geometry
*/
template <typename Geometry>
struct make
{
static const bool is_specialized = false;
};
} // namespace traits
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_CORE_MAKE_HPP
| 24.574468 | 90 | 0.738528 | Harshitha91 |
b1f3e6fbb38df1923434f7be96cccd49082363bf | 654 | cpp | C++ | shared/offline_compiler/source/offline_compiler_helper.cpp | 8tab/compute-runtime | 71bd96ad7184df83c7af04ffa8e0d6678ab26f99 | [
"MIT"
] | 1 | 2020-04-17T05:46:04.000Z | 2020-04-17T05:46:04.000Z | shared/offline_compiler/source/offline_compiler_helper.cpp | 8tab/compute-runtime | 71bd96ad7184df83c7af04ffa8e0d6678ab26f99 | [
"MIT"
] | null | null | null | shared/offline_compiler/source/offline_compiler_helper.cpp | 8tab/compute-runtime | 71bd96ad7184df83c7af04ffa8e0d6678ab26f99 | [
"MIT"
] | 1 | 2020-05-25T21:57:51.000Z | 2020-05-25T21:57:51.000Z | /*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/debug_settings/debug_settings_manager.h"
#include "shared/source/helpers/hw_info.h"
#include "shared/source/utilities/debug_settings_reader_creator.h"
namespace NEO {
template <DebugFunctionalityLevel DebugLevel>
DebugSettingsManager<DebugLevel>::DebugSettingsManager(const char *registryPath) {
}
template <DebugFunctionalityLevel DebugLevel>
DebugSettingsManager<DebugLevel>::~DebugSettingsManager() = default;
// Global Debug Settings Manager
DebugSettingsManager<globalDebugFunctionalityLevel> DebugManager("");
} // namespace NEO
| 27.25 | 82 | 0.80581 | 8tab |
b1f799cfacbfc6ed9281e70eafc7f1e3d15e0ed6 | 771 | cpp | C++ | droneMissionPlannerROSModule/src/sources/droneMissionPlannerROSModuleNode.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | droneMissionPlannerROSModule/src/sources/droneMissionPlannerROSModuleNode.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | droneMissionPlannerROSModule/src/sources/droneMissionPlannerROSModuleNode.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | /*
*
*
*
*
*/
/// ROS
#include "ros/ros.h"
#include <stdio.h>
#include <iostream>
#include "droneMissionPlannerROSModule.h"
using namespace std;
int main(int argc, char **argv)
{
ros::init(argc, argv, MODULE_NAME_MISSION_PLANNER);
ros::NodeHandle n;
//Init
cout<<"Starting drone Mission Planner..."<<endl;
//Simulator
DroneMissionPlanner MyDroneMissionPlanner;
MyDroneMissionPlanner.open(n,MODULE_NAME_MISSION_PLANNER);
//Loop
while(ros::ok())
{
//double timeInitAStar=ros::Time::now().toSec();
//Read ros messages
ros::spinOnce();
//cout<<"Loop"<<endl;
MyDroneMissionPlanner.run();
MyDroneMissionPlanner.sleep();
}
return 1;
}
| 9.402439 | 62 | 0.596628 | MorS25 |
b1f91d73591b7e2ad48c32e6370e9d8fbb5c6499 | 3,145 | hxx | C++ | src/weapon/energy_charge.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | null | null | null | src/weapon/energy_charge.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | null | null | null | src/weapon/energy_charge.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | 1 | 2022-01-29T11:54:41.000Z | 2022-01-29T11:54:41.000Z | /**
* @file
* @author Jason Lingle
* @brief Contains the EnergyCharge weapon
*/
#ifndef ENERGY_CHARGE_HXX_
#define ENERGY_CHARGE_HXX_
#include <vector>
#include <cmath>
#include "src/sim/game_object.hxx"
#include "explode_listener.hxx"
class Ship;
#define EC_SPEED 0.001f ///< Launch speed of EnergyCharge
#define EC_DEGREDATION 0.000125f ///< Rate of energy degradation
#define EC_RADW (STD_CELL_SZ/2) ///< Width of EnergyCharge
#define EC_RADH (EC_RADW/3) ///< Height of EnergyCharge
#define EC_CRRAD (EC_RADW*/*std::sqrt(2.0f)*/1.41421356f) ///< Collision radius of EnergyCharge
/** The EnergyCharge is a burst of energy that becomes progressively weaker as it travels.
*
* Its strength is represented by colour, which is magenta at 100% and red near 0%.
*/
class EnergyCharge: public GameObject {
friend class INO_EnergyCharge;
friend class ENO_EnergyCharge;
friend class ExplodeListener<EnergyCharge>;
private:
ExplodeListener<EnergyCharge>* explodeListeners;
//0..1
const Ship * const parent;
float intensity;
const float theta;
const float tcos, tsin;
CollisionRectangle collisionRectangle;
bool exploded;
unsigned blame;
//For use by net code
EnergyCharge(GameField* field, float x, float y, float vx, float vy,
float _theta, float _inten);
public:
virtual ~EnergyCharge();
/** Constructs a new EnergyCharge with the given parms.
*
* @param field The field the charge will live in
* @param parent The Ship that launched the charge
* @param x Initial X coordinate
* @param y Initial Y coordinate
* @param theta Launch direction
* @param intensity Initial intensity
*/
EnergyCharge(GameField* field, const Ship* parent, float x, float y, float theta, float intensity);
virtual bool update(float) noth;
virtual void draw() noth;
virtual CollisionResult checkCollision(GameObject*) noth;
//The default now does what we want
//virtual vector<CollisionRectangle*>* getCollisionBounds() noth;
virtual bool collideWith(GameObject*) noth;
virtual float getRotation() const noth;
virtual float getRadius() const noth;
/** Returns the alpha component of a charge's colour for the given intensity. */
static float getColourA(float) noth;
/** Returns the red component of a charge's colour for the given intensity. */
static float getColourR(float) noth;
/** Returns the green component of a charge's colour for the given intensity. */
static float getColourG(float) noth;
/** Returns the blue component of a charge's colour for the given intensity. */
static float getColourB(float) noth;
/** Returns the intensity an EnergyCharge with the given starting
* intensity will have after travelling the given distance.
*/
static float getIntensityAt(float initIntensity, float dist) noth;
/** Returns the intensity of the EnergyCharge */
float getIntensity() const noth { return intensity; }
/** Causes the EnergyCharge to spontaneously explode due to the given object.
* Only intended for use by networking code (and internally).
*/
void explode(GameObject*) noth;
};
#endif /*ENERGY_CHARGE_HXX_*/
| 33.457447 | 101 | 0.735453 | AltSysrq |
b1f9c34fc56349a5928d10d96bec1ff376b45084 | 684 | cpp | C++ | Q2/Q2/Q2.cpp | HafizHamza19/C-Plus-Plus-41-Question-of-Assignment | 9a8a14b48439adb12cbb6e13c4cc0ea5fc901579 | [
"MIT"
] | null | null | null | Q2/Q2/Q2.cpp | HafizHamza19/C-Plus-Plus-41-Question-of-Assignment | 9a8a14b48439adb12cbb6e13c4cc0ea5fc901579 | [
"MIT"
] | null | null | null | Q2/Q2/Q2.cpp | HafizHamza19/C-Plus-Plus-41-Question-of-Assignment | 9a8a14b48439adb12cbb6e13c4cc0ea5fc901579 | [
"MIT"
] | null | null | null | #include <iostream>
#include <conio.h>
using namespace std;
void main()
{
cout<<"------------------Intermediate-------------------";
int hafiz;
cout<<"\n\n\nEnter Your Marks You Got In Inter Out Off (1100) : ";
cin>>hafiz;
float hamza;
hamza=hafiz*100/1100;
cout <<"\nYour Percentage Is: " << hamza <<"%"<<endl<<endl<<endl;
if (hamza>=85)
{
cout<<"\n\t\t\tEXELLENT";
}
if(hamza>=75 && hamza<85)
{
cout<<"\n\t\t\tOUTSTANDING";
}
if(hamza>=65 && hamza<75)
{
cout<<"\n\t\t\tGOOD";
}
if(hamza>50 && hamza<65)
{
cout<<"\n\t\t\tPass But Need Very Work Hard :( ";
}
if(hamza>=0 && hamza<50)
{
cout<<"\t\t\tSORRY\n\t\t\tRepeat Course :( ";
}
getch();
} | 19 | 67 | 0.55117 | HafizHamza19 |
b1ff9cc00c937dcdbb0295e46f13368921169969 | 14,574 | cpp | C++ | UniEngine/src/SerializationManager.cpp | edisonlee0212/UniEngine-deprecated | 4b899980c280ac501c3b5fa2746cf1e71cfedd28 | [
"MIT"
] | null | null | null | UniEngine/src/SerializationManager.cpp | edisonlee0212/UniEngine-deprecated | 4b899980c280ac501c3b5fa2746cf1e71cfedd28 | [
"MIT"
] | null | null | null | UniEngine/src/SerializationManager.cpp | edisonlee0212/UniEngine-deprecated | 4b899980c280ac501c3b5fa2746cf1e71cfedd28 | [
"MIT"
] | 1 | 2021-09-06T08:07:37.000Z | 2021-09-06T08:07:37.000Z | #include "pch.h"
#include "SerializationManager.h"
#include "CameraComponent.h"
#include "DirectionalLight.h"
#include "Particles.h"
#include "PointLight.h"
#include "Ray.h"
#include "SpotLight.h"
#include "Transforms.h"
#include "MeshRenderer.h"
#include "RigidBody.h"
using namespace UniEngine;
ComponentDataRegistration<Transform> TransformRegistry(1);
ComponentDataRegistration<GlobalTransform> GlobalTransformRegistry(1);
ComponentDataRegistration<Ray> RayRegistry(1);
ComponentDataRegistration<SpotLight> SpotLightRegistry(1);
ComponentDataRegistration<PointLight> PointLightRegistry(1);
ComponentDataRegistration<DirectionalLight> DirectionalLightRegistry(1);
ComponentDataRegistration<CameraLayerMask> CameraLayerMaskRegistry(1);
SerializableRegistration<CameraComponent> CameraComponentRegistry(1);
SerializableRegistration<Particles> ParticlesRegistry(1);
SerializableRegistration<MeshRenderer> MeshRendererRegistry(1);
SerializableRegistration<RigidBody> RigidBodyRegistry(1);
void UniEngine::SerializationManager::Init()
{
RegisterComponentDataSerializerDeserializer<Transform>(
{
[](ComponentDataBase* data)
{
Transform* out = static_cast<Transform*>(data);
glm::mat4 val = out->m_value;
std::stringstream stream;
EXPORT_PARAM(stream, val);
return stream.str();
},
[](const std::string& data, ComponentDataBase* ptr)
{
std::stringstream stream;
stream << data;
Transform* out = static_cast<Transform*>(ptr);
char temp;
IMPORT_PARAM(stream, out->m_value, temp);
}
}
);
RegisterComponentDataSerializerDeserializer<GlobalTransform>(
{
[](ComponentDataBase* data)
{
GlobalTransform* out = static_cast<GlobalTransform*>(data);
glm::mat4 val = out->m_value;
std::stringstream stream;
EXPORT_PARAM(stream, val);
return stream.str();
},
[](const std::string& data, ComponentDataBase* ptr)
{
std::stringstream stream;
stream << data;
GlobalTransform* out = static_cast<GlobalTransform*>(ptr);
char temp;
IMPORT_PARAM(stream, out->m_value, temp);
}
}
);
RegisterComponentDataSerializerDeserializer<Ray>(
{
[](ComponentDataBase* data)
{
Ray* out = static_cast<Ray*>(data);
std::stringstream stream;
EXPORT_PARAM(stream, out->m_start);
EXPORT_PARAM(stream, out->m_direction);
EXPORT_PARAM(stream, out->m_length);
return stream.str();
},
[](const std::string& data, ComponentDataBase* ptr)
{
std::stringstream stream;
stream << data;
Ray* out = static_cast<Ray*>(ptr);
char temp;
IMPORT_PARAM(stream, out->m_start, temp);
IMPORT_PARAM(stream, out->m_direction, temp);
IMPORT_PARAM(stream, out->m_length, temp);
}
}
);
/*
RegisterComponentDataSerializerDeserializer<SpotLight>(
{
[](ComponentDataBase* data)
{
SpotLight* out = static_cast<SpotLight*>(data);
std::stringstream stream;
EXPORT_PARAM(stream, out->innerDegrees);
EXPORT_PARAM(stream, out->outerDegrees);
EXPORT_PARAM(stream, out->constant);
EXPORT_PARAM(stream, out->linear);
EXPORT_PARAM(stream, out->quadratic);
EXPORT_PARAM(stream, out->bias);
EXPORT_PARAM(stream, out->farPlane);
EXPORT_PARAM(stream, out->diffuse);
EXPORT_PARAM(stream, out->diffuseBrightness);
EXPORT_PARAM(stream, out->specular);
EXPORT_PARAM(stream, out->specularBrightness);
EXPORT_PARAM(stream, out->lightSize);
return stream.str();
},
[](const std::string& data, ComponentDataBase* ptr)
{
std::stringstream stream;
stream << data;
SpotLight* out = static_cast<SpotLight*>(ptr);
char temp;
IMPORT_PARAM(stream, out->innerDegrees, temp);
IMPORT_PARAM(stream, out->outerDegrees, temp);
IMPORT_PARAM(stream, out->constant, temp);
IMPORT_PARAM(stream, out->linear, temp);
IMPORT_PARAM(stream, out->quadratic, temp);
IMPORT_PARAM(stream, out->bias, temp);
IMPORT_PARAM(stream, out->farPlane, temp);
IMPORT_PARAM(stream, out->diffuse, temp);
IMPORT_PARAM(stream, out->diffuseBrightness, temp);
IMPORT_PARAM(stream, out->specular, temp);
IMPORT_PARAM(stream, out->specularBrightness, temp);
IMPORT_PARAM(stream, out->lightSize, temp);
}
}
);
RegisterComponentDataSerializerDeserializer<PointLight>(
{
[](ComponentDataBase* data)
{
PointLight* out = static_cast<PointLight*>(data);
std::stringstream stream;
EXPORT_PARAM(stream, out->constant);
EXPORT_PARAM(stream, out->linear);
EXPORT_PARAM(stream, out->quadratic);
EXPORT_PARAM(stream, out->bias);
EXPORT_PARAM(stream, out->farPlane);
EXPORT_PARAM(stream, out->diffuse);
EXPORT_PARAM(stream, out->diffuseBrightness);
EXPORT_PARAM(stream, out->specular);
EXPORT_PARAM(stream, out->specularBrightness);
EXPORT_PARAM(stream, out->lightSize);
return stream.str();
},
[](const std::string& data, ComponentDataBase* ptr)
{
std::stringstream stream;
stream << data;
PointLight* out = static_cast<PointLight*>(ptr);
char temp;
IMPORT_PARAM(stream, out->constant, temp);
IMPORT_PARAM(stream, out->linear, temp);
IMPORT_PARAM(stream, out->quadratic, temp);
IMPORT_PARAM(stream, out->bias, temp);
IMPORT_PARAM(stream, out->farPlane, temp);
IMPORT_PARAM(stream, out->diffuse, temp);
IMPORT_PARAM(stream, out->diffuseBrightness, temp);
IMPORT_PARAM(stream, out->specular, temp);
IMPORT_PARAM(stream, out->specularBrightness, temp);
IMPORT_PARAM(stream, out->lightSize, temp);
}
}
);
RegisterComponentDataSerializerDeserializer<DirectionalLight>(
{
[](ComponentDataBase* data)
{
DirectionalLight* out = static_cast<DirectionalLight*>(data);
std::stringstream stream;
EXPORT_PARAM(stream, out->bias);
EXPORT_PARAM(stream, out->normalOffset);
EXPORT_PARAM(stream, out->diffuse);
EXPORT_PARAM(stream, out->diffuseBrightness);
EXPORT_PARAM(stream, out->specular);
EXPORT_PARAM(stream, out->specularBrightness);
EXPORT_PARAM(stream, out->lightSize);
return stream.str();
},
[](const std::string& data, ComponentDataBase* ptr)
{
std::stringstream stream;
stream << data;
DirectionalLight* out = static_cast<DirectionalLight*>(ptr);
char temp;
IMPORT_PARAM(stream, out->bias, temp);
IMPORT_PARAM(stream, out->normalOffset, temp);
IMPORT_PARAM(stream, out->diffuse, temp);
IMPORT_PARAM(stream, out->diffuseBrightness, temp);
IMPORT_PARAM(stream, out->specular, temp);
IMPORT_PARAM(stream, out->specularBrightness, temp);
IMPORT_PARAM(stream, out->lightSize, temp);
}
}
);
*/
RegisterComponentDataSerializerDeserializer<CameraLayerMask>(
{
[](ComponentDataBase* data)
{
CameraLayerMask* out = static_cast<CameraLayerMask*>(data);
std::stringstream stream;
EXPORT_PARAM(stream, out->m_value);
return stream.str();
},
[](const std::string& data, ComponentDataBase* ptr)
{
std::stringstream stream;
stream << data;
CameraLayerMask* out = static_cast<CameraLayerMask*>(ptr);
char temp;
IMPORT_PARAM(stream, out->m_value, temp);
}
}
);
}
YAML::Emitter& UniEngine::operator<<(YAML::Emitter& out, const glm::vec2& v)
{
out << YAML::Flow;
out << YAML::BeginSeq << v.x << v.y <<YAML::EndSeq;
return out;
}
YAML::Emitter& UniEngine::operator<<(YAML::Emitter& out, const glm::vec3& v)
{
out << YAML::Flow;
out << YAML::BeginSeq << v.x << v.y << v.z << YAML::EndSeq;
return out;
}
YAML::Emitter& UniEngine::operator<<(YAML::Emitter& out, const glm::vec4& v)
{
out << YAML::Flow;
out << YAML::BeginSeq << v.x << v.y << v.z << v.w << YAML::EndSeq;
return out;
}
YAML::Emitter& UniEngine::operator<<(YAML::Emitter& out, const glm::mat4& v)
{
out << YAML::BeginMap;
out << YAML::Key << "Row0" << YAML::Value << v[0];
out << YAML::Key << "Row1" << YAML::Value << v[1];
out << YAML::Key << "Row2" << YAML::Value << v[2];
out << YAML::Key << "Row3" << YAML::Value << v[3];
out << YAML::EndMap;
return out;
}
std::ostream& UniEngine::operator<<(std::ostream& out, const glm::vec2& v)
{
out << "[" << v.x << ',' << v.y << ']';
return out;
}
std::ostream& UniEngine::operator<<(std::ostream& out, const glm::vec3& v)
{
out << "[" << v.x << ',' << v.y << ',' << v.z << ']';
return out;
}
std::ostream& UniEngine::operator<<(std::ostream& out, const glm::vec4& v)
{
out << "[" << v.x << ',' << v.y << ',' << v.z << ',' << v.w << ']';
return out;
}
std::ostream& UniEngine::operator<<(std::ostream& out, const glm::mat4& v)
{
out << "[" << v[0] << ',' << v[1] << ',' << v[2] << ',' << v[3] << ']';
return out;
}
std::istream& UniEngine::operator>>(std::istream& in, glm::vec2& v)
{
char temp;
in >> temp >> v.x >> temp >> v.y >> temp;
return in;
}
std::istream& UniEngine::operator>>(std::istream& in, glm::vec3& v)
{
char temp;
in >> temp >> v.x >> temp >> v.y >> temp >> v.z >> temp;
return in;
}
std::istream& UniEngine::operator>>(std::istream& in, glm::vec4& v)
{
char temp;
in >> temp >> v.x >> temp >> v.y >> temp >> v.z >> temp >> v.w >> temp;
return in;
}
std::istream& UniEngine::operator>>(std::istream& in, glm::mat4& v)
{
char temp;
in >> temp >> v[0] >> temp >> v[1] >> temp >> v[2] >> temp >> v[3] >> temp;
return in;
}
void UniEngine::SerializationManager::SerializeEntity(std::unique_ptr<World>& world, YAML::Emitter& out, const Entity& entity)
{
out << YAML::BeginMap;
out << YAML::Key << "Entity" << YAML::Value << std::to_string(entity.m_index);
out << YAML::Key << "IsEnabled" << YAML::Value << entity.IsEnabled();
out << YAML::Key << "ArchetypeName" << YAML::Value << EntityManager::GetEntityArchetypeName(EntityManager::GetEntityArchetype(entity));
out << YAML::Key << "Name" << YAML::Value << entity.GetName();
out << YAML::Key << "Parent" << YAML::Value << EntityManager::GetParent(entity).m_index;
#pragma region ComponentData
out << YAML::Key << "ComponentData" << YAML::Value << YAML::BeginSeq;
auto& storage = world->m_worldEntityStorage;
std::vector<ComponentDataType>& componentTypes =
storage.m_entityComponentStorage[storage.m_entityInfos[entity.m_index].m_archetypeInfoIndex].m_archetypeInfo->m_componentTypes;
for (const auto& type : componentTypes)
{
out << YAML::BeginMap;
out << YAML::Key << "Name" << YAML::Value << type.m_name;
std::string value;
const auto it = GetInstance().m_componentDataSerializers.find(type.m_typeId);
if (it != GetInstance().m_componentDataSerializers.end())
{
ComponentDataBase* ptr = EntityManager::GetComponentDataPointer(entity, type.m_typeId);
value = it->second.first(ptr);
}
out << YAML::Key << "Content" << YAML::Value << value;
out << YAML::EndMap;
}
out << YAML::EndSeq;
#pragma endregion
#pragma region Private Components
out << YAML::Key << "PrivateComponent" << YAML::Value << YAML::BeginSeq;
EntityManager::ForEachPrivateComponent(entity, [&](PrivateComponentElement& data)
{
out << YAML::BeginMap;
out << YAML::Key << "Name" << YAML::Value << data.m_name;
out << YAML::Key << "IsEnabled" << YAML::Value << data.m_privateComponentData.get()->m_enabled;
data.m_privateComponentData->Serialize(out);
out << YAML::EndMap;
}
);
out << YAML::EndSeq;
#pragma endregion
out << YAML::EndMap;
}
UniEngine::Entity UniEngine::SerializationManager::DeserializeEntity(std::unique_ptr<World>& world,
const YAML::Node& node)
{
const auto entityName = node["Name"].as<std::string>();
const auto archetypeName = node["ArchetypeName"].as<std::string>();
auto componentDatum = node["ComponentData"];
Entity retVal;
std::vector<std::shared_ptr<ComponentDataBase>> ptrs;
std::vector<ComponentDataType> types;
for (const auto& componentData : componentDatum)
{
auto name = componentData["Name"].as<std::string>();
size_t hashCode;
size_t size;
auto ptr = ComponentFactory::ProduceComponentData(name, hashCode, size);
//Deserialize componentData here.
const auto it = GetInstance().m_componentDataSerializers.find(hashCode);
if (it != GetInstance().m_componentDataSerializers.end())
{
it->second.second(componentData["Content"].as<std::string>(), ptr.get());
}
ptrs.push_back(ptr);
types.emplace_back(name, hashCode, size);
}
const EntityArchetype archetype = EntityManager::CreateEntityArchetype(archetypeName, types);
retVal = EntityManager::CreateEntity(archetype, entityName);
for (int i = 0; i < ptrs.size(); i++)
{
EntityManager::SetComponentData(retVal, types[i].m_typeId, types[i].m_size, ptrs[i].get());
}
auto privateComponents = node["PrivateComponent"];
if(privateComponents)
{
for(const auto& privateComponent : privateComponents)
{
auto name = privateComponent["Name"].as<std::string>();
size_t hashCode;
auto* ptr = dynamic_cast<PrivateComponentBase*>(ComponentFactory::ProduceSerializableObject(
name, hashCode));
ptr->Deserialize(privateComponent);
ptr->m_enabled = privateComponent["IsEnabled"].as<bool>();
EntityManager::SetPrivateComponent(retVal, name, hashCode, ptr);
}
}
return retVal;
}
void UniEngine::SerializationManager::Serialize(std::unique_ptr<World>& world, const std::string& path)
{
YAML::Emitter out;
out << YAML::BeginMap;
out << YAML::Key << "World";
out << YAML::Value << "World_Name";
out << YAML::Key << "Entities";
out << YAML::Value << YAML::BeginSeq;
for (const auto& entity : world->m_worldEntityStorage.m_entities)
{
if (entity.m_version == 0) continue;
SerializeEntity(world, out, entity);
}
out << YAML::EndSeq;
out << YAML::EndMap;
std::ofstream fout(path);
fout << out.c_str();
fout.flush();
}
bool UniEngine::SerializationManager::Deserialize(std::unique_ptr<World>& world, const std::string& path)
{
std::ifstream stream(path);
std::stringstream stringStream;
stringStream << stream.rdbuf();
YAML::Node data = YAML::Load(stringStream.str());
if (!data["World"])
{
return false;
}
Debug::Log("Loading world...");
world->Purge();
auto entities = data["Entities"];
if (entities)
{
std::unordered_map<unsigned, Entity> entityMap;
std::vector<std::pair<unsigned, unsigned>> childParentPairs;
for (const auto& node : entities)
{
auto id = node["Entity"].as<unsigned>();
auto parent = node["Parent"].as<unsigned>();
auto entity = DeserializeEntity(world, node);
world->m_worldEntityStorage.m_entityInfos[entity.m_index].m_enabled = node["IsEnabled"].as<bool>();
if (entity.IsNull())
{
Debug::Error("Error!");
}
entityMap.insert({ id, entity });
if (parent == 0)
continue;
childParentPairs.emplace_back(id, parent);
}
for (const auto& [fst, snd] : childParentPairs)
{
EntityManager::SetParent(entityMap[fst], entityMap[snd]);
}
}
return true;
}
| 30.553459 | 136 | 0.687114 | edisonlee0212 |
5900bb923ce23f5ecfc198079133edc6a76a0809 | 308 | hpp | C++ | src/kernel/utility/utility.hpp | 7E00h/septos | d8f43c98a49c69efef1ec8b0c05420c47784dab8 | [
"Unlicense"
] | 1 | 2021-09-30T16:17:52.000Z | 2021-09-30T16:17:52.000Z | src/kernel/utility/utility.hpp | 7E00h/septos | d8f43c98a49c69efef1ec8b0c05420c47784dab8 | [
"Unlicense"
] | null | null | null | src/kernel/utility/utility.hpp | 7E00h/septos | d8f43c98a49c69efef1ec8b0c05420c47784dab8 | [
"Unlicense"
] | null | null | null | #pragma once
#include <kernel/int.hpp>
namespace utility
{
void memset(u8* src, size_t amt, u8 val);
void memzro(u8* src, size_t amt);
void memcpy(u8* src, u8* dst, size_t amt);
template <typename T>
T divceil(T a, T b)
{
return a / b + (a % b != 0);
}
} | 19.25 | 47 | 0.542208 | 7E00h |
5902f67cba5ebd917c5dc285ce27efeb5e6d0940 | 983 | cpp | C++ | utility/scope_exit.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | 47 | 2016-05-20T08:49:47.000Z | 2022-01-03T01:17:07.000Z | utility/scope_exit.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | null | null | null | utility/scope_exit.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | 37 | 2016-07-25T04:52:08.000Z | 2022-02-14T03:55:08.000Z | // Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
//using namespace std;
#include <boost/scope_exit.hpp>
///////////////////////////////////////
void case1()
{
int *p = new int[100];
BOOST_SCOPE_EXIT((p))
{
std::cout << "scope exit called." << std::endl;
delete[] p;
std::cout << "scope exit end." << std::endl;
}BOOST_SCOPE_EXIT_END
std::cout << "ok. scope exit." << std::endl;
}
///////////////////////////////////////
#include <boost/smart_ptr.hpp>
using namespace boost;
void case2()
{
int *p = new int[100];
shared_ptr<void> x(nullptr, [&](void*)
{
std::cout << "lambda exit called." << std::endl;
delete[] p;
std::cout << "lambda exit end." << std::endl;
}
);
std::cout << "ok. lambda exit." << std::endl;
}
///////////////////////////////////////
int main()
{
std::cout << "hello scope_exit" << std::endl;
case1();
case2();
}
| 18.54717 | 60 | 0.464903 | MaxHonggg |
590355da99fddf5b554352eea44d7b13609bedf5 | 12,913 | hpp | C++ | include/mantella0_bits/optimiser/nelder_mead_method.hpp | LadySoulnight/Mantella | abc1342a67e126fb569010e14890c2fb2b014628 | [
"MIT"
] | null | null | null | include/mantella0_bits/optimiser/nelder_mead_method.hpp | LadySoulnight/Mantella | abc1342a67e126fb569010e14890c2fb2b014628 | [
"MIT"
] | null | null | null | include/mantella0_bits/optimiser/nelder_mead_method.hpp | LadySoulnight/Mantella | abc1342a67e126fb569010e14890c2fb2b014628 | [
"MIT"
] | null | null | null | /**
Nelder-Mead method
------------------
.. cpp:class:: nelder_mead_method : public optimiser
.. versionadded:: 1.0.0
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
.. list-table:: Template parameters
* - T
Any floating point type
- The value type of the parameter and objective value.
* - N
``std::size_t``
- The number of dimensions.
Must be within ``[1, std::numeric_limits<std::size_t>::max()]``.
.. list-table:: Member variables
* - reflection_weight
``T``
- Lorem ipsum dolor sit amet
* - expansion_weight
``T``
- Lorem ipsum dolor sit amet
* - contraction_weight
``T``
- Lorem ipsum dolor sit amet
* - shrinking_weight
``T``
- Lorem ipsum dolor sit amet
.. list-table:: Member functions
* - nelder_mead_method
Constructor
- Initialises all member variables to their default value.
Will never throw an exception.
*/
template <typename T, std::size_t N>
struct nelder_mead_method : optimiser<T, N> {
T reflection_weight;
T expansion_weight;
T contraction_weight;
T shrinking_weight;
nelder_mead_method() noexcept;
};
//
// Implementation
//
template <typename T, std::size_t N>
nelder_mead_method<T, N>::nelder_mead_method() noexcept
: optimiser<T, N>(),
reflection_weight(T(1.0)),
expansion_weight(T(2.0)),
contraction_weight(T(0.5)),
shrinking_weight(T(0.5)) {
this->optimisation_function = [this](const mant::problem<T, N>& problem, const std::vector<std::array<T, N>>& initial_parameters) {
assert(initial_parameters.size() == N + 1);
assert(reflection_weight > T(0.0));
assert(expansion_weight > T(0.0));
assert(contraction_weight > T(0.0));
assert(shrinking_weight > T(0.0));
auto&& start_time = std::chrono::steady_clock::now();
optimise_result<T, N> result;
result.parameter = initial_parameters.at(0);
result.objective_value = problem.objective_function(initial_parameters.at(0));
++result.evaluations;
result.duration = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start_time);
if (result.objective_value <= this->acceptable_objective_value) {
return result;
} else if (result.evaluations >= this->maximal_evaluations) {
return result;
} else if (result.duration >= this->maximal_duration) {
return result;
}
std::array<std::pair<std::array<T, N>, T>, N> simplex;
for (std::size_t n = 1; n < initial_parameters.size(); ++n) {
const auto& parameter = initial_parameters.at(n);
const auto objective_value = problem.objective_function(parameter);
++result.evaluations;
result.duration = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start_time);
simplex.at(n - 1) = {parameter, objective_value};
if (objective_value <= result.objective_value) {
result.parameter = parameter;
result.objective_value = objective_value;
if (result.objective_value <= this->acceptable_objective_value) {
return result;
}
}
if (result.evaluations >= this->maximal_evaluations) {
return result;
} else if (result.duration >= this->maximal_duration) {
return result;
}
}
std::sort(
simplex.begin(), simplex.end(),
[](const auto& simplex, const auto& other_simplex){
return std::get<1>(simplex) < std::get<1>(other_simplex);
});
std::array<T, N> centroid = result.parameter;
std::for_each(
simplex.cbegin(), std::prev(simplex.cend()),
[this, ¢roid](const auto& point) {
for (std::size_t n = 0; n < this->active_dimensions.size(); ++n) {
centroid.at(n) += std::get<0>(point).at(n) / static_cast<T>(N);
}
});
while (result.duration < this->maximal_duration && result.evaluations < this->maximal_evaluations && result.objective_value > this->acceptable_objective_value) {
std::array<T, N> reflected_point;
std::transform(
centroid.cbegin(), std::next(centroid.cbegin(), this->active_dimensions.size()),
result.parameter.cbegin(),
reflected_point.begin(),
[this](const auto centroid, const auto parameter) {
return std::fmin(std::fmax(centroid + reflection_weight * (centroid - parameter), T(0.0)), T(1.0));
});
auto objective_value = problem.objective_function(reflected_point);
++result.evaluations;
result.duration = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start_time);
if (objective_value < result.objective_value) {
for (std::size_t n = 0; n < N; ++n) {
centroid.at(n) += (reflected_point.at(n) - result.parameter.at(n)) / static_cast<T>(N);
}
result.parameter = reflected_point;
result.objective_value = objective_value;
if (result.objective_value <= this->acceptable_objective_value) {
return result;
} else if (result.evaluations >= this->maximal_evaluations) {
return result;
} else if (result.duration >= this->maximal_duration) {
return result;
}
std::array<T, N> expanded_point;
std::transform(
centroid.cbegin(), std::next(centroid.cbegin(), this->active_dimensions.size()),
reflected_point.cbegin(),
expanded_point.begin(),
[this](const auto centroid, const auto reflected_point) {
return std::fmin(std::fmax(centroid + expansion_weight * (reflected_point - centroid), T(0.0)), T(1.0));
});
objective_value = problem.objective_function(expanded_point);
++result.evaluations;
result.duration = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start_time);
if (objective_value < result.objective_value) {
for (std::size_t n = 0; n < N; ++n) {
centroid.at(n) += (expanded_point.at(n) - result.parameter.at(n)) / static_cast<T>(N);
}
result.parameter = expanded_point;
result.objective_value = objective_value;
}
continue;
}
if (result.evaluations >= this->maximal_evaluations) {
return result;
} else if (result.duration >= this->maximal_duration) {
return result;
}
if (objective_value < std::get<1>(std::get<N-1>(simplex))) {
auto position = std::find_if(
simplex.begin(), std::prev(simplex.end()),
[objective_value](const auto& point) {
return objective_value < std::get<1>(point);
});
for (std::size_t n = 0; n < N; ++n) {
centroid.at(n) += (reflected_point.at(n) - std::get<0>(*position).at(n)) / static_cast<T>(N);
}
std::copy_backward(position, std::prev(simplex.end()), simplex.end());
*position = {reflected_point, objective_value};
} else {
std::array<T, N> contracted_point;
std::transform(
centroid.cbegin(), std::next(centroid.cbegin(), this->active_dimensions.size()),
std::get<0>(std::get<N-1>(simplex)).cbegin(),
contracted_point.begin(),
[this](const auto centroid, const auto worst_parameter) {
return centroid + contraction_weight * (worst_parameter - centroid);
});
auto objective_value = problem.objective_function(contracted_point);
++result.evaluations;
result.duration = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start_time);
if (result.evaluations >= this->maximal_evaluations) {
return result;
} else if (result.duration >= this->maximal_duration) {
return result;
}
if (objective_value < result.objective_value) {
for (std::size_t n = 0; n < N; ++n) {
centroid.at(n) += (contracted_point.at(n) - result.parameter.at(n)) / static_cast<T>(N);
}
result.parameter = contracted_point;
result.objective_value = objective_value;
} else if (objective_value < std::get<1>(std::get<N-1>(simplex))) {
auto position = std::find_if(
simplex.begin(), std::prev(simplex.end()),
[objective_value](const auto& point) {
return objective_value < std::get<1>(point);
});
for (std::size_t n = 0; n < N; ++n) {
centroid.at(n) += (contracted_point.at(n) - std::get<0>(*position).at(n)) / static_cast<T>(N);
}
std::copy_backward(position, std::prev(simplex.end()), simplex.end());
*position = {contracted_point, objective_value};
} else {
for (auto& point : simplex) {
std::transform(
result.parameter.cbegin(), std::next(result.parameter.cbegin(), this->active_dimensions.size()),
std::get<0>(point).cbegin(),
std::get<0>(point).begin(),
[this](const auto parameter, const auto point) {
return parameter + shrinking_weight * (point - parameter);
});
point = {std::get<0>(point), problem.objective_function(std::get<0>(point))};
++result.evaluations;
if (result.evaluations >= this->maximal_evaluations) {
return result;
} else if (result.duration >= this->maximal_duration) {
return result;
}
}
std::sort(
simplex.begin(), simplex.end(),
[](const auto& simplex, const auto& other_simplex){
return std::get<1>(simplex) < std::get<1>(other_simplex);
});
std::array<T, N> centroid = result.parameter;
std::for_each(
simplex.cbegin(), std::prev(simplex.cend()),
[this, ¢roid](const auto& point) {
for (std::size_t n = 0; n < this->active_dimensions.size(); ++n) {
centroid.at(n) += std::get<0>(point).at(n) / static_cast<T>(N);
}
});
}
}
}
return result;
};
}
//
// Unit tests
//
#if defined(MANTELLA_BUILD_TESTS)
TEST_CASE("nelder_mead_method", "[optimser][nelder_mead_method]") {
constexpr std::size_t dimensions = 3;
mant::nelder_mead_method<double, dimensions> optimiser;
std::vector<std::array<double, dimensions>> initial_parameters(dimensions + 1);
for (auto& parameter : initial_parameters) {
std::generate(
parameter.begin(), std::next(parameter.begin(), optimiser.active_dimensions.size()),
std::bind(
std::uniform_real_distribution<double>(0.0, 1.0),
std::ref(random_number_generator())));
}
SECTION("Default configuration") {
CHECK(optimiser.reflection_weight == Approx(1.0));
CHECK(optimiser.expansion_weight == Approx(2.0));
CHECK(optimiser.contraction_weight == Approx(0.5));
CHECK(optimiser.shrinking_weight == Approx(0.5));
}
SECTION("Boundary handling") {
mant::problem<double, dimensions> problem;
problem.objective_function = [](const auto& parameter) {
return std::accumulate(parameter.cbegin(), parameter.cend(), 0.0);
};
const auto&& result = optimiser.optimisation_function(problem, initial_parameters);
CHECK(std::all_of(
result.parameter.cbegin(), std::next(result.parameter.cbegin(), optimiser.active_dimensions.size()),
std::bind(std::greater_equal<double>{}, std::placeholders::_1, 0.0)
) == true);
}
SECTION("Stopping criteria") {
optimiser.maximal_duration = std::chrono::seconds(10);
optimiser.maximal_evaluations = 1000;
auto&& result = optimiser.optimisation_function(mant::sphere_function<double, dimensions>(), initial_parameters);
CHECK(result.evaluations == 1000);
optimiser.maximal_duration = std::chrono::microseconds(1);
result = optimiser.optimisation_function(mant::sphere_function<double, dimensions>(), initial_parameters);
CHECK(result.duration >= std::chrono::microseconds(1));
CHECK(result.duration < std::chrono::milliseconds(1));
}
}
#endif
| 37.213256 | 417 | 0.624564 | LadySoulnight |
5906026c6411cb327cc5e3b2358a984a200bbd9a | 548 | hpp | C++ | src/providers/irc/IrcAccount.hpp | devolution2409/chatterino2 | 978931bcfc40bae63f65c18e7a3274c77c0f45ca | [
"MIT"
] | null | null | null | src/providers/irc/IrcAccount.hpp | devolution2409/chatterino2 | 978931bcfc40bae63f65c18e7a3274c77c0f45ca | [
"MIT"
] | null | null | null | src/providers/irc/IrcAccount.hpp | devolution2409/chatterino2 | 978931bcfc40bae63f65c18e7a3274c77c0f45ca | [
"MIT"
] | null | null | null | #pragma once
#include <QString>
// namespace chatterino {
//
// class IrcAccount
//{
// public:
// IrcAccount(const QString &userName, const QString &nickName, const QString &realName,
// const QString &password);
// const QString &getUserName() const;
// const QString &getNickName() const;
// const QString &getRealName() const;
// const QString &getPassword() const;
// private:
// QString userName;
// QString nickName;
// QString realName;
// QString password;
//};
//
//} // namespace chatterino
| 21.076923 | 91 | 0.642336 | devolution2409 |
5908e7163dbd2312fd54a7ff3a83fee267b8a2cb | 12,153 | cpp | C++ | code/pilotfile/JSONFileHandler.cpp | brihernandez/fs2open.github.com | 5b173c6060a884bba83ef965ba32f8ad67709de1 | [
"Unlicense"
] | 307 | 2015-04-10T13:27:32.000Z | 2022-03-21T03:30:38.000Z | code/pilotfile/JSONFileHandler.cpp | brihernandez/fs2open.github.com | 5b173c6060a884bba83ef965ba32f8ad67709de1 | [
"Unlicense"
] | 2,231 | 2015-04-27T10:47:35.000Z | 2022-03-31T19:22:37.000Z | code/pilotfile/JSONFileHandler.cpp | brihernandez/fs2open.github.com | 5b173c6060a884bba83ef965ba32f8ad67709de1 | [
"Unlicense"
] | 282 | 2015-01-05T12:16:57.000Z | 2022-03-28T04:45:11.000Z |
#include <jansson.h>
#include "pilotfile/JSONFileHandler.h"
#include "libs/jansson.h"
#include "parse/parselo.h"
namespace {
const SCP_vector<std::pair<Section, const char*>> SectionMapping {
std::pair<Section, const char*>(Section::Unnamed, nullptr),
std::pair<Section, const char*>(Section::Flags, "flags"),
std::pair<Section, const char*>(Section::Info, "info"),
std::pair<Section, const char*>(Section::Loadout, "loadout"),
std::pair<Section, const char*>(Section::Controls, "controls"),
std::pair<Section, const char*>(Section::Multiplayer, "multiplayer"),
std::pair<Section, const char*>(Section::Scoring, "scoring"),
std::pair<Section, const char*>(Section::ScoringMulti, "scoring_multi"),
std::pair<Section, const char*>(Section::Techroom, "techroom"),
std::pair<Section, const char*>(Section::HUD, "hud"),
std::pair<Section, const char*>(Section::Settings, "settings"),
std::pair<Section, const char*>(Section::RedAlert, "red_alert"),
std::pair<Section, const char*>(Section::Variables, "variables"),
std::pair<Section, const char*>(Section::Missions, "missions"),
std::pair<Section, const char*>(Section::Cutscenes, "cutscenes"),
std::pair<Section, const char*>(Section::LastMissions, "last_mission"),
std::pair<Section, const char*>(Section::Containers, "containers")
};
const char* lookupSectionName(Section s) {
for (auto& pair : SectionMapping) {
if (pair.first == s) {
return pair.second;
}
}
return nullptr;
}
Section lookupSectionValue(const char* name) {
Assertion(name != nullptr, "Key name must be a valid pointer!");
for (auto& pair : SectionMapping) {
if (pair.second == nullptr) {
// Skip the unnamed section
continue;
}
if (!strcmp(pair.second, name)) {
return pair.first;
}
}
return Section::Invalid;
}
}
pilot::JSONFileHandler::JSONFileHandler(CFILE* cfp, bool reading) : _cfp(cfp) {
Assertion(cfp != nullptr, "File pointer must be valid!");
if (reading) {
json_error_t error;
_rootObj = json_load_cfile(cfp, 0, &error);
if (!_rootObj) {
SCP_string errorStr;
sprintf(errorStr, "Error while reading pilot file! %d: %s", error.line, error.text);
throw std::runtime_error(errorStr);
}
} else {
_rootObj = json_object();
}
_currentEl = _rootObj;
_elementStack.push_back(_currentEl);
}
pilot::JSONFileHandler::~JSONFileHandler() {
json_decref(_rootObj);
cfclose(_cfp);
_cfp = nullptr;
}
void pilot::JSONFileHandler::pushElement(json_t* t) {
Assertion(t != nullptr, "Invalid JSON element pointer passed!");
_currentEl = t;
_elementStack.push_back(_currentEl);
}
void pilot::JSONFileHandler::popElement() {
Assertion(_elementStack.size() > 1, "Element stack may not get smaller than one element!");
_elementStack.pop_back();
_currentEl = _elementStack.back();
}
void pilot::JSONFileHandler::writeUByte(const char* name, std::uint8_t value) {
writeInteger(name, value);
}
void pilot::JSONFileHandler::writeShort(const char* name, std::int16_t value) {
writeInteger(name, value);
}
void pilot::JSONFileHandler::writeInt(const char* name, std::int32_t value) {
writeInteger(name, value);
}
void pilot::JSONFileHandler::writeUInt(const char* name, std::uint32_t value) {
writeInteger(name, value);
}
void pilot::JSONFileHandler::writeFloat(const char* name, float value) {
ensureNotExists(name);
json_object_set_new(_currentEl, name, json_real(value));
}
void pilot::JSONFileHandler::writeString(const char* name, const char* str) {
ensureNotExists(name);
json_t *jstr = nullptr;
if (str) {
// if this string isn't proper UTF-8, try to convert it
auto len = strlen(str);
if (utf8::find_invalid(str, str + len) != str + len) {
SCP_string buffer;
coerce_to_utf8(buffer, str);
jstr = json_string(buffer.c_str());
} else {
jstr = json_string(str);
}
}
json_object_set_new(_currentEl, name, jstr);
}
void pilot::JSONFileHandler::beginWritingSections() {
ensureNotExists("sections");
json_t* obj = json_object();
Assertion(json_typeof(_currentEl) == JSON_OBJECT, "Sections can only be written into a JSON object!");
json_object_set_new(_currentEl, "sections", obj);
pushElement(obj);
}
void pilot::JSONFileHandler::startSectionWrite(Section id) {
auto key_name = lookupSectionName(id);
json_t* obj = json_object();
if (json_is_array(_currentEl)) {
// We are in an array, section must be unnamed
Assertion(key_name == nullptr, "Inside an array there can be no named section!");
json_array_append_new(_currentEl, obj);
} else {
Assertion(key_name != nullptr, "Section outside of arrays must be named!");
json_object_set_new(_currentEl, key_name, obj);
}
pushElement(obj);
}
void pilot::JSONFileHandler::endSectionWrite() {
Assertion(json_is_object(_currentEl), "Section ended while not in a section!");
popElement();
}
void pilot::JSONFileHandler::endWritingSections() {
Assertion(json_is_object(_currentEl), "Section writing ended while not in object!");
popElement();
}
void pilot::JSONFileHandler::startArrayWrite(const char* name, size_t, bool) {
auto array = json_array();
if (json_is_array(_currentEl)) {
// We are in an array, section must be unnamed
Assertion(name == nullptr, "Inside an array there can be no named section!");
json_array_append_new(_currentEl, array);
} else {
Assertion(name != nullptr, "Section outside of arrays must be named!");
json_object_set_new(_currentEl, name, array);
}
pushElement(array);
}
void pilot::JSONFileHandler::endArrayWrite() {
Assertion(json_is_array(_currentEl), "Array ended while not in an array!");
popElement();
}
void pilot::JSONFileHandler::flush() {
Assertion(_elementStack.size() == 1, "Not all sections or arrays have been ended!");
json_dump_cfile(_rootObj, _cfp, JSON_INDENT(4));
}
void pilot::JSONFileHandler::writeInteger(const char* name, json_int_t val) {
ensureNotExists(name);
json_object_set_new(_currentEl, name, json_integer(val));
}
void pilot::JSONFileHandler::ensureNotExists(const char* name) {
Assertion(json_is_object(_currentEl), "Currently not in an element that supports keys!");
// Make sure we don't overwrite previous values
Assertion(json_object_get(_currentEl, name) == nullptr, "Entry with name %s already exists!", name);
}
json_int_t pilot::JSONFileHandler::readInteger(const char* name) {
auto el = json_object_get(_currentEl, name);
if (el == nullptr || json_typeof(el) != JSON_INTEGER) {
Error(LOCATION, "JSON element %s must be an integer but it is not valid!", name);
return 0;
}
return json_integer_value(el);
}
void pilot::JSONFileHandler::ensureExists(const char* name) {
if (json_typeof(_currentEl) != JSON_OBJECT) {
Error(LOCATION, "JSON reading requires a value with name '%s' but the current element is not an object!", name);
}
if (json_object_get(_currentEl, name) == nullptr) {
Error(LOCATION, "JSON reading requires a value with name '%s' but there is no such value!", name);
}
}
std::uint8_t pilot::JSONFileHandler::readUByte(const char* name) {
return (std::uint8_t)readInteger(name);
}
std::int16_t pilot::JSONFileHandler::readShort(const char* name) {
return (std::int16_t)readInteger(name);
}
std::int32_t pilot::JSONFileHandler::readInt(const char* name) {
return (std::int32_t)readInteger(name);
}
std::uint32_t pilot::JSONFileHandler::readUInt(const char* name) {
return (std::uint32_t)readInteger(name);
}
float pilot::JSONFileHandler::readFloat(const char* name) {
auto el = json_object_get(_currentEl, name);
if (el == nullptr || json_typeof(el) != JSON_REAL) {
Error(LOCATION, "JSON element %s must be a float but it is not valid!", name);
return 0.0f;
}
return (float)json_real_value(el);
}
SCP_string pilot::JSONFileHandler::readString(const char* name) {
auto el = json_object_get(_currentEl, name);
if (el == nullptr || json_typeof(el) != JSON_STRING) {
Error(LOCATION, "JSON element %s must be a string but it is not valid!", name);
return SCP_string();
}
auto json_str = json_string_value(el);
SCP_string val;
val.assign(json_str, json_str + json_string_length(el));
return val;
}
void pilot::JSONFileHandler::beginSectionRead() {
ensureExists("sections");
auto sections = json_object_get(_currentEl, "sections");
if (json_typeof(sections) != JSON_OBJECT) {
Error(LOCATION, "Sections must be a JSON object!");
}
pushElement(sections);
Assertion(_sectionIterator == nullptr, "Section nesting is not yet supported!");
_sectionIterator = json_object_iter(_currentEl);
// Signals to nextSection that we just started iterating though the sections since it needs to do something special in that case
_startingSectionIteration = true;
}
bool pilot::JSONFileHandler::hasMoreSections() {
return _sectionIterator != nullptr;
}
Section pilot::JSONFileHandler::nextSection() {
Assertion(_sectionIterator != nullptr, "Section iterator must be valid for this function!");
// If we just started our iteration then there is no previous element we need to pop from the stack
if (!_startingSectionIteration) {
// We have to pop the previous section first
popElement();
Assertion(json_typeof(_currentEl) == JSON_OBJECT, "The previous element should have been an object!");
} else {
// We are now in normal operations so we can reset this flag
_startingSectionIteration = false;
}
auto key = json_object_iter_key(_sectionIterator);
auto section = lookupSectionValue(key);
auto el = json_object_iter_value(_sectionIterator);
if (json_typeof(el) != JSON_OBJECT) {
Error(LOCATION, "The section element of '%s' must be an object but it's a different type!", key);
return Section::Invalid;
}
// Move the iterator to the next object for the next iteration
_sectionIterator = json_object_iter_next(_currentEl, _sectionIterator);
// Move into the current section element
pushElement(el);
return section;
}
void pilot::JSONFileHandler::endSectionRead() {
// First, remove the element we are currently in, if there is one
if (json_typeof(_currentEl) != JSON_ARRAY) {
popElement();
}
Assertion(json_typeof(_currentEl) == JSON_OBJECT, "Current element for section reading is not an object!");
popElement();
_sectionIterator = nullptr;
}
size_t pilot::JSONFileHandler::startArrayRead(const char* name, bool /*short_index*/) {
Assertion(_arrayIndex == INVALID_SIZE, "Array nesting is not supported yet!");
ensureExists(name);
auto array = json_object_get(_currentEl, name);
if (json_typeof(array) != JSON_ARRAY) {
Error(LOCATION, "Expected an array for '%s' but it was a different type!", name);
return 0;
}
pushElement(array);
auto size = json_array_size(array);
if (size == 0) {
// Nothing to do here, avoid calling nextArraySection since that assumes that there is at least one element
return size;
}
_arrayIndex = 0;
nextArraySection(false);
return size;
}
void pilot::JSONFileHandler::nextArraySection(bool in_section) {
Assertion(_arrayIndex != INVALID_SIZE, "Array index must be valid for this function!");
if (in_section) {
// We have to pop the previous section first
popElement();
Assertion(json_typeof(_currentEl) == JSON_ARRAY, "The previous element should have been an array!");
}
auto max = json_array_size(_currentEl);
Assertion(_arrayIndex <= max, "Invalid array index detected!");
// Silently ignore if we are one past the last element since this function is used in a for loop where this function
// is executed one time after the index is incremented past the last element
if (_arrayIndex == max) {
// Increment the index so we catch usage errors the next time someone tries to call this function
++_arrayIndex;
return;
}
// We use the current array index and then increment it to avoid skipping the first element
auto el = json_array_get(_currentEl, _arrayIndex);
++_arrayIndex;
pushElement(el);
}
void pilot::JSONFileHandler::nextArraySection() {
nextArraySection(true);
}
void pilot::JSONFileHandler::endArrayRead() {
// First, remove the element we are currently in if it exists
if (json_typeof(_currentEl) != JSON_ARRAY) {
popElement();
}
Assertion(json_typeof(_currentEl) == JSON_ARRAY, "Current element must be an array!");
popElement();
_arrayIndex = INVALID_SIZE;
}
| 32.669355 | 129 | 0.731177 | brihernandez |
590b7ccb1d133c82228e9abfa46f5f7410db9919 | 9,361 | cpp | C++ | lib/fractoid/src/painter.cpp | tjira/fractoid | 95973199329627b7e12a09ad9825e4357021c3b8 | [
"MIT"
] | null | null | null | lib/fractoid/src/painter.cpp | tjira/fractoid | 95973199329627b7e12a09ad9825e4357021c3b8 | [
"MIT"
] | null | null | null | lib/fractoid/src/painter.cpp | tjira/fractoid | 95973199329627b7e12a09ad9825e4357021c3b8 | [
"MIT"
] | null | null | null | #include "painter.h"
#include "barnsley.h"
#include "julia.h"
#include "mandelbrot.h"
#include "sierpinski.h"
using namespace Fractoid;
template<class A, class C>
Backend::Painter<A, C>::Painter(const Fractal *fractal, const A &algorithm, const C &color, rgb bg) : bg(bg), algorithm(algorithm), color(color) {
this->fractal = fractal;
}
/* Function to decide what algorithm to use. */
template<class A, class C>
Backend::Image Backend::Painter<A, C>::paint(complex center, double zoom, std::tuple<int, int> res) const {
Image image(std::get<0>(res), std::get<1>(res), bg); // Create the image.
// Cast the fractal pointers to their respective classes.
auto barnsley = dynamic_cast<const Fractoid::Fractal::Chaotic::Barnsley*>(fractal);
auto julia = dynamic_cast<const Fractoid::Fractal::Complex::Julia*>(fractal);
auto mandelbrot = dynamic_cast<const Fractoid::Fractal::Complex::Mandelbrot*>(fractal);
auto sierpinski = dynamic_cast<const Fractoid::Fractal::Chaotic::Sierpinski*>(fractal);
// Select the correct method and paint the image.
if (barnsley || sierpinski) {
if constexpr (std::is_same_v<A, Fractoid::Algorithm::Chaotic::Iterative>) {
iterative(image, center, zoom, algorithm);
} else {
throw std::runtime_error("This fractal cant's use selected algorithm.");
}
} else {
if constexpr (std::is_same_v<A, Fractoid::Algorithm::Complex::Density>) {
density(image, center, zoom, algorithm);
} else if constexpr (std::is_same_v<A, Fractoid::Algorithm::Complex::Differential>) {
if (!julia && !mandelbrot) {
throw std::runtime_error("Selected fractal can't use differential algorithm.");
}
differential(image, center, zoom, algorithm);
} else if constexpr (std::is_same_v<A, Fractoid::Algorithm::Complex::Escape>) {
escape(image, center, zoom, algorithm);
} else if constexpr (std::is_same_v<A, Fractoid::Algorithm::Complex::Nearest>) {
nearest(image, center, zoom, algorithm);
} else {
throw std::runtime_error("This fractal cant's use selected algorithm.");
}
}
return image; // Return the painted image.
}
/* Function to generate a fractal with density algorithm. */
template<class A, class C> template<typename T>
void Backend::Painter<A, C>::density(Image &image, complex center, double zoom, T algorithm) const {
std::uniform_real_distribution<double> dist(-3.5, 3.5);
std::mt19937 twister(algorithm.seed);
std::vector<complex> positions(algorithm.samples);
for (int i = 0; i < algorithm.samples; i++) {
positions[i] = {dist(twister), dist(twister)};
}
std::vector<int> data(image.width * image.height, 0);
for (const complex &position : positions) {
bool escape; auto orbit = fractal->orbit({position.real(), position.imag()}, escape);
if (escape) for (complex p : orbit) {
int i = (int) (((p.imag() + center.imag()) * image.height * zoom + 1.5 * image.height) / 3.0);
int j = (int) (((p.real() - center.real()) * image.height * zoom + 1.5 * image.width) / 3.0);
if (i < 0 || j < 0 || i >= image.height || j >= image.width) {
continue;
}
data[i * image.width + j]++;
}
}
int max = *std::max_element(data.begin(), data.end());
#pragma omp parallel for default(none) shared(image, data, color, max)
for (int i = 0; i < image.height; i++) {
for (int j = 0; j < image.width; j++) {
if (data[i * image.width + j]) {
image(i, j) = color.get((double) data[i * image.width + j] / max);
}
}
}
}
/* Function to generate a fractal with differential algorithm. */
template<class A, class C> template<typename T>
void Backend::Painter<A, C>::differential(Image &image, complex center, double zoom, T algorithm) const {
#pragma omp parallel for default(none) shared(image, algorithm, color, center, zoom)
for (int i = 0; i < image.height; i++) {
complex v = std::exp(-2.0 * M_PI * complex(0, 1) * algorithm.angle / 360.0);
for (int j = 0; j < image.width; j++) {
complex z, dz; double value = fractal->derivative({
center.real() + (3 * (j + 0.5) - 1.5 * image.width) / zoom / image.height,
-center.imag() + (3 * (i + 0.5) - 1.5 * image.height) / zoom / image.height
}, z, dz);
if (value != fractal->iters) {
complex u = z / dz / std::abs(z / dz);
value = u.real() * algorithm.normal.real() + u.imag() * algorithm.normal.imag() + algorithm.factor;
image(i, j) = color.get(value < 0 ? 0 : value / (1 + algorithm.factor));
}
}
}
}
/* Function to generate a fractal with escape algorithm. */
template<class A, class C> template<typename T>
void Backend::Painter<A, C>::escape(Image &image, complex center, double zoom, T algorithm) const {
#pragma omp parallel for default(none) shared(image, algorithm, color, center, zoom)
for (int i = 0; i < image.height; i++) {
for (int j = 0; j < image.width; j++) {
complex z; double value = fractal->time({
center.real() + (3 * (j + 0.5) - 1.5 * image.width) / zoom / image.height,
-center.imag() + (3 * (i + 0.5) - 1.5 * image.height) / zoom / image.height
}, z);
if (value != fractal->iters) {
if (fractal->eps == 0 && algorithm.factor != 0) {
value -= std::log(0.5 * std::log(std::norm(z))) / std::log(algorithm.factor);
}
image(i, j) = color.get(value / fractal->iters);
}
}
}
}
/* Function to generate an iterative fractal. */
template<class A, class C> template<typename T>
void Backend::Painter<A, C>::iterative(Image &image, complex center, double zoom, T algorithm) const {
std::uniform_real_distribution<double> dist(0, 1); std::mt19937 twister(algorithm.seed);
std::tuple<double, double> point = {0, 0};
for (int k = 0; k < algorithm.samples; k++) {
point = fractal->iterate(point, dist(twister));
int i = (int) (((-std::get<1>(point) + center.imag()) * image.height * zoom + 1.5 * image.height) / 3.0);
int j = (int) (((std::get<0>(point) - center.real()) * image.height * zoom + 1.5 * image.width) / 3.0);
if (i < 0 || j < 0 || i >= image.height || j >= image.width) {
continue;
}
double norm = std::get<0>(point) * std::get<0>(point) + std::get<1>(point) * std::get<1>(point);
image(i, j) = color.get(1 / (1 + norm));
}
}
/* Function to generate a fractal with the nearest algorithm. */
template<class A, class C> template<typename T>
void Backend::Painter<A, C>::nearest(Image &image, complex center, double zoom, T algorithm) const {
#pragma omp parallel for default(none) shared(image, algorithm, color, center, zoom)
for (int i = 0; i < image.height; i++) {
for (int j = 0; j < image.width; j++) {
bool escape; auto orbit = fractal->orbit({
center.real() + (3 * (j + 0.5) - 1.5 * image.width) / zoom / image.height,
-center.imag() + (3 * (i + 0.5) - 1.5 * image.height) / zoom / image.height
}, escape);
if (escape || !algorithm.fill) {
double value = algorithm.transform(orbit);
if constexpr (std::is_same_v<C, Fractoid::Color::Linear>) {
value = 1 / (1 + 5 * value);
} else if constexpr (std::is_same_v<C, Fractoid::Color::Periodic>) {
value = 0.05 * log(value);
}
image(i, j) = color.get(value);
}
}
}
}
template class Backend::Painter<Fractoid::Algorithm::Chaotic::Iterative, Fractoid::Color::Linear>;
template class Backend::Painter<Fractoid::Algorithm::Chaotic::Iterative, Fractoid::Color::Periodic>;
template class Backend::Painter<Fractoid::Algorithm::Chaotic::Iterative, Fractoid::Color::Solid>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Density, Fractoid::Color::Linear>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Density, Fractoid::Color::Periodic>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Density, Fractoid::Color::Solid>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Differential, Fractoid::Color::Linear>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Differential, Fractoid::Color::Periodic>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Differential, Fractoid::Color::Solid>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Escape, Fractoid::Color::Linear>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Escape, Fractoid::Color::Periodic>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Escape, Fractoid::Color::Solid>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Nearest, Fractoid::Color::Linear>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Nearest, Fractoid::Color::Periodic>;
template class Backend::Painter<Fractoid::Algorithm::Complex::Nearest, Fractoid::Color::Solid>;
| 51.153005 | 146 | 0.610939 | tjira |
590e04cee7f8234dda2fa64d1ca6e6662bce3804 | 908 | hpp | C++ | src/FourierPlan.hpp | develancer/coulombo | 4e19a9f20d97427f2ba150f86e48bfc0d07ad555 | [
"CC-BY-4.0"
] | null | null | null | src/FourierPlan.hpp | develancer/coulombo | 4e19a9f20d97427f2ba150f86e48bfc0d07ad555 | [
"CC-BY-4.0"
] | null | null | null | src/FourierPlan.hpp | develancer/coulombo | 4e19a9f20d97427f2ba150f86e48bfc0d07ad555 | [
"CC-BY-4.0"
] | null | null | null | // Coulombo Ⓒ 2018
// [Computer Physics Communications] Różański & Zieliński:
// Efficient computation of Coulomb and exchange integrals for multi-million atom nanostructures
#ifndef COULOMBO_FOURIERPLAN_HPP
#define COULOMBO_FOURIERPLAN_HPP
#include <cassert>
#include <memory>
#include <fftw3.h>
#include "base.hpp"
//----------------------------------------------------------------------
/**
* RAII-style wrapper for FFTW plan structure.
*/
class FourierPlan {
std::shared_ptr<fftw_plan_s> plan;
public:
/**
* Create a wrapper for an existing FFT plan.
*/
inline FourierPlan(fftw_plan plan)
:plan(plan, fftw_destroy_plan)
{
if (!plan) {
throw std::runtime_error("failed to create plan for FFT");
}
}
/**
* Execute plan.
*/
inline void execute(void) const
{
fftw_execute(plan.get());
}
};
//----------------------------------------------------------------------
#endif
| 20.636364 | 96 | 0.595815 | develancer |
59141fa4584ac89b07bc0089dd0bdbcce0058ba5 | 496 | hpp | C++ | hpx/parallel/memory.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | hpx/parallel/memory.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | hpx/parallel/memory.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2014 Hartmut Kaiser
//
// 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)
#if !defined(HPX_PARALLEL_MEMORY_OCT_05_2014_0414PM)
#define HPX_PARALLEL_MEMORY_OCT_05_2014_0414PM
#include <hpx/hpx_fwd.hpp>
/// See N4071: 1.3/3
#include <memory>
#include <hpx/parallel/algorithms/uninitialized_copy.hpp>
#include <hpx/parallel/algorithms/uninitialized_fill.hpp>
#endif
| 26.105263 | 80 | 0.780242 | kempj |
59153c5de017714e9d7f9dfa09472f4523813428 | 41,876 | cpp | C++ | cegui/src/FreeTypeFont.cpp | Costallat/cegui | a398f9264c3223966c903c92f61ad110c5286fc1 | [
"MIT"
] | null | null | null | cegui/src/FreeTypeFont.cpp | Costallat/cegui | a398f9264c3223966c903c92f61ad110c5286fc1 | [
"MIT"
] | null | null | null | cegui/src/FreeTypeFont.cpp | Costallat/cegui | a398f9264c3223966c903c92f61ad110c5286fc1 | [
"MIT"
] | null | null | null | /***********************************************************************
created: 21/2/2004
author: Paul D Turner
purpose: Implements FreeTypeFont class
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2017 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/FreeTypeFont.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/Texture.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/System.h"
#include "CEGUI/Logger.h"
#include "CEGUI/PropertyHelper.h"
#include "CEGUI/Font_xmlHandler.h"
#include "CEGUI/SharedStringStream.h"
#include "CEGUI/FreeTypeFontGlyph.h"
#ifdef CEGUI_USE_RAQM
#include <raqm.h>
#endif
#include <cmath>
#include <utility>
namespace
{
void adjustPenPositionForBearingDeltas(glm::vec2& penPosition,
FT_Pos previousRsbDelta, const CEGUI::FreeTypeFontGlyph* glyph)
{
// Needed if using strong auto-hinting.
// Adjusting pen position according to the left side and right
// side bearing deltas
if (previousRsbDelta - glyph->getLsbDelta() >= 32)
{
penPosition.x -= 1.0f;
}
else if (previousRsbDelta - glyph->getLsbDelta() < -32)
{
penPosition.x += 1.0f;
}
}
#ifdef CEGUI_USE_RAQM
raqm_direction_t determineRaqmDirection(CEGUI::DefaultParagraphDirection defaultParagraphDir)
{
switch (defaultParagraphDir)
{
case CEGUI::DefaultParagraphDirection::LeftToRight:
return RAQM_DIRECTION_LTR;
case CEGUI::DefaultParagraphDirection::RightToLeft:
return RAQM_DIRECTION_RTL;
case CEGUI::DefaultParagraphDirection::Automatic:
return RAQM_DIRECTION_DEFAULT;
}
return RAQM_DIRECTION_LTR;
}
raqm_t* createAndSetupRaqmTextObject(
const uint32_t* originalTextArray, const size_t textLength,
CEGUI::DefaultParagraphDirection defaultParagraphDir, FT_Face face)
{
raqm_t* raqmObject = raqm_create();
bool wasSuccess = raqm_set_text(raqmObject, originalTextArray, textLength);
if (!wasSuccess)
{
throw CEGUI::InvalidRequestException("Setting raqm text was unsuccessful");
}
if (!raqm_set_freetype_face(raqmObject, face))
{
throw CEGUI::InvalidRequestException("Could not set the Freetype font Face for "
"a raqm object");
}
raqm_direction_t textDefaultParagraphDirection = determineRaqmDirection(defaultParagraphDir);
if (!raqm_set_par_direction(raqmObject, textDefaultParagraphDirection))
{
throw CEGUI::InvalidRequestException("Could not set the parse direction for "
"a raqm object");
}
wasSuccess = raqm_layout(raqmObject);
if (!wasSuccess)
{
throw CEGUI::InvalidRequestException("Layouting raqm text was unsuccessful");
}
return raqmObject;
}
#endif
}
namespace CEGUI
{
//----------------------------------------------------------------------------//
// Pixels to put between glyphs
static const int s_glyphPadding = 1;
// A multiplication coefficient to convert FT_Pos values into normal floats
static const float s_conversionMultCoeff = (1.0f/64.f);
// Font objects usage count
static int s_fontUsageCount = 0;
// A handle to the FreeType library
static FT_Library s_freetypeLibHandle;
//----------------------------------------------------------------------------//
#undef __FTERRORS_H__
#define FT_ERRORDEF( e, v, s ) { e, s },
#define FT_ERROR_START_LIST {
#define FT_ERROR_END_LIST { 0, 0 } };
struct FreeTypeErrorDescription
{
int err_code;
const char* err_msg;
};
static const FreeTypeErrorDescription ftErrorDescs[] =
#include FT_ERRORS_H
static const std::vector<FreeTypeErrorDescription> freeTypeErrorDescriptions
(ftErrorDescs, ftErrorDescs + sizeof(ftErrorDescs) / sizeof(FreeTypeErrorDescription) );
//----------------------------------------------------------------------------//
FreeTypeFont::FreeTypeFont(
const String& font_name,
const float size,
const FontSizeUnit sizeUnit,
const bool anti_aliased, const String& font_filename,
FreeTypeFontLayerVector fontLayers,
const String& resource_group,
const AutoScaledMode auto_scaled,
const Sizef& native_res,
const float specific_line_spacing) :
Font(font_name, Font_xmlHandler::FontTypeFreeType, font_filename,
resource_group, auto_scaled, native_res),
d_specificLineSpacing(specific_line_spacing),
d_size(size),
d_sizeUnit(sizeUnit),
d_antiAliased(anti_aliased),
d_fontFace(nullptr),
d_fontLayers(std::move(fontLayers))
{
if (!s_fontUsageCount++)
FT_Init_FreeType(&s_freetypeLibHandle);
addFreeTypeFontProperties();
FreeTypeFont::updateFont();
std::stringstream& sstream = SharedStringstream::GetPreparedStream();
sstream << "Successfully loaded " << d_codePointToGlyphMap.size() << " glyphs";
Logger::getSingleton().logEvent(sstream.str(), LoggingLevel::Informative);
}
//----------------------------------------------------------------------------//
FreeTypeFont::~FreeTypeFont()
{
free();
if (!--s_fontUsageCount)
FT_Done_FreeType(s_freetypeLibHandle);
}
//----------------------------------------------------------------------------//
void FreeTypeFont::addFreeTypeFontProperties()
{
const String propertyOrigin("FreeTypeFont");
CEGUI_DEFINE_PROPERTY(FreeTypeFont, float,
"Size", "This is the size of the font.",
&FreeTypeFont::setSize, &FreeTypeFont::getSize, 0
);
CEGUI_DEFINE_PROPERTY(FreeTypeFont, FontSizeUnit,
"SizeUnit", "This is the point size of the font.",
&FreeTypeFont::setSizeUnit, &FreeTypeFont::getSizeUnit, FontSizeUnit::Pixels
);
CEGUI_DEFINE_PROPERTY(FreeTypeFont, bool,
"Antialiased", "This is a flag indicating whenever to render antialiased font or not. "
"Value is either true or false.",
&FreeTypeFont::setAntiAliased, &FreeTypeFont::isAntiAliased, false
);
}
void FreeTypeFont::resizeAndUpdateTexture(Texture* texture, int newSize) const
{
if(d_lastTextureSize >= newSize)
{
throw InvalidRequestException("Must supply a larger than previous size when "
"resizing the glyph atlas");
}
int oldTextureSize = d_lastTextureSize;
std::vector<argb_t> oldTextureData(d_lastTextureBuffer);
Sizef newTextureSize(static_cast<float>(newSize),
static_cast<float>(newSize));
d_lastTextureSize = newSize;
d_lastTextureBuffer.resize(newSize * newSize);
std::fill(d_lastTextureBuffer.begin(), d_lastTextureBuffer.end(), 0);
// Copy our memory buffer into the texture and free it
updateTextureBufferSubImage(d_lastTextureBuffer.data(),
oldTextureSize, oldTextureSize, oldTextureData);
//TODO: why always RGBA if we, and Freetype, only support greyscale?
texture->loadFromMemory(d_lastTextureBuffer.data(), newTextureSize, Texture::PixelFormat::Rgba);
System::getSingleton().getRenderer()->updateGeometryBufferTexCoords(texture,
oldTextureSize / static_cast<float>(newSize));
}
void FreeTypeFont::createTextureSpaceForGlyphRasterisation(Texture* texture, int glyphWidth, int glyphHeight) const
{
int maxTextureSize = System::getSingleton().getRenderer()->getMaxTextureSize();
const int scaleFactor = 2;
if(glyphWidth > maxTextureSize || glyphHeight > maxTextureSize)
{
throw InvalidRequestException("Can not rasterise a glyph that is larger "
"than the maximum supported texture size.");
}
int newSize = d_lastTextureSize * scaleFactor;
if (newSize > maxTextureSize)
{
createGlyphAtlasTexture();
}
else
{
resizeAndUpdateTexture(texture, newSize);
}
}
void FreeTypeFont::addRasterisedGlyphToTextureAndSetupGlyphImage(
FreeTypeFontGlyph* glyph, Texture* texture, FT_Bitmap& glyphBitmap, int glyphLeft, int glyphTop,
int glyphWidth, int glyphHeight, unsigned int layer,
const TextureGlyphLine& glyphTexLine) const
{
// Create the data containing the pixels of the glyph
std::vector<argb_t> subTextureData = createGlyphTextureData(glyphBitmap);
// Update the cached texture data in memory
size_t bufferDataGlyphPos = (glyphTexLine.d_lastYPos * d_lastTextureSize) + glyphTexLine.d_lastXPos;
updateTextureBufferSubImage(d_lastTextureBuffer.data() + bufferDataGlyphPos,
glyphWidth, glyphHeight, subTextureData);
// Update the sub-image in the texture on the GPU
glm::vec2 subImagePos(glyphTexLine.d_lastXPos, glyphTexLine.d_lastYPos);
Sizef subImageSize(static_cast<float>(glyphWidth), static_cast<float>(glyphHeight));
Rectf subImageArea(subImagePos, subImageSize);
texture->blitFromMemory(subTextureData.data(), subImageArea);
// Create a new image in the imageset
const Rectf area(static_cast<float>(glyphTexLine.d_lastXPos),
static_cast<float>(glyphTexLine.d_lastYPos),
static_cast<float>(glyphTexLine.d_lastXPos + glyphWidth),
static_cast<float>(glyphTexLine.d_lastYPos + glyphHeight));
// This is the right bearing for bitmap glyphs, not d_fontFace->glyph->metrics.horiBearingX
const glm::vec2 offset(
glyphLeft,
-glyphTop);
const String name(PropertyHelper<std::uint32_t>::toString(glyph->getCodePoint()));
BitmapImage* img = new BitmapImage(
name, texture, area,
offset, AutoScaledMode::Disabled, d_nativeResolution);
d_glyphImages.push_back(img);
glyph->setImage(img, layer);
}
void FreeTypeFont::findFittingSpotInGlyphTextureLines(
int glyphWidth, int glyphHeight,
bool &fittingLineWasFound, size_t &fittingLineIndex) const
{
// Go through the lines and find one that fits
size_t lineCount = d_textureGlyphLines.size();
for(size_t i = 0; i < lineCount && !fittingLineWasFound; ++i)
{
const auto& currentGlyphLine = d_textureGlyphLines[i];
bool isLastLine = (i == (lineCount - 1));
// Check if glyph right margin exceeds texture size
int curGlyphXEnd = currentGlyphLine.d_lastXPos + glyphWidth;
int curGlyphYEnd = currentGlyphLine.d_lastYPos + glyphHeight;
if (curGlyphXEnd < d_lastTextureSize && curGlyphYEnd < d_lastTextureSize)
{
//Only the last line can be extended into the y-dimension
if (isLastLine)
{
if (curGlyphYEnd > currentGlyphLine.d_maximumExtentY)
{
currentGlyphLine.d_maximumExtentY = curGlyphYEnd;
}
fittingLineIndex = i;
fittingLineWasFound = true;
}
else
{
if (curGlyphYEnd < currentGlyphLine.d_maximumExtentY)
{
fittingLineIndex = i;
fittingLineWasFound = true;
}
}
}
}
}
//----------------------------------------------------------------------------//
void FreeTypeFont::rasterise(FreeTypeFontGlyph* glyph, FT_Bitmap& ft_bitmap, int glyphLeft, int glyphTop,
int glyphWidth, int glyphHeight, int unsigned layer) const
{
if(d_glyphTextures.empty())
{
createGlyphAtlasTexture();
}
bool fittingLineWasFound = false;
size_t fittingLineIndex = -1;
findFittingSpotInGlyphTextureLines(glyphWidth, glyphHeight,
fittingLineWasFound, fittingLineIndex);
if(!fittingLineWasFound)
{
fittingLineWasFound = addNewLineIfFitting(glyphHeight, glyphWidth, fittingLineIndex);
}
if(!fittingLineWasFound)
{
Texture* texture = d_glyphTextures.back();
createTextureSpaceForGlyphRasterisation(texture, glyphWidth, glyphHeight);
rasterise(glyph, ft_bitmap, glyphLeft, glyphTop, glyphWidth, glyphHeight, layer);
return;
}
const TextureGlyphLine& glyphTexLine = d_textureGlyphLines[fittingLineIndex];
// Retrieve the last texture created
Texture* texture = d_glyphTextures.back();
addRasterisedGlyphToTextureAndSetupGlyphImage(glyph, texture, ft_bitmap,
glyphLeft, glyphTop, glyphWidth, glyphHeight, layer, glyphTexLine);
// Advance to next position, add padding
glyphTexLine.d_lastXPos += glyphWidth + s_glyphPadding;
}
bool FreeTypeFont::addNewLineIfFitting(unsigned int glyphHeight, unsigned int glyphWidth,
size_t& fittingLineIndex) const
{
const auto& lastLine = d_textureGlyphLines.back();
unsigned int newLinePosY = lastLine.d_maximumExtentY + s_glyphPadding;
int newMaxYExtent = newLinePosY + glyphHeight;
// Also skip if the texture isn't wide enough
const int curGlyphXEnd = glyphWidth;
if (newMaxYExtent <= d_lastTextureSize && curGlyphXEnd < d_lastTextureSize)
{
// Add the glyph in a new line
d_textureGlyphLines.push_back(TextureGlyphLine(0, newLinePosY, newMaxYExtent));
fittingLineIndex = d_textureGlyphLines.size() - 1;
return true;
}
return false;
}
void FreeTypeFont::createGlyphAtlasTexture() const
{
std::uint32_t newTextureIndex = d_glyphTextures.size();
const String texture_name(d_name + "_auto_glyph_images_texture_" +
PropertyHelper<std::uint32_t>::toString(newTextureIndex));
d_lastTextureSize = d_initialGlyphAtlasSize;
Sizef newTextureSize(static_cast<float>(d_initialGlyphAtlasSize),
static_cast<float>(d_initialGlyphAtlasSize));
Texture& texture = System::getSingleton().getRenderer()->createTexture(
texture_name, newTextureSize);
d_glyphTextures.push_back(&texture);
d_lastTextureBuffer = std::vector<argb_t>(d_lastTextureSize * d_lastTextureSize, 0);
d_textureGlyphLines.clear();
d_textureGlyphLines.push_back(TextureGlyphLine());
}
//----------------------------------------------------------------------------//
std::vector<argb_t> FreeTypeFont::createGlyphTextureData(FT_Bitmap& glyphBitmap)
{
unsigned int bitmapHeight = static_cast<unsigned int>(glyphBitmap.rows);
unsigned int bitmapWidth = static_cast<unsigned int>(glyphBitmap.width);
std::vector<argb_t> glyphTextureData;
glyphTextureData.resize(bitmapHeight * bitmapWidth);
for (unsigned int i = 0; i < bitmapHeight; ++i)
{
argb_t* currentRow = glyphTextureData.data() + i * bitmapWidth;
for (unsigned int j = 0; j < bitmapWidth; ++j)
{
std::uint8_t* src = glyphBitmap.buffer + (i * glyphBitmap.pitch + j);
switch (glyphBitmap.pixel_mode)
{
case FT_PIXEL_MODE_GRAY:
{
currentRow[j] = Colour::calculateArgb(*src, 0xFF, 0xFF, 0xFF);
break;
}
case FT_PIXEL_MODE_MONO:
{
currentRow[j] = (src[j / 8] & (0x80 >> (j & 7))) ? 0xFFFFFFFF : 0x00000000;
break;
}
default:
throw InvalidRequestException(
"The glyph could not be drawn because the pixel mode is "
"unsupported.");
}
}
}
return glyphTextureData;
}
//----------------------------------------------------------------------------//
FT_Stroker_LineCap FreeTypeFont::getLineCap(FreeTypeLineCap line_cap) {
switch (line_cap) {
case FreeTypeLineCap::Round:
return FT_STROKER_LINECAP_ROUND;
case FreeTypeLineCap::Butt:
return FT_STROKER_LINECAP_BUTT;
case FreeTypeLineCap::Square:
return FT_STROKER_LINECAP_SQUARE;
}
return FT_STROKER_LINECAP_SQUARE;
}
//----------------------------------------------------------------------------//
FT_Stroker_LineJoin FreeTypeFont::getLineJoin(FreeTypeLineJoin line_join) {
switch (line_join) {
case FreeTypeLineJoin::Round:
return FT_STROKER_LINEJOIN_ROUND;
case FreeTypeLineJoin::Bevel:
return FT_STROKER_LINEJOIN_BEVEL;
case FreeTypeLineJoin::MiterFixed:
return FT_STROKER_LINEJOIN_MITER_FIXED;
case FreeTypeLineJoin::MiterVariable:
return FT_STROKER_LINEJOIN_MITER_VARIABLE;
}
return FT_STROKER_LINEJOIN_ROUND;
}
//----------------------------------------------------------------------------//
void FreeTypeFont::updateTextureBufferSubImage(argb_t* destTextureData, unsigned int bitmapWidth,
unsigned int bitmapHeight, const std::vector<argb_t>& subImageData) const
{
argb_t* curDestPixelLine = destTextureData;
for (unsigned int i = 0; i < bitmapHeight; ++i)
{
argb_t* curDestPixel = curDestPixelLine;
for (unsigned int j = 0; j < bitmapWidth; ++j)
{
*curDestPixel = subImageData[bitmapWidth * i + j];
++curDestPixel;
}
curDestPixelLine += d_lastTextureSize;
}
}
//----------------------------------------------------------------------------//
void FreeTypeFont::free()
{
if (!d_fontFace)
return;
for(auto codePointMapEntry : d_codePointToGlyphMap)
{
delete codePointMapEntry.second;
}
d_codePointToGlyphMap.clear();
d_indexToGlyphMap.clear();
for (size_t i = 0; i < d_glyphImages.size(); ++i)
delete d_glyphImages[i];
d_glyphImages.clear();
for (size_t i = 0; i < d_glyphTextures.size(); i++)
System::getSingleton().getRenderer()->destroyTexture(*d_glyphTextures[i]);
d_glyphTextures.clear();
FT_Done_Face(d_fontFace);
d_fontFace = nullptr;
System::getSingleton().getResourceProvider()->unloadRawDataContainer(d_fontData);
}
void FreeTypeFont::createFreetypeMemoryFace()
{
// create face using input font
FT_Error error = FT_New_Memory_Face(s_freetypeLibHandle, d_fontData.getDataPtr(),
static_cast<FT_Long>(d_fontData.getSize()), 0,
&d_fontFace);
if (error != 0)
{
findAndThrowFreeTypeError(error, "Failed to create face from font file");
}
}
void FreeTypeFont::findAndThrowFreeTypeError(
FT_Error error,
const String& errorMessageIntro) const
{
String errorMsg = "Unknown freetype error occurred: " + error;
for (size_t i = 0; i < freeTypeErrorDescriptions.size(); ++i)
{
const FreeTypeErrorDescription& currentFreetypeError = freeTypeErrorDescriptions[i];
if (currentFreetypeError.err_code == error)
{
errorMsg = currentFreetypeError.err_msg;
}
}
throw GenericException(errorMessageIntro + " - '" +
d_filename + "' error was: " + errorMsg);
}
void FreeTypeFont::checkUnicodeCharMapAvailability()
{
if (d_fontFace->charmap != nullptr)
{
return;
}
FT_Done_Face(d_fontFace);
d_fontFace = nullptr;
throw GenericException(
"The font '" + d_name + "' does not have a Unicode charmap, and "
"cannot be used.");
}
void FreeTypeFont::tryToCreateFontWithClosestFontHeight(
FT_Error errorResult,
int requestedFontPixelHeight) const
{
FT_Short closestAvailableFontHeight = -1;
int closestHeightDelta = std::numeric_limits<int>::max();
FT_Int fixedSizesCount = d_fontFace->num_fixed_sizes;
for (FT_Int i = 0; i < fixedSizesCount; i++)
{
FT_Short currentFontHeight = d_fontFace->available_sizes[i].height;
int currentFontHeightDelta = std::abs(requestedFontPixelHeight - currentFontHeight);
if(currentFontHeightDelta < closestHeightDelta)
{
closestAvailableFontHeight = currentFontHeight;
closestHeightDelta = currentFontHeightDelta;
}
}
if (closestAvailableFontHeight > 0)
{
errorResult = FT_Set_Pixel_Sizes(d_fontFace, 0, closestAvailableFontHeight);
if (errorResult != 0)
{
findAndThrowFreeTypeError(errorResult, "Failed to create Font using "
"the closest available Font size that was found");
}
}
if (errorResult != 0)
{
std::stringstream& sstream = SharedStringstream::GetPreparedStream();
sstream << d_size;
throw GenericException("The font '" + d_name + "' requested at height "
"of " + sstream.str() + " pixels, could not be created and therefore"
" not used");
}
}
//----------------------------------------------------------------------------//
void FreeTypeFont::updateFont()
{
free();
System::getSingleton().getResourceProvider()->loadRawDataContainer(
d_filename, d_fontData, d_resourceGroup.empty() ?
getDefaultResourceGroup() : d_resourceGroup);
createFreetypeMemoryFace();
checkUnicodeCharMapAvailability();
float fontScaleFactor = System::getSingleton().getRenderer()->getFontScale();
if (d_autoScaled != AutoScaledMode::Disabled)
{
fontScaleFactor *= d_vertScaling;
}
unsigned int requestedFontSizeInPixels = static_cast<unsigned int>(
std::lround(getSizeInPixels() * fontScaleFactor));
FT_Error errorResult = FT_Set_Pixel_Sizes(d_fontFace, 0, requestedFontSizeInPixels);
if(errorResult != 0)
{
// Usually, an error occurs with a fixed-size font format (like FNT or PCF)
// when trying to set the pixel size to a value that is not listed in the
// face->fixed_sizes array.For bitmap fonts we can render only at specific
// point sizes.
// Try to find Font with closest pixel height and use it instead
tryToCreateFontWithClosestFontHeight(errorResult, requestedFontSizeInPixels);
}
if (d_fontFace->face_flags & FT_FACE_FLAG_SCALABLE)
{
float y_scale = d_fontFace->size->metrics.y_scale * float(s_conversionMultCoeff) * (1.0f / 65536.0f);
d_ascender = d_fontFace->ascender * y_scale;
d_descender = d_fontFace->descender * y_scale;
d_height = d_fontFace->height * y_scale;
}
else
{
d_ascender = d_fontFace->size->metrics.ascender * float(s_conversionMultCoeff);
d_descender = d_fontFace->size->metrics.descender * float(s_conversionMultCoeff);
d_height = d_fontFace->size->metrics.height * float(s_conversionMultCoeff);
}
if (d_specificLineSpacing > 0.0f)
{
d_height = d_specificLineSpacing;
}
initialiseGlyphMap();
}
//----------------------------------------------------------------------------//
void FreeTypeFont::initialiseGlyphMap()
{
FT_UInt gindex;
FT_ULong codepoint = FT_Get_First_Char(d_fontFace, &gindex);
while (gindex != 0)
{
if(d_codePointToGlyphMap.find(codepoint) != d_codePointToGlyphMap.end())
{
throw InvalidRequestException("FreeTypeFont::initialiseGlyphMap - Requesting "
"adding an already added glyph to the codepoint glyph map.");
}
FreeTypeFontGlyph* newFontGlyph = new FreeTypeFontGlyph(codepoint, gindex);
d_codePointToGlyphMap[codepoint] = newFontGlyph;
d_indexToGlyphMap[gindex] = static_cast<char32_t>(codepoint);
codepoint = FT_Get_Next_Char(d_fontFace, codepoint, &gindex);
}
}
//----------------------------------------------------------------------------//
void FreeTypeFont::prepareGlyph(FreeTypeFontGlyph* glyph) const
{
if (glyph->isInitialised())
{
return;
}
FT_Glyph ft_glyph;
FT_Bitmap ft_bitmap;
FT_Vector position;
position.x = 0L;
position.y = 0L;
int glyphWidth = 0;
int glyphHeight = 0;
int glyphLeft = 0;
int glyphTop = 0;
FT_Set_Transform(d_fontFace, nullptr, &position);
FT_UInt glyph_index = FT_Get_Char_Index(d_fontFace, glyph->getCodePoint());
unsigned int layerCount = d_fontLayers.size(); //retrieved from font somehow
//layer 0 is the top rendered layer (rendered last over the other layers)
for (unsigned int layer = 0; layer < layerCount; layer++) {
FontLayerType fontLayerType = d_fontLayers[layer].d_fontLayerType;
// Load the code point, "rendering" the glyph
FT_Int32 targetType = d_antiAliased ? FT_LOAD_TARGET_NORMAL : FT_LOAD_TARGET_MONO;
FT_Int32 loadType = (fontLayerType == FontLayerType::Standard) ? FT_LOAD_RENDER : FT_LOAD_NO_BITMAP;
auto loadBitmask = loadType | FT_LOAD_FORCE_AUTOHINT | targetType;
FT_Error error = FT_Load_Glyph(d_fontFace, glyph_index, loadBitmask);
glyph->markAsInitialised();
if (error != 0)
{
return;
}
if (fontLayerType == FontLayerType::Standard) {
ft_bitmap = d_fontFace->glyph->bitmap;
glyphWidth = d_fontFace->glyph->bitmap.width;
glyphHeight = d_fontFace->glyph->bitmap.rows;
glyphTop = d_fontFace->glyph->bitmap_top;
glyphLeft = d_fontFace->glyph->bitmap_left;
} else {
unsigned int outlinePixels = d_fontLayers[layer].d_outlinePixels; // n * 64 result in n pixels outline
bool errorFlag = false;
FT_Stroker stroker;
FT_BitmapGlyph bitmapGlyph;
FT_Stroker_New(s_freetypeLibHandle, &stroker);
FT_Stroker_Set(stroker, outlinePixels * 64, getLineCap(d_fontLayers[layer].d_lineCap),
getLineJoin(d_fontLayers[layer].d_lineJoin), d_fontLayers[layer].d_miterLimit);
if (FT_Get_Glyph(d_fontFace->glyph, &ft_glyph)) {
errorFlag = true;
}
if (fontLayerType == FontLayerType::Outline)
error = FT_Glyph_Stroke(&ft_glyph, stroker, true);
if (fontLayerType == FontLayerType::Outer)
error = FT_Glyph_StrokeBorder(&ft_glyph, stroker, false, true);
if (fontLayerType == FontLayerType::Inner)
error = FT_Glyph_StrokeBorder(&ft_glyph, stroker, true, true);
if (error > 0) {
errorFlag = true;
std::cout << "!!!!!!!!!!!!!!!!failed Stroke " << std::endl;
}
error = FT_Glyph_To_Bitmap(&ft_glyph, FT_RENDER_MODE_NORMAL, 0, true);
if (error > 0) {
errorFlag = true;
std::cout << "failed to create glyph to bitmap" << std::endl;
}
bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(ft_glyph);
ft_bitmap = bitmapGlyph->bitmap;
glyphWidth = bitmapGlyph->bitmap.width;
glyphHeight = bitmapGlyph->bitmap.rows;
glyphTop = bitmapGlyph->top;
glyphLeft = bitmapGlyph->left;
FT_Stroker_Done(stroker);
if (errorFlag)
{
// return;
}
}
bool isRendered = glyph->getImage(layer) != nullptr;
if (!isRendered)
{
#ifdef CEGUI_USE_RAQM
// Rasterise the 0 position glyph
rasterise(glyph, ft_bitmap, glyphLeft, glyphTop, glyphWidth, glyphHeight, layer);
glyph->setLsbDelta(d_fontFace->glyph->lsb_delta);
glyph->setRsbDelta(d_fontFace->glyph->rsb_delta);
#else
rasterise(glyph, ft_bitmap, glyphLeft, glyphTop, glyphWidth, glyphHeight, layer);
#endif
}
float adv;
if (fontLayerType == FontLayerType::Standard)
{
//adv = d_fontFace->glyph->advance.x * static_cast<float>(s_conversionMultCoeff);
adv = d_fontFace->glyph->metrics.horiAdvance * static_cast<float>(s_conversionMultCoeff);
}
else
{
adv = d_fontFace->glyph->metrics.horiAdvance * static_cast<float>(s_conversionMultCoeff);
FT_Done_Glyph(ft_glyph);
}
glyph->setAdvance(adv);
} //for layer loop
}
//----------------------------------------------------------------------------//
void FreeTypeFont::writeXMLToStream_impl(XMLSerializer& xml_stream) const
{
xml_stream.attribute(Font_xmlHandler::FontSizeAttribute,
PropertyHelper<float>::toString(d_size));
if (d_sizeUnit != FontSizeUnit::Points)
xml_stream.attribute(Font_xmlHandler::FontSizeUnitAttribute,
PropertyHelper<FontSizeUnit>::toString(d_sizeUnit));
if (!d_antiAliased)
xml_stream.attribute(Font_xmlHandler::FontAntiAliasedAttribute, "false");
if (d_specificLineSpacing > 0.0f)
xml_stream.attribute(Font_xmlHandler::FontLineSpacingAttribute,
PropertyHelper<float>::toString(d_specificLineSpacing));
}
//----------------------------------------------------------------------------//
bool FreeTypeFont::isAntiAliased() const
{
return d_antiAliased;
}
//----------------------------------------------------------------------------//
void FreeTypeFont::setSize(const float size)
{
setSizeAndUnit(size, d_sizeUnit);
}
void FreeTypeFont::setSizeUnit(const FontSizeUnit sizeUnit)
{
setSizeAndUnit(d_size, sizeUnit);
}
void FreeTypeFont::setSizeInPixels(const float pixelSize)
{
setSizeAndUnit(pixelSize, FontSizeUnit::Pixels);
}
void FreeTypeFont::setSizeInPoints(const float pointSize)
{
setSizeAndUnit(pointSize, FontSizeUnit::Points);
}
void FreeTypeFont::setSizeAndUnit(const float size, const FontSizeUnit sizeUnit)
{
if (d_size == size && d_sizeUnit == sizeUnit)
{
return;
}
d_size = size;
d_sizeUnit = sizeUnit;
handleFontSizeOrFontUnitChange();
}
float FreeTypeFont::getSize() const
{
return d_size;
}
FontSizeUnit FreeTypeFont::getSizeUnit() const
{
return d_sizeUnit;
}
float FreeTypeFont::getSizeInPixels() const
{
if (d_sizeUnit == FontSizeUnit::Pixels)
{
return d_size;
}
if (d_sizeUnit == FontSizeUnit::Points)
{
return convertPointsToPixels(d_size, Renderer::ReferenceDpiValue);
}
throw InvalidRequestException("FreeTypeFont::getSizeInPixels - Requesting "
"font size in pixels but the Font size unit is invalid.");
}
float FreeTypeFont::getSizeInPoints() const
{
if (d_sizeUnit == FontSizeUnit::Pixels)
{
return convertPixelsToPoints(d_size, Renderer::ReferenceDpiValue);
}
if (d_sizeUnit == FontSizeUnit::Points)
{
return d_size;
}
throw InvalidRequestException("FreeTypeFont::getSizeInPixels - Requesting "
"font size in pixels but the Font size unit is invalid.");
}
void FreeTypeFont::handleFontSizeOrFontUnitChange()
{
updateFont();
FontEventArgs args(this);
onRenderSizeChanged(args);
}
//----------------------------------------------------------------------------//
void FreeTypeFont::setAntiAliased(const bool antiAliased)
{
if (antiAliased == d_antiAliased)
return;
d_antiAliased = antiAliased;
updateFont();
FontEventArgs args(this);
onRenderSizeChanged(args);
}
const FT_Face& FreeTypeFont::getFontFace() const
{
return d_fontFace;
}
std::vector<GeometryBuffer*> FreeTypeFont::layoutAndCreateGlyphRenderGeometry(
const String& text,
const Rectf* clip_rect, const ColourRect& colours,
const float space_extra,
ImageRenderSettings imgRenderSettings, DefaultParagraphDirection defaultParagraphDir,
glm::vec2& penPosition) const
{
#ifdef CEGUI_USE_RAQM
return layoutUsingRaqmAndCreateRenderGeometry(text, clip_rect, colours,
space_extra, imgRenderSettings, defaultParagraphDir, penPosition);
#else
CEGUI_UNUSED(defaultParagraphDir);
return layoutUsingFreetypeAndCreateRenderGeometry(text, clip_rect, colours,
space_extra, imgRenderSettings, penPosition);
#endif
}
std::vector<GeometryBuffer*> FreeTypeFont::layoutUsingFreetypeAndCreateRenderGeometry(
const String& text, const Rectf* clip_rect, const ColourRect& colours,
const float space_extra, ImageRenderSettings imgRenderSettings,
glm::vec2& penPosition) const
{
const std::vector<ColourRect> layerColours = { colours };
return layoutUsingFreetypeAndCreateRenderGeometry(text, clip_rect, layerColours, space_extra,
imgRenderSettings, penPosition);
}
std::vector<GeometryBuffer*> FreeTypeFont::layoutUsingFreetypeAndCreateRenderGeometry(
const String& text, const Rectf* clip_rect, const std::vector<ColourRect>& layerColours,
const float space_extra, ImageRenderSettings imgRenderSettings,
glm::vec2& penPosition) const
{
std::vector<GeometryBuffer*> textGeometryBuffers;
if (text.empty())
{
return textGeometryBuffers;
}
#if (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_8) || (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_ASCII)
std::u32string utf32Text = String::convertUtf8ToUtf32(text.c_str(), text.length());
#elif (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_32)
const std::u32string& utf32Text = text.getString();
#endif
glm::vec2 penPositionStart = penPosition;
unsigned int layerCount = d_fontLayers.size();
for (int layerTmp = layerCount -1; layerTmp >= 0; layerTmp--) {
unsigned int layer = static_cast<unsigned int>(layerTmp);
FT_Pos previousRsbDelta = 0;
unsigned int previousGlyphIndex = 0;
penPosition = penPositionStart;
penPosition.y += getBaseline();
size_t charCount = utf32Text.size();
for (size_t i = 0; i < charCount; ++i)
{
const char32_t& codePoint = utf32Text[i];
// Ignore new line characters
if (codePoint == '\n')
{
continue;
}
const FreeTypeFontGlyph* glyph = getPreparedGlyph(codePoint);
if (glyph == nullptr)
{
if(codePoint != UnicodeReplacementCharacter)
{
glyph = getPreparedGlyph(UnicodeReplacementCharacter);
}
if (glyph == nullptr)
{
continue;
}
}
adjustPenPositionForBearingDeltas(penPosition, previousRsbDelta, glyph);
previousRsbDelta = glyph->getRsbDelta();
if (i >= 1)
{
FT_Vector kerning;
unsigned int rightGlyphIndex = glyph->getGlyphIndex();
FT_Get_Kerning(d_fontFace, previousGlyphIndex, rightGlyphIndex,
FT_KERNING_DEFAULT, &kerning);
penPosition.x += kerning.x * s_conversionMultCoeff;
}
previousGlyphIndex = glyph->getGlyphIndex();
const Image* const image = glyph->getImage(layer);
if (image)
{
imgRenderSettings.d_destArea =
Rectf(penPosition, image->getRenderedSize());
const CEGUI::ColourRect fallbackColour;
const CEGUI::ColourRect& currentlayerColour = (layer < layerColours.size()) ?
layerColours[layer] : fallbackColour;
addGlyphRenderGeometry(textGeometryBuffers, image, imgRenderSettings,
clip_rect, currentlayerColour);
}
penPosition.x += glyph->getAdvance();
if (codePoint == ' ')
{
// TODO: This is for justified text and probably wrong because the space was determined
// without considering kerning
penPosition.x += space_extra;
}
}
} //for layers
return textGeometryBuffers;
}
#ifdef CEGUI_USE_RAQM
std::vector<GeometryBuffer*> FreeTypeFont::layoutUsingRaqmAndCreateRenderGeometry(
const String& text, const Rectf* clip_rect, const ColourRect& colours,
const float space_extra, ImageRenderSettings imgRenderSettings,
DefaultParagraphDirection defaultParagraphDir, glm::vec2& penPosition) const
{
const std::vector<ColourRect> layerColours = {colours};
return layoutUsingRaqmAndCreateRenderGeometry(text, clip_rect, layerColours,
space_extra, imgRenderSettings, defaultParagraphDir, penPosition);
}
std::vector<GeometryBuffer*> FreeTypeFont::layoutUsingRaqmAndCreateRenderGeometry(
const String& text, const Rectf* clip_rect, const std::vector<ColourRect>& layerColours,
const float space_extra, ImageRenderSettings imgRenderSettings,
DefaultParagraphDirection defaultParagraphDir, glm::vec2& penPosition) const
{
std::vector<GeometryBuffer*> textGeometryBuffers;
if (text.empty())
{
return textGeometryBuffers;
}
#if (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_8) || (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_ASCII)
std::u32string utf32Text = String::convertUtf8ToUtf32(text.c_str());
size_t origTextLength = utf32Text.length();
const uint32_t* originalTextArray = reinterpret_cast<const std::uint32_t*>(utf32Text.c_str());
#elif (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_32)
size_t origTextLength = text.length();
const uint32_t* originalTextArray = reinterpret_cast<const std::uint32_t*>(text.c_str());
#endif
glm::vec2 penPositionStart = penPosition;
raqm_t* raqmObject = createAndSetupRaqmTextObject(
originalTextArray, origTextLength, defaultParagraphDir, getFontFace());
const std::size_t layerCount = d_fontLayers.size();
for (int layerTmp = layerCount - 1; layerTmp >= 0; layerTmp--) {
unsigned int layer = static_cast<unsigned int>(layerTmp);
size_t count = 0;
raqm_glyph_t* glyphs = raqm_get_glyphs(raqmObject, &count);
penPosition = penPositionStart;
penPosition.y += getBaseline();
for (size_t i = 0; i < count; i++)
{
raqm_glyph_t& currentGlyph = glyphs[i];
char32_t codePoint;
auto foundCodePointIter = d_indexToGlyphMap.find(currentGlyph.index);
if (foundCodePointIter != d_indexToGlyphMap.end())
{
codePoint = foundCodePointIter->second;
}
else
{
codePoint = UnicodeReplacementCharacter;
}
// Ignore new line characters
if (originalTextArray[currentGlyph.cluster] == '\n')
{
continue;
}
const FreeTypeFontGlyph* glyph = getPreparedGlyph(codePoint);
if (glyph == nullptr)
{
if (codePoint != UnicodeReplacementCharacter)
{
glyph = getPreparedGlyph(UnicodeReplacementCharacter);
}
if (glyph == nullptr)
{
continue;
}
}
const Image* const image = glyph->getImage(layer);
if (image) {
imgRenderSettings.d_destArea =
Rectf(penPosition, image->getRenderedSize());
penPosition.x = std::round(penPosition.x);
//The glyph pos will be rounded to full pixels internally
glm::vec2 renderGlyphPos(
penPosition.x + currentGlyph.x_offset * s_conversionMultCoeff,
penPosition.y + currentGlyph.y_offset * s_conversionMultCoeff);
imgRenderSettings.d_destArea =
Rectf(renderGlyphPos, image->getRenderedSize());
const CEGUI::ColourRect fallbackColour;
const CEGUI::ColourRect& currentlayerColour = (layer < layerColours.size()) ?
layerColours[layer] : fallbackColour;
addGlyphRenderGeometry(textGeometryBuffers, image, imgRenderSettings,
clip_rect, currentlayerColour);
}
penPosition.x += currentGlyph.x_advance * s_conversionMultCoeff;
if (codePoint == ' ')
{
// TODO: This is for justified text and probably wrong because the space was determined
// without considering kerning
penPosition.x += space_extra;
}
}
raqm_destroy(raqmObject);
}
return textGeometryBuffers;
}
#endif
bool FreeTypeFont::isCodepointAvailable(char32_t codePoint) const
{
return d_codePointToGlyphMap.find(codePoint) != d_codePointToGlyphMap.end();
}
FreeTypeFontGlyph* FreeTypeFont::getGlyphForCodepoint(const char32_t codepoint) const
{
CodePointToGlyphMap::const_iterator pos = d_codePointToGlyphMap.find(codepoint);
if (pos != d_codePointToGlyphMap.end())
{
return pos->second;
}
return nullptr;
}
int FreeTypeFont::getInitialGlyphAtlasSize() const
{
return d_initialGlyphAtlasSize;
}
void FreeTypeFont::setInitialGlyphAtlasSize(int val)
{
d_initialGlyphAtlasSize = val;
}
const FreeTypeFontGlyph* FreeTypeFont::getPreparedGlyph(char32_t currentCodePoint) const
{
FreeTypeFontGlyph* glyph = getGlyphForCodepoint(currentCodePoint);
if (glyph != nullptr)
{
prepareGlyph(glyph);
}
return glyph;
}
} // End of CEGUI namespace section
| 34.045528 | 115 | 0.642253 | Costallat |
59185c0f2ac685f082098b6714e89a0b17737fa8 | 384 | cpp | C++ | easy/count-the-number-of-consistent-strings/Solution.cpp | xandersavvy/Problem-solving | de9fa307467f9823acfc32754b15671c93000bf1 | [
"Unlicense"
] | null | null | null | easy/count-the-number-of-consistent-strings/Solution.cpp | xandersavvy/Problem-solving | de9fa307467f9823acfc32754b15671c93000bf1 | [
"Unlicense"
] | null | null | null | easy/count-the-number-of-consistent-strings/Solution.cpp | xandersavvy/Problem-solving | de9fa307467f9823acfc32754b15671c93000bf1 | [
"Unlicense"
] | null | null | null | class Solution {
public:
int countConsistentStrings(string allowed, vector<string>& words) {
int count=words.size();
for(int i=0;i<words.size();i++){
for(char j:words[i]){
if(allowed.find(j)==string::npos){
count--;
break;
}
}
}
return count;
}
};
| 24 | 71 | 0.440104 | xandersavvy |
591f8df0d55ce50fbf1d179b4b74649d5a2cd378 | 29,653 | cpp | C++ | CPP/Windows/FileFind.cpp | fooziex/7-Zip-zstd | 3e0e78700e56e126c3615fe606f4d2bbd6cd2928 | [
"BSD-3-Clause"
] | 4 | 2016-07-09T18:03:44.000Z | 2016-07-13T18:06:07.000Z | CPP/Windows/FileFind.cpp | fooziex/7-Zip-zstd | 3e0e78700e56e126c3615fe606f4d2bbd6cd2928 | [
"BSD-3-Clause"
] | 1 | 2021-11-17T14:15:23.000Z | 2021-11-17T14:15:23.000Z | CPP/Windows/FileFind.cpp | fooziex/7-Zip-zstd | 3e0e78700e56e126c3615fe606f4d2bbd6cd2928 | [
"BSD-3-Clause"
] | null | null | null | // Windows/FileFind.cpp
#include "StdAfx.h"
// #include <stdio.h>
#ifndef _WIN32
#include <fcntl.h> /* Definition of AT_* constants */
#include "TimeUtils.h"
#endif
#include "FileFind.h"
#include "FileIO.h"
#include "FileName.h"
#ifndef _UNICODE
extern bool g_IsNT;
#endif
using namespace NWindows;
using namespace NFile;
using namespace NName;
#if defined(_WIN32) && !defined(UNDER_CE)
EXTERN_C_BEGIN
typedef enum
{
My_FindStreamInfoStandard,
My_FindStreamInfoMaxInfoLevel
} MY_STREAM_INFO_LEVELS;
typedef struct
{
LARGE_INTEGER StreamSize;
WCHAR cStreamName[MAX_PATH + 36];
} MY_WIN32_FIND_STREAM_DATA, *MY_PWIN32_FIND_STREAM_DATA;
typedef HANDLE (WINAPI *FindFirstStreamW_Ptr)(LPCWSTR fileName, MY_STREAM_INFO_LEVELS infoLevel,
LPVOID findStreamData, DWORD flags);
typedef BOOL (APIENTRY *FindNextStreamW_Ptr)(HANDLE findStream, LPVOID findStreamData);
EXTERN_C_END
#endif // defined(_WIN32) && !defined(UNDER_CE)
namespace NWindows {
namespace NFile {
#ifdef _WIN32
#ifdef SUPPORT_DEVICE_FILE
namespace NSystem
{
bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize, UInt64 &freeSize);
}
#endif
#endif
namespace NFind {
#define MY_CLEAR_FILETIME(ft) ft.dwLowDateTime = ft.dwHighDateTime = 0;
void CFileInfoBase::ClearBase() throw()
{
Size = 0;
MY_CLEAR_FILETIME(CTime);
MY_CLEAR_FILETIME(ATime);
MY_CLEAR_FILETIME(MTime);
Attrib = 0;
// ReparseTag = 0;
IsAltStream = false;
IsDevice = false;
#ifndef _WIN32
ino = 0;
nlink = 0;
mode = 0;
#endif
}
bool CFileInfo::IsDots() const throw()
{
if (!IsDir() || Name.IsEmpty())
return false;
if (Name[0] != '.')
return false;
return Name.Len() == 1 || (Name.Len() == 2 && Name[1] == '.');
}
#ifdef _WIN32
#define WIN_FD_TO_MY_FI(fi, fd) \
fi.Attrib = fd.dwFileAttributes; \
fi.CTime = fd.ftCreationTime; \
fi.ATime = fd.ftLastAccessTime; \
fi.MTime = fd.ftLastWriteTime; \
fi.Size = (((UInt64)fd.nFileSizeHigh) << 32) + fd.nFileSizeLow; \
/* fi.ReparseTag = fd.dwReserved0; */ \
fi.IsAltStream = false; \
fi.IsDevice = false;
/*
#ifdef UNDER_CE
fi.ObjectID = fd.dwOID;
#else
fi.ReparseTag = fd.dwReserved0;
#endif
*/
static void Convert_WIN32_FIND_DATA_to_FileInfo(const WIN32_FIND_DATAW &fd, CFileInfo &fi)
{
WIN_FD_TO_MY_FI(fi, fd);
fi.Name = us2fs(fd.cFileName);
#if defined(_WIN32) && !defined(UNDER_CE)
// fi.ShortName = us2fs(fd.cAlternateFileName);
#endif
}
#ifndef _UNICODE
static void Convert_WIN32_FIND_DATA_to_FileInfo(const WIN32_FIND_DATA &fd, CFileInfo &fi)
{
WIN_FD_TO_MY_FI(fi, fd);
fi.Name = fas2fs(fd.cFileName);
#if defined(_WIN32) && !defined(UNDER_CE)
// fi.ShortName = fas2fs(fd.cAlternateFileName);
#endif
}
#endif
////////////////////////////////
// CFindFile
bool CFindFileBase::Close() throw()
{
if (_handle == INVALID_HANDLE_VALUE)
return true;
if (!::FindClose(_handle))
return false;
_handle = INVALID_HANDLE_VALUE;
return true;
}
/*
WinXP-64 FindFirstFile():
"" - ERROR_PATH_NOT_FOUND
folder\ - ERROR_FILE_NOT_FOUND
\ - ERROR_FILE_NOT_FOUND
c:\ - ERROR_FILE_NOT_FOUND
c: - ERROR_FILE_NOT_FOUND, if current dir is ROOT ( c:\ )
c: - OK, if current dir is NOT ROOT ( c:\folder )
folder - OK
\\ - ERROR_INVALID_NAME
\\Server - ERROR_INVALID_NAME
\\Server\ - ERROR_INVALID_NAME
\\Server\Share - ERROR_BAD_NETPATH
\\Server\Share - ERROR_BAD_NET_NAME (Win7).
!!! There is problem : Win7 makes some requests for "\\Server\Shar" (look in Procmon),
when we call it for "\\Server\Share"
\\Server\Share\ - ERROR_FILE_NOT_FOUND
\\?\UNC\Server\Share - ERROR_INVALID_NAME
\\?\UNC\Server\Share - ERROR_BAD_PATHNAME (Win7)
\\?\UNC\Server\Share\ - ERROR_FILE_NOT_FOUND
\\Server\Share_RootDrive - ERROR_INVALID_NAME
\\Server\Share_RootDrive\ - ERROR_INVALID_NAME
e:\* - ERROR_FILE_NOT_FOUND, if there are no items in that root folder
w:\* - ERROR_PATH_NOT_FOUND, if there is no such drive w:
*/
bool CFindFile::FindFirst(CFSTR path, CFileInfo &fi)
{
if (!Close())
return false;
#ifndef _UNICODE
if (!g_IsNT)
{
WIN32_FIND_DATAA fd;
_handle = ::FindFirstFileA(fs2fas(path), &fd);
if (_handle == INVALID_HANDLE_VALUE)
return false;
Convert_WIN32_FIND_DATA_to_FileInfo(fd, fi);
}
else
#endif
{
WIN32_FIND_DATAW fd;
IF_USE_MAIN_PATH
_handle = ::FindFirstFileW(fs2us(path), &fd);
#ifdef WIN_LONG_PATH
if (_handle == INVALID_HANDLE_VALUE && USE_SUPER_PATH)
{
UString superPath;
if (GetSuperPath(path, superPath, USE_MAIN_PATH))
_handle = ::FindFirstFileW(superPath, &fd);
}
#endif
if (_handle == INVALID_HANDLE_VALUE)
return false;
Convert_WIN32_FIND_DATA_to_FileInfo(fd, fi);
}
return true;
}
bool CFindFile::FindNext(CFileInfo &fi)
{
#ifndef _UNICODE
if (!g_IsNT)
{
WIN32_FIND_DATAA fd;
if (!::FindNextFileA(_handle, &fd))
return false;
Convert_WIN32_FIND_DATA_to_FileInfo(fd, fi);
}
else
#endif
{
WIN32_FIND_DATAW fd;
if (!::FindNextFileW(_handle, &fd))
return false;
Convert_WIN32_FIND_DATA_to_FileInfo(fd, fi);
}
return true;
}
#if defined(_WIN32) && !defined(UNDER_CE)
////////////////////////////////
// AltStreams
static FindFirstStreamW_Ptr g_FindFirstStreamW;
static FindNextStreamW_Ptr g_FindNextStreamW;
static struct CFindStreamLoader
{
CFindStreamLoader()
{
HMODULE hm = ::GetModuleHandleA("kernel32.dll");
g_FindFirstStreamW = (FindFirstStreamW_Ptr)(void *)::GetProcAddress(hm, "FindFirstStreamW");
g_FindNextStreamW = (FindNextStreamW_Ptr)(void *)::GetProcAddress(hm, "FindNextStreamW");
}
} g_FindStreamLoader;
bool CStreamInfo::IsMainStream() const throw()
{
return StringsAreEqualNoCase_Ascii(Name, "::$DATA");
};
UString CStreamInfo::GetReducedName() const
{
// remove ":$DATA" postfix, but keep postfix, if Name is "::$DATA"
UString s (Name);
if (s.Len() > 6 + 1 && StringsAreEqualNoCase_Ascii(s.RightPtr(6), ":$DATA"))
s.DeleteFrom(s.Len() - 6);
return s;
}
/*
UString CStreamInfo::GetReducedName2() const
{
UString s = GetReducedName();
if (!s.IsEmpty() && s[0] == ':')
s.Delete(0);
return s;
}
*/
static void Convert_WIN32_FIND_STREAM_DATA_to_StreamInfo(const MY_WIN32_FIND_STREAM_DATA &sd, CStreamInfo &si)
{
si.Size = (UInt64)sd.StreamSize.QuadPart;
si.Name = sd.cStreamName;
}
/*
WinXP-64 FindFirstStream():
"" - ERROR_PATH_NOT_FOUND
folder\ - OK
folder - OK
\ - OK
c:\ - OK
c: - OK, if current dir is ROOT ( c:\ )
c: - OK, if current dir is NOT ROOT ( c:\folder )
\\Server\Share - OK
\\Server\Share\ - OK
\\ - ERROR_INVALID_NAME
\\Server - ERROR_INVALID_NAME
\\Server\ - ERROR_INVALID_NAME
*/
bool CFindStream::FindFirst(CFSTR path, CStreamInfo &si)
{
if (!Close())
return false;
if (!g_FindFirstStreamW)
{
::SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return false;
}
{
MY_WIN32_FIND_STREAM_DATA sd;
SetLastError(0);
IF_USE_MAIN_PATH
_handle = g_FindFirstStreamW(fs2us(path), My_FindStreamInfoStandard, &sd, 0);
if (_handle == INVALID_HANDLE_VALUE)
{
if (::GetLastError() == ERROR_HANDLE_EOF)
return false;
// long name can be tricky for path like ".\dirName".
#ifdef WIN_LONG_PATH
if (USE_SUPER_PATH)
{
UString superPath;
if (GetSuperPath(path, superPath, USE_MAIN_PATH))
_handle = g_FindFirstStreamW(superPath, My_FindStreamInfoStandard, &sd, 0);
}
#endif
}
if (_handle == INVALID_HANDLE_VALUE)
return false;
Convert_WIN32_FIND_STREAM_DATA_to_StreamInfo(sd, si);
}
return true;
}
bool CFindStream::FindNext(CStreamInfo &si)
{
if (!g_FindNextStreamW)
{
::SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return false;
}
{
MY_WIN32_FIND_STREAM_DATA sd;
if (!g_FindNextStreamW(_handle, &sd))
return false;
Convert_WIN32_FIND_STREAM_DATA_to_StreamInfo(sd, si);
}
return true;
}
bool CStreamEnumerator::Next(CStreamInfo &si, bool &found)
{
bool res;
if (_find.IsHandleAllocated())
res = _find.FindNext(si);
else
res = _find.FindFirst(_filePath, si);
if (res)
{
found = true;
return true;
}
found = false;
return (::GetLastError() == ERROR_HANDLE_EOF);
}
#endif
/*
WinXP-64 GetFileAttributes():
If the function fails, it returns INVALID_FILE_ATTRIBUTES and use GetLastError() to get error code
\ - OK
C:\ - OK, if there is such drive,
D:\ - ERROR_PATH_NOT_FOUND, if there is no such drive,
C:\folder - OK
C:\folder\ - OK
C:\folderBad - ERROR_FILE_NOT_FOUND
\\Server\BadShare - ERROR_BAD_NETPATH
\\Server\Share - WORKS OK, but MSDN says:
GetFileAttributes for a network share, the function fails, and GetLastError
returns ERROR_BAD_NETPATH. You must specify a path to a subfolder on that share.
*/
DWORD GetFileAttrib(CFSTR path)
{
#ifndef _UNICODE
if (!g_IsNT)
return ::GetFileAttributes(fs2fas(path));
else
#endif
{
IF_USE_MAIN_PATH
{
DWORD dw = ::GetFileAttributesW(fs2us(path));
if (dw != INVALID_FILE_ATTRIBUTES)
return dw;
}
#ifdef WIN_LONG_PATH
if (USE_SUPER_PATH)
{
UString superPath;
if (GetSuperPath(path, superPath, USE_MAIN_PATH))
return ::GetFileAttributesW(superPath);
}
#endif
return INVALID_FILE_ATTRIBUTES;
}
}
/* if path is "c:" or "c::" then CFileInfo::Find() returns name of current folder for that disk
so instead of absolute path we have relative path in Name. That is not good in some calls */
/* In CFileInfo::Find() we want to support same names for alt streams as in CreateFile(). */
/* CFileInfo::Find()
We alow the following paths (as FindFirstFile):
C:\folder
c: - if current dir is NOT ROOT ( c:\folder )
also we support paths that are not supported by FindFirstFile:
\
\\.\c:
c:\ - Name will be without tail slash ( c: )
\\?\c:\ - Name will be without tail slash ( c: )
\\Server\Share
\\?\UNC\Server\Share
c:\folder:stream - Name = folder:stream
c:\:stream - Name = :stream
c::stream - Name = c::stream
*/
bool CFileInfo::Find(CFSTR path, bool followLink)
{
#ifdef SUPPORT_DEVICE_FILE
if (IsDevicePath(path))
{
ClearBase();
Name = path + 4;
IsDevice = true;
if (NName::IsDrivePath2(path + 4) && path[6] == 0)
{
FChar drive[4] = { path[4], ':', '\\', 0 };
UInt64 clusterSize, totalSize, freeSize;
if (NSystem::MyGetDiskFreeSpace(drive, clusterSize, totalSize, freeSize))
{
Size = totalSize;
return true;
}
}
NIO::CInFile inFile;
// ::OutputDebugStringW(path);
if (!inFile.Open(path))
return false;
// ::OutputDebugStringW(L"---");
if (inFile.SizeDefined)
Size = inFile.Size;
return true;
}
#endif
#if defined(_WIN32) && !defined(UNDER_CE)
int colonPos = FindAltStreamColon(path);
if (colonPos >= 0 && path[(unsigned)colonPos + 1] != 0)
{
UString streamName = fs2us(path + (unsigned)colonPos);
FString filePath (path);
filePath.DeleteFrom((unsigned)colonPos);
/* we allow both cases:
name:stream
name:stream:$DATA
*/
const unsigned kPostfixSize = 6;
if (streamName.Len() <= kPostfixSize
|| !StringsAreEqualNoCase_Ascii(streamName.RightPtr(kPostfixSize), ":$DATA"))
streamName += ":$DATA";
bool isOk = true;
if (IsDrivePath2(filePath) &&
(colonPos == 2 || (colonPos == 3 && filePath[2] == '\\')))
{
// FindFirstFile doesn't work for "c:\" and for "c:" (if current dir is ROOT)
ClearBase();
Name.Empty();
if (colonPos == 2)
Name = filePath;
}
else
isOk = Find(filePath, followLink); // check it (followLink)
if (isOk)
{
Attrib &= ~(DWORD)(FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT);
Size = 0;
CStreamEnumerator enumerator(filePath);
for (;;)
{
CStreamInfo si;
bool found;
if (!enumerator.Next(si, found))
return false;
if (!found)
{
::SetLastError(ERROR_FILE_NOT_FOUND);
return false;
}
if (si.Name.IsEqualTo_NoCase(streamName))
{
// we delete postfix, if alt stream name is not "::$DATA"
if (si.Name.Len() > kPostfixSize + 1)
si.Name.DeleteFrom(si.Name.Len() - kPostfixSize);
Name += us2fs(si.Name);
Size = si.Size;
IsAltStream = true;
return true;
}
}
}
}
#endif
CFindFile finder;
#if defined(_WIN32) && !defined(UNDER_CE)
{
/*
DWORD lastError = GetLastError();
if (lastError == ERROR_FILE_NOT_FOUND
|| lastError == ERROR_BAD_NETPATH // XP64: "\\Server\Share"
|| lastError == ERROR_BAD_NET_NAME // Win7: "\\Server\Share"
|| lastError == ERROR_INVALID_NAME // XP64: "\\?\UNC\Server\Share"
|| lastError == ERROR_BAD_PATHNAME // Win7: "\\?\UNC\Server\Share"
)
*/
unsigned rootSize = 0;
if (IsSuperPath(path))
rootSize = kSuperPathPrefixSize;
if (NName::IsDrivePath(path + rootSize) && path[rootSize + 3] == 0)
{
DWORD attrib = GetFileAttrib(path);
if (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
ClearBase();
Attrib = attrib;
Name = path + rootSize;
Name.DeleteFrom(2);
if (!Fill_From_ByHandleFileInfo(path))
{
}
return true;
}
}
else if (IS_PATH_SEPAR(path[0]))
{
if (path[1] == 0)
{
DWORD attrib = GetFileAttrib(path);
if (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
ClearBase();
Name.Empty();
Attrib = attrib;
return true;
}
}
else
{
const unsigned prefixSize = GetNetworkServerPrefixSize(path);
if (prefixSize > 0 && path[prefixSize] != 0)
{
if (NName::FindSepar(path + prefixSize) < 0)
{
if (Fill_From_ByHandleFileInfo(path))
{
Name = path + prefixSize;
return true;
}
FString s (path);
s.Add_PathSepar();
s += '*'; // CHAR_ANY_MASK
bool isOK = false;
if (finder.FindFirst(s, *this))
{
if (Name == FTEXT("."))
{
Name = path + prefixSize;
return true;
}
isOK = true;
/* if "\\server\share" maps to root folder "d:\", there is no "." item.
But it's possible that there are another items */
}
{
DWORD attrib = GetFileAttrib(path);
if (isOK || (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY) != 0))
{
ClearBase();
if (attrib != INVALID_FILE_ATTRIBUTES)
Attrib = attrib;
else
SetAsDir();
Name = path + prefixSize;
return true;
}
}
// ::SetLastError(lastError);
}
}
}
}
}
#endif
bool res = finder.FindFirst(path, *this);
if (!followLink
|| !res
|| !HasReparsePoint())
return res;
// return FollowReparse(path, IsDir());
return Fill_From_ByHandleFileInfo(path);
}
bool CFileInfo::Fill_From_ByHandleFileInfo(CFSTR path)
{
BY_HANDLE_FILE_INFORMATION info;
if (!NIO::CFileBase::GetFileInformation(path, &info))
return false;
{
Size = (((UInt64)info.nFileSizeHigh) << 32) + info.nFileSizeLow;
CTime = info.ftCreationTime;
ATime = info.ftLastAccessTime;
MTime = info.ftLastWriteTime;
Attrib = info.dwFileAttributes;
return true;
}
}
/*
bool CFileInfo::FollowReparse(CFSTR path, bool isDir)
{
if (isDir)
{
FString prefix = path;
prefix.Add_PathSepar();
// "folder/." refers to folder itself. So we can't use that path
// we must use enumerator and search "." item
CEnumerator enumerator;
enumerator.SetDirPrefix(prefix);
for (;;)
{
CFileInfo fi;
if (!enumerator.NextAny(fi))
break;
if (fi.Name.IsEqualTo_Ascii_NoCase("."))
{
// we can copy preperies;
CTime = fi.CTime;
ATime = fi.ATime;
MTime = fi.MTime;
Attrib = fi.Attrib;
Size = fi.Size;
return true;
}
break;
}
// LastError(lastError);
return false;
}
{
NIO::CInFile inFile;
if (inFile.Open(path))
{
BY_HANDLE_FILE_INFORMATION info;
if (inFile.GetFileInformation(&info))
{
ClearBase();
Size = (((UInt64)info.nFileSizeHigh) << 32) + info.nFileSizeLow;
CTime = info.ftCreationTime;
ATime = info.ftLastAccessTime;
MTime = info.ftLastWriteTime;
Attrib = info.dwFileAttributes;
return true;
}
}
return false;
}
}
*/
bool DoesFileExist_Raw(CFSTR name)
{
CFileInfo fi;
return fi.Find(name) && !fi.IsDir();
}
bool DoesFileExist_FollowLink(CFSTR name)
{
CFileInfo fi;
return fi.Find_FollowLink(name) && !fi.IsDir();
}
bool DoesDirExist(CFSTR name, bool followLink)
{
CFileInfo fi;
return fi.Find(name, followLink) && fi.IsDir();
}
bool DoesFileOrDirExist(CFSTR name)
{
CFileInfo fi;
return fi.Find(name);
}
void CEnumerator::SetDirPrefix(const FString &dirPrefix)
{
_wildcard = dirPrefix;
_wildcard += '*';
}
bool CEnumerator::NextAny(CFileInfo &fi)
{
if (_findFile.IsHandleAllocated())
return _findFile.FindNext(fi);
else
return _findFile.FindFirst(_wildcard, fi);
}
bool CEnumerator::Next(CFileInfo &fi)
{
for (;;)
{
if (!NextAny(fi))
return false;
if (!fi.IsDots())
return true;
}
}
bool CEnumerator::Next(CFileInfo &fi, bool &found)
{
/*
for (;;)
{
if (!NextAny(fi))
break;
if (!fi.IsDots())
{
found = true;
return true;
}
}
*/
if (Next(fi))
{
found = true;
return true;
}
found = false;
DWORD lastError = ::GetLastError();
if (_findFile.IsHandleAllocated())
return (lastError == ERROR_NO_MORE_FILES);
// we support the case for empty root folder: FindFirstFile("c:\\*") returns ERROR_FILE_NOT_FOUND
if (lastError == ERROR_FILE_NOT_FOUND)
return true;
if (lastError == ERROR_ACCESS_DENIED)
{
// here we show inaccessible root system folder as empty folder to eliminate redundant user warnings
const char *s = "System Volume Information" STRING_PATH_SEPARATOR "*";
const int len = (int)strlen(s);
const int delta = (int)_wildcard.Len() - len;
if (delta == 0 || (delta > 0 && IS_PATH_SEPAR(_wildcard[(unsigned)delta - 1])))
if (StringsAreEqual_Ascii(_wildcard.Ptr((unsigned)delta), s))
return true;
}
return false;
}
////////////////////////////////
// CFindChangeNotification
// FindFirstChangeNotification can return 0. MSDN doesn't tell about it.
bool CFindChangeNotification::Close() throw()
{
if (!IsHandleAllocated())
return true;
if (!::FindCloseChangeNotification(_handle))
return false;
_handle = INVALID_HANDLE_VALUE;
return true;
}
HANDLE CFindChangeNotification::FindFirst(CFSTR path, bool watchSubtree, DWORD notifyFilter)
{
#ifndef _UNICODE
if (!g_IsNT)
_handle = ::FindFirstChangeNotification(fs2fas(path), BoolToBOOL(watchSubtree), notifyFilter);
else
#endif
{
IF_USE_MAIN_PATH
_handle = ::FindFirstChangeNotificationW(fs2us(path), BoolToBOOL(watchSubtree), notifyFilter);
#ifdef WIN_LONG_PATH
if (!IsHandleAllocated())
{
UString superPath;
if (GetSuperPath(path, superPath, USE_MAIN_PATH))
_handle = ::FindFirstChangeNotificationW(superPath, BoolToBOOL(watchSubtree), notifyFilter);
}
#endif
}
return _handle;
}
#ifndef UNDER_CE
bool MyGetLogicalDriveStrings(CObjectVector<FString> &driveStrings)
{
driveStrings.Clear();
#ifndef _UNICODE
if (!g_IsNT)
{
driveStrings.Clear();
UINT32 size = GetLogicalDriveStrings(0, NULL);
if (size == 0)
return false;
CObjArray<char> buf(size);
UINT32 newSize = GetLogicalDriveStrings(size, buf);
if (newSize == 0 || newSize > size)
return false;
AString s;
UINT32 prev = 0;
for (UINT32 i = 0; i < newSize; i++)
{
if (buf[i] == 0)
{
s = buf + prev;
prev = i + 1;
driveStrings.Add(fas2fs(s));
}
}
return prev == newSize;
}
else
#endif
{
UINT32 size = GetLogicalDriveStringsW(0, NULL);
if (size == 0)
return false;
CObjArray<wchar_t> buf(size);
UINT32 newSize = GetLogicalDriveStringsW(size, buf);
if (newSize == 0 || newSize > size)
return false;
UString s;
UINT32 prev = 0;
for (UINT32 i = 0; i < newSize; i++)
{
if (buf[i] == 0)
{
s = buf + prev;
prev = i + 1;
driveStrings.Add(us2fs(s));
}
}
return prev == newSize;
}
}
#endif // UNDER_CE
#else // _WIN32
// ---------- POSIX ----------
static int MY__lstat(CFSTR path, struct stat *st, bool followLink)
{
memset(st, 0, sizeof(*st));
int res;
// #ifdef ENV_HAVE_LSTAT
if (/* global_use_lstat && */ !followLink)
{
// printf("\nlstat\n");
res = lstat(path, st);
}
else
// #endif
{
// printf("\nstat\n");
res = stat(path, st);
}
/*
printf("\nres = %d\n", res);
printf("\n st_dev = %lld \n", (long long)(st->st_dev));
printf("\n st_ino = %lld \n", (long long)(st->st_ino));
printf("\n st_mode = %lld \n", (long long)(st->st_mode));
printf("\n st_nlink = %lld \n", (long long)(st->st_nlink));
printf("\n st_uid = %lld \n", (long long)(st->st_uid));
printf("\n st_gid = %lld \n", (long long)(st->st_gid));
printf("\n st_size = %lld \n", (long long)(st->st_size));
printf("\n st_blksize = %lld \n", (long long)(st->st_blksize));
printf("\n st_blocks = %lld \n", (long long)(st->st_blocks));
*/
return res;
}
static const char *Get_Name_from_Path(CFSTR path) throw()
{
size_t len = strlen(path);
if (len == 0)
return path;
const char *p = path + len - 1;
{
if (p == path)
return path;
p--;
}
for (;;)
{
char c = *p;
if (IS_PATH_SEPAR(c))
return p + 1;
if (p == path)
return path;
p--;
}
}
void timespec_To_FILETIME(const MY_ST_TIMESPEC &ts, FILETIME &ft)
{
UInt64 v = NTime::UnixTime64ToFileTime64(ts.tv_sec) + ((UInt64)ts.tv_nsec / 100);
ft.dwLowDateTime = (DWORD)v;
ft.dwHighDateTime = (DWORD)(v >> 32);
}
UInt32 Get_WinAttribPosix_From_PosixMode(UInt32 mode)
{
UInt32 attrib = S_ISDIR(mode) ?
FILE_ATTRIBUTE_DIRECTORY :
FILE_ATTRIBUTE_ARCHIVE;
if ((mode & 0222) == 0) // S_IWUSR in p7zip
attrib |= FILE_ATTRIBUTE_READONLY;
return attrib | FILE_ATTRIBUTE_UNIX_EXTENSION | ((mode & 0xFFFF) << 16);
}
/*
UInt32 Get_WinAttrib_From_stat(const struct stat &st)
{
UInt32 attrib = S_ISDIR(st.st_mode) ?
FILE_ATTRIBUTE_DIRECTORY :
FILE_ATTRIBUTE_ARCHIVE;
if ((st.st_mode & 0222) == 0) // check it !!!
attrib |= FILE_ATTRIBUTE_READONLY;
attrib |= FILE_ATTRIBUTE_UNIX_EXTENSION + ((st.st_mode & 0xFFFF) << 16);
return attrib;
}
*/
void CFileInfo::SetFrom_stat(const struct stat &st)
{
IsDevice = false;
if (S_ISDIR(st.st_mode))
{
Size = 0;
}
else
{
Size = (UInt64)st.st_size; // for a symbolic link, size = size of filename
}
Attrib = Get_WinAttribPosix_From_PosixMode(st.st_mode);
// NTime::UnixTimeToFileTime(st.st_ctime, CTime);
// NTime::UnixTimeToFileTime(st.st_mtime, MTime);
// NTime::UnixTimeToFileTime(st.st_atime, ATime);
#ifdef __APPLE__
// #ifdef _DARWIN_FEATURE_64_BIT_INODE
/*
here we can use birthtime instead of st_ctimespec.
but we use st_ctimespec for compatibility with previous versions and p7zip.
st_birthtimespec in OSX
st_birthtim : at FreeBSD, NetBSD
*/
// timespec_To_FILETIME(st.st_birthtimespec, CTime);
// #else
timespec_To_FILETIME(st.st_ctimespec, CTime);
// #endif
timespec_To_FILETIME(st.st_mtimespec, MTime);
timespec_To_FILETIME(st.st_atimespec, ATime);
#else
timespec_To_FILETIME(st.st_ctim, CTime);
timespec_To_FILETIME(st.st_mtim, MTime);
timespec_To_FILETIME(st.st_atim, ATime);
#endif
dev = st.st_dev;
ino = st.st_ino;
nlink = st.st_nlink;
mode = st.st_mode;
}
bool CFileInfo::Find_DontFill_Name(CFSTR path, bool followLink)
{
struct stat st;
if (MY__lstat(path, &st, followLink) != 0)
return false;
SetFrom_stat(st);
return true;
}
bool CFileInfo::Find(CFSTR path, bool followLink)
{
// printf("\nCEnumerator::Find() name = %s\n", path);
if (!Find_DontFill_Name(path, followLink))
return false;
// printf("\nOK\n");
Name = Get_Name_from_Path(path);
if (!Name.IsEmpty())
{
char c = Name.Back();
if (IS_PATH_SEPAR(c))
Name.DeleteBack();
}
return true;
}
bool DoesFileExist_Raw(CFSTR name)
{
// FIXME for symbolic links.
struct stat st;
if (MY__lstat(name, &st, false) != 0)
return false;
return !S_ISDIR(st.st_mode);
}
bool DoesFileExist_FollowLink(CFSTR name)
{
// FIXME for symbolic links.
struct stat st;
if (MY__lstat(name, &st, true) != 0)
return false;
return !S_ISDIR(st.st_mode);
}
bool DoesDirExist(CFSTR name, bool followLink)
{
struct stat st;
if (MY__lstat(name, &st, followLink) != 0)
return false;
return S_ISDIR(st.st_mode);
}
bool DoesFileOrDirExist(CFSTR name)
{
struct stat st;
if (MY__lstat(name, &st, false) != 0)
return false;
return true;
}
CEnumerator::~CEnumerator()
{
if (_dir)
closedir(_dir);
}
void CEnumerator::SetDirPrefix(const FString &dirPrefix)
{
_wildcard = dirPrefix;
}
bool CDirEntry::IsDots() const throw()
{
/* some systems (like CentOS 7.x on XFS) have (Type == DT_UNKNOWN)
we can call fstatat() for that case, but we use only (Name) check here */
#if !defined(_AIX)
if (Type != DT_DIR && Type != DT_UNKNOWN)
return false;
#endif
return Name.Len() != 0
&& Name.Len() <= 2
&& Name[0] == '.'
&& (Name.Len() == 1 || Name[1] == '.');
}
bool CEnumerator::NextAny(CDirEntry &fi, bool &found)
{
found = false;
if (!_dir)
{
const char *w = "./";
if (!_wildcard.IsEmpty())
w = _wildcard.Ptr();
_dir = ::opendir((const char *)w);
if (_dir == NULL)
return false;
}
// To distinguish end of stream from an error, we must set errno to zero before readdir()
errno = 0;
struct dirent *de = readdir(_dir);
if (!de)
{
if (errno == 0)
return true; // it's end of stream, and we report it with (found = false)
// it's real error
return false;
}
fi.iNode = de->d_ino;
#if !defined(_AIX)
fi.Type = de->d_type;
/* some systems (like CentOS 7.x on XFS) have (Type == DT_UNKNOWN)
we can set (Type) from fstatat() in that case.
But (Type) is not too important. So we don't set it here with slow fstatat() */
/*
// fi.Type = DT_UNKNOWN; // for debug
if (fi.Type == DT_UNKNOWN)
{
struct stat st;
if (fstatat(dirfd(_dir), de->d_name, &st, AT_SYMLINK_NOFOLLOW) == 0)
if (S_ISDIR(st.st_mode))
fi.Type = DT_DIR;
}
*/
#endif
/*
if (de->d_type == DT_DIR)
fi.Attrib = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_UNIX_EXTENSION | ((UInt32)(S_IFDIR) << 16);
else if (de->d_type < 16)
fi.Attrib = FILE_ATTRIBUTE_UNIX_EXTENSION | ((UInt32)(de->d_type) << (16 + 12));
*/
fi.Name = de->d_name;
/*
printf("\nCEnumerator::NextAny; len = %d %s \n", (int)fi.Name.Len(), fi.Name.Ptr());
for (unsigned i = 0; i < fi.Name.Len(); i++)
printf (" %02x", (unsigned)(Byte)de->d_name[i]);
printf("\n");
*/
found = true;
return true;
}
bool CEnumerator::Next(CDirEntry &fi, bool &found)
{
// printf("\nCEnumerator::Next()\n");
// PrintName("Next", "");
for (;;)
{
if (!NextAny(fi, found))
return false;
if (!found)
return true;
if (!fi.IsDots())
{
/*
if (!NeedFullStat)
return true;
// we silently skip error file here - it can be wrong link item
if (fi.Find_DontFill_Name(path))
return true;
*/
return true;
}
}
}
/*
bool CEnumerator::Next(CDirEntry &fileInfo, bool &found)
{
bool found;
if (!Next(fi, found))
return false;
return found;
}
*/
bool CEnumerator::Fill_FileInfo(const CDirEntry &de, CFileInfo &fileInfo, bool followLink) const
{
// printf("\nCEnumerator::Fill_FileInfo()\n");
struct stat st;
// probably it's OK to use fstatat() even if it changes file position dirfd(_dir)
int res = fstatat(dirfd(_dir), de.Name, &st, followLink ? 0 : AT_SYMLINK_NOFOLLOW);
// if fstatat() is not supported, we can use stat() / lstat()
/*
const FString path = _wildcard + s;
int res = MY__lstat(path, &st, followLink);
*/
if (res != 0)
return false;
fileInfo.SetFrom_stat(st);
fileInfo.Name = de.Name;
return true;
}
#endif // _WIN32
}}}
| 23.855994 | 110 | 0.616194 | fooziex |
5921bf1e86faca66e55aa79bab604ed77ed19a64 | 1,414 | cpp | C++ | src/QtTracker/treeitem.cpp | spayne/vrtracker | 53249748c0c4d0e3a1a9d9c200ed010600a4e27e | [
"MIT"
] | null | null | null | src/QtTracker/treeitem.cpp | spayne/vrtracker | 53249748c0c4d0e3a1a9d9c200ed010600a4e27e | [
"MIT"
] | null | null | null | src/QtTracker/treeitem.cpp | spayne/vrtracker | 53249748c0c4d0e3a1a9d9c200ed010600a4e27e | [
"MIT"
] | null | null | null |
/*
treeitem.cpp
A container for items of data supplied by the simple tree model.
*/
#include <QStringList>
#include "treeitem.h"
//! [0]
TreeItem::TreeItem(const QList<QVariant> &data, TreeItem *parent)
{
m_parentItem = parent;
m_itemData = data;
}
//! [0]
//! [1]
TreeItem::~TreeItem()
{
qDeleteAll(m_childItems);
}
//! [1]
//! [2]
void TreeItem::appendChild(TreeItem *item)
{
m_childItems.push_back(item);
}
//! [2]
//! [3]
TreeItem *TreeItem::child(int row)
{
if (row >= 0)
return m_childItems[row];
else
return nullptr;
}
//! [3]
//! [4]
int TreeItem::childCount() const
{
return m_childItems.size();
}
//! [4]
//! [5]
int TreeItem::columnCount() const
{
// QVariant is a union. these model
// view things require values as QVariants I think
//
//QList<QVariant> m_itemData;
return m_itemData.count();
}
//! [5]
//! [6]
QVariant TreeItem::data(int column) const
{
return m_itemData.value(column);
}
//! [6]
//! [7]
TreeItem *TreeItem::parentItem()
{
return m_parentItem;
}
//! [7]
//! [8]
int TreeItem::row() const
{
if (m_parentItem)
{
int index = -1;
for (int i = 0; i < m_parentItem->m_childItems.size(); i++)
{
if (m_parentItem->m_childItems[i] == this)
{
index = i;
break;
}
}
}
return 0;
}
//! [8]
| 14.729167 | 69 | 0.556577 | spayne |
5923538aa2b82a7c660cdb1022bd0d96c12cb472 | 32,201 | cc | C++ | lib/poisson/poisson.cc | usmanianas/saras_latest | c9eb0dd800076a5d92d04c96a14031739998bb60 | [
"BSD-3-Clause"
] | null | null | null | lib/poisson/poisson.cc | usmanianas/saras_latest | c9eb0dd800076a5d92d04c96a14031739998bb60 | [
"BSD-3-Clause"
] | null | null | null | lib/poisson/poisson.cc | usmanianas/saras_latest | c9eb0dd800076a5d92d04c96a14031739998bb60 | [
"BSD-3-Clause"
] | null | null | null | /********************************************************************************************************************************************
* Saras
*
* Copyright (C) 2019, Mahendra K. Verma
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder 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.
*
********************************************************************************************************************************************
*/
/*! \file poisson.cc
*
* \brief Definitions for functions of class poisson
* \sa poisson.h
* \author Roshan Samuel
* \date Nov 2019
* \copyright New BSD License
*
********************************************************************************************************************************************
*/
#include "poisson.h"
/**
********************************************************************************************************************************************
* \brief Constructor of the base poisson class
*
* The short base constructor of the poisson class merely assigns the const references to the grid and parser
* class instances being used in the solver.
* Moreover, it resizes and populates a local array of multi-grid sizes as used in the grid class.
* An array of strides to be used at different V-cycle levels is also generated and stored.
* Finally, the maximum allowable number of iterations for the Jacobi iterative solver being used at the
* coarsest mesh is set as \f$ N_{max} = N_x \times N_y \times N_z \f$, where \f$N_x\f$, \f$N_y\f$ and \f$N_z\f$
* are the number of grid points in the collocated grid at the local sub-domains along x, y and z directions
* respectively.
*
* \param mesh is a const reference to the global data contained in the grid class
* \param solParam is a const reference to the user-set parameters contained in the parser class
********************************************************************************************************************************************
*/
poisson::poisson(const grid &mesh, const parser &solParam): mesh(mesh), inputParams(solParam) {
int maxIndex = 15;
all = blitz::Range::all();
mgSizeArray.resize(maxIndex);
for (int i=0; i < maxIndex; i++) {
mgSizeArray(i) = int(pow(2, i)) + 1;
}
mgSizeArray(0) = 1;
strideValues.resize(inputParams.vcDepth + 1);
for (int i=0; i<=inputParams.vcDepth; i++) {
strideValues(i) = int(pow(2, i));
}
#ifdef TIME_RUN
smothTimeComp = 0.0;
smothTimeTran = 0.0;
#endif
}
/**
********************************************************************************************************************************************
* \brief The core, publicly accessible function of poisson to compute the solution for the Poisson equation
*
* The function calls the V-cycle as many times as set by the user.
* Before doing so, the input data is transferred into the data-structures used by the poisson class to
* perform restrictions and prolongations without copying.
* Finally, the computed solution is transferred back from the internal data-structures back into the
* scalar field supplied by the calling function.
*
* \param inFn is a pointer to the plain scalar field (cell-centered) into which the computed soltuion must be transferred
* \param rhs is a const reference to the plain scalar field (cell-centered) which contains the RHS for the Poisson equation to solve
********************************************************************************************************************************************
*/
void poisson::mgSolve(plainsf &inFn, const plainsf &rhs) {
#ifndef TEST_POISSON
real prevResidual = 0.0;
#endif
vLevel = 0;
for (int i=0; i <= inputParams.vcDepth; i++) {
pressureData(i) = 0.0;
residualData(i) = 0.0;
smoothedPres(i) = 0.0;
}
// TRANSFER DATA FROM THE INPUT SCALAR FIELDS INTO THE DATA-STRUCTURES USED BY poisson
residualData(0)(stagCore(0)) = rhs.F(stagCore(0));
pressureData(0)(stagCore(0)) = inFn.F(stagCore(0));
updatePads(residualData);
updatePads(pressureData);
#ifndef TEST_POISSON
// TO MAKE THE PROBLEM WELL-POSED (WHEN USING NEUMANN BC ONLY), SUBTRACT THE MEAN OF THE RHS FROM THE RHS
real localMean = blitz::mean(residualData(0));
real globalAvg = 0.0;
MPI_Allreduce(&localMean, &globalAvg, 1, MPI_FP_REAL, MPI_SUM, MPI_COMM_WORLD);
globalAvg /= mesh.rankData.nProc;
residualData(0) -= globalAvg;
#endif
// PERFORM V-CYCLES AS MANY TIMES AS REQUIRED
for (int i=0; i<inputParams.vcCount; i++) {
vCycle();
real mgResidual = computeError(inputParams.resType);
#ifdef TEST_POISSON
blitz::Array<real, 3> pAnalytic, tempArray;
pAnalytic.resize(blitz::TinyVector<int, 3>(stagCore(0).ubound() + 1));
pAnalytic = 0.0;
#ifdef PLANAR
real xDist, zDist;
for (int i=0; i<=stagCore(0).ubound(0); ++i) {
xDist = mesh.xStaggr(i) - 0.5;
for (int k=0; k<=stagCore(0).ubound(2); ++k) {
zDist = mesh.zStaggr(k) - 0.5;
pAnalytic(i, 0, k) = (xDist*xDist + zDist*zDist)/4.0;
}
}
#else
real xDist, yDist, zDist;
for (int i=0; i<=stagCore(0).ubound(0); ++i) {
xDist = mesh.xStaggr(i) - 0.5;
for (int j=0; j<=stagCore(0).ubound(1); ++j) {
yDist = mesh.yStaggr(j) - 0.5;
for (int k=0; k<=stagCore(0).ubound(2); ++k) {
zDist = mesh.zStaggr(k) - 0.5;
pAnalytic(i, j, k) = (xDist*xDist + yDist*yDist + zDist*zDist)/6.0;
}
}
}
#endif
tempArray.resize(pAnalytic.shape());
tempArray = pAnalytic - pressureData(0)(stagCore(0));
real gloMax = 0.0;
real locMax = blitz::max(fabs(tempArray));
MPI_Allreduce(&locMax, &gloMax, 1, MPI_FP_REAL, MPI_MAX, MPI_COMM_WORLD);
if (mesh.rankData.rank == 0) {
std::cout << std::endl;
std::cout << "Maximum absolute deviation from analytic solution is: " << std::scientific << std::setprecision(3) << gloMax << std::endl;
}
#endif
if (inputParams.printResidual) {
#ifdef TEST_POISSON
if (mesh.rankData.rank == 0) std::cout << std::endl << "Residual after V Cycle " << i << " is " << std::scientific << std::setprecision(3) << mgResidual << std::endl;
#else
if (mesh.rankData.rank == 0) std::cout << std::endl << "Residual after V Cycle " << i << " is " << mgResidual << std::endl;
#endif
}
#ifndef TEST_POISSON
if (fabs(prevResidual - mgResidual) < inputParams.mgTolerance) break;
prevResidual = mgResidual;
#endif
}
// RETURN CALCULATED PRESSURE DATA
inFn.F(stagFull(0)) = pressureData(0)(stagFull(0));
};
/**
********************************************************************************************************************************************
* \brief Function to perform one loop of V-cycle
*
* The V-cycle of restrictions, prolongations and smoothings are performed within this function.
* First the input data contained in \ref pressureData is smoothed, after which the residual is computed and stored
* in the \ref residualData array.
* The restrictions, smoothing, and prolongations are performed on these two arrays subsequently.
********************************************************************************************************************************************
*/
void poisson::vCycle() {
/*
* OUTLINE OF THE MULTI-GRID V-CYCLE
* 1) Starting at finest grid, perform N Gauss-Siedel pre-smoothing iterations to solve for the solution, Ax=b.
* 2) Compute the residual r=b-Ax, and restrict it to a coarser level.
* 3) Perform N Gauss-Siedel pre-smoothing iterations to solve for the error, Ae=r.
* 4) Repeat steps 2-3 until you reach the coarsest grid level.
* 5) Perform 2N (pre + post) Gauss-Siedel smoothing iterations to solve for the error 'e'.
* 6) Prolong the error 'e' to the next finer level.
* 7) Perform N post-smoothing iterations.
* 8) Repeat steps 6-7 until the finest grid is reached.
* 9) Add error 'e' to the solution 'x' and perform N post-smoothing iterations.
* 10) End of one V-cycle - check for convergence by computing the normalized residual: r_normalized = ||b-Ax||/||b||.
*/
vLevel = 0;
// When using Dirichlet BC, the residue, r, has homogeneous BC (r=0 at boundary) and only the original solution, x, has non-homogeneous BC.
// Since pre-smoothing is performed on x, non-homogeneous (non-zero) Dirichlet BC is imposed
zeroBC = false;
// Step 1) Pre-smoothing iterations of Ax = b
smooth(inputParams.preSmooth);
//int nStart = int(pow(2, (5-vLevel)) - 1);
//std::cout << pressureData(vLevel)(blitz::Range(nStart, blitz::toEnd), blitz::Range(nStart, blitz::toEnd), blitz::Range(nStart, blitz::toEnd)) << std::endl;
//std::cout << pressureData(vLevel)(blitz::Range(blitz::fromStart, 1), blitz::Range(blitz::fromStart, 1), blitz::Range(blitz::fromStart, 1)) << std::endl;
// From now on, homogeneous Dirichlet BCs are used till end of V-Cycle
zeroBC = true;
// RESTRICTION OPERATIONS DOWN TO COARSEST MESH
for (int i=0; i<inputParams.vcDepth; i++) {
// Step 2) Compute the residual r = b - Ax
computeResidual();
// Copy pressureData into smoothedPres
smoothedPres(vLevel) = pressureData(vLevel);
// Restrict the residual to a coarser level
coarsen();
//int nStart = int(pow(2, (5-vLevel)) - 2);
//std::cout << residualData(vLevel)(blitz::Range(nStart, nStart+2), blitz::Range(nStart, nStart+2), blitz::Range(nStart, nStart+2)) << std::endl;
// Initialize pressureData to 0, or the convergence will be drastically slow
pressureData(vLevel) = 0.0;
// Step 3) Perform pre-smoothing iterations to solve for the error: Ae = r
(vLevel == inputParams.vcDepth)?
inputParams.solveFlag?
solve():
smooth(inputParams.preSmooth + inputParams.postSmooth):
smooth(inputParams.preSmooth);
}
// Step 4) Repeat steps 2-3 until you reach the coarsest grid level,
// PROLONGATION OPERATIONS UP TO FINEST MESH
for (int i=0; i<inputParams.vcDepth; i++) {
// Step 6) Prolong the error 'e' to the next finer level.
prolong();
// Step 9) Add error 'e' to the solution 'x' and perform post-smoothing iterations.
pressureData(vLevel) += smoothedPres(vLevel);
// Once the error/residual has been added to the solution at finest level, the Dirichlet BC to be applied is again non-zero
(vLevel == 0)? zeroBC = false: zeroBC = true;
// Step 7) Perform post-smoothing iterations
smooth(inputParams.postSmooth);
}
// Step 8) Repeat steps 6-7 until you reach the finest grid level,
};
/**
********************************************************************************************************************************************
* \brief Function to initialize the arrays used in multi-grid
*
* The memory required for various arrays in multi-grid solver are pre-allocated through this function.
* The function is called from within the constructor to perform this allocation once and for all.
* The arrays are initialized to 0.
********************************************************************************************************************************************
*/
void poisson::initializeArrays() {
pressureData.resize(inputParams.vcDepth + 1);
residualData.resize(inputParams.vcDepth + 1);
tmpDataArray.resize(inputParams.vcDepth + 1);
smoothedPres.resize(inputParams.vcDepth + 1);
for (int i=0; i <= inputParams.vcDepth; i++) {
pressureData(i).resize(blitz::TinyVector<int, 3>(stagFull(i).ubound() - stagFull(i).lbound() + 1));
pressureData(i).reindexSelf(stagFull(i).lbound());
pressureData(i) = 0.0;
tmpDataArray(i).resize(blitz::TinyVector<int, 3>(stagFull(i).ubound() - stagFull(i).lbound() + 1));
tmpDataArray(i).reindexSelf(stagFull(i).lbound());
tmpDataArray(i) = 0.0;
residualData(i).resize(blitz::TinyVector<int, 3>(stagFull(i).ubound() - stagFull(i).lbound() + 1));
residualData(i).reindexSelf(stagFull(i).lbound());
residualData(i) = 0.0;
smoothedPres(i).resize(blitz::TinyVector<int, 3>(stagFull(i).ubound() - stagFull(i).lbound() + 1));
smoothedPres(i).reindexSelf(stagFull(i).lbound());
smoothedPres(i) = 0.0;
}
}
/**
********************************************************************************************************************************************
* \brief Function to set the RectDomain variables for all future references throughout the poisson solver
*
* The function sets the core and full domain staggered grid sizes for all the sub-domains.
********************************************************************************************************************************************
*/
void poisson::setStagBounds() {
blitz::TinyVector<int, 3> loBound, upBound;
stagFull.resize(inputParams.vcDepth + 1);
stagCore.resize(inputParams.vcDepth + 1);
xEnd.resize(inputParams.vcDepth + 1);
yEnd.resize(inputParams.vcDepth + 1);
zEnd.resize(inputParams.vcDepth + 1);
for (int i=0; i<=inputParams.vcDepth; i++) {
// LOWER BOUND AND UPPER BOUND OF STAGGERED CORE - USED TO CONSTRUCT THE CORE SLICE
loBound = 0, 0, 0;
#ifdef PLANAR
upBound = mgSizeArray(localSizeIndex(0) - i) - 1, 0, mgSizeArray(localSizeIndex(2) - i) - 1;
#else
upBound = mgSizeArray(localSizeIndex(0) - i) - 1, mgSizeArray(localSizeIndex(1) - i) - 1, mgSizeArray(localSizeIndex(2) - i) - 1;
#endif
stagCore(i) = blitz::RectDomain<3>(loBound, upBound);
// LOWER BOUND AND UPPER BOUND OF STAGGERED FULL SUB-DOMAIN - USED TO CONSTRUCT THE FULL SUB-DOMAIN SLICE
// NOTE THAT THE PAD WIDTH USED IN POISSON SOLVER IS 1 BY DEFAULT, AND NOT THE SAME AS THAT IN GRID CLASS
loBound = -1, -1, -1;
upBound = stagCore(i).ubound() - loBound;
stagFull(i) = blitz::RectDomain<3>(loBound, upBound);
// SET THE LIMTS FOR ARRAY LOOPS IN smooth FUNCTION, AND A FEW OTHER PLACES
xEnd(i) = stagCore(i).ubound(0);
#ifndef PLANAR
yEnd(i) = stagCore(i).ubound(1);
#endif
zEnd(i) = stagCore(i).ubound(2);
}
// SET MAXIMUM NUMBER OF ITERATIONS FOR THE GAUSS-SEIDEL SOLVER AT COARSEST LEVEL OF MULTIGRID SOLVER
blitz::TinyVector<int, 3> cgSize = stagFull(inputParams.vcDepth).ubound() - stagFull(inputParams.vcDepth).lbound();
maxCount = cgSize(0)*cgSize(1)*cgSize(2);
int locPoints = (xEnd(0) + 1)*(yEnd(0) + 1)*(zEnd(0) + 1);
MPI_Allreduce(&locPoints, &pointCount, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
};
/**
********************************************************************************************************************************************
* \brief Function to calculate the local size indices of sub-domains after MPI domain decomposition
*
* For the multi-grid solver, the number of grid nodes must be \f$ 2^N + 1 \f$ to perform V-Cycles
* The domain decomposition is also done in such a way that each sub-domain will also have \f$ 2^M + 1 \f$ points.
* As a result, the number of processors in each direction must be a power of 2.
* In this case, the the value \f$ M \f$ of \f$ 2^M + 1 \f$ can be computed as \f$ M = N - log_2(np) \f$
* where \f$ np \f$ is the number of processors along the direction under consideration.
********************************************************************************************************************************************
*/
void poisson::setLocalSizeIndex() {
#ifdef PLANAR
localSizeIndex = blitz::TinyVector<int, 3>(mesh.sizeIndex(0) - int(log2(inputParams.npX)),
mesh.sizeIndex(1),
mesh.sizeIndex(2));
#else
localSizeIndex = blitz::TinyVector<int, 3>(mesh.sizeIndex(0) - int(log2(inputParams.npX)),
mesh.sizeIndex(1) - int(log2(inputParams.npY)),
mesh.sizeIndex(2));
#endif
};
/**
********************************************************************************************************************************************
* \brief Function to set the coefficients used for calculating laplacian and in smoothing
*
* The function assigns values to the variables \ref hx, \ref hy etc.
* These coefficients are repeatedly used at many places in the Poisson solver.
********************************************************************************************************************************************
*/
void poisson::setCoefficients() {
hx.resize(inputParams.vcDepth + 1);
#ifndef PLANAR
hy.resize(inputParams.vcDepth + 1);
#endif
hz.resize(inputParams.vcDepth + 1);
#ifdef PLANAR
hx2.resize(inputParams.vcDepth + 1);
hz2.resize(inputParams.vcDepth + 1);
#else
hxhy.resize(inputParams.vcDepth + 1);
hyhz.resize(inputParams.vcDepth + 1);
#endif
hzhx.resize(inputParams.vcDepth + 1);
#ifndef PLANAR
hxhyhz.resize(inputParams.vcDepth + 1);
#endif
for(int i=0; i<=inputParams.vcDepth; i++) {
hx(i) = strideValues(i)*mesh.dXi;
#ifndef PLANAR
hy(i) = strideValues(i)*mesh.dEt;
#endif
hz(i) = strideValues(i)*mesh.dZt;
#ifdef PLANAR
hx2(i) = pow(strideValues(i)*mesh.dXi, 2.0);
hz2(i) = pow(strideValues(i)*mesh.dZt, 2.0);
#else
hxhy(i) = pow(strideValues(i), 4.0)*pow(mesh.dXi, 2.0)*pow(mesh.dEt, 2.0);
hyhz(i) = pow(strideValues(i), 4.0)*pow(mesh.dEt, 2.0)*pow(mesh.dZt, 2.0);
#endif
hzhx(i) = pow(strideValues(i), 4.0)*pow(mesh.dZt, 2.0)*pow(mesh.dXi, 2.0);
#ifndef PLANAR
hxhyhz(i) = pow(strideValues(i), 6.0)*pow(mesh.dXi, 2.0)*pow(mesh.dEt, 2.0)*pow(mesh.dZt, 2.0);
#endif
}
};
/**
********************************************************************************************************************************************
* \brief Function to copy the staggered grid derivatives from the grid class to local arrays
*
* Though the grid derivatives in the grid class can be read and accessed, they cannot be used directly
* along with the arrays defined in the poisson class.
* Depending on the differentiation scheme selected by user, the arrays in grid class may have different
* pad widths, but within poisson class, only a single pad point is used everywhere, since the schemes
* used here are second order accurate by default.
* Therefore, corresponding arrays with single pad for grid derivatives are used, into which the staggered
* grid derivatives from the grid class are written and stored.
* This function serves this purpose of copying the grid derivatives.
********************************************************************************************************************************************
*/
void poisson::copyStaggrDerivs() {
xixx.resize(inputParams.vcDepth + 1);
xix2.resize(inputParams.vcDepth + 1);
#ifndef PLANAR
etyy.resize(inputParams.vcDepth + 1);
ety2.resize(inputParams.vcDepth + 1);
#endif
ztzz.resize(inputParams.vcDepth + 1);
ztz2.resize(inputParams.vcDepth + 1);
for(int n=0; n<=inputParams.vcDepth; ++n) {
xixx(n).resize(stagFull(n).ubound(0) - stagFull(n).lbound(0) + 1);
xixx(n).reindexSelf(stagFull(n).lbound(0));
xixx(n) = 0.0;
xixx(n)(blitz::Range(0, stagCore(n).ubound(0), 1)) = mesh.xixxStaggr(blitz::Range(0, stagCore(0).ubound(0), strideValues(n)));
xix2(n).resize(stagFull(n).ubound(0) - stagFull(n).lbound(0) + 1);
xix2(n).reindexSelf(stagFull(n).lbound(0));
xix2(n) = 0.0;
xix2(n)(blitz::Range(0, stagCore(n).ubound(0), 1)) = mesh.xix2Staggr(blitz::Range(0, stagCore(0).ubound(0), strideValues(n)));
#ifndef PLANAR
etyy(n).resize(stagFull(n).ubound(1) - stagFull(n).lbound(1) + 1);
etyy(n).reindexSelf(stagFull(n).lbound(1));
etyy(n) = 0.0;
etyy(n)(blitz::Range(0, stagCore(n).ubound(1), 1)) = mesh.etyyStaggr(blitz::Range(0, stagCore(0).ubound(1), strideValues(n)));
ety2(n).resize(stagFull(n).ubound(1) - stagFull(n).lbound(1) + 1);
ety2(n).reindexSelf(stagFull(n).lbound(1));
ety2(n) = 0.0;
ety2(n)(blitz::Range(0, stagCore(n).ubound(1), 1)) = mesh.ety2Staggr(blitz::Range(0, stagCore(0).ubound(1), strideValues(n)));
#endif
ztzz(n).resize(stagFull(n).ubound(2) - stagFull(n).lbound(2) + 1);
ztzz(n).reindexSelf(stagFull(n).lbound(2));
ztzz(n) = 0.0;
ztzz(n)(blitz::Range(0, stagCore(n).ubound(2), 1)) = mesh.ztzzStaggr(blitz::Range(0, stagCore(0).ubound(2), strideValues(n)));
ztz2(n).resize(stagFull(n).ubound(2) - stagFull(n).lbound(2) + 1);
ztz2(n).reindexSelf(stagFull(n).lbound(2));
ztz2(n) = 0.0;
ztz2(n)(blitz::Range(0, stagCore(n).ubound(2), 1)) = mesh.ztz2Staggr(blitz::Range(0, stagCore(0).ubound(2), strideValues(n)));
}
};
/**
********************************************************************************************************************************************
* \brief Function to coarsen the grid down the levels of the V-Cycle
*
* Coarsening reduces the number of points in the grid by averaging values at two adjacent nodes onto an intermediate point between them
* As a result, the number of points in the domain decreases from \f$ 2^{N+1} + 1 \f$ at the input level to \f$ 2^N + 1 \f$.
* The vLevel variable is accordingly incremented by 1 to reflect this descent by one step down the V-Cycle.
********************************************************************************************************************************************
*/
void poisson::coarsen() { };
/**
********************************************************************************************************************************************
* \brief Function to perform prolongation on the array being solved
*
* Prolongation makes the grid finer by averaging values at two adjacent nodes onto an intermediate point between them
* As a result, the number of points in the domain increases from \f$ 2^N + 1 \f$ at the input level to \f$ 2^{N+1} + 1 \f$.
* The vLevel variable is accordingly reduced by 1 to reflect this ascent by one step up the V-Cycle.
********************************************************************************************************************************************
*/
void poisson::prolong() { };
/**
********************************************************************************************************************************************
* \brief Function to compute the residual at the start of each V-Cycle
*
* The Poisson solver solves for the residual r = b - Ax
* This function computes this residual by calculating the Laplacian of the pressure field and
* subtracting it from the RHS of Poisson equation.
*
********************************************************************************************************************************************
*/
void poisson::computeResidual() { };
/**
********************************************************************************************************************************************
* \brief Function to perform smoothing operation on the input array
*
* The smoothing operation is always performed on the data contained in the array \ref pressureData.
* The array \ref tmpDataArray is used to store the temporary data and it is continuously swapped with the
* \ref pressureData array at every iteration.
* This operation can be performed at any level of the V-cycle.
*
* \param smoothCount is the integer value of the number of smoothing iterations to be performed
********************************************************************************************************************************************
*/
void poisson::smooth(const int smoothCount) { };
/**
********************************************************************************************************************************************
* \brief Function to compute the error at the end of each V-Cycle
*
* To check for convergence, the residual must be computed throughout the domain.
* This function offers multiple ways to compute the residual (global maximum, rms, mean, etc.)
*
* \param normOrder is the integer value of the order of norm used to calculate the residual.
********************************************************************************************************************************************
*/
real poisson::computeError(const int normOrder) { return 0.0; };
/**
********************************************************************************************************************************************
* \brief Function to impose the boundary conditions of Poisson solver at different levels of the V-cycle
*
* This function is called mainly during smoothing operations to impose the boundary conditions for the
* Poisson equation.
* The sub-domains close to the wall will have the Neumann boundary condition on pressure imposeed at the walls.
* Meanwhile at the interior boundaries at the inter-processor sub-domains, data is transferred from the neighbouring cells
* by calling the \ref updatePads function.
********************************************************************************************************************************************
*/
void poisson::imposeBC() { };
/**
********************************************************************************************************************************************
* \brief Function to update the pad points of the local sub-domains at different levels of the V-cycle
*
* This function is called mainly during smoothing operations by the \ref imposeBC function.
* At the interior boundaries at the inter-processor sub-domains, data is transferred from the neighbouring cells
* using a combination of MPI_Irecv and MPI_Send functions.
********************************************************************************************************************************************
*/
void poisson::updatePads(blitz::Array<blitz::Array<real, 3>, 1> &data) { };
/**
********************************************************************************************************************************************
* \brief Function to create the MPI sub-array data types necessary to transfer data across sub-domains
*
* The inter-domain boundaries of all the sub-domains at different V-cycle levels need data to be transfered at
* with different mesh strides.
* The number of sub-arrays along each edge/face of the sub-domains are equal to the number of V-cycle levels.
* Since this data transfer has to take place at all the mesh levels including the finest mesh, there will be
* vcDepth + 1 elements.
********************************************************************************************************************************************
*/
void poisson::createMGSubArrays() { };
/**
********************************************************************************************************************************************
* \brief Function to test whether strided data transfer is performing as expected
*
* The function populates the arrays with predetermined values at all locations.
* It then calls updatePads at different vLevels and checks is the data is being transferred along x and y directions
* This done by printing the contents of the arrays for visual inspection for now.
********************************************************************************************************************************************
*/
real poisson::testTransfer() { return 0; };
/**
********************************************************************************************************************************************
* \brief Function to test whether prolongation operations are interpolating correctly
*
* The function populates the arrays with predetermined values at all locations.
* It then calls prolong function at a lower vLevel and checks if the data is being interpolated correctly at higher vLevel
* This done by returning the average deviation from correct values as a real value
********************************************************************************************************************************************
*/
real poisson::testProlong() { return 0; };
/**
********************************************************************************************************************************************
* \brief Function to test whether periodic BC is being implemented properly
*
* The function populates the arrays with predetermined values at all locations.
* It then calls imposeBC function at different vLevels and checks if the correct values of the functions are imposed at boundaries
* This done by printing the contents of the arrays for visual inspection for now.
********************************************************************************************************************************************
*/
real poisson::testPeriodic() { return 0; };
poisson::~poisson() {
#ifdef TIME_RUN
if (mesh.rankData.rank == 0) {
std::cout << std::left << std::setw(50) << "Time taken in computation within smooth: " << std::fixed << std::setprecision(6) << smothTimeComp << std::endl;
std::cout << std::left << std::setw(50) << "Time taken in data-transfer within smooth: " << std::fixed << std::setprecision(6) << smothTimeTran << std::endl;
}
#endif
};
| 49.312404 | 178 | 0.536412 | usmanianas |
5927738a0fa14fae876f0e31dd0ffa42b89e7745 | 490 | cc | C++ | apps/SerStacker/src/c_display_function.cc | amyznikov/SerStacker | 6657240210af0b35fff1c5adc1d6f9d51b469e80 | [
"CC0-1.0"
] | 1 | 2021-09-03T06:02:59.000Z | 2021-09-03T06:02:59.000Z | apps/SerStacker/src/c_display_function.cc | amyznikov/SerStacker | 6657240210af0b35fff1c5adc1d6f9d51b469e80 | [
"CC0-1.0"
] | 1 | 2021-09-03T03:43:54.000Z | 2021-09-10T01:30:46.000Z | apps/SerStacker/src/c_display_function.cc | amyznikov/SerStacker | 6657240210af0b35fff1c5adc1d6f9d51b469e80 | [
"CC0-1.0"
] | null | null | null | /*
* c_display_function.cc
*
* Created on: Dec 14, 2020
* Author: amyznikov
*/
#include "c_display_function.h"
#include <core/debug.h>
c_display_function::c_display_function()
: mtf_(c_pixinsight_midtones_transfer_function::create())
{
}
const c_pixinsight_midtones_transfer_function::ptr & c_display_function::mtf() const
{
return mtf_;
}
void c_display_function::operator () (const cv::Mat & src, cv::Mat & dst, int ddepth) const
{
mtf_->apply(src, dst, ddepth);
}
| 18.148148 | 91 | 0.714286 | amyznikov |
592c15135d6013ce2289270a7d1d204246176382 | 4,506 | cpp | C++ | CPPProjects/LongestCommonSubsequence.cpp | ducaddepar/ProgrammingContest | 4c47cada50ed23bd841cfea06a377a4129d4d88f | [
"MIT"
] | 39 | 2018-08-26T05:53:19.000Z | 2021-12-11T07:47:24.000Z | CPPProjects/LongestCommonSubsequence.cpp | ducaddepar/ProgrammingContest | 4c47cada50ed23bd841cfea06a377a4129d4d88f | [
"MIT"
] | 1 | 2018-06-21T00:40:41.000Z | 2018-06-21T00:40:46.000Z | CPPProjects/LongestCommonSubsequence.cpp | ducaddepar/ProgrammingContest | 4c47cada50ed23bd841cfea06a377a4129d4d88f | [
"MIT"
] | 8 | 2018-08-27T00:34:23.000Z | 2020-09-27T12:51:22.000Z | //#define SUBMIT
#ifdef SUBMIT
#define LOGLEVEL 0
#define NDEBUG
#else
#define LOGLEVEL 1
#endif
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cassert>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <cmath>
#include <cstdlib>
#include <array>
#include <type_traits>
#include <queue>
#include <stack>
#include <functional>
#include <unordered_map>
using namespace std;
#define LOG(l, x) if (l <= LOGLEVEL) cout << x << endl
#define int64 long long
#define repeat(x) for (auto repeat_var = 0; repeat_var < x; ++repeat_var)
#define for_inc(i, x) for (auto i = 0; i < x; ++i)
#define for_dec(i, x) for (auto i = x - 1; i >= 0; --i)
#define for_inc_range(i, x, y) for (auto i = x; i <= y; ++i)
#define for_dec_range(i, x, y) for (auto i = x; i >= y; --i)
#define fill0(x) memset(x, 0, sizeof(x))
#define INT_INF ((int)2E9L)
#define INT64_INF ((int64)1E18L)
#define MOD 1000000007
int MODP(int64 x) {
int r = x % MOD;
if (r < 0) r += MOD;
return r;
}
void testGen() {
freopen("biginput1.txt", "w", stdout);
fclose(stdout);
}
// Compute LCS up ot length L of two sequences in O(L*(l1 + l2)) where l1, l2
// are the length of the two sequences
// Memory: O(L*l1)
// Usage: construct with the two sequences, and L
template<class T> class LongestCommonSubsequence {
vector<int> seq1, seq2;
int l1, l2, upper, longest;
vector<vector<int>> pos; // pos[l][i] = min{j, lcs(i, j) = l, or l2 if not exists}
unordered_map<T, int> valueMap;
void discretize(const vector<T> &s1, const vector<T> &s2) {
int idx = 0;
for (auto &x: s1) {
if (!valueMap.count(x)) {
valueMap[x] = idx;
idx++;
}
}
for (auto &x: s2) {
if (!valueMap.count(x)) {
valueMap[x] = idx;
idx++;
}
}
l1 = (int) s1.size();
l2 = (int) s2.size();
upper=min(upper, l1);
upper=min(upper, l2);
seq1.resize(l1);
seq2.resize(l2);
for_inc(i, l1) {
seq1[i] = valueMap[s1[i]];
}
for_inc(i, l2) {
seq2[i] = valueMap[s2[i]];
}
}
public:
LongestCommonSubsequence(const vector<T> &s1, const vector<T> &s2, int upper) {
this->upper = upper;
discretize(s1, s2);
pos.resize(upper + 1, vector<int>(l1));
int numValues = (int)valueMap.size();
vector<int> minPos(numValues, l2);
for_dec(j, l2) {
minPos[seq2[j]] = j;
}
longest = 0;
if (minPos[seq1[0]] < l2) {
pos[1][0] = minPos[seq1[0]];
longest = 1;
} else {
pos[1][0] = l2;
}
for_inc_range(i, 1, l1 - 1) {
pos[1][i] = pos[1][i - 1];
if (minPos[seq1[i]] < l2) {
pos[1][i] = min(pos[1][i], minPos[seq1[i]]);
}
}
for_inc_range(l, 2, upper) {
pos[l][0] = l2;
int leftIndex = l2;
for_inc(x, numValues) {
minPos[x] = l2;
}
for_inc_range(i, 1, l1 - 1) {
pos[l][i] = pos[l][i - 1];
if (pos[l - 1][i - 1] != l2) {
int newLeftIndex = pos[l - 1][i - 1] + 1;
for_dec_range(j, leftIndex - 1, newLeftIndex) {
minPos[seq2[j]] = j;
}
leftIndex = newLeftIndex;
if (minPos[seq1[i]] < l2) {
pos[l][i] = min(pos[l][i], minPos[seq1[i]]);
}
}
if (pos[l][i] != l2) {
longest = l;
}
}
}
}
int getLongest() const {
return longest;
}
// Is there a j so that {lcs(i, j) = l}
bool hasLCS(int i, int l) const {
if (l > upper) return false;
return pos[l][i] != l2;
}
// Return min{j, lcs(i, j) = l}
int getMinPos(int i, int l) const {
assert(hasLCS(i, l));
return pos[l][i];
}
};
// Sample: CF243_C
int l1, l2, s, e;
vector<int> s1, s2;
int main() {
#ifndef SUBMIT
freopen("input1.txt", "r", stdin);
#endif
cin >> l1 >> l2 >> s >> e;
int x;
repeat(l1) {
cin >> x;
s1.push_back(x);
}
repeat(l2) {
cin >> x;
s2.push_back(x);
}
if (s1.size() > s2.size()) {
swap(s1, s2);
swap(l1, l2);
}
int maxCS = s / e;
LongestCommonSubsequence<int> lcs(s1, s2, maxCS);
int best = 0;
for_inc_range(l, 1, maxCS) {
int remainingEnergy = s - l * e;
for_inc(i, l1) {
if (lcs.hasLCS(i, l)) {
int j = lcs.getMinPos(i, l);
if (i + 1 + j + 1 <= remainingEnergy) {
best = l;
break;
}
}
}
}
cout << best << endl;
return 0;
}
| 21.15493 | 84 | 0.524412 | ducaddepar |
592d2cbaf6d84488c6ef527becbe20d9f118b572 | 17,721 | cc | C++ | quic/core/qpack/qpack_header_table_test.cc | hanpfei/quiche | a366010c5f5736436338acad1e2a11d17f80c0fe | [
"BSD-3-Clause"
] | 8 | 2019-11-08T04:16:04.000Z | 2021-07-11T11:56:52.000Z | quic/core/qpack/qpack_header_table_test.cc | hanpfei/quiche | a366010c5f5736436338acad1e2a11d17f80c0fe | [
"BSD-3-Clause"
] | null | null | null | quic/core/qpack/qpack_header_table_test.cc | hanpfei/quiche | a366010c5f5736436338acad1e2a11d17f80c0fe | [
"BSD-3-Clause"
] | 6 | 2019-09-08T05:40:06.000Z | 2021-03-31T01:19:10.000Z | // Copyright (c) 2018 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 "net/third_party/quiche/src/quic/core/qpack/qpack_header_table.h"
#include "net/third_party/quiche/src/quic/core/qpack/qpack_static_table.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_arraysize.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
#include "net/third_party/quiche/src/spdy/core/hpack/hpack_entry.h"
using ::testing::Mock;
using ::testing::StrictMock;
namespace quic {
namespace test {
namespace {
const uint64_t kMaximumDynamicTableCapacityForTesting = 1024 * 1024;
class MockObserver : public QpackHeaderTable::Observer {
public:
~MockObserver() override = default;
MOCK_METHOD0(OnInsertCountReachedThreshold, void());
};
class QpackHeaderTableTest : public QuicTest {
protected:
QpackHeaderTableTest() {
table_.SetMaximumDynamicTableCapacity(
kMaximumDynamicTableCapacityForTesting);
}
~QpackHeaderTableTest() override = default;
void ExpectEntryAtIndex(bool is_static,
uint64_t index,
QuicStringPiece expected_name,
QuicStringPiece expected_value) const {
const auto* entry = table_.LookupEntry(is_static, index);
ASSERT_TRUE(entry);
EXPECT_EQ(expected_name, entry->name());
EXPECT_EQ(expected_value, entry->value());
}
void ExpectNoEntryAtIndex(bool is_static, uint64_t index) const {
EXPECT_FALSE(table_.LookupEntry(is_static, index));
}
void ExpectMatch(QuicStringPiece name,
QuicStringPiece value,
QpackHeaderTable::MatchType expected_match_type,
bool expected_is_static,
uint64_t expected_index) const {
// Initialize outparams to a value different from the expected to ensure
// that FindHeaderField() sets them.
bool is_static = !expected_is_static;
uint64_t index = expected_index + 1;
QpackHeaderTable::MatchType matchtype =
table_.FindHeaderField(name, value, &is_static, &index);
EXPECT_EQ(expected_match_type, matchtype) << name << ": " << value;
EXPECT_EQ(expected_is_static, is_static) << name << ": " << value;
EXPECT_EQ(expected_index, index) << name << ": " << value;
}
void ExpectNoMatch(QuicStringPiece name, QuicStringPiece value) const {
bool is_static = false;
uint64_t index = 0;
QpackHeaderTable::MatchType matchtype =
table_.FindHeaderField(name, value, &is_static, &index);
EXPECT_EQ(QpackHeaderTable::MatchType::kNoMatch, matchtype)
<< name << ": " << value;
}
void InsertEntry(QuicStringPiece name, QuicStringPiece value) {
EXPECT_TRUE(table_.InsertEntry(name, value));
}
void ExpectToFailInsertingEntry(QuicStringPiece name, QuicStringPiece value) {
EXPECT_FALSE(table_.InsertEntry(name, value));
}
bool SetDynamicTableCapacity(uint64_t capacity) {
return table_.SetDynamicTableCapacity(capacity);
}
void RegisterObserver(QpackHeaderTable::Observer* observer,
uint64_t required_insert_count) {
table_.RegisterObserver(observer, required_insert_count);
}
uint64_t max_entries() const { return table_.max_entries(); }
uint64_t inserted_entry_count() const {
return table_.inserted_entry_count();
}
uint64_t dropped_entry_count() const { return table_.dropped_entry_count(); }
private:
QpackHeaderTable table_;
};
TEST_F(QpackHeaderTableTest, LookupStaticEntry) {
ExpectEntryAtIndex(/* is_static = */ true, 0, ":authority", "");
ExpectEntryAtIndex(/* is_static = */ true, 1, ":path", "/");
// 98 is the last entry.
ExpectEntryAtIndex(/* is_static = */ true, 98, "x-frame-options",
"sameorigin");
ASSERT_EQ(99u, QpackStaticTableVector().size());
ExpectNoEntryAtIndex(/* is_static = */ true, 99);
}
TEST_F(QpackHeaderTableTest, InsertAndLookupDynamicEntry) {
// Dynamic table is initially entry.
ExpectNoEntryAtIndex(/* is_static = */ false, 0);
ExpectNoEntryAtIndex(/* is_static = */ false, 1);
ExpectNoEntryAtIndex(/* is_static = */ false, 2);
ExpectNoEntryAtIndex(/* is_static = */ false, 3);
// Insert one entry.
InsertEntry("foo", "bar");
ExpectEntryAtIndex(/* is_static = */ false, 0, "foo", "bar");
ExpectNoEntryAtIndex(/* is_static = */ false, 1);
ExpectNoEntryAtIndex(/* is_static = */ false, 2);
ExpectNoEntryAtIndex(/* is_static = */ false, 3);
// Insert a different entry.
InsertEntry("baz", "bing");
ExpectEntryAtIndex(/* is_static = */ false, 0, "foo", "bar");
ExpectEntryAtIndex(/* is_static = */ false, 1, "baz", "bing");
ExpectNoEntryAtIndex(/* is_static = */ false, 2);
ExpectNoEntryAtIndex(/* is_static = */ false, 3);
// Insert an entry identical to the most recently inserted one.
InsertEntry("baz", "bing");
ExpectEntryAtIndex(/* is_static = */ false, 0, "foo", "bar");
ExpectEntryAtIndex(/* is_static = */ false, 1, "baz", "bing");
ExpectEntryAtIndex(/* is_static = */ false, 2, "baz", "bing");
ExpectNoEntryAtIndex(/* is_static = */ false, 3);
}
TEST_F(QpackHeaderTableTest, FindStaticHeaderField) {
// A header name that has multiple entries with different values.
ExpectMatch(":method", "GET", QpackHeaderTable::MatchType::kNameAndValue,
true, 17u);
ExpectMatch(":method", "POST", QpackHeaderTable::MatchType::kNameAndValue,
true, 20u);
ExpectMatch(":method", "TRACE", QpackHeaderTable::MatchType::kName, true,
15u);
// A header name that has a single entry with non-empty value.
ExpectMatch("accept-encoding", "gzip, deflate, br",
QpackHeaderTable::MatchType::kNameAndValue, true, 31u);
ExpectMatch("accept-encoding", "compress", QpackHeaderTable::MatchType::kName,
true, 31u);
ExpectMatch("accept-encoding", "", QpackHeaderTable::MatchType::kName, true,
31u);
// A header name that has a single entry with empty value.
ExpectMatch("location", "", QpackHeaderTable::MatchType::kNameAndValue, true,
12u);
ExpectMatch("location", "foo", QpackHeaderTable::MatchType::kName, true, 12u);
// No matching header name.
ExpectNoMatch("foo", "");
ExpectNoMatch("foo", "bar");
}
TEST_F(QpackHeaderTableTest, FindDynamicHeaderField) {
// Dynamic table is initially entry.
ExpectNoMatch("foo", "bar");
ExpectNoMatch("foo", "baz");
// Insert one entry.
InsertEntry("foo", "bar");
// Match name and value.
ExpectMatch("foo", "bar", QpackHeaderTable::MatchType::kNameAndValue, false,
0u);
// Match name only.
ExpectMatch("foo", "baz", QpackHeaderTable::MatchType::kName, false, 0u);
// Insert an identical entry. FindHeaderField() should return the index of
// the most recently inserted matching entry.
InsertEntry("foo", "bar");
// Match name and value.
ExpectMatch("foo", "bar", QpackHeaderTable::MatchType::kNameAndValue, false,
1u);
// Match name only.
ExpectMatch("foo", "baz", QpackHeaderTable::MatchType::kName, false, 1u);
}
TEST_F(QpackHeaderTableTest, FindHeaderFieldPrefersStaticTable) {
// Insert an entry to the dynamic table that exists in the static table.
InsertEntry(":method", "GET");
// Insertion works.
ExpectEntryAtIndex(/* is_static = */ false, 0, ":method", "GET");
// FindHeaderField() prefers static table if both have name-and-value match.
ExpectMatch(":method", "GET", QpackHeaderTable::MatchType::kNameAndValue,
true, 17u);
// FindHeaderField() prefers static table if both have name match but no value
// match, and prefers the first entry with matching name.
ExpectMatch(":method", "TRACE", QpackHeaderTable::MatchType::kName, true,
15u);
// Add new entry to the dynamic table.
InsertEntry(":method", "TRACE");
// FindHeaderField prefers name-and-value match in dynamic table over name
// only match in static table.
ExpectMatch(":method", "TRACE", QpackHeaderTable::MatchType::kNameAndValue,
false, 1u);
}
// MaxEntries is determined by maximum dynamic table capacity,
// which is set at construction time.
TEST_F(QpackHeaderTableTest, MaxEntries) {
QpackHeaderTable table1;
table1.SetMaximumDynamicTableCapacity(1024);
EXPECT_EQ(32u, table1.max_entries());
QpackHeaderTable table2;
table2.SetMaximumDynamicTableCapacity(500);
EXPECT_EQ(15u, table2.max_entries());
}
TEST_F(QpackHeaderTableTest, SetDynamicTableCapacity) {
// Dynamic table capacity does not affect MaxEntries.
EXPECT_TRUE(SetDynamicTableCapacity(1024));
EXPECT_EQ(32u * 1024, max_entries());
EXPECT_TRUE(SetDynamicTableCapacity(500));
EXPECT_EQ(32u * 1024, max_entries());
// Dynamic table capacity cannot exceed maximum dynamic table capacity.
EXPECT_FALSE(
SetDynamicTableCapacity(2 * kMaximumDynamicTableCapacityForTesting));
}
TEST_F(QpackHeaderTableTest, EvictByInsertion) {
EXPECT_TRUE(SetDynamicTableCapacity(40));
// Entry size is 3 + 3 + 32 = 38.
InsertEntry("foo", "bar");
EXPECT_EQ(1u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
ExpectMatch("foo", "bar", QpackHeaderTable::MatchType::kNameAndValue,
/* expected_is_static = */ false, 0u);
// Inserting second entry evicts the first one.
InsertEntry("baz", "qux");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
ExpectNoMatch("foo", "bar");
ExpectMatch("baz", "qux", QpackHeaderTable::MatchType::kNameAndValue,
/* expected_is_static = */ false, 1u);
// Inserting an entry that does not fit results in error.
ExpectToFailInsertingEntry("foobar", "foobar");
}
TEST_F(QpackHeaderTableTest, EvictByUpdateTableSize) {
// Entry size is 3 + 3 + 32 = 38.
InsertEntry("foo", "bar");
InsertEntry("baz", "qux");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
ExpectMatch("foo", "bar", QpackHeaderTable::MatchType::kNameAndValue,
/* expected_is_static = */ false, 0u);
ExpectMatch("baz", "qux", QpackHeaderTable::MatchType::kNameAndValue,
/* expected_is_static = */ false, 1u);
EXPECT_TRUE(SetDynamicTableCapacity(40));
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
ExpectNoMatch("foo", "bar");
ExpectMatch("baz", "qux", QpackHeaderTable::MatchType::kNameAndValue,
/* expected_is_static = */ false, 1u);
EXPECT_TRUE(SetDynamicTableCapacity(20));
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(2u, dropped_entry_count());
ExpectNoMatch("foo", "bar");
ExpectNoMatch("baz", "qux");
}
TEST_F(QpackHeaderTableTest, EvictOldestOfIdentical) {
EXPECT_TRUE(SetDynamicTableCapacity(80));
// Entry size is 3 + 3 + 32 = 38.
// Insert same entry twice.
InsertEntry("foo", "bar");
InsertEntry("foo", "bar");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
// Find most recently inserted entry.
ExpectMatch("foo", "bar", QpackHeaderTable::MatchType::kNameAndValue,
/* expected_is_static = */ false, 1u);
// Inserting third entry evicts the first one, not the second.
InsertEntry("baz", "qux");
EXPECT_EQ(3u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
ExpectMatch("foo", "bar", QpackHeaderTable::MatchType::kNameAndValue,
/* expected_is_static = */ false, 1u);
ExpectMatch("baz", "qux", QpackHeaderTable::MatchType::kNameAndValue,
/* expected_is_static = */ false, 2u);
}
TEST_F(QpackHeaderTableTest, EvictOldestOfSameName) {
EXPECT_TRUE(SetDynamicTableCapacity(80));
// Entry size is 3 + 3 + 32 = 38.
// Insert two entries with same name but different values.
InsertEntry("foo", "bar");
InsertEntry("foo", "baz");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
// Find most recently inserted entry with matching name.
ExpectMatch("foo", "foo", QpackHeaderTable::MatchType::kName,
/* expected_is_static = */ false, 1u);
// Inserting third entry evicts the first one, not the second.
InsertEntry("baz", "qux");
EXPECT_EQ(3u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
ExpectMatch("foo", "foo", QpackHeaderTable::MatchType::kName,
/* expected_is_static = */ false, 1u);
ExpectMatch("baz", "qux", QpackHeaderTable::MatchType::kNameAndValue,
/* expected_is_static = */ false, 2u);
}
// Returns the size of the largest entry that could be inserted into the
// dynamic table without evicting entry |index|.
TEST_F(QpackHeaderTableTest, MaxInsertSizeWithoutEvictingGivenEntry) {
const uint64_t dynamic_table_capacity = 100;
QpackHeaderTable table;
table.SetMaximumDynamicTableCapacity(dynamic_table_capacity);
// Empty table can take an entry up to its capacity.
EXPECT_EQ(dynamic_table_capacity,
table.MaxInsertSizeWithoutEvictingGivenEntry(0));
const uint64_t entry_size1 = QpackEntry::Size("foo", "bar");
EXPECT_TRUE(table.InsertEntry("foo", "bar"));
EXPECT_EQ(dynamic_table_capacity - entry_size1,
table.MaxInsertSizeWithoutEvictingGivenEntry(0));
// Table can take an entry up to its capacity if all entries are allowed to be
// evicted.
EXPECT_EQ(dynamic_table_capacity,
table.MaxInsertSizeWithoutEvictingGivenEntry(1));
const uint64_t entry_size2 = QpackEntry::Size("baz", "foobar");
EXPECT_TRUE(table.InsertEntry("baz", "foobar"));
// Table can take an entry up to its capacity if all entries are allowed to be
// evicted.
EXPECT_EQ(dynamic_table_capacity,
table.MaxInsertSizeWithoutEvictingGivenEntry(2));
// Second entry must stay.
EXPECT_EQ(dynamic_table_capacity - entry_size2,
table.MaxInsertSizeWithoutEvictingGivenEntry(1));
// First and second entry must stay.
EXPECT_EQ(dynamic_table_capacity - entry_size2 - entry_size1,
table.MaxInsertSizeWithoutEvictingGivenEntry(0));
// Third entry evicts first one.
const uint64_t entry_size3 = QpackEntry::Size("last", "entry");
EXPECT_TRUE(table.InsertEntry("last", "entry"));
EXPECT_EQ(1u, table.dropped_entry_count());
// Table can take an entry up to its capacity if all entries are allowed to be
// evicted.
EXPECT_EQ(dynamic_table_capacity,
table.MaxInsertSizeWithoutEvictingGivenEntry(3));
// Third entry must stay.
EXPECT_EQ(dynamic_table_capacity - entry_size3,
table.MaxInsertSizeWithoutEvictingGivenEntry(2));
// Second and third entry must stay.
EXPECT_EQ(dynamic_table_capacity - entry_size3 - entry_size2,
table.MaxInsertSizeWithoutEvictingGivenEntry(1));
}
TEST_F(QpackHeaderTableTest, Observer) {
StrictMock<MockObserver> observer1;
RegisterObserver(&observer1, 1);
EXPECT_CALL(observer1, OnInsertCountReachedThreshold);
InsertEntry("foo", "bar");
EXPECT_EQ(1u, inserted_entry_count());
Mock::VerifyAndClearExpectations(&observer1);
// Registration order does not matter.
StrictMock<MockObserver> observer2;
StrictMock<MockObserver> observer3;
RegisterObserver(&observer3, 3);
RegisterObserver(&observer2, 2);
EXPECT_CALL(observer2, OnInsertCountReachedThreshold);
InsertEntry("foo", "bar");
EXPECT_EQ(2u, inserted_entry_count());
Mock::VerifyAndClearExpectations(&observer3);
EXPECT_CALL(observer3, OnInsertCountReachedThreshold);
InsertEntry("foo", "bar");
EXPECT_EQ(3u, inserted_entry_count());
Mock::VerifyAndClearExpectations(&observer2);
// Multiple observers with identical |required_insert_count| should all be
// notified.
StrictMock<MockObserver> observer4;
StrictMock<MockObserver> observer5;
RegisterObserver(&observer4, 4);
RegisterObserver(&observer5, 4);
EXPECT_CALL(observer4, OnInsertCountReachedThreshold);
EXPECT_CALL(observer5, OnInsertCountReachedThreshold);
InsertEntry("foo", "bar");
EXPECT_EQ(4u, inserted_entry_count());
Mock::VerifyAndClearExpectations(&observer4);
Mock::VerifyAndClearExpectations(&observer5);
}
TEST_F(QpackHeaderTableTest, DrainingIndex) {
QpackHeaderTable table;
table.SetMaximumDynamicTableCapacity(4 * QpackEntry::Size("foo", "bar"));
// Empty table: no draining entry.
EXPECT_EQ(0u, table.draining_index(0.0));
EXPECT_EQ(0u, table.draining_index(1.0));
// Table with one entry.
EXPECT_TRUE(table.InsertEntry("foo", "bar"));
// Any entry can be referenced if none of the table is draining.
EXPECT_EQ(0u, table.draining_index(0.0));
// No entry can be referenced if all of the table is draining.
EXPECT_EQ(1u, table.draining_index(1.0));
// Table with two entries is at half capacity.
EXPECT_TRUE(table.InsertEntry("foo", "bar"));
// Any entry can be referenced if at most half of the table is draining,
// because current entries only take up half of total capacity.
EXPECT_EQ(0u, table.draining_index(0.0));
EXPECT_EQ(0u, table.draining_index(0.5));
// No entry can be referenced if all of the table is draining.
EXPECT_EQ(2u, table.draining_index(1.0));
// Table with four entries is full.
EXPECT_TRUE(table.InsertEntry("foo", "bar"));
EXPECT_TRUE(table.InsertEntry("foo", "bar"));
// Any entry can be referenced if none of the table is draining.
EXPECT_EQ(0u, table.draining_index(0.0));
// In a full table with identically sized entries, |draining_fraction| of all
// entries are draining.
EXPECT_EQ(2u, table.draining_index(0.5));
// No entry can be referenced if all of the table is draining.
EXPECT_EQ(4u, table.draining_index(1.0));
}
} // namespace
} // namespace test
} // namespace quic
| 35.8 | 80 | 0.707974 | hanpfei |
592d61922f5631770827bd8bfe8dfe1ad1184b33 | 26,286 | cpp | C++ | src/control/velocity_controller/src/velocity_controller_core.cpp | zqw-hooper/AutowareArchitectureProposal | 93ca87fd7255be697219a100a97a639a56f6c4a7 | [
"Apache-2.0"
] | null | null | null | src/control/velocity_controller/src/velocity_controller_core.cpp | zqw-hooper/AutowareArchitectureProposal | 93ca87fd7255be697219a100a97a639a56f6c4a7 | [
"Apache-2.0"
] | null | null | null | src/control/velocity_controller/src/velocity_controller_core.cpp | zqw-hooper/AutowareArchitectureProposal | 93ca87fd7255be697219a100a97a639a56f6c4a7 | [
"Apache-2.0"
] | 4 | 2021-06-21T11:58:51.000Z | 2021-08-06T08:25:54.000Z | /*
* Copyright 2018-2019 Autoware Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not enable 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 "velocity_controller.h"
VelocityController::VelocityController()
: nh_(""),
pnh_("~"),
tf_listener_(tf_buffer_),
is_smooth_stop_(false),
is_emergency_stop_(false),
prev_acc_cmd_(0.0)
{
// parameters
pnh_.param("show_debug_info", show_debug_info_, bool(false));
// parameters timer
pnh_.param("control_rate", control_rate_, double(30.0));
// parameters to enable functions
pnh_.param("enable_smooth_stop", enable_smooth_stop_, bool(true));
pnh_.param("enable_overshoot_emergency", enable_overshoot_emergency_, bool(true));
pnh_.param("enable_slope_compensation", enable_slope_compensation_, bool(true));
// parameters to find a closest waypoint
pnh_.param("closest_waypoint_distance_threshold", closest_dist_thr_, double(3.0));
pnh_.param("closest_waypoint_angle_threshold", closest_angle_thr_, double(M_PI_4));
// parameters for stop state
pnh_.param("stop_state_vel", stop_state_vel_, double(0.0)); // [m/s]
pnh_.param("stop_state_acc", stop_state_acc_, double(-2.0)); // [m/s^2]
pnh_.param("stop_state_entry_ego_speed", stop_state_entry_ego_speed_, double(0.2)); // [m/s]
pnh_.param(
"stop_state_entry_target_speed", stop_state_entry_target_speed_, double(0.1)); // [m/s]
// parameters for delay compensation
pnh_.param("delay_compensation_time", delay_compensation_time_, double(0.17)); // [sec]
// parameters for emergency stop by this controller
pnh_.param("emergency_stop_acc", emergency_stop_acc_, double(-2.0)); // [m/s^2]
pnh_.param("emergency_stop_jerk", emergency_stop_jerk_, double(-1.5)); // [m/s^3]
pnh_.param("emergency_overshoot_dist", emergency_overshoot_dist_, double(1.5)); // [m]
// parameters for smooth stop
pnh_.param(
"smooth_stop/exit_ego_speed", smooth_stop_param_.exit_ego_speed, double(2.0)); // [m/s]
pnh_.param(
"smooth_stop/exit_target_speed", smooth_stop_param_.exit_target_speed, double(2.0)); // [m/s]
pnh_.param(
"smooth_stop/entry_ego_speed", smooth_stop_param_.entry_ego_speed, double(1.0)); // [m/s]
pnh_.param(
"smooth_stop/entry_target_speed", smooth_stop_param_.entry_target_speed, double(1.0)); // [m/s]
pnh_.param(
"smooth_stop/weak_brake_time", smooth_stop_param_.weak_brake_time, double(3.0)); // [sec]
pnh_.param(
"smooth_stop/weak_brake_acc", smooth_stop_param_.weak_brake_acc, double(-0.4)); // [m/s^2]
pnh_.param(
"smooth_stop/increasing_brake_time", smooth_stop_param_.increasing_brake_time,
double(3.0)); // [sec]
pnh_.param(
"smooth_stop/increasing_brake_gradient", smooth_stop_param_.increasing_brake_gradient,
double(-0.05)); // [m/s^3]
pnh_.param(
"smooth_stop/stop_brake_time", smooth_stop_param_.stop_brake_time, double(2.0)); // [sec]
pnh_.param(
"smooth_stop/stop_brake_acc", smooth_stop_param_.stop_brake_acc, double(-1.7)); // [m/s^2]
pnh_.param("smooth_stop/stop_dist_", smooth_stop_param_.stop_dist_, double(3.0)); // [m/s^2]
// parameters for acceleration limit
pnh_.param("max_acc", max_acc_, double(2.0)); // [m/s^2]
pnh_.param("min_acc", min_acc_, double(-5.0)); // [m/s^2]
// parameters for jerk limit
pnh_.param("max_jerk", max_jerk_, double(2.0)); // [m/s^3]
pnh_.param("min_jerk", min_jerk_, double(-5.0)); // [m/s^3]
// parameters for slope compensation
pnh_.param("max_pitch_rad", max_pitch_rad_, double(0.1)); // [rad]
pnh_.param("min_pitch_rad", min_pitch_rad_, double(-0.1)); // [rad]
pnh_.param(
"pid_controller/current_vel_threshold_pid_integration", current_vel_threshold_pid_integrate_,
double(0.5)); // [m/s]
// subscriber, publisher and timer
sub_current_vel_ =
pnh_.subscribe("current_velocity", 1, &VelocityController::callbackCurrentVelocity, this);
sub_trajectory_ =
pnh_.subscribe("current_trajectory", 1, &VelocityController::callbackTrajectory, this);
pub_control_cmd_ = pnh_.advertise<autoware_control_msgs::ControlCommandStamped>("control_cmd", 1);
pub_debug_ = pnh_.advertise<std_msgs::Float32MultiArray>("debug_values", 1);
timer_control_ = nh_.createTimer(
ros::Duration(1.0 / control_rate_), &VelocityController::callbackTimerControl, this);
// initialize PID gain
double kp, ki, kd;
pnh_.param("pid_controller/kp", kp, double(0.0));
pnh_.param("pid_controller/ki", ki, double(0.0));
pnh_.param("pid_controllerd/kd", kd, double(0.0));
pid_vel_.setGains(kp, ki, kd);
// initialize PID limits
double max_pid, min_pid, max_p, min_p, max_i, min_i, max_d, min_d;
pnh_.param("pid_controller/max_out", max_pid, double(0.0)); // [m/s^2]
pnh_.param("pid_controller/min_out", min_pid, double(0.0)); // [m/s^2]
pnh_.param("pid_controller/max_p_effort", max_p, double(0.0)); // [m/s^2]
pnh_.param("pid_controller/min_p_effort", min_p, double(0.0)); // [m/s^2]
pnh_.param("pid_controller/max_i_effort", max_i, double(0.0)); // [m/s^2]
pnh_.param("pid_controller/min_i_effort", min_i, double(0.0)); // [m/s^2]
pnh_.param("pid_controller/max_d_effort", max_d, double(0.0)); // [m/s^2]
pnh_.param("pid_controller/min_d_effort", min_d, double(0.0)); // [m/s^2]
pid_vel_.setLimits(max_pid, min_pid, max_p, min_p, max_i, min_i, max_d, min_d);
// set lowpass filter
double lpf_vel_error_gain;
pnh_.param("pid_controller/lpf_vel_error_gain", lpf_vel_error_gain, double(0.9));
lpf_vel_error_.init(lpf_vel_error_gain);
double lpf_pitch_gain;
pnh_.param("lpf_pitch_gain", lpf_pitch_gain, double(0.95));
lpf_pitch_.init(lpf_pitch_gain);
debug_values_.data.clear();
debug_values_.data.resize(num_debug_values_, 0.0);
/* wait to get vehicle position */
while (ros::ok()) {
if (!updateCurrentPose(5.0)) {
ROS_INFO("waiting map to base_link at initialize.");
} else {
break;
}
}
}
void VelocityController::callbackCurrentVelocity(const geometry_msgs::TwistStamped::ConstPtr & msg)
{
current_vel_ptr_ = std::make_shared<geometry_msgs::TwistStamped>(*msg);
}
void VelocityController::callbackTrajectory(const autoware_planning_msgs::TrajectoryConstPtr & msg)
{
trajectory_ptr_ = std::make_shared<autoware_planning_msgs::Trajectory>(*msg);
}
bool VelocityController::getCurretPoseFromTF(
const double timeout_sec, geometry_msgs::PoseStamped & ps)
{
geometry_msgs::TransformStamped transform;
try {
transform =
tf_buffer_.lookupTransform("map", "base_link", ros::Time(0), ros::Duration(timeout_sec));
} catch (tf2::TransformException & ex) {
ROS_WARN_DELAYED_THROTTLE(3.0, "cannot get map to base_link transform. %s", ex.what());
return false;
}
ps.header = transform.header;
ps.pose.position.x = transform.transform.translation.x;
ps.pose.position.y = transform.transform.translation.y;
ps.pose.position.z = transform.transform.translation.z;
ps.pose.orientation = transform.transform.rotation;
return true;
}
bool VelocityController::updateCurrentPose(const double timeout_sec)
{
geometry_msgs::PoseStamped ps;
if (!getCurretPoseFromTF(timeout_sec, ps)) {
return false;
}
current_pose_ptr_ = std::make_shared<geometry_msgs::PoseStamped>(ps);
return true;
}
void VelocityController::callbackTimerControl(const ros::TimerEvent & event)
{
const bool is_pose_updated = updateCurrentPose(0.0);
/* gurad */
if (!is_pose_updated || !current_pose_ptr_ || !current_vel_ptr_ || !trajectory_ptr_) {
ROS_INFO_COND(
show_debug_info_,
"Waiting topics, Publish stop command. pose_update: %d, pose: %d, vel: %d, trajectory: %d",
is_pose_updated, current_pose_ptr_ != nullptr, current_vel_ptr_ != nullptr,
trajectory_ptr_ != nullptr);
controller_mode_ = ControlMode::INIT;
publishCtrlCmd(stop_state_vel_, stop_state_acc_);
return;
}
/* calculate command velocity & acceleration */
const CtrlCmd ctrl_cmd = calcCtrlCmd();
/* publish control command */
publishCtrlCmd(ctrl_cmd.vel, ctrl_cmd.acc);
debug_values_.data.at(DBGVAL::FLAG_SMOOTH_STOP) = is_smooth_stop_;
debug_values_.data.at(DBGVAL::FLAG_EMERGENCY_STOP) = is_emergency_stop_;
/* reset parameters depending on the current control mode */
resetHandling(controller_mode_);
}
CtrlCmd VelocityController::calcCtrlCmd()
{
/* initialize parameters */
const double dt = getDt();
/* -- find a closest waypoint index --
*
* If the closest is not found (when the threshold is exceeded), it is treated as an emergency stop.
*
* Outout velocity : "0" with maximum acceleration constraint
* Output acceleration : "emergency_stop_acc_" with maximum jerk constraint
*
*/
int closest_idx;
if (!vcutils::calcClosestWithThr(
*trajectory_ptr_, current_pose_ptr_->pose, closest_angle_thr_, closest_dist_thr_,
closest_idx)) {
ROS_ERROR_DELAYED_THROTTLE(
5.0,
"calcClosestWithThr: closest not found. Emergency Stop! (dist_thr = %3.3f [m], angle_thr = "
"%3.3f [rad])",
closest_dist_thr_, closest_angle_thr_);
double vel_cmd =
applyRateFilter(0.0, prev_vel_cmd_, dt, std::fabs(emergency_stop_acc_), emergency_stop_acc_);
double acc_cmd = applyRateFilter(
emergency_stop_acc_, prev_acc_cmd_, dt, std::fabs(emergency_stop_jerk_),
emergency_stop_jerk_);
controller_mode_ = ControlMode::ERROR;
ROS_INFO_COND(show_debug_info_, "[closest error]. vel: %3.3f, acc: %3.3f", vel_cmd, acc_cmd);
return CtrlCmd{vel_cmd, acc_cmd};
}
double current_vel = current_vel_ptr_->twist.linear.x;
int target_idx = DelayCompensator::getTrajectoryPointIndexAfterTimeDelay(
*trajectory_ptr_, closest_idx, delay_compensation_time_, current_vel);
double target_vel =
calcInterpolatedTargetVelocity(*trajectory_ptr_, *current_pose_ptr_, current_vel, target_idx);
double target_acc = DelayCompensator::getAccelerationAfterTimeDelay(
*trajectory_ptr_, closest_idx, delay_compensation_time_, current_vel);
/* shift check */
const Shift shift = getCurrentShift(target_vel);
if (shift != prev_shift_) pid_vel_.reset();
prev_shift_ = shift;
const double pitch_filtered = lpf_pitch_.filter(getPitch(current_pose_ptr_->pose.orientation));
const double stop_dist = calcStopDistance(*trajectory_ptr_, closest_idx);
writeDebugValues(dt, current_vel, target_vel, target_acc, shift, pitch_filtered, closest_idx);
/* ===== STOPPED =====
*
* If the current velocity and target velocity is almost zero,
* and the smooth stop is not working, enter the stop state.
*
* Outout velocity : "stop_state_vel_" (assumed to be zero, depending on the vehicle interface)
* Output acceleration : "stop_state_acc_" with max_jerk limit. (depending on the vehicle interface)
*
*/
if (checkIsStopped(current_vel, target_vel)) {
double acc_cmd = calcFilteredAcc(stop_state_acc_, pitch_filtered, dt, shift);
controller_mode_ = ControlMode::STOPPED;
ROS_INFO_COND(show_debug_info_, "[Stopped]. vel: %3.3f, acc: %3.3f", stop_state_vel_, acc_cmd);
return CtrlCmd{stop_state_vel_, acc_cmd};
}
/* ===== EMERGENCY STOP =====
*
* If the emergency flag is true, enter the emergency state.
* The condition of the energency is checked in checkEmergency() function.
* The flag is reset when the vehicle is stopped.
*
* Outout velocity : "0" with maximum acceleration constraint
* Output acceleration : "emergency_stop_acc_" with max_jerk limit.
*
*/
is_emergency_stop_ = checkEmergency(closest_idx, target_vel);
if (is_emergency_stop_) {
double vel_cmd =
applyRateFilter(0.0, prev_vel_cmd_, dt, std::fabs(emergency_stop_acc_), emergency_stop_acc_);
double acc_cmd = applyRateFilter(
emergency_stop_acc_, prev_acc_cmd_, dt, std::fabs(emergency_stop_jerk_),
emergency_stop_jerk_);
controller_mode_ = ControlMode::EMERGENCY_STOP;
ROS_ERROR_COND(show_debug_info_, "[Emergency stop] vel: %3.3f, acc: %3.3f", 0.0, acc_cmd);
return CtrlCmd{vel_cmd, acc_cmd};
}
/* ===== SMOOTH STOP =====
*
* If the vehicle veloicity & target velocity is low ehough, and there is a stop point nearby the ego vehicle,
* enter the smooth stop state.
*
* Outout velocity : "target_vel" from the reference trajectory
* Output acceleration : "emergency_stop_acc_" with max_jerk limit.
*
*/
is_smooth_stop_ = checkSmoothStop(closest_idx, target_vel);
if (is_smooth_stop_) {
if (!start_time_smooth_stop_) {
start_time_smooth_stop_ = std::make_shared<ros::Time>(ros::Time::now());
}
double smooth_stop_acc_cmd = calcSmoothStopAcc();
double acc_cmd = calcFilteredAcc(smooth_stop_acc_cmd, pitch_filtered, dt, shift);
controller_mode_ = ControlMode::SMOOTH_STOP;
ROS_WARN_COND(
show_debug_info_, "[smooth stop]: Smooth stopping. vel: %3.3f, acc: %3.3f", target_vel,
acc_cmd);
return CtrlCmd{target_vel, acc_cmd};
}
/* ===== FEEDBACK CONTROL =====
*
* Execute PID feedback control.
*
* Outout velocity : "target_vel" from the reference trajectory
* Output acceleration : calculated by PID controller with max_acceleration & max_jerk limit.
*
*/
double feedback_acc_cmd = applyVelocityFeedback(target_acc, target_vel, dt, current_vel);
double acc_cmd = calcFilteredAcc(feedback_acc_cmd, pitch_filtered, dt, shift);
controller_mode_ = ControlMode::PID_CONTROL;
ROS_INFO_COND(
show_debug_info_,
"[feedback control] vel: %3.3f, acc: %3.3f, dt: %3.3f, vcurr: %3.3f, vref: %3.3f "
"feedback_acc_cmd: "
"%3.3f, shift: %d",
target_vel, acc_cmd, dt, current_vel, target_vel, feedback_acc_cmd, shift);
return CtrlCmd{target_vel, acc_cmd};
}
void VelocityController::resetHandling(const ControlMode control_mode)
{
if (control_mode == ControlMode::EMERGENCY_STOP) {
pid_vel_.reset();
lpf_vel_error_.reset();
resetSmoothStop();
if (std::fabs(current_vel_ptr_->twist.linear.x) < stop_state_entry_ego_speed_) {
is_emergency_stop_ = false;
}
} else if (control_mode == ControlMode::ERROR) {
pid_vel_.reset();
resetSmoothStop();
} else if (control_mode == ControlMode::STOPPED) {
pid_vel_.reset();
lpf_vel_error_.reset();
resetSmoothStop();
resetEmergencyStop();
} else if (control_mode == ControlMode::SMOOTH_STOP) {
pid_vel_.reset();
lpf_vel_error_.reset();
} else if (control_mode == ControlMode::PID_CONTROL) {
resetSmoothStop();
}
}
void VelocityController::publishCtrlCmd(const double vel, const double acc)
{
prev_acc_cmd_ = acc;
prev_vel_cmd_ = vel;
autoware_control_msgs::ControlCommandStamped cmd;
cmd.header.stamp = ros::Time::now();
cmd.header.frame_id = "base_link";
cmd.control.velocity = vel;
cmd.control.acceleration = acc;
pub_control_cmd_.publish(cmd);
// debug
debug_values_.data.at(DBGVAL::CTRL_MODE) = static_cast<double>(controller_mode_);
debug_values_.data.at(DBGVAL::ACCCMD_PUBLISHED) = acc;
pub_debug_.publish(debug_values_);
debug_values_.data.clear();
debug_values_.data.resize(num_debug_values_, 0.0);
}
bool VelocityController::checkSmoothStop(const int closest, const double target_vel) const
{
if (!enable_smooth_stop_) {
return false;
}
if (
std::fabs(current_vel_ptr_->twist.linear.x) > smooth_stop_param_.entry_ego_speed ||
std::fabs(target_vel) > smooth_stop_param_.entry_target_speed) {
return false;
}
const double stop_dist = calcStopDistance(*trajectory_ptr_, closest);
if (std::fabs(stop_dist) < smooth_stop_param_.stop_dist_) {
return true; // stop point is found around ego position.
}
return false;
}
bool VelocityController::checkIsStopped(double current_vel, double target_vel) const
{
if (is_smooth_stop_) return false; // stopping.
if (
std::fabs(current_vel) < stop_state_entry_ego_speed_ &&
std::fabs(target_vel) < stop_state_entry_target_speed_) {
return true;
} else {
return false;
}
}
bool VelocityController::checkEmergency(int closest, double target_vel) const
{
// already in emergency.
if (is_emergency_stop_) {
return true;
}
// velocity is getting high when smoth stopping.
if (
is_smooth_stop_ &&
(std::fabs(current_vel_ptr_->twist.linear.x) > smooth_stop_param_.exit_ego_speed)) {
return true;
}
// overshoot stop line.
if (enable_overshoot_emergency_) {
double stop_dist = calcStopDistance(*trajectory_ptr_, closest);
if (stop_dist < -emergency_overshoot_dist_) {
return true;
}
}
return false;
}
double VelocityController::calcFilteredAcc(
const double raw_acc, const double pitch, const double dt, const Shift shift) const
{
double acc_max_filtered = applyLimitFilter(raw_acc, max_acc_, min_acc_);
debug_values_.data.at(DBGVAL::ACCCMD_ACC_LIMITED) = acc_max_filtered;
double acc_jerk_filtered =
applyRateFilter(acc_max_filtered, prev_acc_cmd_, dt, max_jerk_, min_jerk_);
debug_values_.data.at(DBGVAL::ACCCMD_JERK_LIMITED) = acc_jerk_filtered;
double acc_slope_filtered = applySlopeCompensation(acc_jerk_filtered, pitch, shift);
debug_values_.data.at(DBGVAL::ACCCMD_SLOPE_APPLIED) = acc_slope_filtered;
return acc_slope_filtered;
}
double VelocityController::getDt()
{
double dt;
if (!prev_control_time_) {
dt = 1.0 / control_rate_;
prev_control_time_ = std::make_shared<ros::Time>(ros::Time::now());
} else {
dt = (ros::Time::now() - *prev_control_time_).toSec();
*prev_control_time_ = ros::Time::now();
}
const double max_dt = 1.0 / control_rate_ * 2.0;
const double min_dt = 1.0 / control_rate_ * 0.5;
return std::max(std::min(dt, max_dt), min_dt);
}
enum VelocityController::Shift VelocityController::getCurrentShift(const double target_vel) const
{
const double ep = 1.0e-5;
return target_vel > ep ? Shift::Forward : (target_vel < -ep ? Shift::Reverse : prev_shift_);
}
double VelocityController::getPitch(const geometry_msgs::Quaternion & quaternion) const
{
Eigen::Quaterniond q(quaternion.w, quaternion.x, quaternion.y, quaternion.z);
Eigen::Vector3d v = q.toRotationMatrix() * Eigen::Vector3d::UnitX();
double den = std::max(std::sqrt(v.x() * v.x() + v.y() * v.y()), 1.0E-8 /* avoid 0 divide */);
double pitch = (-1.0) * std::atan2(v.z(), den);
return pitch;
}
double VelocityController::calcSmoothStopAcc()
{
const double elapsed_time = (ros::Time::now() - *start_time_smooth_stop_).toSec();
double acc_cmd;
if (elapsed_time < smooth_stop_param_.weak_brake_time) {
acc_cmd = smooth_stop_param_.weak_brake_acc;
ROS_INFO_COND(show_debug_info_, "[VC Smooth Stop] weak breaking! acc = %f", acc_cmd);
} else if (
elapsed_time <
(smooth_stop_param_.weak_brake_time + smooth_stop_param_.increasing_brake_time)) {
const double dt = elapsed_time - smooth_stop_param_.weak_brake_time;
acc_cmd = smooth_stop_param_.weak_brake_acc + smooth_stop_param_.increasing_brake_gradient * dt;
ROS_INFO_COND(show_debug_info_, "[VC Smooth Stop] break increasing! acc = %f", acc_cmd);
} else if (
elapsed_time < (smooth_stop_param_.weak_brake_time + smooth_stop_param_.increasing_brake_time +
smooth_stop_param_.stop_brake_time)) {
acc_cmd = smooth_stop_param_.stop_brake_acc;
ROS_INFO_COND(show_debug_info_, "[VC Smooth Stop] stop breaking! acc = %f", acc_cmd);
} else {
acc_cmd = smooth_stop_param_.stop_brake_acc;
ROS_INFO_COND(show_debug_info_, "[VC Smooth Stop] finish smooth stopping! acc = %f", acc_cmd);
resetSmoothStop();
}
return acc_cmd;
}
double VelocityController::calcStopDistance(
const autoware_planning_msgs::Trajectory & trajectory, const int origin) const
{
const double zero_velocity = 0.01;
const double origin_velocity = trajectory.points.at(origin).twist.linear.x;
double stop_dist = 0.0;
// search forward
if (std::fabs(origin_velocity) > zero_velocity) {
for (int i = origin + 1; i < (int)trajectory.points.size() - 1; ++i) {
stop_dist +=
vcutils::calcDistance2D(trajectory.points.at(i).pose, trajectory.points.at(i - 1).pose);
if (std::fabs(trajectory.points.at(i).twist.linear.x) < zero_velocity) {
break;
}
}
return stop_dist;
}
// search backward
for (int i = origin - 1; 0 < i; --i) {
if (std::fabs(trajectory.points.at(i).twist.linear.x) > zero_velocity) {
break;
}
stop_dist -=
vcutils::calcDistance2D(trajectory.points.at(i).pose, trajectory.points.at(i + 1).pose);
}
return stop_dist;
}
double VelocityController::calcInterpolatedTargetVelocity(
const autoware_planning_msgs::Trajectory & traj, const geometry_msgs::PoseStamped & curr_pose,
const double curr_vel, const int closest) const
{
const double closest_vel = traj.points.at(closest).twist.linear.x;
if (traj.points.size() < 2) {
return closest_vel;
}
/* If the current position is at the edge of the reference trajectory, enable the edge velocity. Else, calc secondary
* closest index for interpolation */
int closest_second;
geometry_msgs::Point rel_pos =
vcutils::transformToRelativeCoordinate2D(curr_pose.pose.position, traj.points.at(closest).pose);
if (closest == 0) {
if (rel_pos.x * curr_vel <= 0.0) {
return closest_vel;
}
closest_second = 1;
} else if (closest == (int)traj.points.size() - 1) {
if (rel_pos.x * curr_vel >= 0.0) {
return closest_vel;
}
closest_second = traj.points.size() - 2;
} else {
const double dist1 =
vcutils::calcDistSquared2D(traj.points.at(closest).pose, traj.points.at(closest - 1).pose);
const double dist2 =
vcutils::calcDistSquared2D(traj.points.at(closest).pose, traj.points.at(closest + 1).pose);
closest_second = dist1 < dist2 ? closest - 1 : closest + 1;
}
/* apply linear interpolation */
const double dist_c1 = vcutils::calcDistance2D(curr_pose.pose, traj.points.at(closest).pose);
const double dist_c2 =
vcutils::calcDistance2D(curr_pose.pose, traj.points.at(closest_second).pose);
const double v1 = traj.points.at(closest).twist.linear.x;
const double v2 = traj.points.at(closest_second).twist.linear.x;
const double vel_interp = (dist_c1 * v2 + dist_c2 * v1) / (dist_c1 + dist_c2);
return vel_interp;
}
double VelocityController::applyLimitFilter(
const double input_val, const double max_val, const double min_val) const
{
const double limitted_val = std::min(std::max(input_val, min_val), max_val);
return limitted_val;
}
double VelocityController::applyRateFilter(
const double input_val, const double prev_val, const double dt, const double max_val,
const double min_val) const
{
const double diff_raw = (input_val - prev_val) / dt;
const double diff = std::min(std::max(diff_raw, min_val), max_val);
const double filtered_val = prev_val + (diff * dt);
return filtered_val;
}
double VelocityController::applySlopeCompensation(
const double input_acc, const double pitch, const Shift shift) const
{
if (!enable_slope_compensation_) {
return input_acc;
}
constexpr double gravity = 9.80665;
const double pitch_limited = std::min(std::max(pitch, min_pitch_rad_), max_pitch_rad_);
double sign = (shift == Shift::Forward) ? -1 : (shift == Shift::Reverse ? 1 : 0);
double compensated_acc = input_acc + sign * gravity * std::sin(pitch_limited);
return compensated_acc;
}
double VelocityController::applyVelocityFeedback(
const double target_acc, const double target_vel, const double dt, const double current_vel)
{
const bool enable_integration =
std::fabs(current_vel) < current_vel_threshold_pid_integrate_ ? false : true;
const double error_vel_filtered =
lpf_vel_error_.filter(std::fabs(target_vel) - std::fabs(current_vel));
std::vector<double> pid_contributions(3);
const double pid_acc =
pid_vel_.calculate(error_vel_filtered, dt, enable_integration, pid_contributions);
const double feedbacked_acc = target_acc + pid_acc;
debug_values_.data.at(DBGVAL::ACCCMD_PID_APPLIED) = feedbacked_acc;
debug_values_.data.at(DBGVAL::ERROR_V_FILTERED) = error_vel_filtered;
debug_values_.data.at(DBGVAL::ACCCMD_FB_P_CONTRIBUTION) = pid_contributions.at(0); // P
debug_values_.data.at(DBGVAL::ACCCMD_FB_I_CONTRIBUTION) = pid_contributions.at(1); // I
debug_values_.data.at(DBGVAL::ACCCMD_FB_D_CONTRIBUTION) = pid_contributions.at(2); // D
return feedbacked_acc;
}
void VelocityController::resetSmoothStop()
{
is_smooth_stop_ = false;
start_time_smooth_stop_ = nullptr;
}
void VelocityController::resetEmergencyStop() { is_emergency_stop_ = false; }
void VelocityController::writeDebugValues(
const double dt, const double current_vel, const double target_vel, const double target_acc,
const Shift shift, const double pitch, const int32_t closest)
{
constexpr double rad2deg = 180.0 / 3.141592;
const double raw_pitch = getPitch(current_pose_ptr_->pose.orientation);
debug_values_.data.at(DBGVAL::DT) = dt;
debug_values_.data.at(DBGVAL::CURR_V) = current_vel;
debug_values_.data.at(DBGVAL::TARGET_V) = target_vel;
debug_values_.data.at(DBGVAL::TARGET_ACC) = target_acc;
debug_values_.data.at(DBGVAL::CLOSEST_V) = trajectory_ptr_->points.at(closest).twist.linear.x;
debug_values_.data.at(DBGVAL::CLOSEST_ACC) = trajectory_ptr_->points.at(closest).accel.linear.x;
debug_values_.data.at(DBGVAL::SHIFT) = static_cast<double>(shift);
debug_values_.data.at(DBGVAL::PITCH_LPFED_RAD) = pitch;
debug_values_.data.at(DBGVAL::PITCH_LPFED_DEG) = pitch * rad2deg;
debug_values_.data.at(DBGVAL::PITCH_RAW_RAD) = raw_pitch;
debug_values_.data.at(DBGVAL::PITCH_RAW_DEG) = raw_pitch * rad2deg;
debug_values_.data.at(DBGVAL::ERROR_V) = target_vel - current_vel;
}
| 39.057949 | 119 | 0.723275 | zqw-hooper |
592e8867399e10c8e956d9759ba667daeb494455 | 215 | hpp | C++ | include/zisa/mpi/mpi.hpp | 1uc/ZisaMPI | 4a832e6ea3e3806a5aa26e8bfd6dcdf89902cf2e | [
"MIT"
] | null | null | null | include/zisa/mpi/mpi.hpp | 1uc/ZisaMPI | 4a832e6ea3e3806a5aa26e8bfd6dcdf89902cf2e | [
"MIT"
] | null | null | null | include/zisa/mpi/mpi.hpp | 1uc/ZisaMPI | 4a832e6ea3e3806a5aa26e8bfd6dcdf89902cf2e | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: MIT
// Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval
#ifndef ZISA_MPI_HPP_CIKDL
#define ZISA_MPI_HPP_CIKDL
#include "mpi_decl.hpp"
#include "mpi_impl.hpp"
#endif // ZISA_MPI_HPP
| 19.545455 | 54 | 0.772093 | 1uc |
59320cb7a543e86a75f1dda55da6389a2c0d611e | 1,126 | hpp | C++ | Zadatak 5.5/trezor.hpp | pikacxe/Cpp_Projects | 4c1defc292a284b359a7583fa48ef51f2fec484b | [
"MIT"
] | null | null | null | Zadatak 5.5/trezor.hpp | pikacxe/Cpp_Projects | 4c1defc292a284b359a7583fa48ef51f2fec484b | [
"MIT"
] | null | null | null | Zadatak 5.5/trezor.hpp | pikacxe/Cpp_Projects | 4c1defc292a284b359a7583fa48ef51f2fec484b | [
"MIT"
] | null | null | null | #ifndef DEF_TREZOR
#define DEF_TREZOR
#include <iostream>
using namespace std;
template <class T, int N>
class Trezor{
private:
T sefovi[N];
bool popunjeni[N];
public:
Trezor(){
for (int i = 0; i< N;i++){
sefovi[i] = T();
popunjeni[i] = false;
}
}
int getBrojPopunjenihSefova() const {
int brPopunjenih = 0;
for(int i = 0; i < N;i++)
if(popunjeni[i] == true)
brPopunjenih++;
return brPopunjenih;
}
int ubaciSadrzaj(const T& predmet){
for(int i = 0;i < N;i++){
if(popunjeni[i] == false){
sefovi[i] = predmet;
popunjeni[i] = true;
return i;
}
}
return -1;
}
bool izbaciSadrzaj(int sef){
if(popunjeni[sef]){
popunjeni[sef] = false;
sefovi[sef] = T();
return true;
}
return false;
}
};
#endif
| 22.078431 | 45 | 0.408526 | pikacxe |
5933c571fdfd1a8905dc21d08d06dd5a442c4694 | 3,968 | cpp | C++ | Tudat/Astrodynamics/Propagators/UnitTests/unitTestFullPropagationLambertTargeter.cpp | ViktorJordanov/tudat | 069ceeab8f12405c356e19f50d6df037914df85c | [
"BSD-3-Clause"
] | null | null | null | Tudat/Astrodynamics/Propagators/UnitTests/unitTestFullPropagationLambertTargeter.cpp | ViktorJordanov/tudat | 069ceeab8f12405c356e19f50d6df037914df85c | [
"BSD-3-Clause"
] | null | null | null | Tudat/Astrodynamics/Propagators/UnitTests/unitTestFullPropagationLambertTargeter.cpp | ViktorJordanov/tudat | 069ceeab8f12405c356e19f50d6df037914df85c | [
"BSD-3-Clause"
] | null | null | null | <<<<<<< HEAD
/* Copyright (c) 2010-2017, Delft University of Technology
=======
/* Copyright (c) 2010-2019, Delft University of Technology
>>>>>>> origin/master
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*/
#define BOOST_TEST_MAIN
#include <Tudat/SimulationSetup/tudatEstimationHeader.h>
#include "Tudat/SimulationSetup/PropagationSetup/propagationLambertTargeterFullProblem.h"
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include <Eigen/Core>
#include "Tudat/Basics/testMacros.h"
#include "Tudat/Astrodynamics/Ephemerides/approximatePlanetPositions.h"
#include "Tudat/Astrodynamics/TrajectoryDesign/trajectory.h"
#include "Tudat/Astrodynamics/TrajectoryDesign/exportTrajectory.h"
#include "Tudat/Astrodynamics/TrajectoryDesign/planetTrajectory.h"
namespace tudat
{
namespace unit_tests
{
using namespace tudat;
//! Test if the difference between the Lambert targeter solution and the full dynamics problem is computed correctly.
BOOST_AUTO_TEST_CASE( testFullPropagationLambertTargeter )
{
std::cout.precision(20);
double initialTime = 0.0;
double fixedStepSize = 1.0;
Eigen::Vector3d cartesianPositionAtDeparture ( 2.0 * 6.378136e6, 0.0, 0.0 );
Eigen::Vector3d cartesianPositionAtArrival ( 2.0 * 6.378136e6, 2.0 * std::sqrt( 3.0 ) * 6.378136e6, 0.0 );
double timeOfFlight = 806.78 * 5.0;
std::string bodyToPropagate = "spacecraft" ;
std::string centralBody = "Earth";
// Define integrator settings.
std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =
std::make_shared < numerical_integrators::IntegratorSettings < > >
( numerical_integrators::rungeKutta4, initialTime, fixedStepSize);
std::vector< std::string > departureAndArrivalBodies;
departureAndArrivalBodies.push_back("departure");
departureAndArrivalBodies.push_back("arrival");
// Define the body map.
simulation_setup::NamedBodyMap bodyMap = propagators::setupBodyMapFromUserDefinedStatesForLambertTargeter("Earth", "spacecraft", departureAndArrivalBodies,
cartesianPositionAtDeparture, cartesianPositionAtArrival);
basic_astrodynamics::AccelerationMap accelerationModelMap = propagators::setupAccelerationMapLambertTargeter(
"Earth", "spacecraft", bodyMap);
// Compute the difference in state between the full problem and the Lambert targeter solution at departure and at arrival
std::pair< Eigen::Vector6d, Eigen::Vector6d > differenceState =
propagators::getDifferenceFullPropagationWrtLambertTargeterAtDepartureAndArrival(cartesianPositionAtDeparture,
cartesianPositionAtArrival, timeOfFlight, initialTime, bodyMap, accelerationModelMap, bodyToPropagate,
centralBody, integratorSettings, departureAndArrivalBodies, false);
Eigen::Vector6d differenceStateAtDeparture = differenceState.first;
Eigen::Vector6d differenceStateAtArrival = differenceState.second;
std::cout << "differenceStateAtDeparture: " << differenceStateAtDeparture << "\n\n";
std::cout << "differenceStateAtArrival: " << differenceStateAtArrival << "\n\n";
for( int i = 0; i < 3; i++ )
{
BOOST_CHECK_SMALL( std::fabs( differenceStateAtDeparture( i ) ), 1.0 );
BOOST_CHECK_SMALL( std::fabs( differenceStateAtDeparture( i + 3 ) ), 1.0E-6 );
BOOST_CHECK_SMALL( std::fabs( differenceStateAtArrival( i ) ), 1.0 );
BOOST_CHECK_SMALL( std::fabs( differenceStateAtArrival( i + 3 ) ), 1.0E-6 );
}
}
}
}
| 38.524272 | 159 | 0.722278 | ViktorJordanov |
59367cf9297e5ccdb6022b930e4a2176f39b1462 | 10,013 | cc | C++ | qpdf/test_large_file.cc | 1006079161/qpdf | baeb0f06124c859f71e614d8089ef2e6e6ff954f | [
"Apache-2.0"
] | 1,812 | 2015-01-27T09:07:20.000Z | 2022-03-30T23:03:15.000Z | qpdf/test_large_file.cc | 1006079161/qpdf | baeb0f06124c859f71e614d8089ef2e6e6ff954f | [
"Apache-2.0"
] | 584 | 2015-01-24T00:31:12.000Z | 2022-03-24T21:42:38.000Z | qpdf/test_large_file.cc | 1006079161/qpdf | baeb0f06124c859f71e614d8089ef2e6e6ff954f | [
"Apache-2.0"
] | 204 | 2015-04-09T16:28:06.000Z | 2022-03-29T14:29:45.000Z | // NOTE: This test program doesn't do anything special to enable large
// file support. This is important since it verifies that programs
// don't have to do anything special -- all the work is done
// internally by the library as long as they don't do their own file
// I/O.
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFPageDocumentHelper.hh>
#include <qpdf/QPDFWriter.hh>
#include <qpdf/QPDFObjectHandle.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/QIntC.hh>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
// Run "test_large_file write small a.pdf" to get a PDF file that you
// can look at in a reader.
// This program reads and writes specially crafted files for testing
// large file support. In write mode, write a file of npages pages
// where each page contains unique text and a unique image. The image
// is a binary representation of the page number. The image contains
// horizontal stripes with light stripes representing 1, dark stripes
// representing 0, and the high bit on top. In read mode, read the
// file back checking to make sure all the image data and page
// contents are as expected.
// Running this is small mode produces a small file that is easy to
// look at in any viewer. Since there is no question about proper
// functionality for small files, writing and reading the small file
// allows the qpdf library to test this test program. Writing and
// reading the large file then allows us to verify large file support
// with confidence.
static char const* whoami = 0;
// Height should be a multiple of 10
static size_t const nstripes = 10;
static size_t const stripesize_large = 500;
static size_t const stripesize_small = 5;
static size_t const npages = 200;
// initialized in main
size_t stripesize = 0;
size_t width = 0;
size_t height = 0;
static unsigned char* buf = 0;
static inline unsigned char get_pixel_color(size_t n, size_t row)
{
return ((n & (1LLU << (nstripes - 1LLU - row)))
? static_cast<unsigned char>('\xc0')
: static_cast<unsigned char>('\x40'));
}
class ImageChecker: public Pipeline
{
public:
ImageChecker(size_t n);
virtual ~ImageChecker();
virtual void write(unsigned char* data, size_t len);
virtual void finish();
private:
size_t n;
size_t offset;
bool okay;
};
ImageChecker::ImageChecker(size_t n) :
Pipeline("image checker", 0),
n(n),
offset(0),
okay(true)
{
}
ImageChecker::~ImageChecker()
{
}
void
ImageChecker::write(unsigned char* data, size_t len)
{
for (size_t i = 0; i < len; ++i)
{
size_t y = (this->offset + i) / width / stripesize;
unsigned char color = get_pixel_color(n, y);
if (data[i] != color)
{
okay = false;
}
}
this->offset += len;
}
void
ImageChecker::finish()
{
if (! okay)
{
std::cout << "errors found checking image data for page " << n
<< std::endl;
}
}
class ImageProvider: public QPDFObjectHandle::StreamDataProvider
{
public:
ImageProvider(size_t n);
virtual ~ImageProvider();
virtual void provideStreamData(int objid, int generation,
Pipeline* pipeline);
private:
size_t n;
};
ImageProvider::ImageProvider(size_t n) :
n(n)
{
}
ImageProvider::~ImageProvider()
{
}
void
ImageProvider::provideStreamData(int objid, int generation,
Pipeline* pipeline)
{
if (buf == 0)
{
buf = new unsigned char[width * stripesize];
}
std::cout << "page " << n << " of " << npages << std::endl;
for (size_t y = 0; y < nstripes; ++y)
{
unsigned char color = get_pixel_color(n, y);
memset(buf, color, width * stripesize);
pipeline->write(buf, width * stripesize);
}
pipeline->finish();
}
void usage()
{
std::cerr << "Usage: " << whoami << " {read|write} {large|small} outfile"
<< std::endl;
exit(2);
}
static void set_parameters(bool large)
{
stripesize = large ? stripesize_large : stripesize_small;
height = nstripes * stripesize;
width = height;
}
std::string generate_page_contents(size_t pageno)
{
std::string contents =
"BT /F1 24 Tf 72 720 Td (page " + QUtil::uint_to_string(pageno) +
") Tj ET\n"
"q 468 0 0 468 72 72 cm /Im1 Do Q\n";
return contents;
}
static QPDFObjectHandle create_page_contents(QPDF& pdf, size_t pageno)
{
return QPDFObjectHandle::newStream(&pdf, generate_page_contents(pageno));
}
QPDFObjectHandle newName(std::string const& name)
{
return QPDFObjectHandle::newName(name);
}
QPDFObjectHandle newInteger(size_t val)
{
return QPDFObjectHandle::newInteger(QIntC::to_longlong(val));
}
static void create_pdf(char const* filename)
{
QPDF pdf;
pdf.emptyPDF();
QPDFObjectHandle font = pdf.makeIndirectObject(
QPDFObjectHandle::newDictionary());
font.replaceKey("/Type", newName("/Font"));
font.replaceKey("/Subtype", newName("/Type1"));
font.replaceKey("/Name", newName("/F1"));
font.replaceKey("/BaseFont", newName("/Helvetica"));
font.replaceKey("/Encoding", newName("/WinAnsiEncoding"));
QPDFObjectHandle procset =
pdf.makeIndirectObject(QPDFObjectHandle::newArray());
procset.appendItem(newName("/PDF"));
procset.appendItem(newName("/Text"));
procset.appendItem(newName("/ImageC"));
QPDFObjectHandle rfont = QPDFObjectHandle::newDictionary();
rfont.replaceKey("/F1", font);
QPDFObjectHandle mediabox = QPDFObjectHandle::newArray();
mediabox.appendItem(newInteger(0));
mediabox.appendItem(newInteger(0));
mediabox.appendItem(newInteger(612));
mediabox.appendItem(newInteger(792));
QPDFPageDocumentHelper dh(pdf);
for (size_t pageno = 1; pageno <= npages; ++pageno)
{
QPDFObjectHandle image = QPDFObjectHandle::newStream(&pdf);
QPDFObjectHandle image_dict = image.getDict();
image_dict.replaceKey("/Type", newName("/XObject"));
image_dict.replaceKey("/Subtype", newName("/Image"));
image_dict.replaceKey("/ColorSpace", newName("/DeviceGray"));
image_dict.replaceKey("/BitsPerComponent", newInteger(8));
image_dict.replaceKey("/Width", newInteger(width));
image_dict.replaceKey("/Height", newInteger(height));
ImageProvider* p = new ImageProvider(pageno);
PointerHolder<QPDFObjectHandle::StreamDataProvider> provider(p);
image.replaceStreamData(provider,
QPDFObjectHandle::newNull(),
QPDFObjectHandle::newNull());
QPDFObjectHandle xobject = QPDFObjectHandle::newDictionary();
xobject.replaceKey("/Im1", image);
QPDFObjectHandle resources = QPDFObjectHandle::newDictionary();
resources.replaceKey("/ProcSet", procset);
resources.replaceKey("/Font", rfont);
resources.replaceKey("/XObject", xobject);
QPDFObjectHandle contents = create_page_contents(pdf, pageno);
QPDFObjectHandle page = pdf.makeIndirectObject(
QPDFObjectHandle::newDictionary());
page.replaceKey("/Type", newName("/Page"));
page.replaceKey("/MediaBox", mediabox);
page.replaceKey("/Contents", contents);
page.replaceKey("/Resources", resources);
dh.addPage(page, false);
}
QPDFWriter w(pdf, filename);
w.setStaticID(true); // for testing only
w.setStreamDataMode(qpdf_s_preserve);
w.setObjectStreamMode(qpdf_o_disable);
w.write();
}
static void check_page_contents(size_t pageno, QPDFObjectHandle page)
{
PointerHolder<Buffer> buf =
page.getKey("/Contents").getStreamData();
std::string actual_contents =
std::string(reinterpret_cast<char *>(buf->getBuffer()),
buf->getSize());
std::string expected_contents = generate_page_contents(pageno);
if (expected_contents != actual_contents)
{
std::cout << "page contents wrong for page " << pageno << std::endl
<< "ACTUAL: " << actual_contents
<< "EXPECTED: " << expected_contents
<< "----\n";
}
}
static void check_image(size_t pageno, QPDFObjectHandle page)
{
QPDFObjectHandle image =
page.getKey("/Resources").getKey("/XObject").getKey("/Im1");
ImageChecker ic(pageno);
image.pipeStreamData(&ic, 0, qpdf_dl_specialized);
}
static void check_pdf(char const* filename)
{
QPDF pdf;
pdf.processFile(filename);
std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages();
assert(pages.size() == QIntC::to_size(npages));
for (size_t i = 0; i < npages; ++i)
{
size_t pageno = i + 1;
std::cout << "page " << pageno << " of " << npages << std::endl;
check_page_contents(pageno, pages.at(i));
check_image(pageno, pages.at(i));
}
}
int main(int argc, char* argv[])
{
whoami = QUtil::getWhoami(argv[0]);
QUtil::setLineBuf(stdout);
// For libtool's sake....
if (strncmp(whoami, "lt-", 3) == 0)
{
whoami += 3;
}
if (argc != 4)
{
usage();
}
char const* operation = argv[1];
char const* size = argv[2];
char const* filename = argv[3];
bool op_write = false;
bool size_large = false;
if (strcmp(operation, "write") == 0)
{
op_write = true;
}
else if (strcmp(operation, "read") == 0)
{
op_write = false;
}
else
{
usage();
}
if (strcmp(size, "large") == 0)
{
size_large = true;
}
else if (strcmp(size, "small") == 0)
{
size_large = false;
}
else
{
usage();
}
set_parameters(size_large);
try
{
if (op_write)
{
create_pdf(filename);
}
else
{
check_pdf(filename);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
exit(2);
}
delete [] buf;
return 0;
}
| 27.135501 | 77 | 0.633177 | 1006079161 |
59385a9dcf20c4042c5bae157db6e38bac235608 | 12,992 | cpp | C++ | legion/engine/core/scheduling/scheduler.cpp | Legion-Engine/Legion-Engine | a2b898e1cc763b82953c6990dde0b379491a30d0 | [
"MIT"
] | 258 | 2020-10-22T07:09:57.000Z | 2021-09-09T05:47:09.000Z | legion/engine/core/scheduling/scheduler.cpp | LeonBrands/Legion-Engine | 40aa1f4a8c59eb0824de1cdda8e17d8dba7bed7c | [
"MIT"
] | 51 | 2020-11-17T13:02:10.000Z | 2021-09-07T18:19:39.000Z | legion/engine/core/scheduling/scheduler.cpp | LeonBrands/Legion-Engine | 40aa1f4a8c59eb0824de1cdda8e17d8dba7bed7c | [
"MIT"
] | 13 | 2020-12-08T08:06:48.000Z | 2021-09-09T05:47:19.000Z | #include <core/scheduling/scheduler.hpp>
#include <core/events/events.hpp>
#include <core/engine/engine.hpp>
namespace legion::core::scheduling
{
void Scheduler::onInit()
{
reportDependency<events::EventBus>();
reportDependency<Clock>();
events::EventBus::bindToEvent<events::exit>([](events::exit& evnt)
{
instance.m_exitFromEvent.store(true, std::memory_order_release);
Scheduler::exit(evnt.exitcode);
});
create();
}
void Scheduler::onShutdown()
{
if (!isExiting())
exit(0);
}
void Scheduler::threadMain(bool lowPower, std::string name)
{
log::info("Thread {} assigned.", std::this_thread::get_id());
async::set_thread_name(name.c_str());
OPTICK_THREAD(name.c_str());
while (!instance.m_start.load(std::memory_order_relaxed))
std::this_thread::yield();
log::info("Starting thread.");
time::timer clock;
time::span timeBuffer;
time::span sleepTime;
while (!instance.m_exit.load(std::memory_order_relaxed))
{
bool noWork = true;
std::shared_ptr<async::job_pool> jobPoolPtr = nullptr;
{
auto& [lock, jobQueue] = instance.m_jobs;
async::readonly_guard guard(lock);
if (!jobQueue.empty())
{
noWork = false;
jobPoolPtr = jobQueue.front();
if (!jobPoolPtr->is_done())
{
if (jobPoolPtr->prime_job()) // Returns true when this is the last job.
{
async::readwrite_guard wguard(lock);
if (!jobQueue.empty())
{
if (jobQueue.front() == jobPoolPtr)
jobQueue.pop_front();
else
jobQueue.remove(jobPoolPtr);
}
}
}
else
{
async::readwrite_guard wguard(lock);
if (!jobQueue.empty())
{
if (jobQueue.front() == jobPoolPtr)
jobQueue.pop_front();
else
jobQueue.remove(jobPoolPtr);
}
jobPoolPtr = nullptr;
}
}
}
if (jobPoolPtr)
jobPoolPtr->complete_job();
if (noWork)
{
timeBuffer += clock.restart();
if (lowPower || LEGION_CONFIGURATION == LEGION_DEBUG_VALUE)
{
OPTICK_EVENT("Sleep");
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
else if (timeBuffer >= sleepTime * instance.m_pollTime.load(std::memory_order_relaxed))
{
OPTICK_EVENT("Sleep");
timeBuffer -= sleepTime;
time::timer sleepTimer;
sleepTimer.start();
std::this_thread::sleep_for(std::chrono::nanoseconds(1));
sleepTime = sleepTimer.elapsed_time();
}
else
std::this_thread::yield();
}
else
{
timeBuffer = 0.f;
clock.start();
}
}
log::info("Shutting down thread.");
}
void Scheduler::tryCompleteJobPool()
{
auto& [lock, jobQueue] = instance.m_jobs;
async::readwrite_guard wguard(lock);
if (!jobQueue.empty() && jobQueue.front()->is_done())
{
jobQueue.pop_front();
}
}
void Scheduler::doTick(Clock::span_type deltaTime)
{
OPTICK_FRAME("Main thread");
time::span dt{ deltaTime };
instance.m_onFrameStart(dt, time::span(Clock::elapsedSinceTickStart()));
for (auto [_, chain] : instance.m_processChains)
chain.runInCurrentThread(dt);
instance.m_onFrameEnd(dt, time::span(Clock::elapsedSinceTickStart()));
}
pointer<std::thread> Scheduler::getThread(std::thread::id id)
{
return { &instance.m_threads.at(id) };
}
int Scheduler::run(bool lowPower, size_type minThreads)
{
bool m_lowPower = lowPower;
size_type m_minThreads = minThreads < 1 ? 1 : minThreads;
if (instance.m_maxThreadCount < m_minThreads)
m_lowPower = true;
if (instance.m_availableThreads < m_minThreads)
instance.m_availableThreads = m_minThreads;
pointer<std::thread> ptr;
std::string name = "Worker ";
{
auto& logData = log::impl::get();
async::readwrite_guard guard(logData.threadNamesLock);
while ((ptr = createThread(Scheduler::threadMain, m_lowPower, name + std::to_string(instance.m_jobPoolSize))) != nullptr)
logData.threadNames[ptr->get_id()] = name + std::to_string(instance.m_jobPoolSize++);
logData.threadNames[std::this_thread::get_id()] = "Main thread";
}
instance.m_start.store(true, std::memory_order_release);
Clock::subscribeToTick(doTick);
while (!instance.m_exit.load(std::memory_order_relaxed))
{
Clock::update();
float deltaTime = static_cast<float>(Clock::lastTickDuration());
static size_type framecount = 0;
static float totalTime = 0;
static uint bestAvg = 0;
static float bestPollTime = 0.1f;
totalTime += deltaTime;
framecount++;
if (totalTime > 5.f)
{
uint avg = math::uround(1.f / (totalTime / static_cast<float>(framecount)));
totalTime = 0.f;
framecount = 0;
float pollTime = instance.m_pollTime.load(std::memory_order_relaxed);
log::debug("avg: {} poll: {:.3f}\tbAvg: {} bPoll: {:.3f}", avg, pollTime, bestAvg, bestPollTime);
if (avg > bestAvg)
{
bestPollTime = pollTime;
bestAvg = avg;
pollTime += (math::linearRand<int8>(0, 1) ? 0.05f : -0.05f);
pollTime = math::mod(pollTime + 1.f, 1.f);
}
else if (math::close_enough(bestPollTime, pollTime))
{
if (avg < static_cast<uint>(static_cast<float>(bestAvg) * 0.9f))
bestAvg = 0;
pollTime += (math::linearRand<int8>(0, 1) ? 0.05f : -0.05f);
pollTime = math::mod(pollTime + 1.f, 1.f);
}
else
{
pollTime = bestPollTime;
}
instance.m_pollTime.store(pollTime, std::memory_order_relaxed);
}
if (m_lowPower)
std::this_thread::yield();
else
L_PAUSE_INSTRUCTION();
}
Engine::shutdownModules();
for (auto& [_, thread] : instance.m_threads)
if (thread.joinable())
thread.join();
return instance.m_exitCode;
}
void Scheduler::exit(int exitCode)
{
if (!instance.m_exitFromEvent.load(std::memory_order_relaxed))
{
events::EventBus::raiseEvent<events::exit>(exitCode);
return;
}
if (instance.m_exit.load(std::memory_order_relaxed))
{
log::warn("Engine was already exiting, triggered additional exit event with code {}", exitCode);
return;
}
log::undecoratedInfo("=========================\n"
"| Shutting down engine. |\n"
"=========================");
instance.m_exitCode = exitCode;
instance.m_exit.store(true, std::memory_order_release);
}
bool Scheduler::isExiting()
{
return instance.m_exit.load(std::memory_order_relaxed);
}
size_type Scheduler::jobPoolSize() noexcept
{
return instance.m_jobPoolSize;
}
pointer<ProcessChain> Scheduler::createProcessChain(cstring name)
{
id_type id = nameHash(name);
return { &instance.m_processChains.emplace(id, name, id).first.value() };
}
pointer<ProcessChain> Scheduler::getChain(id_type id)
{
if (instance.m_processChains.contains(id))
return { &instance.m_processChains.at(id) };
return { nullptr };
}
pointer<ProcessChain> Scheduler::getChain(cstring name)
{
id_type id = nameHash(name);
if (instance.m_processChains.contains(id))
return { &instance.m_processChains.at(id) };
return { nullptr };
}
void Scheduler::subscribeToChainStart(id_type chainId, const chain_callback_delegate& callback)
{
instance.m_processChains.at(chainId).subscribeToChainStart(callback);
}
void Scheduler::subscribeToChainStart(cstring chainName, const chain_callback_delegate& callback)
{
id_type chainId = nameHash(chainName);
instance.m_processChains.at(chainId).subscribeToChainStart(callback);
}
void Scheduler::unsubscribeFromChainStart(id_type chainId, const chain_callback_delegate& callback)
{
instance.m_processChains.at(chainId).unsubscribeFromChainStart(callback);
}
void Scheduler::unsubscribeFromChainStart(cstring chainName, const chain_callback_delegate& callback)
{
id_type chainId = nameHash(chainName);
instance.m_processChains.at(chainId).unsubscribeFromChainStart(callback);
}
void Scheduler::subscribeToChainEnd(id_type chainId, const chain_callback_delegate& callback)
{
instance.m_processChains.at(chainId).subscribeToChainEnd(callback);
}
void Scheduler::subscribeToChainEnd(cstring chainName, const chain_callback_delegate& callback)
{
id_type chainId = nameHash(chainName);
instance.m_processChains.at(chainId).subscribeToChainEnd(callback);
}
void Scheduler::subscribeToFrameStart(const frame_callback_delegate& callback)
{
instance.m_onFrameStart.push_back(callback);
}
void Scheduler::unsubscribeFromFrameStart(const frame_callback_delegate& callback)
{
instance.m_onFrameStart.erase(callback);
}
void Scheduler::subscribeToFrameEnd(const frame_callback_delegate& callback)
{
instance.m_onFrameEnd.push_back(callback);
}
void Scheduler::unsubscribeFromFrameEnd(const frame_callback_delegate& callback)
{
instance.m_onFrameEnd.erase(callback);
}
void Scheduler::unsubscribeFromChainEnd(id_type chainId, const chain_callback_delegate& callback)
{
instance.m_processChains.at(chainId).unsubscribeFromChainEnd(callback);
}
void Scheduler::unsubscribeFromChainEnd(cstring chainName, const chain_callback_delegate& callback)
{
id_type chainId = nameHash(chainName);
instance.m_processChains.at(chainId).unsubscribeFromChainEnd(callback);
}
bool Scheduler::hookProcess(cstring chainName, Process& process)
{
id_type chainId = nameHash(chainName);
if (instance.m_processChains.contains(chainId))
{
instance.m_processChains[chainId].addProcess(process);
return true;
}
return false;
}
bool Scheduler::hookProcess(cstring chainName, pointer<Process> process)
{
id_type chainId = nameHash(chainName);
if (instance.m_processChains.contains(chainId))
{
instance.m_processChains[chainId].addProcess(process);
return true;
}
return false;
}
bool Scheduler::unhookProcess(cstring chainName, Process& process)
{
id_type chainId = nameHash(chainName);
if (instance.m_processChains.contains(chainId))
return instance.m_processChains[chainId].removeProcess(process);
return false;
}
bool Scheduler::unhookProcess(cstring chainName, pointer<Process> process)
{
id_type chainId = nameHash(chainName);
if (instance.m_processChains.contains(chainId))
return instance.m_processChains[chainId].removeProcess(process);
return false;
}
bool Scheduler::unhookProcess(id_type chainId, pointer<Process> process)
{
if (instance.m_processChains.contains(chainId))
return instance.m_processChains[chainId].removeProcess(process);
return false;
}
}
| 31.843137 | 133 | 0.558267 | Legion-Engine |
593b161afaef7e0b72adced5a6162694b17503f8 | 1,212 | hpp | C++ | include/operations/data.hpp | rationalis-petra/hydra | a1c14e560f5f1c64983468e5fd0be7b32824971d | [
"MIT"
] | 2 | 2021-01-14T11:19:02.000Z | 2021-03-07T03:08:08.000Z | include/operations/data.hpp | rationalis-petra/hydra | a1c14e560f5f1c64983468e5fd0be7b32824971d | [
"MIT"
] | null | null | null | include/operations/data.hpp | rationalis-petra/hydra | a1c14e560f5f1c64983468e5fd0be7b32824971d | [
"MIT"
] | null | null | null | #ifndef __MODULUS_OPERATIONS_DATA_HPP
#define __MODULUS_OPERATIONS_DATA_HPP
#include "expressions.hpp"
namespace op {
void initialize_data();
void initialize_symbol();
void initialize_string();
void initialize_vector();
void initialize_tuple();
void initialize_object();
void initialize_cons();
void initialize_user_obj();
extern expr::GenericFn *len;
extern expr::GenericFn *get;
extern expr::GenericFn *set;
extern expr::GenericFn *cat;
// String operations: creation, indexing, length & concatenation
extern expr::GenericFn* to_str;
// character
// Cons-Cell creation, Car, Cdr
extern expr::Operator* mk_list;
extern expr::Operator* mk_cons;
extern expr::GenericFn* car;
extern expr::GenericFn* cdr;
// Vector operations: creation, indexing, length & concatenation
extern expr::Operator* mk_vec;
extern expr::Operator* mk_union;
extern expr::Operator* mk_tuple;
// Object operations: creation, slot retreival, inheritance (expr::Operator* op,
// prototyping)
extern expr::GenericFn* mk_obj;
extern expr::GenericFn* clone;
// Symbol operations: making mutable/unmutable
extern expr::Operator* mk_mutable;
extern expr::Operator* mk_const;
}
#endif
| 24.24 | 80 | 0.744224 | rationalis-petra |
593c4327a4a7631b41377359a3e2dc8627314753 | 5,786 | cpp | C++ | VC2010Samples/MFC/Visual C++ 2008 Feature Pack/VisualStudioDemo/ResourceView.cpp | alonmm/VCSamples | 6aff0b4902f5027164d593540fcaa6601a0407c3 | [
"MIT"
] | 300 | 2019-05-09T05:32:33.000Z | 2022-03-31T20:23:24.000Z | VC2010Samples/MFC/Visual C++ 2008 Feature Pack/VisualStudioDemo/ResourceView.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 9 | 2016-09-19T18:44:26.000Z | 2018-10-26T10:20:05.000Z | VC2010Samples/MFC/Visual C++ 2008 Feature Pack/VisualStudioDemo/ResourceView.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 633 | 2019-05-08T07:34:12.000Z | 2022-03-30T04:38:28.000Z | // This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "VisualStudioDemo.h"
#include "MainFrm.h"
#include "ResourceView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CResourceViewBar
CResourceViewBar::CResourceViewBar()
{
}
CResourceViewBar::~CResourceViewBar()
{
}
BEGIN_MESSAGE_MAP(CResourceViewBar, CDockablePane)
ON_WM_CREATE()
ON_WM_SIZE()
ON_WM_CONTEXTMENU()
ON_COMMAND(ID_EDIT_CUT, OnEditCut)
ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
ON_COMMAND(ID_EDIT_CLEAR, OnEditClear)
ON_WM_PAINT()
ON_WM_SETFOCUS()
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CResourceViewBar message handlers
int CResourceViewBar::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDockablePane::OnCreate(lpCreateStruct) == -1)
return -1;
CRect rectDummy;
rectDummy.SetRectEmpty();
// Create view:
const DWORD dwViewStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS;
if (!m_wndResourceView.Create(dwViewStyle, rectDummy, this, 3))
{
TRACE0("Failed to create workspace view\n");
return -1; // fail to create
}
// Load view images:
m_ResourceViewImages.Create(IDB_RESOURCE_VIEW, 16, 0, RGB(255, 0, 255));
m_wndResourceView.SetImageList(&m_ResourceViewImages, TVSIL_NORMAL);
// Fill view context(dummy code, don't seek here something magic :-)):
FillResourceView();
OnChangeVisualStyle();
return 0;
}
void CResourceViewBar::OnSize(UINT nType, int cx, int cy)
{
CDockablePane::OnSize(nType, cx, cy);
if (CanAdjustLayout())
{
m_wndResourceView.SetWindowPos(NULL, 1, 1, cx - 2, cy - 2, SWP_NOACTIVATE | SWP_NOZORDER);
}
}
void CResourceViewBar::FillResourceView()
{
HTREEITEM hRoot = m_wndResourceView.InsertItem(_T("Hello resources"), 0, 0);
m_wndResourceView.SetItemState(hRoot, TVIS_BOLD, TVIS_BOLD);
HTREEITEM hFolder = m_wndResourceView.InsertItem(_T("Accelerator"), 0, 0, hRoot);
m_wndResourceView.InsertItem(_T("IDR_MAINFRAME"), 1, 1, hFolder);
m_wndResourceView.Expand(hRoot, TVE_EXPAND);
hFolder = m_wndResourceView.InsertItem(_T("Dialog"), 0, 0, hRoot);
m_wndResourceView.InsertItem(_T("IDD_ABOUTBOX"), 3, 3, hFolder);
hFolder = m_wndResourceView.InsertItem(_T("Icon"), 0, 0, hRoot);
m_wndResourceView.InsertItem(_T("IDR_HELLO"), 4, 4, hFolder);
m_wndResourceView.InsertItem(_T("IDR_MAINFRAME"), 4, 4, hFolder);
m_wndResourceView.Expand(hFolder, TVE_EXPAND);
hFolder = m_wndResourceView.InsertItem(_T("Menu"), 0, 0, hRoot);
m_wndResourceView.InsertItem(_T("IDR_CONTEXT_MENU"), 5, 5, hFolder);
m_wndResourceView.InsertItem(_T("IDR_HELLO"), 5, 5, hFolder);
m_wndResourceView.InsertItem(_T("IDR_MAINFRAME"), 5, 5, hFolder);
m_wndResourceView.InsertItem(_T("IDR_POPUP_TOOLBAR"), 5, 5, hFolder);
m_wndResourceView.Expand(hFolder, TVE_EXPAND);
hFolder = m_wndResourceView.InsertItem(_T("String Table"), 0, 0, hRoot);
m_wndResourceView.InsertItem(_T("String Table"), 6, 6, hFolder);
hFolder = m_wndResourceView.InsertItem(_T("Toolbar"), 0, 0, hRoot);
m_wndResourceView.InsertItem(_T("IDR_MAINFRAME"), 7, 7, hFolder);
hFolder = m_wndResourceView.InsertItem(_T("Version"), 0, 0, hRoot);
m_wndResourceView.InsertItem(_T("VS_VERSION_INFO"), 8, 8, hFolder);
}
void CResourceViewBar::OnContextMenu(CWnd* pWnd, CPoint point)
{
CTreeCtrl* pWndTree = (CTreeCtrl*) &m_wndResourceView;
ASSERT_VALID(pWndTree);
if (pWnd != pWndTree)
{
CDockablePane::OnContextMenu(pWnd, point);
return;
}
if (point != CPoint(-1, -1))
{
// Select clicked item:
CPoint ptTree = point;
pWndTree->ScreenToClient(&ptTree);
UINT flags = 0;
HTREEITEM hTreeItem = pWndTree->HitTest(ptTree, &flags);
if (hTreeItem != NULL)
{
pWndTree->SelectItem(hTreeItem);
}
}
pWndTree->SetFocus();
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_RESOURCE, point.x, point.y, this, TRUE);
}
void CResourceViewBar::OnEditCut()
{
// TODO: Add your command handler code here
}
void CResourceViewBar::OnEditCopy()
{
// TODO: Add your command handler code here
}
void CResourceViewBar::OnEditPaste()
{
// TODO: Add your command handler code here
}
void CResourceViewBar::OnEditClear()
{
// TODO: Add your command handler code here
}
void CResourceViewBar::OnPaint()
{
CPaintDC dc(this); // device context for painting
CRect rectTree;
m_wndResourceView.GetWindowRect(rectTree);
ScreenToClient(rectTree);
rectTree.InflateRect(1, 1);
dc.Draw3dRect(rectTree, ::GetSysColor(COLOR_3DSHADOW), ::GetSysColor(COLOR_3DSHADOW));
}
void CResourceViewBar::OnSetFocus(CWnd* pOldWnd)
{
CDockablePane::OnSetFocus(pOldWnd);
m_wndResourceView.SetFocus();
}
void CResourceViewBar::OnChangeVisualStyle()
{
m_ResourceViewImages.DeleteImageList();
UINT uiBmpId = theApp.m_bHiColorIcons ? IDB_RESOURCE_VIEW24 : IDB_RESOURCE_VIEW;
CBitmap bmp;
if (!bmp.LoadBitmap(uiBmpId))
{
TRACE(_T("Can't load bitmap: %x\n"), uiBmpId);
ASSERT(FALSE);
return;
}
BITMAP bmpObj;
bmp.GetBitmap(&bmpObj);
UINT nFlags = ILC_MASK;
nFlags |= (theApp.m_bHiColorIcons) ? ILC_COLOR24 : ILC_COLOR4;
m_ResourceViewImages.Create(16, bmpObj.bmHeight, nFlags, 0, 0);
m_ResourceViewImages.Add(&bmp, RGB(255, 0, 255));
m_wndResourceView.SetImageList(&m_ResourceViewImages, TVSIL_NORMAL);
}
| 26.3 | 117 | 0.728483 | alonmm |
86c8792fb1229559a8fe3edcba44ccbe6e41f5b0 | 456 | cpp | C++ | exercises/4/seminar/10/SoftwareCompany/SoftwareCompany.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 19 | 2020-02-21T16:46:50.000Z | 2022-01-26T19:59:49.000Z | exercises/4/seminar/10/SoftwareCompany/SoftwareCompany.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 1 | 2020-03-14T08:09:45.000Z | 2020-03-14T08:09:45.000Z | exercises/4/seminar/10/SoftwareCompany/SoftwareCompany.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 11 | 2020-02-23T12:29:58.000Z | 2021-04-11T08:30:12.000Z | // SoftwareCompany.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include "Person.h"
#include "Client.h"
#include "Employee.h"
using namespace std;
int main() {
Person p1("georgi", "todorov", 42);
cout << p1;
string ordersArr[] = { "order1", "order2" };
Vector<string> orders(ordersArr, 2);
Client c(p1, orders);
cout << c;
Employee e(p1);
cout << e;
} | 18.24 | 105 | 0.627193 | triffon |
86cb2f98c386e8bf3258725260e3e9158753bc1d | 3,319 | cpp | C++ | Wrappers/d3d8/d3d8wrapper.cpp | FrozenFish24/Silent-Hill-2-Enhancements | 36c55524824c1e0bb3bdfcaac88ee4a564881a33 | [
"Zlib"
] | null | null | null | Wrappers/d3d8/d3d8wrapper.cpp | FrozenFish24/Silent-Hill-2-Enhancements | 36c55524824c1e0bb3bdfcaac88ee4a564881a33 | [
"Zlib"
] | null | null | null | Wrappers/d3d8/d3d8wrapper.cpp | FrozenFish24/Silent-Hill-2-Enhancements | 36c55524824c1e0bb3bdfcaac88ee4a564881a33 | [
"Zlib"
] | null | null | null | /**
* Copyright (C) 2020 Elisha Riedlinger
*
* This software is provided 'as-is', without any express or implied warranty. In no event will the
* authors be held liable for any damages arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you wrote the
* original software. If you use this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented as
* being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "d3d8wrapper.h"
#include "Wrappers\wrapper.h"
#include "Common\Utils.h"
Direct3DCreate8Proc m_pDirect3DCreate8 = nullptr;
HMODULE GetD3d8ScriptDll()
{
// Load wrapper d3d8 from scripts or plugins folder
HMODULE script_d3d8_dll = nullptr;
// Get script paths
wchar_t scriptpath[MAX_PATH];
if (GetSH2FolderPath(scriptpath, MAX_PATH) && wcsrchr(scriptpath, '\\'))
{
wcscpy_s(wcsrchr(scriptpath, '\\'), MAX_PATH - wcslen(scriptpath), L"\0");
}
std::wstring script_path(scriptpath + std::wstring(L"\\scripts"));
std::wstring script_path_dll(script_path + L"\\d3d8.dll");
std::wstring plugin_path(scriptpath + std::wstring(L"\\plugins"));
std::wstring plugin_path_dll(plugin_path + L"\\d3d8.dll");
// Store the current folder
wchar_t currentDir[MAX_PATH] = { 0 };
GetCurrentDirectory(MAX_PATH, currentDir);
// Load d3d8.dll from 'scripts' folder
SetCurrentDirectory(script_path.c_str());
script_d3d8_dll = LoadLibrary(script_path_dll.c_str());
if (script_d3d8_dll)
{
Logging::Log() << "Loaded d3d8.dll from: " << script_path_dll.c_str();
}
// Load d3d8.dll from 'plugins' folder
if (!script_d3d8_dll)
{
SetCurrentDirectory(plugin_path.c_str());
script_d3d8_dll = LoadLibrary(plugin_path_dll.c_str());
if (script_d3d8_dll)
{
Logging::Log() << "Loaded d3d8.dll from: " << plugin_path_dll.c_str();
}
}
// Set current folder back
SetCurrentDirectory(currentDir);
return script_d3d8_dll;
}
// Hook d3d8 API
void HookDirect3DCreate8()
{
// Get Direct3DCreate8 address
constexpr BYTE SearchBytes[]{ 0x84, 0xC0, 0x74, 0x06, 0xB8, 0x03, 0x00, 0x00, 0x00, 0xC3, 0x68, 0xDC, 0x00, 0x00, 0x00, 0xE8 };
DWORD Address = SearchAndGetAddresses(0x004F6315, 0x004F65C5, 0x004F5E85, SearchBytes, sizeof(SearchBytes), 0x0F);
// Checking address pointer
if (!Address)
{
Logging::Log() << __FUNCTION__ << " Error: failed to find memory address!";
return;
}
// Get function address
m_pDirect3DCreate8 = (Direct3DCreate8Proc)(Address + 5 + *(DWORD*)(Address + 1));
// Write to memory
WriteCalltoMemory((BYTE*)Address, *Direct3DCreate8Wrapper, 5);
}
IDirect3D8 *WINAPI Direct3DCreate8Wrapper(UINT SDKVersion)
{
LOG_LIMIT(3, "Redirecting 'Direct3DCreate8' ...");
LPDIRECT3D8 pD3D8 = m_pDirect3DCreate8(SDKVersion);
if (pD3D8)
{
return new m_IDirect3D8(pD3D8);
}
else
{
Logging::Log() << "'Direct3DCreate8' Failed!";
}
return nullptr;
}
| 31.311321 | 128 | 0.726122 | FrozenFish24 |
86cbb51d76787ea3229d814cc1ff3e1cc8c74dd9 | 1,687 | hpp | C++ | generator/translator_geocoder_base.hpp | kadetlessy/omim | f28560ac36899ef8694e75a36535b0f1487b285b | [
"Apache-2.0"
] | 1 | 2021-07-02T08:45:02.000Z | 2021-07-02T08:45:02.000Z | generator/translator_geocoder_base.hpp | kadetlessy/omim | f28560ac36899ef8694e75a36535b0f1487b285b | [
"Apache-2.0"
] | 1 | 2020-06-15T15:16:23.000Z | 2020-06-15T15:59:19.000Z | generator/translator_geocoder_base.hpp | maksimandrianov/omim | cbc5a80d09d585afbda01e471887f63b9d3ab0c2 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "generator/osm_element.hpp"
#include "generator/translator_interface.hpp"
#include "indexer/feature_data.hpp"
#include <memory>
#include <vector>
#include <string>
class FeatureBuilder1;
struct OsmElement;
namespace feature
{
struct GenerateInfo;
} // namespace feature
namespace generator
{
class EmitterInterface;
namespace cache
{
class IntermediateDataReader;
} // namespace cache
class CollectorInterface;
// TranslatorGeocoderBase class is responsible for processing only points and polygons.
class TranslatorGeocoderBase : public TranslatorInterface
{
public:
explicit TranslatorGeocoderBase(std::shared_ptr<EmitterInterface> emitter,
cache::IntermediateDataReader & holder);
virtual ~TranslatorGeocoderBase() = default;
// TranslatorInterface overrides:
void EmitElement(OsmElement * p) override;
bool Finish() override;
void GetNames(std::vector<std::string> & names) const override;
void AddCollector(std::shared_ptr<CollectorInterface> collector);
protected:
virtual bool IsSuitableElement(OsmElement const * p) const = 0;
bool ParseParams(OsmElement * p, FeatureParams & params) const;
void BuildFeatureAndEmitFromRelation(OsmElement const * p, FeatureParams & params);
void BuildFeatureAndEmitFromWay(OsmElement const * p, FeatureParams & params);
void BuildFeatureAndEmitFromNode(OsmElement const * p, FeatureParams & params);
private:
void Emit(FeatureBuilder1 & fb, OsmElement const * p);
std::shared_ptr<EmitterInterface> m_emitter;
cache::IntermediateDataReader & m_holder;
std::vector<std::shared_ptr<CollectorInterface>> m_collectors;
};
} // namespace generator
| 28.116667 | 87 | 0.771784 | kadetlessy |
86ce6ba56deb9630a300c67eb817c923731f78da | 466 | hpp | C++ | src/util/serialization/serialization.hpp | wchang22/Nova | 3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb | [
"MIT"
] | 21 | 2020-05-02T06:32:23.000Z | 2021-07-14T11:22:07.000Z | src/util/serialization/serialization.hpp | wchang22/Nova | 3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb | [
"MIT"
] | null | null | null | src/util/serialization/serialization.hpp | wchang22/Nova | 3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb | [
"MIT"
] | 1 | 2021-05-24T13:44:56.000Z | 2021-05-24T13:44:56.000Z | #ifndef SERIALIZATION_HPP
#define SERIALIZATION_HPP
#include <iostream>
#include <vector>
template <typename T>
std::istream& operator>>(std::istream& in, std::vector<T>& vec) {
T t;
while (in >> t) {
vec.emplace_back(std::move(t));
}
return in;
}
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& vec) {
for (const auto& el : vec) {
out << el << std::endl;
}
return out;
}
#endif // SERIALIZATION_HPP
| 18.64 | 72 | 0.645923 | wchang22 |
86d19d1336c945d1de4b4b3a01c94cf9a65b2dbf | 738 | hh | C++ | include/lowi/registers/r10d.hh | kmc7468/lowi | 067358f6b1beaf94286488675b3efaa89359a48b | [
"MIT"
] | 4 | 2017-10-01T07:08:58.000Z | 2017-12-03T02:40:49.000Z | include/lowi/registers/r10d.hh | kmc7468/lowi | 067358f6b1beaf94286488675b3efaa89359a48b | [
"MIT"
] | null | null | null | include/lowi/registers/r10d.hh | kmc7468/lowi | 067358f6b1beaf94286488675b3efaa89359a48b | [
"MIT"
] | null | null | null | #ifndef LOWI_HEADER_REGISTERS_R10D_HH
#define LOWI_HEADER_REGISTERS_R10D_HH
#include <lowi/register_type.hh>
namespace lowi
{
namespace registers
{
class r10d final : public register_type
{
public:
r10d();
r10d(const r10d& r10d) = default;
r10d(r10d&& r10d) noexcept = default;
virtual ~r10d() override = default;
public:
r10d& operator=(const r10d& r10d) = default;
r10d& operator=(r10d&& r10d) noexcept = default;
bool operator==(const r10d& r10d) const noexcept;
bool operator!=(const r10d& r10d) const noexcept;
public:
r10d& assign(const r10d& r10d);
r10d& assign(r10d&& r10d) noexcept;
bool equal(const r10d& r10d) const noexcept;
public:
static ptr create();
};
}
}
#endif | 21.085714 | 52 | 0.693767 | kmc7468 |
86d4f06ee7cc06073e9f6aba981d247ecb20924d | 931 | hpp | C++ | PUTM_EV_TELEMETRY_2022/Core/Inc/lib/CanHeaders/PM08-CANBUS-BMS_HV.hpp | PUT-Motorsport/PUTM_EV_TELEMETRY_2022 | 808ed3e7c9b4263b541a804233e5905f6a9b4240 | [
"Apache-2.0"
] | null | null | null | PUTM_EV_TELEMETRY_2022/Core/Inc/lib/CanHeaders/PM08-CANBUS-BMS_HV.hpp | PUT-Motorsport/PUTM_EV_TELEMETRY_2022 | 808ed3e7c9b4263b541a804233e5905f6a9b4240 | [
"Apache-2.0"
] | null | null | null | PUTM_EV_TELEMETRY_2022/Core/Inc/lib/CanHeaders/PM08-CANBUS-BMS_HV.hpp | PUT-Motorsport/PUTM_EV_TELEMETRY_2022 | 808ed3e7c9b4263b541a804233e5905f6a9b4240 | [
"Apache-2.0"
] | 1 | 2021-11-22T20:06:58.000Z | 2021-11-22T20:06:58.000Z | //Generated on Sat Apr 30 12:45:15 2022
#ifndef BMS_HV
#define BMS_HV
#include <cstdint>
#include "lib/message_abstraction.hpp"
enum struct BMS_HV_states: uint8_t {
AIR_opened, // normal
AIR_closed, // normal
Precharge, // normal
Charger_connected, // normal
Unbalanced, // warning
Unbalanced_critical, // shut down
Voltage_low, // shut down
Voltage_high, // shut down
Temp_high, // shut down
Current_high, // shut down
};
struct __attribute__ ((packed)) BMS_HV_main{
int16_t voltage_sum;
int8_t soc; // state of charge
int8_t temp_max;
int8_t temp_avg; // in Celsius
int8_t current;
BMS_HV_states device_state; //
};
const uint16_t BMS_HV_MAIN_CAN_ID = 0xa;
const uint8_t BMS_HV_MAIN_CAN_DLC = sizeof(BMS_HV_main);
const uint8_t BMS_HV_MAIN_FREQUENCY = 100;
const CAN_TxHeaderTypeDef can_tx_header_BMS_HV_MAIN{
BMS_HV_MAIN_CAN_ID, 0xFFF, CAN_ID_STD, CAN_RTR_DATA, BMS_HV_MAIN_CAN_DLC, DISABLE};
#endif
| 23.275 | 83 | 0.765843 | PUT-Motorsport |
86d62028db76db5e8e68caf4f76b0bae74d438ce | 38,267 | hpp | C++ | include/HoudiniEngineUnity/HEU_ObjectNode.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/HoudiniEngineUnity/HEU_ObjectNode.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/HoudiniEngineUnity/HEU_ObjectNode.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.ScriptableObject
#include "UnityEngine/ScriptableObject.hpp"
// Including type: HoudiniEngineUnity.IEquivable`1
#include "HoudiniEngineUnity/IEquivable_1.hpp"
// Including type: HoudiniEngineUnity.HAPI_ObjectInfo
#include "HoudiniEngineUnity/HAPI_ObjectInfo.hpp"
// Including type: HoudiniEngineUnity.HAPI_Transform
#include "HoudiniEngineUnity/HAPI_Transform.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: HoudiniEngineUnity
namespace HoudiniEngineUnity {
// Forward declaring type: HEU_HoudiniAsset
class HEU_HoudiniAsset;
// Forward declaring type: HEU_GeoNode
class HEU_GeoNode;
// Forward declaring type: HEU_SessionBase
class HEU_SessionBase;
// Forward declaring type: HAPI_GeoInfo
struct HAPI_GeoInfo;
// Forward declaring type: HEU_MaterialData
class HEU_MaterialData;
// Forward declaring type: HEU_PartData
class HEU_PartData;
// Forward declaring type: HEU_GeneratedOutput
class HEU_GeneratedOutput;
// Forward declaring type: HEU_Curve
class HEU_Curve;
// Forward declaring type: HEU_ObjectInstanceInfo
class HEU_ObjectInstanceInfo;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Forward declaring namespace: System::Text
namespace System::Text {
// Forward declaring type: StringBuilder
class StringBuilder;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: GameObject
class GameObject;
}
// Completed forward declares
// Type namespace: HoudiniEngineUnity
namespace HoudiniEngineUnity {
// Forward declaring type: HEU_ObjectNode
class HEU_ObjectNode;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::HoudiniEngineUnity::HEU_ObjectNode);
DEFINE_IL2CPP_ARG_TYPE(::HoudiniEngineUnity::HEU_ObjectNode*, "HoudiniEngineUnity", "HEU_ObjectNode");
// Type namespace: HoudiniEngineUnity
namespace HoudiniEngineUnity {
// Size: 0x74
#pragma pack(push, 1)
// Autogenerated type: HoudiniEngineUnity.HEU_ObjectNode
// [TokenAttribute] Offset: FFFFFFFF
class HEU_ObjectNode : public ::UnityEngine::ScriptableObject/*, public ::HoudiniEngineUnity::IEquivable_1<::HoudiniEngineUnity::HEU_ObjectNode*>*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private System.String _objName
// Size: 0x8
// Offset: 0x18
::StringW objName;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// private HoudiniEngineUnity.HEU_HoudiniAsset _parentAsset
// Size: 0x8
// Offset: 0x20
::HoudiniEngineUnity::HEU_HoudiniAsset* parentAsset;
// Field size check
static_assert(sizeof(::HoudiniEngineUnity::HEU_HoudiniAsset*) == 0x8);
// private HoudiniEngineUnity.HAPI_ObjectInfo _objectInfo
// Size: 0x1C
// Offset: 0x28
::HoudiniEngineUnity::HAPI_ObjectInfo objectInfo;
// Field size check
static_assert(sizeof(::HoudiniEngineUnity::HAPI_ObjectInfo) == 0x1C);
// Padding between fields: objectInfo and: geoNodes
char __padding2[0x4] = {};
// private System.Collections.Generic.List`1<HoudiniEngineUnity.HEU_GeoNode> _geoNodes
// Size: 0x8
// Offset: 0x48
::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_GeoNode*>* geoNodes;
// Field size check
static_assert(sizeof(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_GeoNode*>*) == 0x8);
// public HoudiniEngineUnity.HAPI_Transform _objectTransform
// Size: 0x24
// Offset: 0x50
::HoudiniEngineUnity::HAPI_Transform objectTransform;
// Field size check
static_assert(sizeof(::HoudiniEngineUnity::HAPI_Transform) == 0x24);
public:
// Creating interface conversion operator: operator ::HoudiniEngineUnity::IEquivable_1<::HoudiniEngineUnity::HEU_ObjectNode*>
operator ::HoudiniEngineUnity::IEquivable_1<::HoudiniEngineUnity::HEU_ObjectNode*>() noexcept {
return *reinterpret_cast<::HoudiniEngineUnity::IEquivable_1<::HoudiniEngineUnity::HEU_ObjectNode*>*>(this);
}
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: private System.String _objName
::StringW& dyn__objName();
// Get instance field reference: private HoudiniEngineUnity.HEU_HoudiniAsset _parentAsset
::HoudiniEngineUnity::HEU_HoudiniAsset*& dyn__parentAsset();
// Get instance field reference: private HoudiniEngineUnity.HAPI_ObjectInfo _objectInfo
::HoudiniEngineUnity::HAPI_ObjectInfo& dyn__objectInfo();
// Get instance field reference: private System.Collections.Generic.List`1<HoudiniEngineUnity.HEU_GeoNode> _geoNodes
::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_GeoNode*>*& dyn__geoNodes();
// Get instance field reference: public HoudiniEngineUnity.HAPI_Transform _objectTransform
::HoudiniEngineUnity::HAPI_Transform& dyn__objectTransform();
// public System.Int32 get_ObjectID()
// Offset: 0x185FB7C
int get_ObjectID();
// public System.String get_ObjectName()
// Offset: 0x185FB84
::StringW get_ObjectName();
// public HoudiniEngineUnity.HEU_HoudiniAsset get_ParentAsset()
// Offset: 0x185FB8C
::HoudiniEngineUnity::HEU_HoudiniAsset* get_ParentAsset();
// public System.Boolean IsInstanced()
// Offset: 0x185FB94
bool IsInstanced();
// public System.Boolean IsVisible()
// Offset: 0x185FB9C
bool IsVisible();
// public System.Void Reset()
// Offset: 0x185FBCC
void Reset();
// private System.Void SyncWithObjectInfo(HoudiniEngineUnity.HEU_SessionBase session)
// Offset: 0x185FC8C
void SyncWithObjectInfo(::HoudiniEngineUnity::HEU_SessionBase* session);
// public System.Void Initialize(HoudiniEngineUnity.HEU_SessionBase session, HoudiniEngineUnity.HAPI_ObjectInfo objectInfo, HoudiniEngineUnity.HAPI_Transform objectTranform, HoudiniEngineUnity.HEU_HoudiniAsset parentAsset)
// Offset: 0x185FD90
void Initialize(::HoudiniEngineUnity::HEU_SessionBase* session, ::HoudiniEngineUnity::HAPI_ObjectInfo objectInfo, ::HoudiniEngineUnity::HAPI_Transform objectTranform, ::HoudiniEngineUnity::HEU_HoudiniAsset* parentAsset);
// public System.Void DestroyAllData(System.Boolean bIsRebuild)
// Offset: 0x186014C
void DestroyAllData(bool bIsRebuild);
// private HoudiniEngineUnity.HEU_GeoNode CreateGeoNode(HoudiniEngineUnity.HEU_SessionBase session, HoudiniEngineUnity.HAPI_GeoInfo geoInfo)
// Offset: 0x1860090
::HoudiniEngineUnity::HEU_GeoNode* CreateGeoNode(::HoudiniEngineUnity::HEU_SessionBase* session, ::HoudiniEngineUnity::HAPI_GeoInfo geoInfo);
// public System.Void GetDebugInfo(System.Text.StringBuilder sb)
// Offset: 0x1860250
void GetDebugInfo(::System::Text::StringBuilder* sb);
// public System.Void SetObjectInfo(HoudiniEngineUnity.HAPI_ObjectInfo newObjectInfo)
// Offset: 0x18604A0
void SetObjectInfo(::HoudiniEngineUnity::HAPI_ObjectInfo newObjectInfo);
// public System.Void UpdateObject(HoudiniEngineUnity.HEU_SessionBase session, System.Boolean bForceUpdate)
// Offset: 0x18604BC
void UpdateObject(::HoudiniEngineUnity::HEU_SessionBase* session, bool bForceUpdate);
// public System.Void GenerateGeometry(HoudiniEngineUnity.HEU_SessionBase session, System.Boolean bRebuild)
// Offset: 0x1860C5C
void GenerateGeometry(::HoudiniEngineUnity::HEU_SessionBase* session, bool bRebuild);
// public System.Void GeneratePartInstances(HoudiniEngineUnity.HEU_SessionBase session)
// Offset: 0x1861340
void GeneratePartInstances(::HoudiniEngineUnity::HEU_SessionBase* session);
// public System.Void GenerateAttributesStore(HoudiniEngineUnity.HEU_SessionBase session)
// Offset: 0x1861448
void GenerateAttributesStore(::HoudiniEngineUnity::HEU_SessionBase* session);
// public System.Void ApplyObjectTransformToGeoNodes()
// Offset: 0x1861240
void ApplyObjectTransformToGeoNodes();
// public System.Boolean IsUsingMaterial(HoudiniEngineUnity.HEU_MaterialData materialData)
// Offset: 0x1861550
bool IsUsingMaterial(::HoudiniEngineUnity::HEU_MaterialData* materialData);
// public System.Void GetClonableParts(System.Collections.Generic.List`1<HoudiniEngineUnity.HEU_PartData> clonableParts)
// Offset: 0x1861668
void GetClonableParts(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_PartData*>* clonableParts);
// public System.Void GetOutputGameObjects(System.Collections.Generic.List`1<UnityEngine.GameObject> outputObjects)
// Offset: 0x1861788
void GetOutputGameObjects(::System::Collections::Generic::List_1<::UnityEngine::GameObject*>* outputObjects);
// public System.Void GetOutput(System.Collections.Generic.List`1<HoudiniEngineUnity.HEU_GeneratedOutput> outputs)
// Offset: 0x1861890
void GetOutput(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_GeneratedOutput*>* outputs);
// public HoudiniEngineUnity.HEU_PartData GetHDAPartWithGameObject(UnityEngine.GameObject outputGameObject)
// Offset: 0x1861998
::HoudiniEngineUnity::HEU_PartData* GetHDAPartWithGameObject(::UnityEngine::GameObject* outputGameObject);
// public HoudiniEngineUnity.HEU_GeoNode GetGeoNode(System.String geoName)
// Offset: 0x1861AF0
::HoudiniEngineUnity::HEU_GeoNode* GetGeoNode(::StringW geoName);
// public System.Void GetCurves(System.Collections.Generic.List`1<HoudiniEngineUnity.HEU_Curve> curves, System.Boolean bEditableOnly)
// Offset: 0x1861C1C
void GetCurves(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_Curve*>* curves, bool bEditableOnly);
// public System.Void GetOutputGeoNodes(System.Collections.Generic.List`1<HoudiniEngineUnity.HEU_GeoNode> outGeoNodes)
// Offset: 0x1861D30
void GetOutputGeoNodes(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_GeoNode*>* outGeoNodes);
// public System.Void GenerateObjectInstances(HoudiniEngineUnity.HEU_SessionBase session)
// Offset: 0x1861E64
void GenerateObjectInstances(::HoudiniEngineUnity::HEU_SessionBase* session);
// public System.Void ClearObjectInstances(HoudiniEngineUnity.HEU_SessionBase session)
// Offset: 0x18624D0
void ClearObjectInstances(::HoudiniEngineUnity::HEU_SessionBase* session);
// public System.Void PopulateObjectInstanceInfos(System.Collections.Generic.List`1<HoudiniEngineUnity.HEU_ObjectInstanceInfo> objInstanceInfos)
// Offset: 0x186269C
void PopulateObjectInstanceInfos(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_ObjectInstanceInfo*>* objInstanceInfos);
// public System.Void ProcessUnityScriptAttributes(HoudiniEngineUnity.HEU_SessionBase session)
// Offset: 0x18627F4
void ProcessUnityScriptAttributes(::HoudiniEngineUnity::HEU_SessionBase* session);
// public System.Void HideAllGeometry()
// Offset: 0x18628FC
void HideAllGeometry();
// public System.Void CalculateVisibility()
// Offset: 0x18629F4
void CalculateVisibility();
// public System.Void CalculateColliderState()
// Offset: 0x1862AF0
void CalculateColliderState();
// public System.Void DisableAllColliders()
// Offset: 0x1862BE8
void DisableAllColliders();
// public System.Boolean IsInstancer()
// Offset: 0x18623B8
bool IsInstancer();
// public System.Boolean IsEquivalentTo(HoudiniEngineUnity.HEU_ObjectNode other)
// Offset: 0x1862D58
bool IsEquivalentTo(::HoudiniEngineUnity::HEU_ObjectNode* other);
// public System.Void .ctor()
// Offset: 0x185FBA4
// Implemented from: UnityEngine.ScriptableObject
// Base method: System.Void ScriptableObject::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static HEU_ObjectNode* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::HoudiniEngineUnity::HEU_ObjectNode::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<HEU_ObjectNode*, creationType>()));
}
// public override System.String ToString()
// Offset: 0x1862CE0
// Implemented from: UnityEngine.Object
// Base method: System.String Object::ToString()
::StringW ToString();
}; // HoudiniEngineUnity.HEU_ObjectNode
#pragma pack(pop)
static check_size<sizeof(HEU_ObjectNode), 80 + sizeof(::HoudiniEngineUnity::HAPI_Transform)> __HoudiniEngineUnity_HEU_ObjectNodeSizeCheck;
static_assert(sizeof(HEU_ObjectNode) == 0x74);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::get_ObjectID
// Il2CppName: get_ObjectID
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::get_ObjectID)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "get_ObjectID", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::get_ObjectName
// Il2CppName: get_ObjectName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::get_ObjectName)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "get_ObjectName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::get_ParentAsset
// Il2CppName: get_ParentAsset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::HoudiniEngineUnity::HEU_HoudiniAsset* (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::get_ParentAsset)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "get_ParentAsset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::IsInstanced
// Il2CppName: IsInstanced
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::IsInstanced)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "IsInstanced", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::IsVisible
// Il2CppName: IsVisible
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::IsVisible)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "IsVisible", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::Reset
// Il2CppName: Reset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::Reset)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::SyncWithObjectInfo
// Il2CppName: SyncWithObjectInfo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_SessionBase*)>(&HoudiniEngineUnity::HEU_ObjectNode::SyncWithObjectInfo)> {
static const MethodInfo* get() {
static auto* session = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_SessionBase")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "SyncWithObjectInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{session});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::Initialize
// Il2CppName: Initialize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_SessionBase*, ::HoudiniEngineUnity::HAPI_ObjectInfo, ::HoudiniEngineUnity::HAPI_Transform, ::HoudiniEngineUnity::HEU_HoudiniAsset*)>(&HoudiniEngineUnity::HEU_ObjectNode::Initialize)> {
static const MethodInfo* get() {
static auto* session = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_SessionBase")->byval_arg;
static auto* objectInfo = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HAPI_ObjectInfo")->byval_arg;
static auto* objectTranform = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HAPI_Transform")->byval_arg;
static auto* parentAsset = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_HoudiniAsset")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "Initialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{session, objectInfo, objectTranform, parentAsset});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::DestroyAllData
// Il2CppName: DestroyAllData
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(bool)>(&HoudiniEngineUnity::HEU_ObjectNode::DestroyAllData)> {
static const MethodInfo* get() {
static auto* bIsRebuild = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "DestroyAllData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{bIsRebuild});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::CreateGeoNode
// Il2CppName: CreateGeoNode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::HoudiniEngineUnity::HEU_GeoNode* (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_SessionBase*, ::HoudiniEngineUnity::HAPI_GeoInfo)>(&HoudiniEngineUnity::HEU_ObjectNode::CreateGeoNode)> {
static const MethodInfo* get() {
static auto* session = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_SessionBase")->byval_arg;
static auto* geoInfo = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HAPI_GeoInfo")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "CreateGeoNode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{session, geoInfo});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GetDebugInfo
// Il2CppName: GetDebugInfo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::System::Text::StringBuilder*)>(&HoudiniEngineUnity::HEU_ObjectNode::GetDebugInfo)> {
static const MethodInfo* get() {
static auto* sb = &::il2cpp_utils::GetClassFromName("System.Text", "StringBuilder")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GetDebugInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sb});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::SetObjectInfo
// Il2CppName: SetObjectInfo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HAPI_ObjectInfo)>(&HoudiniEngineUnity::HEU_ObjectNode::SetObjectInfo)> {
static const MethodInfo* get() {
static auto* newObjectInfo = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HAPI_ObjectInfo")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "SetObjectInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{newObjectInfo});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::UpdateObject
// Il2CppName: UpdateObject
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_SessionBase*, bool)>(&HoudiniEngineUnity::HEU_ObjectNode::UpdateObject)> {
static const MethodInfo* get() {
static auto* session = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_SessionBase")->byval_arg;
static auto* bForceUpdate = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "UpdateObject", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{session, bForceUpdate});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GenerateGeometry
// Il2CppName: GenerateGeometry
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_SessionBase*, bool)>(&HoudiniEngineUnity::HEU_ObjectNode::GenerateGeometry)> {
static const MethodInfo* get() {
static auto* session = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_SessionBase")->byval_arg;
static auto* bRebuild = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GenerateGeometry", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{session, bRebuild});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GeneratePartInstances
// Il2CppName: GeneratePartInstances
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_SessionBase*)>(&HoudiniEngineUnity::HEU_ObjectNode::GeneratePartInstances)> {
static const MethodInfo* get() {
static auto* session = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_SessionBase")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GeneratePartInstances", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{session});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GenerateAttributesStore
// Il2CppName: GenerateAttributesStore
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_SessionBase*)>(&HoudiniEngineUnity::HEU_ObjectNode::GenerateAttributesStore)> {
static const MethodInfo* get() {
static auto* session = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_SessionBase")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GenerateAttributesStore", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{session});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::ApplyObjectTransformToGeoNodes
// Il2CppName: ApplyObjectTransformToGeoNodes
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::ApplyObjectTransformToGeoNodes)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "ApplyObjectTransformToGeoNodes", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::IsUsingMaterial
// Il2CppName: IsUsingMaterial
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_MaterialData*)>(&HoudiniEngineUnity::HEU_ObjectNode::IsUsingMaterial)> {
static const MethodInfo* get() {
static auto* materialData = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_MaterialData")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "IsUsingMaterial", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{materialData});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GetClonableParts
// Il2CppName: GetClonableParts
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_PartData*>*)>(&HoudiniEngineUnity::HEU_ObjectNode::GetClonableParts)> {
static const MethodInfo* get() {
static auto* clonableParts = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_PartData")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GetClonableParts", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{clonableParts});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GetOutputGameObjects
// Il2CppName: GetOutputGameObjects
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::System::Collections::Generic::List_1<::UnityEngine::GameObject*>*)>(&HoudiniEngineUnity::HEU_ObjectNode::GetOutputGameObjects)> {
static const MethodInfo* get() {
static auto* outputObjects = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "GameObject")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GetOutputGameObjects", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{outputObjects});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GetOutput
// Il2CppName: GetOutput
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_GeneratedOutput*>*)>(&HoudiniEngineUnity::HEU_ObjectNode::GetOutput)> {
static const MethodInfo* get() {
static auto* outputs = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_GeneratedOutput")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GetOutput", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{outputs});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GetHDAPartWithGameObject
// Il2CppName: GetHDAPartWithGameObject
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::HoudiniEngineUnity::HEU_PartData* (HoudiniEngineUnity::HEU_ObjectNode::*)(::UnityEngine::GameObject*)>(&HoudiniEngineUnity::HEU_ObjectNode::GetHDAPartWithGameObject)> {
static const MethodInfo* get() {
static auto* outputGameObject = &::il2cpp_utils::GetClassFromName("UnityEngine", "GameObject")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GetHDAPartWithGameObject", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{outputGameObject});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GetGeoNode
// Il2CppName: GetGeoNode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::HoudiniEngineUnity::HEU_GeoNode* (HoudiniEngineUnity::HEU_ObjectNode::*)(::StringW)>(&HoudiniEngineUnity::HEU_ObjectNode::GetGeoNode)> {
static const MethodInfo* get() {
static auto* geoName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GetGeoNode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{geoName});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GetCurves
// Il2CppName: GetCurves
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_Curve*>*, bool)>(&HoudiniEngineUnity::HEU_ObjectNode::GetCurves)> {
static const MethodInfo* get() {
static auto* curves = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_Curve")})->byval_arg;
static auto* bEditableOnly = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GetCurves", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{curves, bEditableOnly});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GetOutputGeoNodes
// Il2CppName: GetOutputGeoNodes
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_GeoNode*>*)>(&HoudiniEngineUnity::HEU_ObjectNode::GetOutputGeoNodes)> {
static const MethodInfo* get() {
static auto* outGeoNodes = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_GeoNode")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GetOutputGeoNodes", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{outGeoNodes});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::GenerateObjectInstances
// Il2CppName: GenerateObjectInstances
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_SessionBase*)>(&HoudiniEngineUnity::HEU_ObjectNode::GenerateObjectInstances)> {
static const MethodInfo* get() {
static auto* session = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_SessionBase")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "GenerateObjectInstances", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{session});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::ClearObjectInstances
// Il2CppName: ClearObjectInstances
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_SessionBase*)>(&HoudiniEngineUnity::HEU_ObjectNode::ClearObjectInstances)> {
static const MethodInfo* get() {
static auto* session = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_SessionBase")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "ClearObjectInstances", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{session});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::PopulateObjectInstanceInfos
// Il2CppName: PopulateObjectInstanceInfos
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_ObjectInstanceInfo*>*)>(&HoudiniEngineUnity::HEU_ObjectNode::PopulateObjectInstanceInfos)> {
static const MethodInfo* get() {
static auto* objInstanceInfos = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_ObjectInstanceInfo")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "PopulateObjectInstanceInfos", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{objInstanceInfos});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::ProcessUnityScriptAttributes
// Il2CppName: ProcessUnityScriptAttributes
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_SessionBase*)>(&HoudiniEngineUnity::HEU_ObjectNode::ProcessUnityScriptAttributes)> {
static const MethodInfo* get() {
static auto* session = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_SessionBase")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "ProcessUnityScriptAttributes", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{session});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::HideAllGeometry
// Il2CppName: HideAllGeometry
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::HideAllGeometry)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "HideAllGeometry", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::CalculateVisibility
// Il2CppName: CalculateVisibility
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::CalculateVisibility)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "CalculateVisibility", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::CalculateColliderState
// Il2CppName: CalculateColliderState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::CalculateColliderState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "CalculateColliderState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::DisableAllColliders
// Il2CppName: DisableAllColliders
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::DisableAllColliders)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "DisableAllColliders", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::IsInstancer
// Il2CppName: IsInstancer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::IsInstancer)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "IsInstancer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::IsEquivalentTo
// Il2CppName: IsEquivalentTo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (HoudiniEngineUnity::HEU_ObjectNode::*)(::HoudiniEngineUnity::HEU_ObjectNode*)>(&HoudiniEngineUnity::HEU_ObjectNode::IsEquivalentTo)> {
static const MethodInfo* get() {
static auto* other = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_ObjectNode")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "IsEquivalentTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{other});
}
};
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_ObjectNode::ToString
// Il2CppName: ToString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (HoudiniEngineUnity::HEU_ObjectNode::*)()>(&HoudiniEngineUnity::HEU_ObjectNode::ToString)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_ObjectNode*), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 65.525685 | 324 | 0.774924 | RedBrumbler |
86d629595d8750b14d1ac5acf316403bf7ca8e4d | 6,383 | cpp | C++ | extrautils/SimpleShredder.cpp | jlzhangfafafa/blasr | be8b7929e05f14cd7199003fd21528df9261dbdd | [
"BSD-3-Clause-Clear"
] | 129 | 2015-01-29T17:18:38.000Z | 2022-01-29T14:01:10.000Z | extrautils/SimpleShredder.cpp | jlzhangfafafa/blasr | be8b7929e05f14cd7199003fd21528df9261dbdd | [
"BSD-3-Clause-Clear"
] | 268 | 2015-01-26T16:54:32.000Z | 2021-05-27T18:15:35.000Z | extrautils/SimpleShredder.cpp | jlzhangfafafa/blasr | be8b7929e05f14cd7199003fd21528df9261dbdd | [
"BSD-3-Clause-Clear"
] | 99 | 2015-01-02T18:21:38.000Z | 2021-10-08T06:49:36.000Z | #include <sstream>
#include <string>
#include <alignment/statistics/StatUtils.hpp>
#include <pbdata/CommandLineParser.hpp>
#include <pbdata/FASTAReader.hpp>
#include <pbdata/FASTASequence.hpp>
#include <pbdata/FASTQSequence.hpp>
#include <pbdata/metagenome/FindRandomSequence.hpp>
#include <pbdata/utils.hpp>
int main(int argc, char* argv[])
{
std::string inFileName, readsFileName;
DNALength readLength;
float coverage = 0;
bool noRandInit = false;
int numReads = -1;
CommandLineParser clp;
int qualityValue = 20;
bool printFastq = false;
int stratify = 0;
std::string titleType = "pacbio";
std::string fastqType = "illumina"; // or "sanger"
clp.RegisterStringOption("inFile", &inFileName, "Reference sequence", 0);
clp.RegisterPreviousFlagsAsHidden();
clp.RegisterIntOption("readLength", (int*)&readLength,
"The length of reads to simulate. The length is fixed.",
CommandLineParser::PositiveInteger, 0);
clp.RegisterFloatOption("coverage", &coverage,
"Total coverage (from which the number of reads is calculated",
CommandLineParser::PositiveFloat, 0);
clp.RegisterFlagOption("nonRandInit", &noRandInit,
"Skip initializing the random number generator with time.");
clp.RegisterIntOption("nReads", &numReads,
"Total number of reads (from which coverage is calculated)",
CommandLineParser::PositiveInteger, 0);
clp.RegisterStringOption("readsFile", &readsFileName, "Reads output file", 0);
clp.RegisterFlagOption("fastq", &printFastq,
"Fake fastq output with constant quality value (20)");
clp.RegisterIntOption("quality", &qualityValue, "Value to use for fastq quality",
CommandLineParser::PositiveInteger);
clp.RegisterIntOption("stratify", &stratify,
"Sample a read every 'stratify' bases, rather than randomly.",
CommandLineParser::PositiveInteger);
clp.RegisterStringOption("titleType", &titleType,
"Set the name of the title: 'pacbio'|'illumina'");
clp.RegisterStringOption("fastqType", &fastqType, "Set the type of fastq: 'illumina'|'sanger'");
std::vector<std::string> leftovers;
clp.ParseCommandLine(argc, argv, leftovers);
if (!noRandInit) {
InitializeRandomGeneratorWithTime();
}
FASTAReader inReader;
inReader.Init(inFileName);
std::vector<FASTASequence> reference;
inReader.ReadAllSequences(reference);
std::ofstream readsFile;
if (readsFileName == "") {
std::cout << "ERROR. You must specify a reads file." << std::endl;
std::exit(EXIT_FAILURE);
}
CrucialOpen(readsFileName, readsFile, std::ios::out);
std::ofstream sangerFastqFile;
if (fastqType == "sanger") {
std::string sangerFastqFileName = readsFileName + ".fastq";
CrucialOpen(sangerFastqFileName, sangerFastqFile, std::ios::out);
}
DNALength refLength = 0;
for (size_t i = 0; i < reference.size(); i++) {
refLength += reference[i].length;
}
if (numReads == -1 and coverage == 0 and stratify == 0) {
std::cout << "ERROR, you must specify either coverage, nReads, or stratify." << std::endl;
std::exit(EXIT_FAILURE);
} else if (numReads == -1) {
numReads = (refLength / readLength) * coverage;
}
if (stratify) {
if (!readLength) {
std::cout << "ERROR. If you are using stratification, a read length must be specified."
<< std::endl;
std::exit(EXIT_FAILURE);
}
}
DNASequence sampleSeq;
sampleSeq.length = readLength;
int maxRetry = 10000000;
int retryNumber = 0;
DNALength seqIndex, seqPos;
if (stratify) {
seqIndex = 0;
seqPos = 0;
}
DNALength origReadLength = readLength;
for (int i = 0; stratify or i < numReads; i++) {
if (stratify == 0) {
FindRandomPos(reference, seqIndex, seqPos, readLength);
} else {
//
// find the next start pos, or bail if done
//
if (seqPos >= reference[seqIndex].length) {
if (seqIndex == reference.size() - 1) {
break;
} else {
seqIndex = seqIndex + 1;
seqPos = 0;
continue;
}
}
readLength = std::min(reference[seqIndex].length - seqPos, origReadLength);
}
sampleSeq.seq = &reference[seqIndex].seq[seqPos];
int j;
int gappedRead = 0;
std::string title;
std::stringstream titleStrm;
if (titleType == "pacbio") {
titleStrm << i << "|" << reference[seqIndex].GetName() << "|" << seqPos << "|"
<< seqPos + readLength;
} else if (titleType == "illumina") {
titleStrm << "SE_" << i << "_0@" << seqPos << "-" << seqPos + readLength << "/1";
} else {
std::cout << "ERROR. Bad title type " << titleType << std::endl;
std::exit(EXIT_FAILURE);
}
title = titleStrm.str();
sampleSeq.length = readLength;
if (!printFastq) {
readsFile << ">" << title << std::endl;
sampleSeq.PrintSeq(readsFile);
} else {
FASTQSequence fastqSampleSeq;
fastqSampleSeq.CopyTitle(title);
fastqSampleSeq.seq = sampleSeq.seq;
fastqSampleSeq.length = sampleSeq.length;
fastqSampleSeq.qual.data = new unsigned char[sampleSeq.length];
std::fill(fastqSampleSeq.qual.data, fastqSampleSeq.qual.data + sampleSeq.length,
qualityValue);
if (fastqType == "illumina") {
fastqSampleSeq.PrintFastq(readsFile, fastqSampleSeq.length + 1);
} else {
fastqSampleSeq.PrintSeq(readsFile);
fastqSampleSeq.PrintQual(sangerFastqFile);
}
delete[] fastqSampleSeq.qual.data;
delete[] fastqSampleSeq.title;
}
if (stratify) {
seqPos += readLength;
}
}
return 0;
}
| 38.920732 | 100 | 0.575905 | jlzhangfafafa |
86d96364c570e7a4215e527422095d29374bba76 | 3,881 | cpp | C++ | ql/models/marketmodels/products/multistep/multistepinversefloater.cpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 4 | 2016-03-28T15:05:23.000Z | 2020-02-17T23:05:57.000Z | ql/models/marketmodels/products/multistep/multistepinversefloater.cpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 1 | 2015-02-02T20:32:43.000Z | 2015-02-02T20:32:43.000Z | ql/models/marketmodels/products/multistep/multistepinversefloater.cpp | pcaspers/quantlib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 10 | 2015-01-26T14:50:24.000Z | 2015-10-23T07:41:30.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2006 Giorgio Facchinetti
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
#include <ql/models/marketmodels/products/multistep/multistepinversefloater.hpp>
#include <ql/models/marketmodels/curvestate.hpp>
#include <ql/models/marketmodels/utilities.hpp>
namespace QuantLib {
MultiStepInverseFloater::MultiStepInverseFloater(const std::vector<Time>& rateTimes,
const std::vector<Real>& fixedAccruals,
const std::vector<Real>& floatingAccruals,
const std::vector<Real>& fixedStrikes,
const std::vector<Real>& fixedMultipliers,
const std::vector<Real>& floatingSpreads,
const std::vector<Time>& paymentTimes,
bool payer)
: MultiProductMultiStep(rateTimes),
fixedAccruals_(fixedAccruals),
floatingAccruals_(floatingAccruals),
fixedStrikes_(fixedStrikes),
fixedMultipliers_(fixedMultipliers),
floatingSpreads_(floatingSpreads),
paymentTimes_(paymentTimes),
payer_(payer),
multiplier_(payer ? -1.0 : 1.0),
lastIndex_(rateTimes.size()-1)
{
checkIncreasingTimes(paymentTimes);
QL_REQUIRE(fixedAccruals_.size() == lastIndex_," Incorrect number of fixedAccruals given, should be " << lastIndex_ << " not " << fixedAccruals_.size() );
QL_REQUIRE(floatingAccruals.size() == lastIndex_," Incorrect number of floatingAccruals given, should be " << lastIndex_ << " not " << floatingAccruals.size() );
QL_REQUIRE(fixedStrikes.size() == lastIndex_," Incorrect number of fixedStrikes given, should be " << lastIndex_ << " not " << fixedStrikes.size() );
QL_REQUIRE(fixedMultipliers.size() == lastIndex_," Incorrect number of fixedMultipliers given, should be " << lastIndex_ << " not " << fixedMultipliers.size() );
QL_REQUIRE(floatingSpreads.size() == lastIndex_," Incorrect number of floatingSpreads given, should be " << lastIndex_ << " not " << floatingSpreads.size() );
QL_REQUIRE(paymentTimes.size() == lastIndex_," Incorrect number of paymentTimes given, should be " << lastIndex_ << " not " << paymentTimes.size() );
}
bool MultiStepInverseFloater::nextTimeStep(
const CurveState& currentState,
std::vector<Size>& numberCashFlowsThisStep,
std::vector<std::vector<MarketModelMultiProduct::CashFlow> >&
genCashFlows)
{
Rate liborRate = currentState.forwardRate(currentIndex_);
Real inverseFloatingCoupon = std::max((fixedStrikes_[currentIndex_] - fixedMultipliers_[currentIndex_]*liborRate),0.0)*fixedAccruals_[currentIndex_] ;
Real floatingCoupon = (liborRate+floatingSpreads_[currentIndex_])*floatingAccruals_[currentIndex_];
genCashFlows[0][0].timeIndex = currentIndex_;
genCashFlows[0][0].amount =multiplier_*(inverseFloatingCoupon - floatingCoupon);
numberCashFlowsThisStep[0] = 1;
++currentIndex_;
return (currentIndex_ == lastIndex_);
}
std::unique_ptr<MarketModelMultiProduct> MultiStepInverseFloater::clone() const
{
return std::unique_ptr<MarketModelMultiProduct>( new MultiStepInverseFloater(*this));
}
}
| 47.329268 | 170 | 0.709096 | universe1987 |
86ddbd9fc929077f83e42ffa0b4da80fb82bbb60 | 7,826 | cpp | C++ | arangod/Statistics/RequestStatistics.cpp | iamjpn/arangodb | 818b3dcbbcf7dc323bbbb8f3fac34444a8afdb25 | [
"Apache-2.0"
] | 1 | 2020-10-27T12:19:33.000Z | 2020-10-27T12:19:33.000Z | arangod/Statistics/RequestStatistics.cpp | charity1475/arangodb | 32bef3ed9abef6f41a11466fe6361ae3e6d99b5e | [
"Apache-2.0"
] | null | null | null | arangod/Statistics/RequestStatistics.cpp | charity1475/arangodb | 32bef3ed9abef6f41a11466fe6361ae3e6d99b5e | [
"Apache-2.0"
] | 1 | 2020-10-01T08:49:12.000Z | 2020-10-01T08:49:12.000Z | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "RequestStatistics.h"
#include "Basics/MutexLocker.h"
#include "Logger/LogMacros.h"
#include "Logger/Logger.h"
#include "Logger/LoggerStream.h"
#include <iomanip>
#include <boost/lockfree/queue.hpp>
using namespace arangodb;
// -----------------------------------------------------------------------------
// --SECTION-- global variables
// -----------------------------------------------------------------------------
static size_t const QUEUE_SIZE = 64 * 1024 - 2; // current (1.62) boost maximum
static std::unique_ptr<RequestStatistics[]> _statisticsBuffer;
static boost::lockfree::queue<RequestStatistics*, boost::lockfree::capacity<QUEUE_SIZE>> _freeList;
static boost::lockfree::queue<RequestStatistics*, boost::lockfree::capacity<QUEUE_SIZE>> _finishedList;
// -----------------------------------------------------------------------------
// --SECTION-- static public methods
// -----------------------------------------------------------------------------
void RequestStatistics::initialize() {
_statisticsBuffer.reset(new RequestStatistics[QUEUE_SIZE]());
for (size_t i = 0; i < QUEUE_SIZE; ++i) {
RequestStatistics* entry = &_statisticsBuffer[i];
TRI_ASSERT(entry->_released);
TRI_ASSERT(!entry->_inQueue);
bool ok = _freeList.push(entry);
TRI_ASSERT(ok);
}
}
size_t RequestStatistics::processAll() {
RequestStatistics* statistics = nullptr;
size_t count = 0;
while (_finishedList.pop(statistics)) {
if (statistics != nullptr) {
TRI_ASSERT(!statistics->_released);
TRI_ASSERT(statistics->_inQueue);
statistics->_inQueue = false;
process(statistics);
++count;
}
}
return count;
}
RequestStatistics::Item RequestStatistics::acquire() {
if (!StatisticsFeature::enabled()) {
return Item{};
}
RequestStatistics* statistics = nullptr;
if (_freeList.pop(statistics)) {
TRI_ASSERT(statistics->_released);
TRI_ASSERT(!statistics->_inQueue);
statistics->_released = false;
} else {
statistics = nullptr;
LOG_TOPIC("62d99", TRACE, arangodb::Logger::FIXME)
<< "no free element on statistics queue";
}
return Item{statistics};
}
// -----------------------------------------------------------------------------
// --SECTION-- static private methods
// -----------------------------------------------------------------------------
void RequestStatistics::process(RequestStatistics* statistics) {
TRI_ASSERT(statistics != nullptr);
{
statistics::TotalRequests.incCounter();
if (statistics->_async) {
statistics::AsyncRequests.incCounter();
}
statistics::MethodRequests[(size_t)statistics->_requestType].incCounter();
// check that the request was completely received and transmitted
if (statistics->_readStart != 0.0 &&
(statistics->_async || statistics->_writeEnd != 0.0)) {
double totalTime;
if (statistics->_async) {
totalTime = statistics->_requestEnd - statistics->_readStart;
} else {
totalTime = statistics->_writeEnd - statistics->_readStart;
}
statistics::RequestFigures& figures = statistics->_superuser
? statistics::GeneralRequestFigures
: statistics::UserRequestFigures;
figures.totalTimeDistribution.addFigure(totalTime);
double requestTime = statistics->_requestEnd - statistics->_requestStart;
figures.requestTimeDistribution.addFigure(requestTime);
double queueTime = 0.0;
if (statistics->_queueStart != 0.0 && statistics->_queueEnd != 0.0) {
queueTime = statistics->_queueEnd - statistics->_queueStart;
figures.queueTimeDistribution.addFigure(queueTime);
}
double ioTime = totalTime - requestTime - queueTime;
if (ioTime >= 0.0) {
figures.ioTimeDistribution.addFigure(ioTime);
}
figures.bytesSentDistribution.addFigure(statistics->_sentBytes);
figures.bytesReceivedDistribution.addFigure(statistics->_receivedBytes);
}
}
// clear statistics
statistics->reset();
// put statistics item back onto the freelist
int tries = 0;
while (++tries < 1000) {
if (_freeList.push(statistics)) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
if (tries > 1) {
LOG_TOPIC("fb453", WARN, Logger::MEMORY) << "_freeList.push failed " << tries - 1 << " times.";
}
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
void RequestStatistics::release() {
TRI_ASSERT(!_released);
TRI_ASSERT(!_inQueue);
if (!_ignore) {
_inQueue = true;
bool ok = _finishedList.push(this);
TRI_ASSERT(ok);
} else {
reset();
bool ok = _freeList.push(this);
TRI_ASSERT(ok);
}
}
void RequestStatistics::getSnapshot(Snapshot& snapshot, stats::RequestStatisticsSource source) {
if (!StatisticsFeature::enabled()) {
// all the below objects may be deleted if we don't have statistics enabled
return;
}
statistics::RequestFigures& figures = source == stats::RequestStatisticsSource::USER
? statistics::UserRequestFigures
: statistics::GeneralRequestFigures;
snapshot.totalTime = figures.totalTimeDistribution;
snapshot.requestTime = figures.requestTimeDistribution;
snapshot.queueTime = figures.queueTimeDistribution;
snapshot.ioTime = figures.ioTimeDistribution;
snapshot.bytesSent = figures.bytesSentDistribution;
snapshot.bytesReceived = figures.bytesReceivedDistribution;
if (source == stats::RequestStatisticsSource::ALL) {
snapshot.totalTime.add(statistics::UserRequestFigures.totalTimeDistribution);
snapshot.requestTime.add(statistics::UserRequestFigures.requestTimeDistribution);
snapshot.queueTime.add(statistics::UserRequestFigures.queueTimeDistribution);
snapshot.ioTime.add(statistics::UserRequestFigures.ioTimeDistribution);
snapshot.bytesSent.add(statistics::UserRequestFigures.bytesSentDistribution);
snapshot.bytesReceived.add(statistics::UserRequestFigures.bytesReceivedDistribution);
}
}
std::string RequestStatistics::Item::timingsCsv() {
TRI_ASSERT(_stat != nullptr);
std::stringstream ss;
ss << std::setprecision(9) << std::fixed
<< "read," << (_stat->_readEnd - _stat->_readStart)
<< ",queue," << (_stat->_queueEnd - _stat->_queueStart)
<< ",queue-size," << _stat->_queueSize
<< ",request," << (_stat->_requestEnd - _stat->_requestStart)
<< ",total," << (StatisticsFeature::time() - _stat->_readStart)
<< ",error," << (_stat->_executeError ? "true" : "false");
return ss.str();
}
| 33.878788 | 103 | 0.613596 | iamjpn |
86ddeae3c50affcfd7122d5ce163beab90bf0e58 | 1,150 | cpp | C++ | search_and_graph/bfs/demo/leetcode_lp07.cpp | Fanjunmin/algorithm-template | db0d37a7c9c37ee9a167918fb74b03d1d09b6fad | [
"MIT"
] | 1 | 2021-04-26T11:03:04.000Z | 2021-04-26T11:03:04.000Z | search_and_graph/bfs/demo/leetcode_lp07.cpp | Fanjunmin/algrithm-template | db0d37a7c9c37ee9a167918fb74b03d1d09b6fad | [
"MIT"
] | null | null | null | search_and_graph/bfs/demo/leetcode_lp07.cpp | Fanjunmin/algrithm-template | db0d37a7c9c37ee9a167918fb74b03d1d09b6fad | [
"MIT"
] | null | null | null | class Solution {
private:
int h[15];
int e[100], ne[100], idx;
void init() {
memset(h, -1, sizeof(h));
memset(e, 0, sizeof(e));
memset(ne, 0, sizeof(ne));
idx = 0;
}
void add(int a, int b) {
idx++;
e[idx] = b;
ne[idx] = h[a];
h[a] = idx;
}
int bfs(int n, int k) {
queue<pair<int, int>> q;
int cnt = 0;
q.push({0, 0});
while (!q.empty()) {
auto t = q.front();
q.pop();
int index = t.first;
int time = t.second;
if (time == k) {
if (index == n - 1) {
cnt++;
}
continue;
}
for (int i = h[index]; i != -1; i = ne[i]) {
int j = e[i];
int j_time = 1 + time;
q.push({j, j_time});
}
}
return cnt;
}
public:
int numWays(int n, vector<vector<int>>& relation, int k) {
init();
for (auto rela : relation) {
add(rela[0], rela[1]);
}
return bfs(n, k);
}
}; | 23.958333 | 62 | 0.36 | Fanjunmin |
86df9c9b5f6f471382314d4371ef4ac688ca5e0c | 1,382 | cpp | C++ | z80/z80_processor.cpp | lukka/CppOpenGLWebAssemblyCMake | 1e2f161812f808d4467cec7cfd8c2e7181af0a75 | [
"MIT"
] | 59 | 2018-06-10T03:29:03.000Z | 2022-01-19T18:01:05.000Z | z80/z80_processor.cpp | BlueSolei/CppOpenGLWebAssemblyCMake | 4da1c47dd3548aa9595ee8d78b5c01c94b217dad | [
"MIT"
] | 3 | 2019-05-04T10:58:19.000Z | 2020-05-15T03:08:20.000Z | z80/z80_processor.cpp | BlueSolei/CppOpenGLWebAssemblyCMake | 4da1c47dd3548aa9595ee8d78b5c01c94b217dad | [
"MIT"
] | 7 | 2018-07-02T22:31:07.000Z | 2021-05-10T12:07:26.000Z | #include "z80_processor.h"
#include "z80_processor_impl.h"
namespace Z80
{
Processor::Processor(double clockFrequency, uint8_t ram[],
Emulator::IOHandler& ioHandler, const std::string tag,
Emulator::IMemoryHandler* memoryHandler,
Emulator::Cpu& cpu)
: _impl(new Z80ProcessorImpl(clockFrequency, ram, ioHandler, tag,
memoryHandler, cpu))
{
}
Processor::~Processor() {}
void Processor::Reset() { _impl->Reset(); }
int64_t Processor::get_ExecutionTimeInCurrentTimeslice() const
{
return _impl->get_ExecutionTimeInCurrentTimeslice();
}
int64_t Processor::Execute(int64_t us) { return _impl->Execute(us); }
void Processor::AbortTimeslice() { _impl->AbortTimeslice(); }
Emulator::IDeviceInputLine& Processor::get_IrqInputLine()
{
return _impl->get_IrqInputLine();
}
Emulator::IDeviceInputLine& Processor::get_ResetInputLine()
{
return _impl->get_ResetInputLine();
}
Emulator::IDeviceInputLine& Processor::get_NmiInputLine()
{
return _impl->get_NmiInputLine();
}
std::vector<Emulator::IDeviceInputLine*> Processor::get_InputLines()
{
return _impl->get_InputLines();
}
void Processor::SetProgramCounterListener(ProgramCounterListener& pcListener)
{
_impl->SetProgramCounterListener(pcListener);
}
} // namespace Z80
| 30.043478 | 78 | 0.686686 | lukka |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.