hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
705658634a60fc40f81896bba578391775961240 | 490 | cpp | C++ | Bit Manipulation/singleNumberTriplet.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | Bit Manipulation/singleNumberTriplet.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | Bit Manipulation/singleNumberTriplet.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | // Given an array of integers, every element appears thrice except one. Find that single one.
#include <iostream>
#include <vector>
using namespace std;
int singleNumber(vector<int>& nums) {
int ones = 0, twos = 0;
for (int i = 0; i < nums.size(); i++) {
ones = (ones ^ nums[i]) & ~twos;
twos = (twos ^ nums[i]) & ~ones;
}
return ones;
}
int main() {
vector<int> nums = {3, 4, 2, 3, 3, 4, 4};
cout << singleNumber(nums) << endl;
return 0;
}
| 21.304348 | 93 | 0.569388 | [
"vector"
] |
7060a557cfeff735c566f8f3e1d7518d4d781f62 | 11,668 | cpp | C++ | src/test/OpenEXRTest/testMultiScanlinePartThreading.cpp | remia/openexr | 566087f13259f4429d55125d1001b2696ac2bfc3 | [
"BSD-3-Clause"
] | 587 | 2015-01-04T09:56:19.000Z | 2019-11-21T13:23:33.000Z | third_party/openexr-672c77d7c923402f549371e08b39ece4552cbb85/src/test/OpenEXRTest/testMultiScanlinePartThreading.cpp | Vertexwahn/FlatlandRT | 37d09fde38b25eff5f802200b43628efbd1e3198 | [
"Apache-2.0"
] | 360 | 2015-01-04T10:55:17.000Z | 2019-11-21T16:37:22.000Z | third_party/openexr-672c77d7c923402f549371e08b39ece4552cbb85/src/test/OpenEXRTest/testMultiScanlinePartThreading.cpp | Vertexwahn/FlatlandRT | 37d09fde38b25eff5f802200b43628efbd1e3198 | [
"Apache-2.0"
] | 297 | 2015-01-11T12:06:42.000Z | 2019-11-19T21:59:57.000Z | //
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) Contributors to the OpenEXR Project.
//
#ifdef NDEBUG
# undef NDEBUG
#endif
#include <iostream>
#include <string>
#include <vector>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "tmpDir.h"
#include "testMultiScanlinePartThreading.h"
#include <IlmThreadPool.h>
#include <ImfArray.h>
#include <ImfChannelList.h>
#include <ImfFrameBuffer.h>
#include <ImfGenericOutputFile.h>
#include <ImfHeader.h>
#include <ImfInputPart.h>
#include <ImfMultiPartInputFile.h>
#include <ImfMultiPartOutputFile.h>
#include <ImfOutputFile.h>
#include <ImfOutputPart.h>
#include <ImfPartType.h>
#include <ImfTiledInputPart.h>
#include <ImfTiledOutputFile.h>
#include <ImfTiledOutputPart.h>
namespace IMF = OPENEXR_IMF_NAMESPACE;
using namespace IMF;
using namespace std;
using namespace IMATH_NAMESPACE;
using namespace ILMTHREAD_NAMESPACE;
namespace
{
const int height = 263;
const int width = 197;
vector<Header> headers;
template <class T>
void
fillPixels (Array2D<T>& ph, int width, int height)
{
ph.resizeErase (height, width);
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
{
//
// We do this because half cannot store number bigger than 2048 exactly.
//
ph[y][x] = (y * width + x) % 2049;
}
}
template <class T>
bool
checkPixels (Array2D<T>& ph, int lx, int rx, int ly, int ry, int width)
{
for (int y = ly; y <= ry; ++y)
for (int x = lx; x <= rx; ++x)
if (ph[y][x] != static_cast<T> (((y * width + x) % 2049)))
{
cout << "value at " << x << ", " << y << ": " << ph[y][x]
<< ", should be " << (y * width + x) % 2049 << endl
<< flush;
return false;
}
return true;
}
template <class T>
bool
checkPixels (Array2D<T>& ph, int width, int height)
{
return checkPixels<T> (ph, 0, width - 1, 0, height - 1, width);
}
class WritingTask : public Task
{
public:
WritingTask (TaskGroup* group, OutputPart& part, int outputLines)
: Task (group), part (part), outputLines (outputLines)
{}
void execute ()
{
for (int i = 0; i < outputLines; i++)
part.writePixels ();
}
private:
OutputPart& part;
int outputLines;
};
class ReadingTask : public Task
{
public:
ReadingTask (TaskGroup* group, InputPart& part, int startPos)
: Task (group), part (part), startPos (startPos)
{}
void execute ()
{
int endPos = startPos + 9;
if (endPos >= height) endPos = height - 1;
part.readPixels (startPos, endPos);
}
private:
InputPart& part;
int startPos;
};
void
setOutputFrameBuffer (
FrameBuffer& frameBuffer,
int pixelType,
Array2D<unsigned int>& uData,
Array2D<float>& fData,
Array2D<half>& hData,
int width)
{
switch (pixelType)
{
case 0:
frameBuffer.insert (
"UINT",
Slice (
IMF::UINT,
(char*) (&uData[0][0]),
sizeof (uData[0][0]) * 1,
sizeof (uData[0][0]) * width));
break;
case 1:
frameBuffer.insert (
"FLOAT",
Slice (
IMF::FLOAT,
(char*) (&fData[0][0]),
sizeof (fData[0][0]) * 1,
sizeof (fData[0][0]) * width));
break;
case 2:
frameBuffer.insert (
"HALF",
Slice (
IMF::HALF,
(char*) (&hData[0][0]),
sizeof (hData[0][0]) * 1,
sizeof (hData[0][0]) * width));
break;
}
}
void
setInputFrameBuffer (
FrameBuffer& frameBuffer,
int pixelType,
Array2D<unsigned int>& uData,
Array2D<float>& fData,
Array2D<half>& hData,
int width,
int height)
{
switch (pixelType)
{
case 0:
uData.resizeErase (height, width);
frameBuffer.insert (
"UINT",
Slice (
IMF::UINT,
(char*) (&uData[0][0]),
sizeof (uData[0][0]) * 1,
sizeof (uData[0][0]) * width,
1,
1,
0));
break;
case 1:
fData.resizeErase (height, width);
frameBuffer.insert (
"FLOAT",
Slice (
IMF::FLOAT,
(char*) (&fData[0][0]),
sizeof (fData[0][0]) * 1,
sizeof (fData[0][0]) * width,
1,
1,
0));
break;
case 2:
hData.resizeErase (height, width);
frameBuffer.insert (
"HALF",
Slice (
IMF::HALF,
(char*) (&hData[0][0]),
sizeof (hData[0][0]) * 1,
sizeof (hData[0][0]) * width,
1,
1,
0));
break;
}
}
void
generateFiles (int pixelTypes[], const std::string& fn)
{
//
// Generate headers.
//
cout << "Generating headers " << flush;
headers.clear ();
for (int i = 0; i < 2; i++)
{
Header header (width, height);
int pixelType = pixelTypes[i];
stringstream ss;
ss << i;
header.setName (ss.str ());
switch (pixelType)
{
case 0:
header.channels ().insert ("UINT", Channel (IMF::UINT));
break;
case 1:
header.channels ().insert ("FLOAT", Channel (IMF::FLOAT));
break;
case 2:
header.channels ().insert ("HALF", Channel (IMF::HALF));
break;
}
header.setType (SCANLINEIMAGE);
headers.push_back (header);
}
//
// Preparing.
//
cout << "Writing files " << flush;
Array2D<half> halfData;
Array2D<float> floatData;
Array2D<unsigned int> uintData;
fillPixels<unsigned int> (uintData, width, height);
fillPixels<half> (halfData, width, height);
fillPixels<float> (floatData, width, height);
remove (fn.c_str ());
MultiPartOutputFile file (fn.c_str (), &headers[0], headers.size ());
vector<OutputPart> parts;
FrameBuffer frameBuffers[2];
for (int i = 0; i < 2; i++)
{
OutputPart part (file, i);
FrameBuffer& frameBuffer = frameBuffers[i];
setOutputFrameBuffer (
frameBuffer, pixelTypes[i], uintData, floatData, halfData, width);
part.setFrameBuffer (frameBuffer);
parts.push_back (part);
}
//
// Writing tasks.
//
TaskGroup taskGroup;
ThreadPool* threadPool = new ThreadPool (2);
for (int i = 0; i < height / 10; i++)
{
threadPool->addTask ((new WritingTask (&taskGroup, parts[0], 10)));
threadPool->addTask ((new WritingTask (&taskGroup, parts[1], 10)));
}
threadPool->addTask ((new WritingTask (&taskGroup, parts[0], height % 10)));
threadPool->addTask ((new WritingTask (&taskGroup, parts[1], height % 10)));
delete threadPool;
}
void
readFiles (int pixelTypes[], const std::string& fn)
{
cout << "Checking headers " << flush;
MultiPartInputFile file (fn.c_str ());
assert (file.parts () == 2);
for (size_t i = 0; i < 2; i++)
{
const Header& header = file.header (i);
assert (header.displayWindow () == headers[i].displayWindow ());
assert (header.dataWindow () == headers[i].dataWindow ());
assert (header.pixelAspectRatio () == headers[i].pixelAspectRatio ());
assert (
header.screenWindowCenter () == headers[i].screenWindowCenter ());
assert (header.screenWindowWidth () == headers[i].screenWindowWidth ());
assert (header.lineOrder () == headers[i].lineOrder ());
assert (header.compression () == headers[i].compression ());
assert (header.channels () == headers[i].channels ());
assert (header.name () == headers[i].name ());
assert (header.type () == headers[i].type ());
}
//
// Preparing.
//
Array2D<unsigned int> uData[2];
Array2D<float> fData[2];
Array2D<half> hData[2];
vector<InputPart> parts;
FrameBuffer frameBuffers[2];
for (int i = 0; i < 2; i++)
{
InputPart part (file, i);
FrameBuffer& frameBuffer = frameBuffers[i];
setInputFrameBuffer (
frameBuffer,
pixelTypes[i],
uData[i],
fData[i],
hData[i],
width,
height);
part.setFrameBuffer (frameBuffer);
parts.push_back (part);
}
//
// Reading files.
//
cout << "Reading files " << flush;
TaskGroup taskGroup;
ThreadPool* threadPool = new ThreadPool (2);
for (int i = 0; i <= height / 10; i++)
{
threadPool->addTask ((new ReadingTask (&taskGroup, parts[0], i * 10)));
threadPool->addTask ((new ReadingTask (&taskGroup, parts[1], i * 10)));
}
delete threadPool;
//
// Checking data.
//
cout << "Comparing" << endl << flush;
for (int i = 0; i < 2; i++)
{
switch (pixelTypes[i])
{
case 0:
assert (checkPixels<unsigned int> (uData[i], width, height));
break;
case 1:
assert (checkPixels<float> (fData[i], width, height));
break;
case 2: assert (checkPixels<half> (hData[i], width, height)); break;
}
}
}
void
testWriteRead (int pixelTypes[], const std::string& tempDir)
{
std::string fn = tempDir + "imf_test_multi_scanline_part_threading.exr";
string typeNames[2];
for (int i = 0; i < 2; i++)
{
switch (pixelTypes[i])
{
case 0: typeNames[i] = "unsigned int"; break;
case 1: typeNames[i] = "float"; break;
case 2: typeNames[i] = "half"; break;
}
}
cout << "part 1: " << typeNames[0] << " scanline part, "
<< "part 2: " << typeNames[1] << " scanline part. " << endl
<< flush;
generateFiles (pixelTypes, fn);
readFiles (pixelTypes, fn);
remove (fn.c_str ());
cout << endl << flush;
}
} // namespace
void
testMultiScanlinePartThreading (const std::string& tempDir)
{
try
{
cout
<< "Testing the two threads reading/writing on two-scanline-part file"
<< endl;
int numThreads = ThreadPool::globalThreadPool ().numThreads ();
ThreadPool::globalThreadPool ().setNumThreads (2);
int pixelTypes[2];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
pixelTypes[0] = i;
pixelTypes[1] = j;
testWriteRead (pixelTypes, tempDir);
}
ThreadPool::globalThreadPool ().setNumThreads (numThreads);
cout << "ok\n" << endl;
}
catch (const std::exception& e)
{
cerr << "ERROR -- caught exception: " << e.what () << endl;
assert (false);
}
}
| 26.102908 | 84 | 0.5024 | [
"vector"
] |
70652f0562b99ffdbde758a86e3f5d990c0249ea | 85,972 | cpp | C++ | c_src/common/xapian_core.cpp | schaerli/xapian-erlang-bindings | be72c73b0da254d7d21168c913f11cbf458f36e2 | [
"MIT"
] | 6 | 2015-06-28T20:14:31.000Z | 2020-10-12T21:45:45.000Z | c_src/common/xapian_core.cpp | schaerli/xapian-erlang-bindings | be72c73b0da254d7d21168c913f11cbf458f36e2 | [
"MIT"
] | 1 | 2015-08-11T08:07:14.000Z | 2015-08-11T08:07:14.000Z | c_src/common/xapian_core.cpp | schaerli/xapian-erlang-bindings | be72c73b0da254d7d21168c913f11cbf458f36e2 | [
"MIT"
] | 5 | 2016-06-02T06:22:56.000Z | 2022-01-31T16:21:42.000Z | /* vim: set filetype=cpp shiftwidth=4 tabstop=4 expandtab tw=80: */
/**
* Prefix m_ (member) for properties means that property is private.
*/
// -------------------------------------------------------------------
// Includes
// -------------------------------------------------------------------
/* Include other headers from the binding. */
#include "param_decoder.h"
#include "param_decoder_controller.h"
#include "result_encoder.h"
#include "xapian_exception.h"
#include "xapian_helpers.h"
#include "qlc.h"
#include "extension/value_count_mspy.h"
#include <assert.h>
#include <cstdlib>
// -------------------------------------------------------------------
// Main Driver Class
// -------------------------------------------------------------------
#include "xapian_core.h"
XAPIAN_ERLANG_NS_BEGIN
const uint8_t Driver::PARSER_FEATURE_COUNT = 13;
const unsigned
Driver::PARSER_FEATURES[PARSER_FEATURE_COUNT] = {
0,
/* 1 */ Xapian::QueryParser::FLAG_BOOLEAN,
/* 2 */ Xapian::QueryParser::FLAG_PHRASE,
/* 3 */ Xapian::QueryParser::FLAG_LOVEHATE,
/* 4 */ Xapian::QueryParser::FLAG_BOOLEAN_ANY_CASE,
/* 5 */ Xapian::QueryParser::FLAG_WILDCARD,
/* 6 */ Xapian::QueryParser::FLAG_PURE_NOT,
/* 7 */ Xapian::QueryParser::FLAG_PARTIAL,
/* 8 */ Xapian::QueryParser::FLAG_SPELLING_CORRECTION,
/* 9 */ Xapian::QueryParser::FLAG_SYNONYM,
/* 10 */ Xapian::QueryParser::FLAG_AUTO_SYNONYMS,
/* 11 */ Xapian::QueryParser::FLAG_AUTO_MULTIWORD_SYNONYMS,
/* 12 */ Xapian::QueryParser::FLAG_DEFAULT
};
/// Used to separate generator and text features.
const int
Driver::GENERATOR_AND_TEXT_FEATURES_DELIM = 50;
/// Reset settings to default flag
const int
Driver::GENERATOR_AND_TEXT_DEFAULT_FEATURES = 50;
/// Default flags
const unsigned
Driver::GENERATOR_DEFAULT_FEATURES = 0;
const unsigned
Driver::TEXT_DEFAULT_FEATURES = Driver::TEXT_FLAG_POSITIONS;
const uint8_t Driver::GENERATOR_FEATURE_COUNT = 2;
const unsigned
Driver::GENERATOR_FEATURES[GENERATOR_FEATURE_COUNT] = {
0,
/* 1 */ Xapian::TermGenerator::FLAG_SPELLING,
};
const uint8_t Driver::TEXT_FEATURE_COUNT = 2;
const unsigned
Driver::TEXT_FEATURES[TEXT_FEATURE_COUNT] = {
0,
/* 1 */ Driver::TEXT_FLAG_POSITIONS,
};
const uint8_t Driver::STEM_STRATEGY_COUNT = 3;
const Xapian::QueryParser::stem_strategy
Driver::STEM_STRATEGIES[STEM_STRATEGY_COUNT] = {
/* 0 */ Xapian::QueryParser::STEM_NONE, // default
/* 1 */ Xapian::QueryParser::STEM_SOME,
/* 2 */ Xapian::QueryParser::STEM_ALL
};
const uint8_t Driver::DOCID_ORDER_TYPE_COUNT = 3;
const Xapian::Enquire::docid_order
Driver::DOCID_ORDER_TYPES[DOCID_ORDER_TYPE_COUNT] = {
/* 0 */ Xapian::Enquire::ASCENDING, // default
/* 1 */ Xapian::Enquire::DESCENDING,
/* 2 */ Xapian::Enquire::DONT_CARE
};
Driver::Driver(MemoryManager& mm)
: m_store(*this), m_number_of_databases(0), m_mm(mm)
{
}
Driver::~Driver()
{}
void
Driver::setDefaultStemmer(const Xapian::Stem& stemmer)
{
m_default_stemmer = stemmer;
m_default_parser.set_stemmer(m_default_stemmer);
m_default_generator.set_stemmer(m_default_stemmer);
m_default_parser_factory.set_stemmer(m_default_stemmer);
m_default_generator_factory.set_stemmer(m_default_stemmer);
}
void
Driver::setDefaultStemmer(ParamDecoder& params)
{
const Xapian::Stem& stemmer = params;
setDefaultStemmer(Xapian::Stem(stemmer));
}
void
Driver::setDefaultPrefixes(ParamDecoder& params)
{
const uint32_t count = params;
for (uint32_t i = 0; i < count; i++)
{
addPrefix(params, m_default_parser_factory);
}
// Update the mirror
m_default_parser = m_default_parser_factory;
}
void
Driver::getLastDocId(ResultEncoder& result)
{
//Xapian::docid get_lastdocid() const
const Xapian::docid
docid = m_db.get_lastdocid();
result << static_cast<uint32_t>(docid);
}
void
Driver::addDocument(PR)
{
assertWriteable();
Xapian::Document doc;
applyDocument(params, doc);
const Xapian::docid
docid = m_wdb.add_document(doc);
result << static_cast<uint32_t>(docid);
}
void
Driver::addSpelling(ParamDecoder& params)
{
assertWriteable();
Resource::Element gen_con =
Resource::Element::createContext();
Xapian::TermGenerator tg = m_default_generator;
while (const uint8_t command = params)
/* Do, while command != stop != 0 */
{
switch (command)
{
case STEMMER:
{
// see xapian_document:append_stemmer
const Xapian::Stem& stemmer = params;
tg.set_stemmer(stemmer);
break;
}
case TERM_GENERATOR:
{
tg = readGenerator(gen_con, params);
break;
}
case TEXT:
{
// see xapian_document:append_delta
const std::string& text = params; // value
const uint32_t wdf_inc = params; // pos
const std::string& prefix = params;
unsigned genFlags = 0, textFlags = 0;
decodeGeneratorFeatureFlags(params, genFlags, textFlags);
genFlags |= Xapian::TermGenerator::FLAG_SPELLING;
tg.set_flags(Xapian::TermGenerator::flags(genFlags));
// if isset(TEXT_FLAG_POSITIONS)
if ((textFlags & TEXT_FLAG_POSITIONS) == TEXT_FLAG_POSITIONS)
tg.index_text(text,
static_cast<Xapian::termcount>(wdf_inc),
prefix);
else
tg.index_text(text,
static_cast<Xapian::termcount>(wdf_inc),
prefix);
break;
}
case SET_TERM:
case ADD_TERM:
case UPDATE_TERM:
case REMOVE_TERM:
handleSpelling(params, command, m_wdb);
break;
case SET_WDF:
case DEC_WDF:
// see append_decrease_wdf
// see append_set_wdf
{
const std::string& tname = params; // value
const uint32_t wdf = params;
const bool ignore = params;
const Xapian::termcount wdf2 =
static_cast<Xapian::termcount>(wdf);
if (command == SET_WDF)
Helpers::trySetSpellingFreq(m_wdb, tname, wdf2, ignore);
else
Helpers::tryDecreaseSpellingFreq(m_wdb, tname, wdf2, ignore);
break;
}
default:
throw BadCommandDriverError(POS, command);
}
}
}
// REP_CRT_DOC_MARK
void
Driver::replaceOrCreateDocument(PR)
{
assertWriteable();
Xapian::Document doc;
Xapian::docid docid;
applyDocument(params, doc);
switch(uint8_t idType = params)
{
case UNIQUE_DOCID:
{
docid = params;
m_wdb.replace_document(docid, doc);
break;
}
case UNIQUE_TERM:
{
const std::string& unique_term = params;
docid = m_wdb.replace_document(unique_term, doc);
break;
}
default:
throw BadCommandDriverError(POS, idType);
}
result << static_cast<uint32_t>(docid);
}
// REP_DOC_MARK
void
Driver::replaceDocument(PR)
{
assertWriteable();
Xapian::Document doc;
Xapian::docid docid;
applyDocument(params, doc);
switch(uint8_t idType = params)
{
case UNIQUE_DOCID:
{
docid = params;
try {
m_wdb.get_document(docid);
m_wdb.replace_document(docid, doc);
} catch (Xapian::DocNotFoundError e) {
// Set to undefined if it is not found.
docid = 0;
}
break;
}
case UNIQUE_TERM:
{
const std::string& unique_term = params;
if (m_wdb.term_exists(unique_term))
docid = m_wdb.replace_document(unique_term, doc);
else
docid = 0;
break;
}
default:
throw BadCommandDriverError(POS, idType);
}
result << static_cast<uint32_t>(docid);
}
void
Driver::updateDocument(PR, bool create)
{
assertWriteable();
const ParamDecoderController& schema
= applyDocumentSchema(params);
Xapian::Document doc;
Xapian::docid docid;
switch(uint8_t idType = params)
{
case UNIQUE_DOCID:
{
docid = params;
// If create = true, then ignore errors.
if (create)
try {
doc = m_wdb.get_document(docid);
} catch (Xapian::DocNotFoundError e) {}
else
doc = m_wdb.get_document(docid);
ParamDecoder params = schema;
applyDocument(params, doc);
m_wdb.replace_document(docid, doc);
break;
}
case UNIQUE_TERM:
{
const std::string& unique_term = params;
if (m_wdb.term_exists(unique_term))
{
// Start searching
Xapian::Enquire enquire(m_wdb);
enquire.set_query(Xapian::Query(unique_term));
// Get a set of documents with term
Xapian::MSet mset = enquire.get_mset(
0, m_wdb.get_doccount());
for (Xapian::MSetIterator m = mset.begin();
m != mset.end(); ++m) {
docid = *m;
Xapian::Document doc = m.get_document();
ParamDecoder params = schema;
applyDocument(params, doc);
m_wdb.replace_document(docid, doc);
}
// new document was not added.
docid = 0;
}
else if (create)
{
ParamDecoder params = schema;
applyDocument(params, doc);
docid = m_wdb.add_document(doc);
}
else
{
throw BadArgumentDriverError(POS);
}
break;
}
default:
throw BadCommandDriverError(POS, idType);
}
result << static_cast<uint32_t>(docid);
}
void
Driver::deleteDocument(PR)
{
assertWriteable();
uint8_t is_exist;
switch(uint8_t idType = params)
{
case UNIQUE_DOCID:
{
const Xapian::docid
docid = params;
try
{
m_wdb.delete_document(docid);
is_exist = true;
} catch (Xapian::DocNotFoundError e)
{
is_exist = false;
}
break;
}
case UNIQUE_TERM:
{
const std::string& unique_term = params;
is_exist = m_db.term_exists(unique_term);
if (is_exist)
m_wdb.delete_document(unique_term);
break;
}
default:
throw BadCommandDriverError(POS, idType);
}
result << is_exist;
}
void
Driver::isDocumentExist(PR)
{
uint8_t is_exist;
switch(uint8_t idType = params)
{
case UNIQUE_DOCID:
{
const Xapian::docid docid = params;
try
{
m_db.get_document(docid);
is_exist = true;
} catch (Xapian::DocNotFoundError e)
{
is_exist = false;
}
break;
}
case UNIQUE_TERM:
{
// If there is the term in the database, then there is a document
// with this term.
const std::string& unique_term = params;
is_exist = m_db.term_exists(unique_term);
break;
}
default:
throw BadCommandDriverError(POS, idType);
}
result << is_exist;
}
void
Driver::query(CPR)
{
/* offset, pagesize, query, template */
const uint32_t offset = params;
const uint32_t pagesize = params;
// Use an Enquire object on the database to run the query.
Xapian::Enquire enquire(m_db);
Xapian::Query query = buildQuery(con, params);
enquire.set_query(query);
// Get an result
Xapian::MSet mset = enquire.get_mset(
static_cast<Xapian::termcount>(offset),
static_cast<Xapian::termcount>(pagesize));
Xapian::doccount count = mset.size();
result << static_cast<uint32_t>(count);
retrieveDocuments(params, result, mset.begin(), mset.end());
}
void
Driver::retrieveDocuments(PCR,
Xapian::MSetIterator iter, Xapian::MSetIterator end)
{
ParamDecoder params_copy = params;
switch (uint8_t decoder_type = params_copy)
{
case DEC_DOCUMENT:
for (; iter != end; ++iter)
{
Xapian::Document doc = iter.get_document();
retrieveDocument(params, result, doc);
}
break;
case DEC_ITERATOR:
for (; iter != end; ++iter)
retrieveDocument(params, result, iter);
break;
case DEC_BOTH:
for (; iter != end; ++iter)
{
Xapian::Document doc = iter.get_document();
retrieveDocument(params, result, doc, iter);
}
break;
default:
throw BadCommandDriverError(POS, decoder_type);
}
}
/**
* Read sources of information and write information fields.
* Sources are selected from Erlang code.
*/
void
Driver::selectEncoderAndRetrieveDocument(PR, Xapian::MSetIterator& iter)
{
ParamDecoder params_copy = params;
switch (uint8_t decoder_type = params_copy)
{
// Source is a document.
// Fields from the iterator are not used.
case DEC_DOCUMENT:
{
Xapian::Document doc = iter.get_document();
retrieveDocument(params, result, doc);
break;
}
// Source is an iterator.
// Fields from the document are not used.
case DEC_ITERATOR:
retrieveDocument(params, result, iter);
break;
// Fields both from the iterator and from the document are used.
case DEC_BOTH:
{
Xapian::Document doc = iter.get_document();
retrieveDocument(params, result, doc, iter);
break;
}
default:
throw BadCommandDriverError(POS, decoder_type);
}
}
void
Driver::enquire(PR)
{
// Use an Enquire object on the database to run the query.
// Create a new context.
Resource::Element elem =
Resource::Element::wrap(new Xapian::Enquire(m_db));
Xapian::Enquire& enquire = elem;
// Use elem as a context.
fillEnquire(elem, params, enquire);
m_store.save(elem, result);
}
/**
* Create a parser with a corrected string inside.
*/
void
Driver::createQueryParser(PR)
{
// Create a new context.
Resource::Element parser_con = Resource::Element::createContext();
// Read parser into allocated pointer.
// parser_con holds child resources.
Xapian::QueryParser* p_parser =
new Xapian::QueryParser(readParser(parser_con, params));
Resource::Element elem =
Resource::Element::wrap(p_parser);
// Add the context as a child.
// Delete the context (and all inside) when the QueryParser is deleted
// only.
elem.attachContext(parser_con);
m_store.save(elem, result);
}
/**
* Create a parser with a corrected string inside.
*/
void
Driver::createTermGenerator(PR)
{
// Create a new context.
Resource::Element gen_con = Resource::Element::createContext();
// Read a generator into allocated pointer.
// parser_con holds child resources.
Xapian::TermGenerator* p_gen =
new Xapian::TermGenerator(readGenerator(gen_con, params));
Resource::Element elem =
Resource::Element::wrap(p_gen);
// Add the context as a child.
// Delete the context (and all inside) when the TermGenerator is deleted
// only.
elem.attachContext(gen_con);
m_store.save(elem, result);
}
/**
* Suggest a spelling correction.
*/
void
Driver::getSpellingCorrection(PR)
{
const std::string& word = params;
const uint32_t max_edit_distance = params;
const std::string& corrected
= m_db.get_spelling_suggestion(word, max_edit_distance);
result << corrected;
}
void
Driver::parseString(CPR)
{
// see xapian_query:append_query_string
Xapian::QueryParser parser = readParser(con, params);
const std::string& query_string = params;
const std::string& default_prefix = params;
const unsigned flags = decodeParserFeatureFlags(params);
Xapian::Query q =
parser.parse_query(
query_string,
flags,
default_prefix);
while(uint8_t field_id = params)
switch(field_id)
{
case PS_QUERY_RESOURCE:
{
Resource::Element elem =
Resource::Element::wrap(new Xapian::Query(q));
m_store.save(elem, result);
break;
}
case PS_CORRECTED_QUERY_STRING:
{
const std::string& corrected
= parser.get_corrected_query_string();
result << corrected;
break;
}
default:
throw BadCommandDriverError(POS, field_id);
}
}
// Get a copy of a document.
// Caller must deallocate the returned object.
Xapian::Document
Driver::getDocument(ParamDecoder& params)
{
switch(uint8_t idType = params)
{
case UNIQUE_DOCID:
{
Xapian::docid docid = params;
return m_db.get_document(docid);
}
case UNIQUE_TERM:
{
const std::string& unique_term = params;
if (m_wdb.term_exists(unique_term))
{
// Start searching
Xapian::Enquire enquire(m_wdb);
enquire.set_query(Xapian::Query(unique_term));
// Get a set of documents with term
Xapian::MSet mset = enquire.get_mset(
0, 1);
Xapian::MSetIterator
iter = mset.begin(),
end = mset.end();
if (iter == end)
throw BadArgumentDriverError(POS); // doc us not found
return iter.get_document();
}
break;
}
default:
throw BadCommandDriverError(POS, idType);
}
throw BadArgumentDriverError(POS);
}
// Create a doc as a resource
void
Driver::document(PR)
{
const Xapian::Document& doc = getDocument(params);
Resource::Element elem =
Resource::Element::wrap(new Xapian::Document(doc));
m_store.save(elem, result);
}
void
Driver::releaseResource(ParamDecoder& params)
{
m_store.release(params);
}
void
Driver::releaseResources(ParamDecoder& params)
{
m_store.multiRelease(params);
}
void
Driver::addSynonym(ParamDecoder& params)
{
assertWriteable();
const std::string& term = params;
const std::string& synonym = params;
m_wdb.add_synonym(term, synonym);
}
void
Driver::removeSynonym(ParamDecoder& params)
{
assertWriteable();
const std::string& term = params;
const std::string& synonym = params;
m_wdb.remove_synonym(term, synonym);
}
void
Driver::clearSynonyms(ParamDecoder& params)
{
assertWriteable();
const std::string& term = params;
m_wdb.clear_synonyms(term);
}
void
Driver::matchSet(CPR)
{
// Spies and MatchSpy must be sepated.
// Enquire and Spies will be stored inside a temporary context (con
// parameter).
Xapian::Enquire& enquire = extractEnquire(con, params);
Xapian::doccount first, maxitems, checkatleast;
first = params;
uint8_t is_undefined = params;
maxitems = is_undefined
? m_db.get_doccount()
: params;
checkatleast = params;
/* Read a count of passed Spy objects. */
uint32_t count = params;
while (count--)
{
// It can be added just once
Xapian::MatchSpy& spy = extractWritableSpy(con, params);
enquire.add_matchspy(&spy);
}
Xapian::MSet mset = enquire.get_mset(
first,
maxitems,
checkatleast);
enquire.clear_matchspies();
Resource::Element elem =
Resource::Element::wrap(new Xapian::MSet(mset));
m_store.save(elem, result);
}
Xapian::MatchSpy&
Driver::extractWritableSpy(CP)
{
Resource::Element elem = m_store.extract(con, params);
if (elem.is_finalized())
throw MatchSpyFinalizedDriverError(POS);
elem.finalize();
return elem;
}
void
Driver::qlcInit(PR)
{
switch (uint8_t qlc_type = params)
{
case QlcType::MSET:
{
// Cannot use extractMSet(), because we need Element for linking.
Resource::Element mset_elem = m_store.extract(params);
Xapian::MSet& mset = mset_elem;
// Extract a schema (a list of fields, settings for QLC).
const ParamDecoderController& schema
= retrieveDocumentSchema(params);
// Allocate the object
MSetQlcTable* qlcTable = new MSetQlcTable(*this, mset, schema);
Resource::Element elem =
Resource::Element::wrap(qlcTable);
// Add MSet as a child of the QLC Table.
elem.attach(mset_elem);
// Write a resource.
m_store.save(elem, result);
// Write the size.
const uint32_t mset_size = qlcTable->size();
result << mset_size;
break;
}
case QlcType::TERMS:
{
// Don't store copy of the document controller.
// The whole document will be copied into QlcTable.
Xapian::Document& doc = m_store.extract(params);
TermGenerator::Iterator* p_gen = TermGenerator::Iterator::create(doc);
const ParamDecoderController& schema
= retrieveTermSchema(params);
TermQlcTable* qlcTable = new TermQlcTable(*this, p_gen, schema);
Resource::Element elem =
Resource::Element::wrap(qlcTable);
// Write a resource.
m_store.save(elem, result);
// Write the size.
const uint32_t size = qlcTable->size();
result << size;
break;
}
// ValueCountMatchSpy top_values, values
case QlcType::SPY_TERMS:
{
Resource::Element spy_elem = m_store.extract(params);
Xapian::ValueCountMatchSpy& spy = spy_elem;
TermGenerator::Iterator* p_gen =
TermGenerator::Iterator::create(params, spy);
const ParamDecoderController& schema
= retrieveTermSchema(params);
TermQlcTable* qlcTable = new TermQlcTable(*this, p_gen, schema);
Resource::Element elem =
Resource::Element::wrap(qlcTable);
// Delete the ValueCountMatchSpy when the QlcTable is deleted only.
elem.attach(spy_elem);
// Write a QlcTable resource.
m_store.save(elem, result);
// Write the size.
const uint32_t size = qlcTable->size();
result << size;
break;
}
// QueryParser unstem_begin, stoplist_begin
case QlcType::QUERY_PARSER_TERMS:
{
Resource::Element qp_elem = m_store.extract(params);
Xapian::QueryParser& qp = qp_elem;
TermGenerator::Iterator* p_gen =
TermGenerator::Iterator::create(params, qp);
const ParamDecoderController& schema
= retrieveTermSchema(params);
TermQlcTable* qlcTable = new TermQlcTable(*this, p_gen, schema);
Resource::Element elem =
Resource::Element::wrap(qlcTable);
// Delete the QueryParser when the QlcTable is deleted only.
elem.attach(qp_elem);
// Write a QlcTable resource.
m_store.save(elem, result);
// Write the size.
const uint32_t size = qlcTable->size();
result << size;
break;
}
// Database spellings_begin, ...
case QlcType::DATABASE_TERMS:
{
m_store.skip(params);
TermGenerator::Iterator* p_gen =
TermGenerator::Iterator::create(params, m_db);
const ParamDecoderController& schema
= retrieveTermSchema(params);
TermQlcTable* qlcTable = new TermQlcTable(*this, p_gen, schema);
Resource::Element elem =
Resource::Element::wrap(qlcTable);
// Write a QlcTable resource.
m_store.save(elem, result);
// Write the size.
const uint32_t size = qlcTable->size();
result << size;
break;
}
default:
throw BadCommandDriverError(POS, qlc_type);
}
}
void
Driver::qlcNext(PR)
{
QlcTable& qlc_table = m_store.extract(params);
uint32_t from = params;
uint32_t count = params;
qlc_table.getPage(result, from, count);
}
void
Driver::qlcLookup(PR)
{
QlcTable& qlc_table = m_store.extract(params);
qlc_table.lookup(params, result);
}
void
Driver::assertWriteable() const
{}
void
Driver::startTransaction()
{
assertWriteable();
m_wdb.begin_transaction();
}
void
Driver::cancelTransaction()
{
assertWriteable();
m_wdb.cancel_transaction();
}
void
Driver::commitTransaction()
{
assertWriteable();
m_wdb.commit_transaction();
}
void
Driver::getDocumentById(PR)
{
const Xapian::docid docid = params;
Xapian::Document doc = m_db.get_document(docid);
retrieveDocument(params, result, doc);
}
/**
* Get document metadata without putting it in DB.
*/
void
Driver::documentInfo(PR)
{
Xapian::Document doc;
applyDocument(params, doc);
retrieveDocument(params, result, doc);
}
/**
* Return the document resource without putting it in DB.
*/
void
Driver::documentInfoResource(PR)
{
Xapian::Document* doc = new Xapian::Document();
applyDocument(params, *doc);
Resource::Element elem = Resource::Element::wrap(doc);
m_store.save(elem, result);
}
void
Driver::test(PR)
{
const int8_t num = params;
switch (num)
{
case TEST_RESULT_ENCODER:
{
const Xapian::docid from = params;
const Xapian::docid to = params;
testResultEncoder(result, from, to);
break;
}
case TEST_EXCEPTION:
testException();
break;
case TEST_ECHO:
testEcho(params, result);
break;
case TEST_MEMORY:
testMemory();
break;
default:
throw BadCommandDriverError(POS, num);
}
}
void
Driver::testResultEncoder(ResultEncoder& result,
Xapian::docid from, Xapian::docid to)
{
for (; from <= to; from++)
result << static_cast<uint32_t>(from);
}
void Driver::testEcho(PR)
{
for (uint32_t len = params; len; len--)
{
uint8_t value = params;
result << value;
}
}
void
Driver::testException()
{
throw MemoryAllocationDriverError(POS, 1000);
}
void
Driver::testMemory()
{
void* cblock = malloc(100);
free(cblock);
void* block = m_mm.alloc(100);
m_mm.free(block);
}
unsigned
Driver::idToParserFeature(int type)
{
if ((type > PARSER_FEATURE_COUNT) || (type < 1))
throw BadCommandDriverError(POS, type);
return PARSER_FEATURES[type];
}
unsigned
Driver::decodeParserFeatureFlags(ParamDecoder& params)
{
unsigned flags = 0;
while (const int8_t type = params)
{
if (type > 0)
// set flag
flags |= idToParserFeature(type);
else
// unset flag
flags &= ~idToParserFeature(-type);
}
return flags;
}
unsigned
Driver::idToGeneratorFeature(int type)
{
if ((type > GENERATOR_FEATURE_COUNT) || (type < 1))
throw BadCommandDriverError(POS, type);
return GENERATOR_FEATURES[type];
}
unsigned
Driver::idToTextFeature(int type)
{
// GEN_FEATURE < DELIM < TEXT_FEATURE
type -= GENERATOR_AND_TEXT_FEATURES_DELIM;
if ((type > TEXT_FEATURE_COUNT) || (type < 1))
throw BadCommandDriverError(POS, type);
return TEXT_FEATURES[type];
}
void
Driver::decodeGeneratorFeatureFlags(
ParamDecoder& params,
unsigned& genFlags,
unsigned& textFlags)
{
while (const int8_t type = params)
{
if (type == GENERATOR_AND_TEXT_DEFAULT_FEATURES)
{
/// Reset settings to default flag
genFlags = GENERATOR_DEFAULT_FEATURES;
textFlags = TEXT_DEFAULT_FEATURES;
}
else
if (type > 0)
{
// set flag
if (type > GENERATOR_AND_TEXT_FEATURES_DELIM)
textFlags |= idToTextFeature(type);
else
genFlags |= idToGeneratorFeature(type);
}
else
{
int pos_type = -type;
// unset flag
if (pos_type > GENERATOR_AND_TEXT_FEATURES_DELIM)
textFlags &= ~idToTextFeature(pos_type);
else
genFlags &= ~idToGeneratorFeature(pos_type);
}
}
}
Xapian::QueryParser::stem_strategy
Driver::readStemmingStrategy(ParamDecoder& params)
{
const uint8_t type = params;
if (type > STEM_STRATEGY_COUNT)
throw BadCommandDriverError(POS, type);
return STEM_STRATEGIES[type];
}
// TODO: add a STEM_ALL_Z
//// It was new in 1.3.1
//Xapian::TermGenerator::stem_strategy
//Driver::readTermGeneratorStemmingStrategy(ParamDecoder& params)
//{
// const uint8_t type = params;
// if (type > TG_STEM_STRATEGY_COUNT)
// throw BadCommandDriverError(POS, type);
// return TG_STEM_STRATEGIES[type];
//}
void
Driver::addPrefix(ParamDecoder& params, Xapian::QueryParser& qp)
{
const std::string& field = params;
const std::string& prefix = params;
const bool is_boolean = params;
const bool is_exclusive = params;
if (is_boolean)
qp.add_boolean_prefix(field, prefix, is_exclusive);
else
qp.add_prefix(field, prefix);
}
void
Driver::addPrefix(ParamDecoder& params, QueryParserFactory& qpf)
{
const std::string& field = params;
const std::string& prefix = params;
const bool is_boolean = params;
const bool is_exclusive = params;
if (is_boolean)
qpf.add_boolean_prefix(field, prefix, is_exclusive);
else
qpf.add_prefix(field, prefix);
}
Xapian::Query
Driver::buildQuery(CP)
{
const uint8_t type = params;
switch (type)
{
case QUERY_GROUP:
{
const uint8_t op = params;
const uint32_t parameter = params;
const uint32_t subQueryCount = params;
std::vector<Xapian::Query> subQueries;
for (uint32_t i = 0; i < subQueryCount; i++)
subQueries.push_back(buildQuery(con, params));
std::vector<Xapian::Query>::iterator qbegin = subQueries.begin();
std::vector<Xapian::Query>::iterator qend = subQueries.end();
Xapian::Query q(
static_cast<Xapian::Query::op>(op),
qbegin,
qend,
static_cast<Xapian::termcount>(parameter));
return q;
}
case QUERY_VALUE:
{
const uint8_t op = params;
const Xapian::valueno slot = params;
const std::string& value = decodeValue(params);
Xapian::Query q(
static_cast<Xapian::Query::op>(op),
slot,
value);
return q;
}
case QUERY_VALUE_RANGE:
{
const uint8_t op = params;
const Xapian::valueno slot = params;
const std::string& from = decodeValue(params);
const std::string& to = decodeValue(params);
Xapian::Query q(
static_cast<Xapian::Query::op>(op),
slot,
from,
to);
return q;
}
case QUERY_TERM:
{
const std::string& name = params;
const uint32_t wqf = params;
const uint32_t pos = params;
Xapian::Query q(
name,
wqf,
pos);
return q;
}
case QUERY_PARSER: // query_string
{
Xapian::QueryParser parser = readParser(con, params);
const std::string& query_string = params;
const std::string& default_prefix = params;
const unsigned flags = decodeParserFeatureFlags(params);
Xapian::Query q =
parser.parse_query(
query_string,
flags,
default_prefix);
return q;
}
case QUERY_SCALE_WEIGHT: // case with a double parameter
{
const uint8_t op = params;
const double factor = params;
Xapian::Query sub_query = buildQuery(con, params);
Xapian::Query q(
static_cast<Xapian::Query::op>(op),
sub_query,
factor);
return q;
}
case QUERY_SIMILAR_DOCUMENT:
{
const uint32_t maxitems = params;
Xapian::Enquire enquire(m_db);
Xapian::RSet rset;
while (const Xapian::docid docid = params)
{
rset.add_document(docid);
}
Xapian::ESet eset = enquire.get_eset(static_cast<Xapian::doccount>(maxitems), rset);
Xapian::Query q(Xapian::Query::OP_OR, eset.begin(), eset.end());
return q;
}
case QUERY_REFERENCE:
{
return extractQuery(con, params);
}
default:
throw BadCommandDriverError(POS, type);
}
}
void
Driver::fillEnquire(CP, Xapian::Enquire& enquire)
{
Xapian::termcount qlen = 0;
while (uint8_t command = params)
switch (command)
{
case EC_QUERY:
{
Xapian::Query query = buildQuery(con, params);
enquire.set_query(query, qlen);
break;
}
case EC_QUERY_LEN:
{
uint32_t value = params;
qlen = value;
break;
}
case EC_ORDER:
{
fillEnquireOrder(con, params, enquire);
break;
}
case EC_DOCID_ORDER:
{
uint8_t type = params;
if (type >= DOCID_ORDER_TYPE_COUNT)
throw BadCommandDriverError(POS, type);
Xapian::Enquire::docid_order order = DOCID_ORDER_TYPES[type];
enquire.set_docid_order(order);
break;
}
case EC_WEIGHTING_SCHEME:
{
const Xapian::Weight& weight = extractWeight(con, params);
enquire.set_weighting_scheme(weight);
break;
}
case EC_CUTOFF:
{
uint8_t percent_cutoff = params;
double weight_cutoff = params;
enquire.set_cutoff(percent_cutoff, weight_cutoff);
break;
}
case EC_COLLAPSE_KEY:
{
uint32_t collapse_key = params;
uint32_t collapse_max = params;
enquire.set_collapse_key(
collapse_key,
collapse_max);
break;
}
default:
throw BadCommandDriverError(POS, command);
}
}
void
Driver::fillEnquireOrder(CP, Xapian::Enquire& enquire)
{
uint8_t type = params;
bool reverse = params;
switch(type)
{
case OT_KEY:
{
Xapian::KeyMaker& sorter = extractKeyMaker(con, params);
enquire.set_sort_by_key(&sorter, reverse);
break;
}
case OT_KEY_RELEVANCE:
{
Xapian::KeyMaker& sorter = extractKeyMaker(con, params);
enquire.set_sort_by_key_then_relevance(&sorter, reverse);
break;
}
case OT_RELEVANCE_KEY:
{
Xapian::KeyMaker& sorter = extractKeyMaker(con, params);
enquire.set_sort_by_relevance_then_key(&sorter, reverse);
break;
}
case OT_VALUE:
{
uint32_t value = params;
enquire.set_sort_by_value(value, reverse);
break;
}
case OT_RELEVANCE_VALUE:
{
uint32_t value = params;
enquire.set_sort_by_relevance_then_value(value, reverse);
break;
}
case OT_VALUE_RELEVANCE:
{
uint32_t value = params;
enquire.set_sort_by_value_then_relevance(value, reverse);
break;
}
default:
throw BadCommandDriverError(POS, type);
}
}
/**
* Returns a cloned parser.
*/
Xapian::QueryParser
Driver::selectParser(ParamDecoder& params)
{
uint8_t type = params;
switch (type)
{
case QP_TYPE_DEFAULT:
return m_default_parser_factory;
case QP_TYPE_EMPTY:
return m_standard_parser_factory;
default:
throw BadCommandDriverError(POS, type);
}
}
Xapian::TermGenerator
Driver::selectGenerator(ParamDecoder& params)
{
uint8_t type = params;
switch (type)
{
case TG_TYPE_DEFAULT:
return m_default_generator_factory;
case TG_TYPE_EMPTY:
return m_standard_generator_factory;
default:
throw BadCommandDriverError(POS, type);
}
}
/**
* Return a cloned parser.
*/
Xapian::QueryParser
Driver::readParser(CP)
{
uint8_t command = params;
// No parameters?
// DEFAULT_PARSER_CHECK_MARK -- mark for Erlang
//
// Return the wrapper without changes.
if (!command)
return m_default_parser;
// Clone parser
Xapian::QueryParser qp = m_default_parser_factory;
do
{
switch (command)
{
case QP_STEMMER:
{
const Xapian::Stem& stemmer = params;
qp.set_stemmer(stemmer);
break;
}
case QP_STEMMING_STRATEGY:
{
Xapian::QueryParser::stem_strategy
strategy = readStemmingStrategy(params);
qp.set_stemming_strategy(strategy);
break;
}
case QP_MAX_WILDCARD_EXPANSION:
{
const uint32_t limit = params;
qp.set_max_wildcard_expansion(static_cast<Xapian::termcount>(limit));
break;
}
case QP_DEFAULT_OP:
{
const uint8_t default_op = params;
qp.set_default_op(static_cast<Xapian::Query::op>(default_op));
break;
}
case QP_PREFIX:
addPrefix(params, qp);
break;
case QP_VALUE_RANGE_PROCESSOR:
{
Xapian::ValueRangeProcessor& vrp =
extractRangeProcessor(con, params);
qp.add_valuerangeprocessor(&vrp);
break;
}
case QP_PARSER_TYPE:
// Clone
qp = selectParser(params);
break;
case QP_FROM_RESOURCE:
{
Resource::Element elem = m_store.extract(params);
// The elem is not interesting for us, but its children are.
con.attachContext(elem);
// Copy from resource
qp = elem;
break;
}
case QP_STEMMER_RESOURCE:
{
Xapian::Stem& stemmer = extractStem(con, params);
qp.set_stemmer(stemmer);
break;
}
case QP_STOPPER_RESOURCE:
{
Xapian::Stopper& stopper = extractStopper(con, params);
qp.set_stopper(&stopper);
break;
}
default:
throw BadCommandDriverError(POS, command);
}
} while((command = params)); // yes, it's an assignment [-Wparentheses]
// warning: suggest parentheses around assignment used as truth value
return qp;
}
Xapian::TermGenerator
Driver::readGenerator(CP)
{
uint8_t command = params;
// No parameters?
// DEFAULT_GENERATOR_CHECK_MARK -- mark for Erlang
if (!command)
return m_default_generator;
// Clone parser
Xapian::TermGenerator tg = m_default_generator_factory;
do
{
switch (command)
{
case TG_STEMMER:
{
const Xapian::Stem& stemmer = params;
tg.set_stemmer(stemmer);
break;
}
case TG_STEMMING_STRATEGY:
{
// TODO: fix it in 1.3.1
throw NotImplementedCommandDriverError(POS, command);
// Xapian::TermGenerator::stem_strategy
// strategy = readTermGeneratorStemmingStrategy(params);
// qp.set_stemming_strategy(strategy);
// break;
}
case TG_GENERATOR_TYPE:
// Clone
tg = selectGenerator(params);
break;
case TG_FROM_RESOURCE:
{
Resource::Element elem = m_store.extract(params);
// The elem is not interesting for us, but its children are.
con.attachContext(elem);
// Copy from resource
tg = elem;
break;
}
case TG_STEMMER_RESOURCE:
{
Xapian::Stem& stemmer = extractStem(con, params);
tg.set_stemmer(stemmer);
break;
}
case TG_STOPPER_RESOURCE:
{
Xapian::Stopper& stopper = extractStopper(con, params);
tg.set_stopper(&stopper);
break;
}
default:
throw BadCommandDriverError(POS, command);
}
} while((command = params)); // yes, it's an assignment [-Wparentheses]
// warning: suggest parentheses around assignment used as truth value
return tg;
}
void
Driver::handleCommand(PR,
const unsigned int command)
{
result << static_cast<uint8_t>( SUCCESS );
Resource::Element con = Resource::Element::createContext();
try
{
switch(command) {
case OPEN:
{
const uint8_t mode = params;
const std::string& dbpath = params;
open(mode, dbpath);
break;
}
case OPEN_PROG:
{
const uint8_t mode = params;
const std::string& prog = params;
const std::string& args = params;
const uint32_t timeout = params;
open(mode, prog, args, timeout);
break;
}
// Connect to an external server
case OPEN_TCP:
{
const uint8_t mode = params;
const std::string& host = params;
const uint16_t port = params;
const uint32_t timeout = params;
const uint32_t ctimeout = params;
open(mode, host, port, timeout, ctimeout);
break;
}
case LAST_DOC_ID:
getLastDocId(result);
break;
case ADD_DOCUMENT:
addDocument(params, result);
break;
case ADD_SPELLING:
addSpelling(params);
break;
case ADD_SYNONYM:
addSynonym(params);
break;
case REMOVE_SYNONYM:
removeSynonym(params);
break;
case CLEAR_SYNONYMS:
clearSynonyms(params);
break;
case UPDATE_DOCUMENT:
case UPDATE_OR_CREATE_DOCUMENT:
updateDocument(params, result,
command == UPDATE_OR_CREATE_DOCUMENT);
break;
case IS_DOCUMENT_EXIST:
isDocumentExist(params, result);
break;
case DELETE_DOCUMENT:
deleteDocument(params, result);
break;
case REPLACE_DOCUMENT:
replaceDocument(params, result);
break;
case REPLACE_OR_CREATE_DOCUMENT:
replaceOrCreateDocument(params, result);
break;
case TEST:
test(params, result);
break;
case GET_DOCUMENT_BY_ID:
getDocumentById(params, result);
break;
case DOCUMENT_INFO:
documentInfo(params, result);
break;
case DOCUMENT_INFO_RESOURCE:
documentInfoResource(params, result);
break;
case START_TRANSACTION:
startTransaction();
break;
case CANCEL_TRANSACTION:
cancelTransaction();
break;
case COMMIT_TRANSACTION:
commitTransaction();
break;
case QUERY_PAGE:
query(con, params, result);
break;
case SET_DEFAULT_STEMMER:
setDefaultStemmer(params);
break;
case SET_DEFAULT_PREFIXES:
setDefaultPrefixes(params);
break;
case ENQUIRE:
enquire(params, result);
break;
case DOCUMENT:
document(params, result);
break;
case RELEASE_RESOURCE:
releaseResource(params);
break;
case RELEASE_RESOURCES:
releaseResources(params);
break;
case MATCH_SET:
matchSet(con, params, result);
break;
case QLC_INIT:
qlcInit(params, result);
break;
case QLC_NEXT_PORTION:
qlcNext(params, result);
break;
case QLC_LOOKUP:
qlcLookup(params, result);
break;
case GET_RESOURCE_CONSTRUCTORS:
getResourceConstructors(result);
break;
case CREATE_RESOURCE:
createResource(params, result);
break;
case MSET_INFO:
msetInfo(params, result);
break;
case DB_INFO:
databaseInfo(params, result);
break;
case MATCH_SPY_INFO:
matchSpyInfo(params, result);
break;
case SET_METADATA:
setMetadata(params);
break;
case CLOSE:
m_wdb.close();
m_db.close();
break;
case CREATE_QUERY_PARSER:
createQueryParser(params, result);
break;
case CREATE_TERM_GENERATOR:
createTermGenerator(params, result);
break;
case GET_SPELLING_CORRECTION:
getSpellingCorrection(params, result);
break;
case PARSE_STRING:
parseString(con, params, result);
break;
default:
throw BadCommandDriverError(POS, command);
}
}
catch (DriverRuntimeError& e)
{
result.reset();
result << static_cast<uint8_t>( ERROR_WITH_POSITION );
result << e.get_type();
result << e.what();
result << e.get_line();
result << e.get_file();
}
catch (Xapian::Error& e)
{
result.reset();
result << static_cast<uint8_t>( ERROR );
result << e.get_type();
result << e.get_msg();
}
}
void
Driver::setDatabaseAgain()
{
m_default_parser.set_database(m_db);
m_standard_parser.set_database(m_db);
m_default_generator.set_database(m_wdb);
m_standard_generator.set_database(m_wdb);
m_default_parser_factory.set_database(m_db);
m_standard_parser_factory.set_database(m_db);
m_default_generator_factory.set_database(m_wdb);
m_standard_generator_factory.set_database(m_wdb);
}
void
Driver::open(uint8_t mode, const std::string& dbpath)
{
switch(mode)
{
// Open readOnly db
case READ_OPEN:
m_db.add_database(Xapian::Database(dbpath));
m_number_of_databases++;
break;
case WRITE_CREATE_OR_OPEN:
case WRITE_CREATE:
case WRITE_CREATE_OR_OVERWRITE:
case WRITE_OPEN:
m_wdb = Xapian::WritableDatabase(dbpath, openWriteMode(mode));
m_db = m_wdb;
m_number_of_databases = 1;
break;
default:
throw BadCommandDriverError(POS, mode);
}
setDatabaseAgain();
}
int
Driver::openWriteMode(uint8_t mode)
{
switch(mode)
{
// create new database; fail if db exists
case WRITE_CREATE_OR_OPEN:
return Xapian::DB_CREATE_OR_OPEN;
// overwrite existing db; create if none exists
case WRITE_CREATE:
return Xapian::DB_CREATE;
// open for read/write; fail if no db exists
case WRITE_CREATE_OR_OVERWRITE:
return Xapian::DB_CREATE_OR_OVERWRITE;
// open for read/write; fail if no db exists
case WRITE_OPEN:
return Xapian::DB_OPEN;
default:
throw BadCommandDriverError(POS, mode);
}
}
/**
* Open an remote TCP database.
*
* http://xapian.org/docs/apidoc/html/namespaceXapian_1_1Remote.html
*/
void
Driver::open(uint8_t mode, const std::string& host, uint16_t port,
uint32_t timeout, uint32_t connect_timeout)
{
switch(mode)
{
// Open readOnly db
case READ_OPEN:
m_db.add_database(
Xapian::Remote::open(host, port, timeout, connect_timeout));
m_number_of_databases++;
break;
// open for read/write; fail if no db exists
case WRITE_OPEN:
m_wdb = Xapian::Remote::open_writable(host, port,
timeout, connect_timeout);
m_db = m_wdb;
m_number_of_databases = 1;
break;
default:
throw BadCommandDriverError(POS, mode);
}
setDatabaseAgain();
}
/**
* Open an remote program database.
*
* http://xapian.org/docs/apidoc/html/namespaceXapian_1_1Remote.html
*/
void
Driver::open(uint8_t mode, const std::string& prog, const std::string& args,
uint32_t timeout)
{
switch(mode) {
// Open readOnly db
case READ_OPEN:
m_db.add_database(Xapian::Remote::open(prog, args, timeout));
m_number_of_databases++;
break;
// open for read/write; fail if no db exists
case WRITE_OPEN:
m_wdb = Xapian::Remote::open_writable(prog, args, timeout);
m_db = m_wdb;
m_number_of_databases = 1;
break;
default:
throw BadCommandDriverError(POS, mode);
}
setDatabaseAgain();
}
void
Driver::applyDocument(
ParamDecoder& params,
Xapian::Document& doc)
{
Resource::Element gen_con =
Resource::Element::createContext();
Xapian::TermGenerator tg = m_default_generator;
tg.set_document(doc);
// tg.set_stemmer(m_default_stemmer);
while (const uint8_t command = params)
/* Do, while command != stop != 0 */
{
switch (command)
{
case STEMMER:
{
// see xapian_document:append_stemmer
const Xapian::Stem& stemmer = params;
tg.set_stemmer(stemmer);
break;
}
case TERM_GENERATOR:
{
tg = readGenerator(gen_con, params);
tg.set_document(doc);
break;
}
case SET_TERM_GEN_POS:
{
const uint32_t position = params; // pos
tg.set_termpos(static_cast<Xapian::termcount>(position));
break;
}
case DATA:
{
// see xapian_document:append_data
const std::string& data = params;
doc.set_data(data);
break;
}
case DELTA:
{
// see xapian_document:append_delta
const uint32_t delta = params;
tg.increase_termpos(static_cast<Xapian::termcount>(delta));
break;
}
case TEXT:
{
// see xapian_document:append_delta
const std::string& text = params; // value
const uint32_t wdf_inc = params; // pos
const std::string& prefix = params;
unsigned genFlags = 0, textFlags = 0;
decodeGeneratorFeatureFlags(params, genFlags, textFlags);
tg.set_flags(Xapian::TermGenerator::flags(genFlags));
// if isset(TEXT_FLAG_POSITIONS)
if ((textFlags & TEXT_FLAG_POSITIONS) == TEXT_FLAG_POSITIONS)
tg.index_text(text,
static_cast<Xapian::termcount>(wdf_inc),
prefix);
else
tg.index_text(text,
static_cast<Xapian::termcount>(wdf_inc),
prefix);
break;
}
case SET_TERM:
case ADD_TERM:
case UPDATE_TERM:
case REMOVE_TERM:
handleTerm(params, command, doc);
break;
case ADD_VALUE:
case SET_VALUE:
case UPDATE_VALUE:
case REMOVE_VALUE:
handleValue(params, command, doc);
break;
case SET_POSTING:
case ADD_POSTING:
case UPDATE_POSTING:
case REMOVE_POSTING:
handlePosting(params, command, doc);
break;
case SET_WDF:
case DEC_WDF:
// see append_decrease_wdf
// see append_set_wdf
{
const std::string& tname = params; // value
const uint32_t wdf = params;
const bool ignore = params;
const Xapian::termcount wdf2 =
static_cast<Xapian::termcount>(wdf);
if (command == SET_WDF)
Helpers::trySetWDF(doc, tname, wdf2, ignore);
else
Helpers::tryDecreaseWDF(doc, tname, wdf2, ignore);
break;
}
case REMOVE_VALUES:
doc.clear_values();
break;
case REMOVE_TERMS:
doc.clear_terms();
break;
case REMOVE_POSITIONS:
Helpers::clearTermPositions(doc);
break;
case REMOVE_TERM_POSITIONS:
{
const std::string& tname = params; // value
const bool ignore = params;
Helpers::tryClearTermPositions(doc, tname, ignore);
break;
}
default:
throw BadCommandDriverError(POS, command);
}
}
}
void
Driver::handleTerm(
ParamDecoder& params,
uint8_t command,
Xapian::Document& doc)
{
// see xapian_document:append_term
const std::string& tname = params; // value
const uint32_t wdf = params;
const bool ignore = params;
// Pos = undefined
const Xapian::termcount wdf_inc =
static_cast<Xapian::termcount>(wdf);
bool is_error = false;
switch (command)
{
case REMOVE_TERM:
if ((!wdf_inc)
|| (wdf_inc == Helpers::getTermFrequency(doc, tname)))
{
Helpers::tryRemoveTerm(doc, tname, ignore);
return;
}
else
is_error = true;
case ADD_TERM:
if (Helpers::isTermExist(doc, tname))
is_error = true;
break;
case UPDATE_TERM:
if (!Helpers::isTermExist(doc, tname))
is_error = true;
}
if (is_error)
{
if (ignore) return;
else throw BadArgumentDriverError(POS);
}
doc.add_term(tname, wdf_inc);
}
void
Driver::handleSpelling(
ParamDecoder& params,
uint8_t command,
Xapian::WritableDatabase& wdb)
{
// see xapian_document:append_term
const std::string& tname = params; // value
const uint32_t wdf = params;
const bool ignore = params;
// Pos = undefined
const Xapian::termcount wdf_inc =
static_cast<Xapian::termcount>(wdf);
bool is_error = false;
switch (command)
{
case REMOVE_TERM:
if ((!wdf_inc)
|| (wdf_inc == Helpers::getSpellingFrequency(wdb, tname)))
{
Helpers::tryRemoveSpelling(wdb, tname, ignore);
return;
}
else
is_error = true;
case ADD_TERM:
if (Helpers::isSpellingExist(wdb, tname))
is_error = true;
break;
case UPDATE_TERM:
if (!Helpers::isSpellingExist(wdb, tname))
is_error = true;
}
if (is_error)
{
if (ignore) return;
else throw BadArgumentDriverError(POS);
}
wdb.add_spelling(tname, wdf_inc);
}
const std::string
Driver::decodeValue(ParamDecoder& params)
{
switch(uint8_t type = params)
{
case STRING_TYPE:
return params;
case DOUBLE_TYPE:
return Xapian::sortable_serialise(params);
default:
throw BadCommandDriverError(POS, type);
}
}
void
Driver::handleValue(
ParamDecoder& params,
uint8_t command,
Xapian::Document& doc)
{
// see xapian_document:append_value
const uint32_t slot = params;
const std::string& value = decodeValue(params);
const bool ignore = params;
const Xapian::valueno slot_no =
static_cast<Xapian::valueno>(slot);
bool is_error = false;
switch (command)
{
case REMOVE_VALUE:
// If value is an empty string, then remove any value in
// the slot.
// Otherwise, remove only if passed and current values
// are equal.
if ((value == "") || (value == doc.get_value(slot_no)))
Helpers::tryRemoveValue(doc, slot_no, ignore);
return;
case ADD_VALUE:
if (Helpers::isValueExist(doc, slot_no))
is_error = true;
break;
case UPDATE_VALUE:
if (!Helpers::isValueExist(doc, slot_no))
is_error = true;
}
if (is_error)
{
if (ignore) return;
else throw BadArgumentDriverError(POS);
}
doc.add_value(slot_no, value);
}
void
Driver::handlePosting(
ParamDecoder& params,
uint8_t command,
Xapian::Document& doc)
{
// see xapian_document:append_term
const std::string& tname = params; // value
const uint32_t tpos = params;
const uint32_t wdf = params;
const bool ignore = params;
const Xapian::termpos term_pos =
static_cast<Xapian::termpos>(tpos);
const Xapian::termcount wdf2 =
static_cast<Xapian::termcount>(wdf);
bool is_error = false;
switch (command)
{
case REMOVE_POSTING:
Helpers::tryRemovePosting(doc, tname, term_pos, wdf2, ignore);
return;
case ADD_POSTING:
if (Helpers::isPostingExist(doc, tname, term_pos))
is_error = true;
break;
case UPDATE_POSTING:
if (!Helpers::isPostingExist(doc, tname, term_pos))
is_error = true;
}
if (is_error)
{
if (ignore) return;
else throw BadArgumentDriverError(POS);
}
doc.add_posting(tname, term_pos, wdf2);
}
void
Driver::retrieveDocument(PCR,
Xapian::Document& doc)
{
const uint8_t decoder_type = params;
if (decoder_type != DEC_DOCUMENT)
throw BadArgumentDriverError(POS);
while (const uint8_t command = params)
/* Do, while command != stop != 0 */
{
switch (command)
{
case GET_VALUE:
{
const uint32_t slot = params;
const uint8_t type = STRING_TYPE;
const std::string& value =
doc.get_value(static_cast<Xapian::valueno>(slot));
result << type << value;
break;
}
case GET_FLOAT_VALUE:
{
const uint32_t slot = params;
const uint8_t type = DOUBLE_TYPE;
const double value =
Xapian::sortable_unserialise(
doc.get_value(static_cast<Xapian::valueno>(slot)));
result << type << value;
break;
}
case GET_DATA:
{
const std::string& data = doc.get_data();
result << data;
break;
}
case GET_ALL_TERMS:
{
retrieveTermValues(result, doc);
break;
}
case GET_ALL_TERMS_POS:
{
retrieveTermValuesAndPositions(result, doc);
break;
}
case GET_ALL_VALUES:
{
retrieveSlotAndValues(result, doc);
break;
}
case GET_DOCID:
{
const Xapian::docid docid = doc.get_docid();
result << static_cast<uint32_t>(docid);
break;
}
default:
throw BadCommandDriverError(POS, command);
}
}
}
void
Driver::retrieveDocument(PCR,
Xapian::MSetIterator& mset_iter)
{
const uint8_t decoder_type = params;
if (decoder_type != DEC_ITERATOR)
throw BadArgumentDriverError(POS);
while (const uint8_t command = params)
/* Do, while command != stop != 0 */
{
switch (command)
{
case GET_WEIGHT:
{
const Xapian::weight w = mset_iter.get_weight();
result << static_cast<double>(w);
break;
}
case GET_RANK:
{
const Xapian::doccount r = mset_iter.get_rank();
result << static_cast<uint32_t>(r);
break;
}
case GET_PERCENT:
{
const Xapian::percent p = mset_iter.get_percent();
result << static_cast<uint8_t>(p);
break;
}
// http://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
case GET_DOCID:
{
result << static_cast<uint32_t>(docid_sub(*mset_iter));
break;
}
case GET_MULTI_DOCID:
{
result << static_cast<uint32_t>(*mset_iter);
break;
}
case GET_DB_NUMBER:
{
result << static_cast<uint32_t>(subdb_num(*mset_iter));
break;
}
case GET_COLLAPSE_KEY:
{
const std::string& key = mset_iter.get_collapse_key();
result << key;
break;
}
case GET_COLLAPSE_COUNT:
{
result << static_cast<uint32_t>(mset_iter.get_collapse_count());
break;
}
default:
throw BadCommandDriverError(POS, command);
}
}
}
void
Driver::retrieveDocument(PCR,
Xapian::Document& doc,
Xapian::MSetIterator& mset_iter)
{
const uint8_t decoder_type = params;
if (decoder_type != DEC_BOTH)
throw BadArgumentDriverError(POS);
//Xapian::docid did = *m;
while (const uint8_t command = params)
/* Do, while command != stop != 0 */
{
switch (command)
{
case GET_VALUE:
{
const uint32_t slot = params;
const uint8_t type = STRING_TYPE;
const std::string& value =
doc.get_value(static_cast<Xapian::valueno>(slot));
result << type << value;
break;
}
case GET_FLOAT_VALUE:
{
const uint32_t slot = params;
const uint8_t type = DOUBLE_TYPE;
const double value =
Xapian::sortable_unserialise(
doc.get_value(static_cast<Xapian::valueno>(slot)));
result << type << value;
break;
}
case GET_DATA:
{
const std::string& data = doc.get_data();
result << data;
break;
}
case GET_ALL_TERMS:
{
retrieveTermValues(result, doc);
break;
}
case GET_ALL_TERMS_POS:
{
retrieveTermValuesAndPositions(result, doc);
break;
}
case GET_ALL_VALUES:
{
retrieveSlotAndValues(result, doc);
break;
}
case GET_DOCID:
{
const Xapian::docid docid = doc.get_docid();
result << static_cast<uint32_t>(docid);
break;
}
case GET_WEIGHT:
{
const Xapian::weight w = mset_iter.get_weight();
result << static_cast<double>(w);
break;
}
case GET_RANK:
{
const Xapian::doccount r = mset_iter.get_rank();
result << static_cast<uint32_t>(r);
break;
}
case GET_PERCENT:
{
const Xapian::percent p = mset_iter.get_percent();
result << static_cast<uint8_t>(p);
break;
}
// http://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
case GET_MULTI_DOCID:
{
result << static_cast<uint32_t>(*mset_iter);
break;
}
case GET_DB_NUMBER:
{
result << static_cast<uint32_t>(subdb_num(*mset_iter));
break;
}
case GET_COLLAPSE_KEY:
{
const std::string& key = mset_iter.get_collapse_key();
result << key;
break;
}
case GET_COLLAPSE_COUNT:
{
result << static_cast<uint32_t>(mset_iter.get_collapse_count());
break;
}
default:
throw BadCommandDriverError(POS, command);
}
}
}
/**
* @a params is copy.
*/
void
Driver::retrieveTerm(PCR, const Xapian::TermIterator& iter)
{
while (const uint8_t command = params)
/* Do, while command != stop != 0 */
{
switch (command)
{
case TERM_VALUE:
{
const std::string& value = *iter;
result << value;
break;
}
case TERM_FLOAT_VALUE:
{
const std::string& value = *iter;
const double float_value = Xapian::sortable_unserialise(value);
result << float_value;
break;
}
case TERM_WDF:
{
result << static_cast<uint32_t>(iter.get_wdf());
break;
}
case TERM_FREQ:
{
result << static_cast<uint32_t>(iter.get_termfreq());
break;
}
case TERM_POS_COUNT:
{
result << static_cast<uint32_t>(iter.positionlist_count());
break;
}
case TERM_POSITIONS:
{
Xapian::termcount count = iter.positionlist_count();
result << static_cast<uint32_t>(count);
if (count > 0)
for (Xapian::PositionIterator
piter = iter.positionlist_begin(),
pend = iter.positionlist_end();
piter != pend;
piter++)
result << static_cast<uint32_t>(*piter);
break;
}
default:
throw BadCommandDriverError(POS, command);
}
}
}
ParamDecoderController
Driver::retrieveTermSchema(
ParamDecoder& params) const
{
const char* from = params.currentPosition();
while (const uint8_t command = params)
/* Do, while command != stop != 0 */
{}
const char* to = params.currentPosition();
size_t len = to - from;
ParamDecoderController ctrl(m_mm, from, len);
return ctrl;
}
ParamDecoderController
Driver::retrieveDocumentSchema(
ParamDecoder& params) const
{
const char* from = params.currentPosition();
uint8_t decoder_type = params;
(void) decoder_type;
while (const uint8_t command = params)
/* Do, while command != stop != 0 */
{
switch (command)
{
case GET_FLOAT_VALUE:
case GET_VALUE:
{
//static_cast<uint32_t>( params ); // slot
uint32_t slot = params; // slot
(void) slot;
break;
}
case GET_DATA:
case GET_DOCID:
case GET_WEIGHT:
case GET_RANK:
case GET_PERCENT:
case GET_MULTI_DOCID:
case GET_DB_NUMBER:
case GET_COLLAPSE_KEY:
case GET_COLLAPSE_COUNT:
case GET_ALL_TERMS:
case GET_ALL_VALUES:
break;
default:
throw BadCommandDriverError(POS, command);
}
}
const char* to = params.currentPosition();
size_t len = to - from;
ParamDecoderController ctrl(m_mm, from, len);
return ctrl;
}
ParamDecoderController
Driver::applyDocumentSchema(
ParamDecoder& params)
{
const char* from = params.currentPosition();
while (const uint8_t command = params)
/* Do, while command != stop != 0 */
{
switch (command)
{
case STEMMER:
{
const Xapian::Stem& stemmer = params;
(void) stemmer;
break;
}
case TERM_GENERATOR:
{
// Create a temporary context
Resource::Element gen_con =
Resource::Element::createContext();
Xapian::TermGenerator tg = readGenerator(gen_con, params);
(void) tg;
break;
}
case SET_TERM_GEN_POS:
{
const uint32_t position = params; // pos
(void) position;
break;
}
case DATA:
{
const std::string& data = params;
(void) data;
break;
}
case DELTA:
{
const uint32_t delta = params;
(void) delta;
break;
}
case TEXT:
{
const std::string& text = params; // value
const uint32_t wdf_inc = params; // pos
const std::string& prefix = params;
(void) text;
(void) wdf_inc;
(void) prefix;
break;
}
case SET_TERM:
case ADD_TERM:
case UPDATE_TERM:
case REMOVE_TERM:
{
const std::string& tname = params; // value
const Xapian::termcount wdf_inc = params;
const bool ignore = params;
(void) tname;
(void) wdf_inc;
(void) ignore;
break;
}
case ADD_VALUE:
case SET_VALUE:
case UPDATE_VALUE:
case REMOVE_VALUE:
{
const uint32_t slot = params;
const std::string& value = decodeValue(params);
const bool ignore = params;
(void) slot;
(void) value;
(void) ignore;
break;
}
case SET_POSTING:
case ADD_POSTING:
case UPDATE_POSTING:
case REMOVE_POSTING:
{
const std::string& tname = params; // value
const uint32_t tpos = params;
const uint32_t wdf_inc = params;
const bool ignore = params;
(void) tname;
(void) tpos;
(void) wdf_inc;
(void) ignore;
break;
}
// work with WDF
case DEC_WDF:
case SET_WDF:
{
const std::string& tname = params; // value
const Xapian::termcount wdf = params;
const bool ignore = params;
(void) tname;
(void) wdf;
(void) ignore;
break;
}
case REMOVE_VALUES:
case REMOVE_TERMS:
case REMOVE_POSITIONS:
break;
case REMOVE_TERM_POSITIONS:
{
const std::string& tname = params; // value
const bool ignore = params;
(void) tname;
(void) ignore;
break;
}
default:
throw BadCommandDriverError(POS, command);
}
}
const char* to = params.currentPosition();
size_t len = to - from;
ParamDecoderController ctrl(m_mm, from, len);
return ctrl;
}
// -------------------------------------------------------------------
// Resource Driver Helpers
// -------------------------------------------------------------------
/**
* This function will be called inside xapian_open:init
*/
void
Driver::getResourceConstructors(ResultEncoder& result)
{
m_store.getResourceConstructors(result);
}
void
Driver::createResource(PR)
{
Resource::Element elem = m_store.create(params);
m_store.save(elem, result);
}
void
Driver::msetInfo(PR)
{
Xapian::MSet& mset = m_store.extract(params);
while (uint8_t command = params)
switch (command)
{
case MI_MATCHES_LOWER_BOUND:
result << static_cast<uint32_t>(mset.get_matches_lower_bound());
break;
case MI_MATCHES_ESTIMATED:
result << static_cast<uint32_t>(mset.get_matches_estimated());
break;
case MI_MATCHES_UPPER_BOUND:
result << static_cast<uint32_t>(mset.get_matches_upper_bound());
break;
case MI_UNCOLLAPSED_MATCHES_LOWER_BOUND:
result << static_cast<uint32_t>(
mset.get_uncollapsed_matches_lower_bound());
break;
case MI_UNCOLLAPSED_MATCHES_ESTIMATED:
result << static_cast<uint32_t>(
mset.get_uncollapsed_matches_estimated());
break;
case MI_UNCOLLAPSED_MATCHES_UPPER_BOUND:
result << static_cast<uint32_t>(
mset.get_uncollapsed_matches_upper_bound());
break;
case MI_SIZE:
result << static_cast<uint32_t>(mset.size());
break;
case MI_GET_MAX_POSSIBLE:
result << static_cast<double>(mset.get_max_possible());
break;
case MI_GET_MAX_ATTAINED:
result << static_cast<double>(mset.get_max_attained());
break;
case MI_TERM_WEIGHT:
{
const std::string& tname = params;
result << static_cast<double>(mset.get_termweight(tname));
break;
}
case MI_TERM_FREQ:
{
const std::string& tname = params;
result << static_cast<uint32_t>(mset.get_termfreq(tname));
break;
}
default:
throw BadCommandDriverError(POS, command);
}
}
void
Driver::databaseInfo(PR)
{
while (uint8_t command = params)
switch(command)
{
case DBI_HAS_POSITIONS:
result << static_cast<uint8_t>(m_db.has_positions());
break;
case DBI_DOCCOUNT:
result << static_cast<uint32_t>(m_db.get_doccount());
break;
case DBI_LASTDOCID:
result << static_cast<uint32_t>(m_db.get_lastdocid());
break;
case DBI_AVLENGTH:
result << static_cast<double>(m_db.get_avlength());
break;
case DBI_TERM_EXISTS:
{
const std::string& tname = params;
result << static_cast<uint8_t>(m_db.term_exists(tname));
break;
}
case DBI_TERM_FREQ:
{
const std::string& tname = params;
if (result.maybe(m_db.term_exists(tname)))
result << static_cast<uint32_t>(m_db.get_termfreq(tname));
break;
}
case DBI_COLLECTION_FREQ:
{
const std::string& tname = params;
if (result.maybe(m_db.term_exists(tname)))
result << static_cast<uint32_t>(m_db.get_collection_freq(tname));
break;
}
case DBI_VALUE_FREQ:
{
const Xapian::valueno slot = params;
result << static_cast<uint32_t>(m_db.get_value_freq(slot));
break;
}
case DBI_VALUE_LOWER_BOUND:
{
const Xapian::valueno slot = params;
result << m_db.get_value_lower_bound(slot);
break;
}
case DBI_VALUE_UPPER_BOUND:
{
const Xapian::valueno slot = params;
result << m_db.get_value_upper_bound(slot);
break;
}
case DBI_DOCLENGTH_LOWER_BOUND:
result << m_db.get_doclength_lower_bound();
break;
case DBI_DOCLENGTH_UPPER_BOUND:
result << m_db.get_doclength_upper_bound();
break;
case DBI_WDF_UPPER_BOUND:
{
const std::string& tname = params;
if (result.maybe(m_db.term_exists(tname)))
result << static_cast<uint32_t>(m_db.get_wdf_upper_bound(tname));
break;
}
case DBI_DOCLENGTH:
{
const Xapian::docid docid = params;
try
{
Xapian::termcount len = m_db.get_doclength(docid);
result.maybe(true);
result << static_cast<uint32_t>(len);
} catch (Xapian::DocNotFoundError e)
{
result.maybe(false);
}
break;
}
case DBI_UUID:
result << m_db.get_uuid();
break;
case DBI_METADATA:
{
const std::string& key = params;
result << m_db.get_metadata(key);
break;
}
// TODO: synonym, spellcorrection
default:
throw BadCommandDriverError(POS, command);
}
}
void
Driver::matchSpyInfo(PR)
{
Resource::Element elem = m_store.extract(params);
// Xapian::MatchSpy&
// spy = elem;
while (uint8_t field = params)
switch (field)
{
case SI_DOCUMENT_COUNT:
{
// This field is for ValueCountMatchSpy only.
Xapian::ValueCountMatchSpy&
vc_spy = elem;
uint32_t document_count = vc_spy.get_total();
result << document_count;
break;
}
case SI_VALUE_SLOT:
{
// The extension is for fields, that have no public access.
Extension::ValueCountMatchSpy&
vc_spy_ext = elem;
uint32_t slot = vc_spy_ext.getSlot();
result << slot;
break;
}
default:
throw BadCommandDriverError(POS, field);
}
}
void
Driver::setMetadata(ParamDecoder& params)
{
assertWriteable();
const std::string& key = params;
const std::string& value = params;
m_wdb.set_metadata(key, value);
}
/**
* Allow to find and write terms by name.
*
* Helper for TermQlcTable class.
* Use set order of elements.
*
* @param driver_params Contains which keys (term names) to find. Ends with "".
* @param schema_params Contains which fields to write.
* @param result A buffer for writing.
* @param iter First term for searching in.
* @param end Last term for searching in.
*
* TODO: Move this method into qlc.h.
*/
void
Driver::qlcTermIteratorLookup(
ParamDecoder& driver_params,
const ParamDecoder& schema_params,
ResultEncoder& result,
Xapian::TermIterator iter,
const Xapian::TermIterator end)
{
// Flags, that signal about end of list.
const uint8_t more = 1, stop = 0;
std::set<std::string> terms;
const uint8_t encoder_type = driver_params;
switch (encoder_type)
{
case TERM_VALUE:
{
while(true)
{
const std::string& term = driver_params;
// first term is not empty
assert(!terms.empty() || !term.empty());
if (term.empty()) break;
terms.insert(term);
assert(!terms.empty());
}
break;
}
case TERM_FLOAT_VALUE:
{
for (uint32_t length = driver_params; length; length--)
{
const double& float_term = driver_params;
const std::string& term = Xapian::sortable_serialise(float_term);
terms.insert(term);
assert(!terms.empty());
}
break;
}
default:
throw BadCommandDriverError(POS, encoder_type);
}
assert(!terms.empty());
// TODO: it can be an exception
if (terms.empty())
return;
// Special case when we want to lookup only 1 element
if (terms.size() == 1)
{
std::string term = *(terms.begin());
iter.skip_to(term);
if ((iter != end) && (*iter == term))
{
// Put a flag
result << more;
ParamDecoder params = schema_params;
retrieveTerm(params, result, iter);
}
result << stop;
return;
}
for (; iter != end; iter++)
{
if (terms.find(*iter) != terms.end())
{
// Put a flag
result << more;
// Clone params
ParamDecoder params = schema_params;
retrieveTerm(params, result, iter);
}
};
result << stop;
}
void
Driver::retrieveTermValues(ResultEncoder& result, Xapian::Document& doc)
{
Xapian::TermIterator iter, end;
uint32_t size = static_cast<uint32_t>(doc.termlist_count());
iter = doc.termlist_begin();
end = doc.termlist_end();
result << size;
for (; iter != end; iter++)
{
const std::string& value = *iter;
result << value;
}
}
void
Driver::retrieveTermValuesAndPositions(ResultEncoder& result, Xapian::Document& doc)
{
Xapian::TermIterator iter, end;
uint32_t size = static_cast<uint32_t>(doc.termlist_count());
iter = doc.termlist_begin();
end = doc.termlist_end();
result << size;
for (; iter != end; iter++)
{
const std::string& value = *iter;
result << value;
// See TERM_POSITIONS
Xapian::termcount count = iter.positionlist_count();
result << static_cast<uint32_t>(count);
if (count > 0)
for (Xapian::PositionIterator
piter = iter.positionlist_begin(),
pend = iter.positionlist_end();
piter != pend;
piter++)
result << static_cast<uint32_t>(*piter);
}
}
void
Driver::retrieveSlotAndValues(ResultEncoder& result, Xapian::Document& doc)
{
Xapian::ValueIterator
iter = doc.values_begin(),
end = doc.values_end();
uint32_t size = static_cast<uint32_t>(doc.values_count());
result << size;
for (; iter != end; iter++)
{
Xapian::valueno slot_no = iter.get_valueno();
const std::string& value = *iter;
result << slot_no;
result << value;
}
}
XAPIAN_ERLANG_NS_END
| 25.42798 | 96 | 0.533104 | [
"object",
"vector"
] |
0ad2f023ab628a7408046dd3013d3d69afdc061a | 4,598 | cpp | C++ | Engine/source/platform/input/myo/myoUtil.cpp | lukaspj/MyoT3DDevelopment | 5601e90ece75cc5d335b0a662ed8addba49efb9e | [
"Unlicense"
] | null | null | null | Engine/source/platform/input/myo/myoUtil.cpp | lukaspj/MyoT3DDevelopment | 5601e90ece75cc5d335b0a662ed8addba49efb9e | [
"Unlicense"
] | null | null | null | Engine/source/platform/input/myo/myoUtil.cpp | lukaspj/MyoT3DDevelopment | 5601e90ece75cc5d335b0a662ed8addba49efb9e | [
"Unlicense"
] | null | null | null | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/input/myo/myoUtil.h"
namespace LeapMotionUtil
{
void convertPosition(const myo::Vector3<float>& inPosition, F32& x, F32& y, F32& z)
{
// Convert to Torque coordinates. The conversion is:
//
// Motion Torque
// x y z --> x -z y
x = inPosition.x(); // x = x
y = -inPosition.z(); // y = -z
z = inPosition.y(); // z = y;
}
void convertPosition(const myo::Vector3<float>& inPosition, Point3F& outPosition)
{
// Convert to Torque coordinates. The conversion is:
//
// Motion Torque
// x y z --> x -z y
outPosition.x = inPosition.x(); // x = x
outPosition.y = -inPosition.z(); // y = -z
outPosition.z = inPosition.y(); // z = y;
}
void convertOrientation(const myo::Quaternion<float>& quat, QuatF& outRotation)
{
using std::atan2f;
using std::asinf;
using std::sqrtf;
// Calculate the normalized quaternion.
float norm = sqrtf(quat.x() * quat.x() + quat.y() * quat.y() + quat.z() * quat.z() + quat.w() * quat.w());
myo::Quaternion<float> normalized(quat.x() / norm, quat.y() / norm, quat.z() / norm, quat.w() / norm);
// Calculate Euler angles (roll, pitch, and yaw) from the normalized quaternion.
float roll = atan2f(2.0f * (normalized.w() * normalized.x() + normalized.y() * normalized.z()),
1.0f - 2.0f * (normalized.x() * normalized.x() + normalized.y() * normalized.y()));
float pitch = asinf(2.0f * (normalized.w() * normalized.y() - normalized.z() * normalized.x()));
float yaw = atan2f(2.0f * (normalized.w() * normalized.z() + normalized.x() * normalized.y()),
1.0f - 2.0f * (normalized.y() * normalized.y() + normalized.z() * normalized.z()));
// Convert the floating point angles in radians to a scale from 0 to 20.
F32 x, y, z;
x = roll;
y = -yaw;
z = pitch;
outRotation.set(EulerF(roll, pitch, yaw));
}
/*
void calculateHandAxisRotation(const MatrixF& handRotation, const F32& maxHandAxisRadius, Point2F& outRotation)
{
const VectorF& controllerUp = handRotation.getUpVector();
outRotation.x = controllerUp.x;
outRotation.y = controllerUp.y;
// Limit the axis angle to that given to us
if(outRotation.len() > maxHandAxisRadius)
{
outRotation.normalize(maxHandAxisRadius);
}
// Renormalize to the range of 0..1
if(maxHandAxisRadius != 0.0f)
{
outRotation /= maxHandAxisRadius;
}
}
void convertPointableRotation(const Leap::Pointable& pointable, MatrixF& outRotation)
{
// We need to convert from Motion coordinates to
// Torque coordinates. The conversion is:
//
// Motion Torque
// a b c a b c a -c b
// d e f --> -g -h -i --> -g i -h
// g h i d e f d -f e
Leap::Vector pointableFront = -pointable.direction();
Leap::Vector pointableRight = Leap::Vector::up().cross(pointableFront);
Leap::Vector pointableUp = pointableFront.cross(pointableRight);
outRotation.setColumn(0, Point4F( pointableRight.x, -pointableRight.z, pointableRight.y, 0.0f));
outRotation.setColumn(1, Point4F( -pointableFront.x, pointableFront.z, -pointableFront.y, 0.0f));
outRotation.setColumn(2, Point4F( pointableUp.x, -pointableUp.z, pointableUp.y, 0.0f));
outRotation.setPosition(Point3F::Zero);
}*/
}
| 39.982609 | 111 | 0.638538 | [
"vector"
] |
0ad7d36a9efa813dd94802c5301c2070683cdd9a | 670 | cpp | C++ | external_libraries/vexcl/tests/logical.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | external_libraries/vexcl/tests/logical.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | external_libraries/vexcl/tests/logical.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | #define BOOST_TEST_MODULE Logical
#include <boost/test/unit_test.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/element_index.hpp>
#include <vexcl/logical.hpp>
#include "context_setup.hpp"
BOOST_AUTO_TEST_CASE(logical)
{
const size_t N = 1024;
vex::vector<int> x(ctx, N);
x = vex::element_index();
vex::any_of any_of(ctx);
vex::all_of all_of(ctx);
BOOST_CHECK( any_of(x) );
BOOST_CHECK(!any_of(0 * x) );
BOOST_CHECK( any_of(x > N/2) );
BOOST_CHECK(!any_of(x < 0) );
BOOST_CHECK(!all_of(x) );
BOOST_CHECK( all_of((x + 1) > 0) );
BOOST_CHECK(!all_of(x > N/2) );
}
BOOST_AUTO_TEST_SUITE_END()
| 23.103448 | 39 | 0.632836 | [
"vector"
] |
0adeb3dd76fd2badd1db0591dd0e4f634139902e | 1,396 | cpp | C++ | problemes/probleme0xx/probleme050.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | 6 | 2015-10-13T17:07:21.000Z | 2018-05-08T11:50:22.000Z | problemes/probleme0xx/probleme050.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | null | null | null | problemes/probleme0xx/probleme050.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | null | null | null | #include "problemes.h"
#include "premiers.h"
#include <algorithm>
#include <set>
#include <iterator>
typedef unsigned long long nombre;
typedef std::vector<nombre> vecteur;
ENREGISTRER_PROBLEME(50, "Consecutive prime sum") {
// The prime 41, can be written as the sum of six consecutive primes:
// 41 = 2 + 3 + 5 + 7 + 11 + 13
//
// This is the longest sum of consecutive primes that adds to a prime below one-hundred.
//
// The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms,
// and is equal to 953.
//
// Which prime, below one-million, can be written as the sum of the most consecutive primes?
nombre limite = 1000000;
std::set<nombre> premiers;
premiers::crible2<nombre>(limite, std::inserter(premiers, premiers.begin()));
nombre resultat = 0;
nombre longueur = 0;
for (auto it1 = premiers.begin(), en = premiers.end(); it1 != en; ++it1) {
nombre s = *it1;
nombre l = 1;
for (auto it2 = std::next(it1, 1); it2 != en; ++it2) {
s += *it2;
++l;
if (s > limite)
break;
if (premiers.find(s) != premiers.end() && l > longueur) {
longueur = l;
resultat = s;
}
}
}
return std::to_string(resultat);
}
| 31.022222 | 105 | 0.563037 | [
"vector"
] |
0ae425f0dd61ccd13a6852cc225b239c2207ab26 | 56,704 | hxx | C++ | lib/seldon/computation/interfaces/Lapack_Eigenvalues.hxx | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | 7 | 2021-01-31T23:20:07.000Z | 2021-09-09T20:54:15.000Z | lib/seldon/computation/interfaces/Lapack_Eigenvalues.hxx | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | 1 | 2021-06-07T07:52:38.000Z | 2021-08-13T20:40:55.000Z | lib/seldon/computation/interfaces/Lapack_Eigenvalues.hxx | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2012 Vivien Mallet
//
// This file is part of the linear-algebra library Seldon,
// http://seldon.sourceforge.net/.
//
// Seldon is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your option)
// any later version.
//
// Seldon is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
// more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Seldon. If not, see http://www.gnu.org/licenses/.
#ifndef SELDON_FILE_LAPACK_EIGENVALUES_HXX
/*
Functions included in this file:
xGEEV (GetEigenvalues, GetEigenvaluesEigenvectors)
xSYEV (GetEigenvalues, GetEigenvaluesEigenvectors)
xHEEV (GetEigenvalues, GetEigenvaluesEigenvectors)
xSPEV (GetEigenvalues, GetEigenvaluesEigenvectors)
xHPEV (GetEigenvalues, GetEigenvaluesEigenvectors)
xSYGV (GetEigenvalues, GetEigenvaluesEigenvectors)
xGGEV (GetEigenvalues, GetEigenvaluesEigenvectors)
xHEGV (GetEigenvalues, GetEigenvaluesEigenvectors)
xSPGV (GetEigenvalues, GetEigenvaluesEigenvectors)
xHPGV (GetEigenvalues, GetEigenvaluesEigenvectors)
xGESVD (GetSVD)
xGEQRF (GetHessenberg)
ZGEQRF + ZUNGQR + ZUNMQR + ZGGHRD (GetHessenberg)
ZGEQRF + ZUNGQR + ZUNMQR + ZGGHRD + ZHGEQZ (GetQZ)
(SolveSylvester)
*/
namespace Seldon
{
/////////////////////////////////
// STANDARD EIGENVALUE PROBLEM //
/* RowMajor */
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<float, Prop, RowMajor, Allocator1>& A,
Vector<float, VectFull, Allocator2>& wr,
Vector<float, VectFull, Allocator3>& wi,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<float, Prop, RowMajor, Allocator1>& A,
Vector<float, VectFull, Allocator2>& wr,
Vector<float, VectFull, Allocator3>& wi,
Matrix<float, General, RowMajor, Allocator4>& zr,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<float>, Prop, RowMajor, Allocator1>& A,
Vector<complex<float>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop, RowMajor, Allocator1>& A,
Vector<complex<float>, VectFull, Allocator2>& w,
Matrix<complex<float>,
General, RowMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<double, Prop, RowMajor, Allocator1>& A,
Vector<double, VectFull, Allocator2>& wr,
Vector<double, VectFull, Allocator3>& wi,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<double, Prop, RowMajor, Allocator1>& A,
Vector<double, VectFull, Allocator2>& wr,
Vector<double, VectFull, Allocator3>& wi,
Matrix<double, General, RowMajor, Allocator4>& zr,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<double>, Prop, RowMajor, Allocator1>& A,
Vector<complex<double>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop, RowMajor, Allocator1>& A,
Vector<complex<double>,
VectFull, Allocator2>& w,
Matrix<complex<double>,
General, RowMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
/* ColMajor */
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<float, Prop, ColMajor, Allocator1>& A,
Vector<float, VectFull, Allocator2>& wr,
Vector<float, VectFull, Allocator3>& wi,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<float, Prop, ColMajor, Allocator1>& A,
Vector<float, VectFull, Allocator2>& wr,
Vector<float, VectFull, Allocator3>& wi,
Matrix<float, General, ColMajor, Allocator4>&zr,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<float>, Prop, ColMajor, Allocator1>& A,
Vector<complex<float>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop, ColMajor, Allocator1>& A,
Vector<complex<float>,
VectFull, Allocator2>& w,
Matrix<complex<float>,
General, ColMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<double, Prop, ColMajor, Allocator1>& A,
Vector<double, VectFull, Allocator2>& wr,
Vector<double, VectFull, Allocator3>& wi,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<double, Prop, ColMajor, Allocator1>& A,
Vector<double, VectFull, Allocator2>& wr,
Vector<double, VectFull, Allocator3>& wi,
Matrix<double, General, ColMajor, Allocator4>&zr,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<double>, Prop, ColMajor, Allocator1>& A,
Vector<complex<double>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop, ColMajor, Allocator1>& A,
Vector<complex<double>,
VectFull, Allocator2>& w,
Matrix<complex<double>,
General, ColMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
/* RowSym */
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<float, Prop, RowSym, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<float, Prop, RowSym, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
Matrix<float, General, RowMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<float>, Prop, RowSym, Allocator1>& A,
Vector<complex<float>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop, RowSym, Allocator1>& A,
Vector<complex<float>,
VectFull, Allocator2>& w,
Matrix<complex<float>,
General, RowMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<double, Prop, RowSym, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<double, Prop, RowSym, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
Matrix<double, General, RowMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<double>, Prop, RowSym, Allocator1>& A,
Vector<complex<double>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop, RowSym, Allocator1>& A,
Vector<complex<double>,
VectFull, Allocator2>& w,
Matrix<complex<double>,
General, RowMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
/* ColSym */
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<float, Prop, ColSym, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<float, Prop, ColSym, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
Matrix<float, General, ColMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<float>, Prop, ColSym, Allocator1>& A,
Vector<complex<float>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop, ColSym, Allocator1>& A,
Vector<complex<float>,
VectFull, Allocator2>& w,
Matrix<complex<float>,
General, ColMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<double, Prop, ColSym, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<double, Prop, ColSym, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
Matrix<double, General, ColMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<double>, Prop, ColSym, Allocator1>& A,
Vector<complex<double>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop, ColSym, Allocator1>& A,
Vector<complex<double>,
VectFull, Allocator2>& w,
Matrix<complex<double>,
General, ColMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
/* RowHerm */
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<float>, Prop, RowHerm, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop, RowHerm, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
Matrix<complex<float>,
General, RowMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<double>, Prop, RowHerm, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop, RowHerm, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
Matrix<complex<double>,
General, RowMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
/* ColHerm */
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<float>, Prop, ColHerm, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop, ColHerm, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
Matrix<complex<float>,
General, ColMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<double>, Prop, ColHerm, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop, ColHerm, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
Matrix<complex<double>,
General, ColMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
/* RowSymPacked */
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<float, Prop, RowSymPacked, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<float, Prop,RowSymPacked, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
Matrix<float, General, RowMajor, Allocator3>&z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<float>, Prop, RowSymPacked, Allocator1>& A,
Vector<complex<float>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<float>, Prop,
RowSymPacked, Allocator1>& A,
Vector<complex<float>,VectFull, Allocator2>& w,
Matrix<complex<float>,
General, RowMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<double, Prop, RowSymPacked, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<double,Prop,RowSymPacked, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
Matrix<double, General, RowMajor, Allocator3>&z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<double>, Prop, RowSymPacked, Allocator1>& A,
Vector<complex<double>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<double>, Prop,
RowSymPacked, Allocator1>& A,
Vector<complex<double>,VectFull, Allocator2>& w,
Matrix<complex<double>,
General, RowMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
/* ColSymPacked */
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<float, Prop, ColSymPacked, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<float, Prop,ColSymPacked, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
Matrix<float, General, ColMajor, Allocator3>&z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<float>,
Prop, ColSymPacked, Allocator1>& A,
Vector<complex<float>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop, ColSymPacked, Allocator1>& A,
Vector<complex<float>, VectFull, Allocator2>& w,
Matrix<complex<float>,
General, ColMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<double, Prop, ColSymPacked, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<double, Prop, ColSymPacked, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
Matrix<double, General, ColMajor, Allocator3>&z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<double>,
Prop, ColSymPacked, Allocator1>& A,
Vector<complex<double>, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop, ColSymPacked, Allocator1>& A,
Vector<complex<double>, VectFull, Allocator2>& w,
Matrix<complex<double>,
General, ColMajor, Allocator3>& z,
LapackInfo& info = lapack_info);
/* RowHermPacked */
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<float>,
Prop, RowHermPacked, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop, RowHermPacked, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
Matrix<complex<float>,
General, RowMajor, Allocator3>&z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<double>,
Prop, RowHermPacked, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop, RowHermPacked, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
Matrix<complex<double>,
General, RowMajor, Allocator3>&z,
LapackInfo& info = lapack_info);
/* ColHermPacked */
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<float>,
Prop, ColHermPacked, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop, ColHermPacked, Allocator1>& A,
Vector<float, VectFull, Allocator2>& w,
Matrix<complex<float>,
General, ColMajor, Allocator3>&z,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2>
void GetEigenvalues(Matrix<complex<double>,
Prop, ColHermPacked, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
LapackInfo& info = lapack_info);
template<class Prop, class Allocator1, class Allocator2, class Allocator3>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop, ColHermPacked, Allocator1>& A,
Vector<double, VectFull, Allocator2>& w,
Matrix<complex<double>,
General, ColMajor, Allocator3>&z,
LapackInfo& info = lapack_info);
// STANDARD EIGENVALUE PROBLEM //
/////////////////////////////////
////////////////////////////////////
// GENERALIZED EIGENVALUE PROBLEM //
/* RowSym */
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<float, Prop1, RowSym, Allocator1>& A,
Matrix<float, Prop2, RowSym, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<float, Prop1, RowSym, Allocator1>& A,
Matrix<float, Prop2, RowSym, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
Matrix<float, General, RowMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<complex<float>, Prop1, RowSym, Allocator1>& A,
Matrix<complex<float>, Prop2, RowSym, Allocator2>& B,
Vector<complex<float>, VectFull, Allocator4>& alpha,
Vector<complex<float>, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Allocator1,
class Allocator2, class Allocator4,
class Allocator5, class Allocator6>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop1, RowSym, Allocator1>& A,
Matrix<complex<float>,
Prop2, RowSym, Allocator2>& B,
Vector<complex<float>,
VectFull, Allocator4>& alpha,
Vector<complex<float>,
VectFull, Allocator5>& beta,
Matrix<complex<float>,
Prop3, RowMajor, Allocator6>& V,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<double, Prop1, RowSym, Allocator1>& A,
Matrix<double, Prop2, RowSym, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<double, Prop1, RowSym, Allocator1>& A,
Matrix<double, Prop2, RowSym, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
Matrix<double, General, RowMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<complex<double>, Prop1, RowSym, Allocator1>& A,
Matrix<complex<double>, Prop2, RowSym, Allocator2>& B,
Vector<complex<double>, VectFull, Allocator4>& alpha,
Vector<complex<double>, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Allocator1,
class Allocator2, class Allocator4,
class Allocator5, class Allocator6>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop1, RowSym, Allocator1>& A,
Matrix<complex<double>,
Prop2, RowSym, Allocator2>& B,
Vector<complex<double>,
VectFull, Allocator4>& alpha,
Vector<complex<double>,
VectFull, Allocator5>& beta,
Matrix<complex<double>,
Prop3, RowMajor, Allocator6>& V,
LapackInfo& info = lapack_info);
/* ColSym */
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<float, Prop1, ColSym, Allocator1>& A,
Matrix<float, Prop2, ColSym, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<float, Prop1, ColSym, Allocator1>& A,
Matrix<float, Prop2, ColSym, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
Matrix<float, General, ColMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<complex<float>, Prop1, ColSym, Allocator1>& A,
Matrix<complex<float>, Prop2, ColSym, Allocator2>& B,
Vector<complex<float>, VectFull, Allocator4>& alpha,
Vector<complex<float>, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Alloc1,
class Alloc2, class Alloc4, class Alloc5, class Alloc6>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop1, ColSym, Alloc1>& A,
Matrix<complex<float>,
Prop2, ColSym, Alloc2>& B,
Vector<complex<float>, VectFull, Alloc4>& alpha,
Vector<complex<float>, VectFull, Alloc5>& beta,
Matrix<complex<float>,
Prop3, ColMajor, Alloc6>& V,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<double, Prop1, ColSym, Allocator1>& A,
Matrix<double, Prop2, ColSym, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<double, Prop1, ColSym, Allocator1>& A,
Matrix<double, Prop2, ColSym, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
Matrix<double, General, ColMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<complex<double>, Prop1, ColSym, Allocator1>& A,
Matrix<complex<double>, Prop2, ColSym, Allocator2>& B,
Vector<complex<double>, VectFull, Allocator4>& alpha,
Vector<complex<double>, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Alloc1,
class Alloc2, class Alloc4, class Alloc5, class Alloc6>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop1, ColSym, Alloc1>& A,
Matrix<complex<double>,
Prop2, ColSym, Alloc2>& B,
Vector<complex<double>, VectFull, Alloc4>& alpha,
Vector<complex<double>, VectFull, Alloc5>& beta,
Matrix<complex<double>,
Prop3, ColMajor, Alloc6>& V,
LapackInfo& info = lapack_info);
/* RowHerm */
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<complex<float>, Prop1, RowHerm, Allocator1>& A,
Matrix<complex<float>, Prop2, RowHerm, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop1, RowHerm, Allocator1>& A,
Matrix<complex<float>,
Prop2, RowHerm, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
Matrix<complex<float>,
General, RowMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<complex<double>, Prop1, RowHerm, Allocator1>& A,
Matrix<complex<double>, Prop2, RowHerm, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop1, RowHerm, Allocator1>& A,
Matrix<complex<double>,
Prop2, RowHerm, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
Matrix<complex<double>,
General, RowMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
/* ColHerm */
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<complex<float>, Prop1, ColHerm, Allocator1>& A,
Matrix<complex<float>, Prop2, ColHerm, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop1, ColHerm, Allocator1>& A,
Matrix<complex<float>,
Prop2, ColHerm, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
Matrix<complex<float>,
General, ColMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<complex<double>, Prop1, ColHerm, Allocator1>& A,
Matrix<complex<double>, Prop2, ColHerm, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop1, ColHerm, Allocator1>& A,
Matrix<complex<double>,
Prop2, ColHerm, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
Matrix<complex<double>,
General, ColMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
/* RowSymPacked */
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<float, Prop1, RowSymPacked, Allocator1>& A,
Matrix<float, Prop2, RowSymPacked, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<float,
Prop1, RowSymPacked, Allocator1>& A,
Matrix<float,
Prop2, RowSymPacked, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
Matrix<float,
General, RowMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvalues(Matrix<complex<float>,
Prop1, RowSymPacked, Allocator1>& A,
Matrix<complex<float>,
Prop2, RowSymPacked, Allocator2>& B,
Vector<complex<float>, VectFull, Allocator3>& alpha,
Vector<complex<float>, VectFull, Allocator4>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4, class Allocator5>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop1, RowSymPacked, Allocator1>& A,
Matrix<complex<float>,
Prop2, RowSymPacked, Allocator2>& B,
Vector<complex<float>,
VectFull, Allocator3>& alpha,
Vector<complex<float>,
VectFull, Allocator4>& beta,
Matrix<complex<float>,
General, RowMajor, Allocator5>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<double, Prop1, RowSymPacked, Allocator1>& A,
Matrix<double, Prop2, RowSymPacked, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<double,
Prop1, RowSymPacked, Allocator1>& A,
Matrix<double,
Prop2, RowSymPacked, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
Matrix<double,
General, RowMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvalues(Matrix<complex<double>,
Prop1, RowSymPacked, Allocator1>& A,
Matrix<complex<double>,
Prop2, RowSymPacked, Allocator2>& B,
Vector<complex<double>, VectFull, Allocator3>& alpha,
Vector<complex<double>, VectFull, Allocator4>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4, class Allocator5>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop1, RowSymPacked, Allocator1>& A,
Matrix<complex<double>,
Prop2, RowSymPacked, Allocator2>& B,
Vector<complex<double>,
VectFull, Allocator3>& alpha,
Vector<complex<double>,
VectFull, Allocator4>& beta,
Matrix<complex<double>,
General, RowMajor, Allocator5>& z,
LapackInfo& info = lapack_info);
/* ColSymPacked */
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<float, Prop1, ColSymPacked, Allocator1>& A,
Matrix<float, Prop2, ColSymPacked, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<float,
Prop1, ColSymPacked, Allocator1>& A,
Matrix<float,
Prop2, ColSymPacked, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
Matrix<float,
General, ColMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvalues(Matrix<complex<float>,
Prop1, ColSymPacked, Allocator1>& A,
Matrix<complex<float>,
Prop2, ColSymPacked, Allocator2>& B,
Vector<complex<float>, VectFull, Allocator3>& alpha,
Vector<complex<float>, VectFull, Allocator4>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4, class Allocator5>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop1, ColSymPacked, Allocator1>& A,
Matrix<complex<float>,
Prop2, ColSymPacked, Allocator2>& B,
Vector<complex<float>,
VectFull, Allocator3>& alpha,
Vector<complex<float>,
VectFull, Allocator4>& beta,
Matrix<complex<float>,
General, ColMajor, Allocator5>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<double, Prop1, ColSymPacked, Allocator1>& A,
Matrix<double, Prop2, ColSymPacked, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<double,
Prop1, ColSymPacked, Allocator1>& A,
Matrix<double,
Prop2, ColSymPacked, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
Matrix<double,
General, ColMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvalues(Matrix<complex<double>,
Prop1, ColSymPacked, Allocator1>& A,
Matrix<complex<double>,
Prop2, ColSymPacked, Allocator2>& B,
Vector<complex<double>, VectFull, Allocator3>& alpha,
Vector<complex<double>, VectFull, Allocator4>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4, class Allocator5>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop1, ColSymPacked, Allocator1>& A,
Matrix<complex<double>,
Prop2, ColSymPacked, Allocator2>& B,
Vector<complex<double>,
VectFull, Allocator3>& alpha,
Vector<complex<double>,
VectFull, Allocator4>& beta,
Matrix<complex<double>,
General, ColMajor, Allocator5>& z,
LapackInfo& info = lapack_info);
/* RowHermPacked */
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<complex<float>,
Prop1, RowHermPacked, Allocator1>& A,
Matrix<complex<float>,
Prop2, RowHermPacked, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop1, RowHermPacked, Allocator1>& A,
Matrix<complex<float>,
Prop2, RowHermPacked, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
Matrix<complex<float>,
General, RowMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<complex<double>,
Prop1, RowHermPacked, Allocator1>& A,
Matrix<complex<double>,
Prop2, RowHermPacked, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop1, RowHermPacked, Allocator1>& A,
Matrix<complex<double>,
Prop2, RowHermPacked, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
Matrix<complex<double>,
General, RowMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
/* ColHermPacked */
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<complex<float>,
Prop1, ColHermPacked, Allocator1>& A,
Matrix<complex<float>,
Prop2, ColHermPacked, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop1, ColHermPacked, Allocator1>& A,
Matrix<complex<float>,
Prop2, ColHermPacked, Allocator2>& B,
Vector<float, VectFull, Allocator3>& w,
Matrix<complex<float>,
General, ColMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3>
void GetEigenvalues(Matrix<complex<double>,
Prop1, ColHermPacked, Allocator1>& A,
Matrix<complex<double>,
Prop2, ColHermPacked, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop1, ColHermPacked, Allocator1>& A,
Matrix<complex<double>,
Prop2, ColHermPacked, Allocator2>& B,
Vector<double, VectFull, Allocator3>& w,
Matrix<complex<double>,
General, ColMajor, Allocator4>& z,
LapackInfo& info = lapack_info);
/* RowMajor */
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3,
class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<float, Prop1, RowMajor, Allocator1>& A,
Matrix<float, Prop2, RowMajor, Allocator2>& B,
Vector<float, VectFull, Allocator3>& alpha_real,
Vector<float, VectFull, Allocator4>& alpha_imag,
Vector<float, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Allocator1,
class Allocator2, class Allocator3, class Allocator4,
class Allocator5, class Allocator6>
void GetEigenvaluesEigenvectors(Matrix<float, Prop1, RowMajor, Allocator1>& A,
Matrix<float, Prop2, RowMajor, Allocator2>& B,
Vector<float, VectFull, Allocator3>& alpha_real,
Vector<float, VectFull, Allocator4>& alpha_imag,
Vector<float, VectFull, Allocator5>& beta,
Matrix<float, Prop3, RowMajor, Allocator6>& V,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<complex<float>, Prop1, RowMajor, Allocator1>& A,
Matrix<complex<float>, Prop2, RowMajor, Allocator2>& B,
Vector<complex<float>, VectFull, Allocator4>& alpha,
Vector<complex<float>, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Allocator1,
class Allocator2, class Allocator4,
class Allocator5, class Allocator6>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop1, RowMajor, Allocator1>& A,
Matrix<complex<float>,
Prop2, RowMajor, Allocator2>& B,
Vector<complex<float>,
VectFull, Allocator4>& alpha,
Vector<complex<float>,
VectFull, Allocator5>& beta,
Matrix<complex<float>,
Prop3, RowMajor, Allocator6>& V,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3,
class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<double, Prop1, RowMajor, Allocator1>& A,
Matrix<double, Prop2, RowMajor, Allocator2>& B,
Vector<double, VectFull, Allocator3>& alpha_real,
Vector<double, VectFull, Allocator4>& alpha_imag,
Vector<double, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Allocator1,
class Allocator2, class Allocator3, class Allocator4,
class Allocator5, class Allocator6>
void GetEigenvaluesEigenvectors(Matrix<double, Prop1, RowMajor, Allocator1>& A,
Matrix<double, Prop2, RowMajor, Allocator2>& B,
Vector<double, VectFull, Allocator3>& alpha_real,
Vector<double, VectFull, Allocator4>& alpha_imag,
Vector<double, VectFull, Allocator5>& beta,
Matrix<double, Prop3, RowMajor, Allocator6>& V,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<complex<double>, Prop1, RowMajor, Allocator1>& A,
Matrix<complex<double>, Prop2, RowMajor, Allocator2>& B,
Vector<complex<double>, VectFull, Allocator4>& alpha,
Vector<complex<double>, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Allocator1,
class Allocator2, class Allocator4,
class Allocator5, class Allocator6>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop1, RowMajor, Allocator1>& A,
Matrix<complex<double>,
Prop2, RowMajor, Allocator2>& B,
Vector<complex<double>,
VectFull, Allocator4>& alpha,
Vector<complex<double>,
VectFull, Allocator5>& beta,
Matrix<complex<double>,
Prop3, RowMajor, Allocator6>& V,
LapackInfo& info = lapack_info);
/* ColMajor */
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3,
class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<float, Prop1, ColMajor, Allocator1>& A,
Matrix<float, Prop2, ColMajor, Allocator2>& B,
Vector<float, VectFull, Allocator3>& alpha_real,
Vector<float, VectFull, Allocator4>& alpha_imag,
Vector<float, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Allocator1,
class Allocator2, class Allocator3, class Allocator4,
class Allocator5, class Allocator6>
void GetEigenvaluesEigenvectors(Matrix<float, Prop1, ColMajor, Allocator1>& A,
Matrix<float, Prop2, ColMajor, Allocator2>& B,
Vector<float,
VectFull, Allocator3>& alpha_real,
Vector<float,
VectFull, Allocator4>& alpha_imag,
Vector<float, VectFull, Allocator5>& beta,
Matrix<float, Prop3, ColMajor, Allocator6>& V,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<complex<float>, Prop1, ColMajor, Allocator1>& A,
Matrix<complex<float>, Prop2, ColMajor, Allocator2>& B,
Vector<complex<float>, VectFull, Allocator4>& alpha,
Vector<complex<float>, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Allocator1,
class Allocator2, class Allocator4,
class Allocator5, class Allocator6>
void GetEigenvaluesEigenvectors(Matrix<complex<float>,
Prop1, ColMajor, Allocator1>& A,
Matrix<complex<float>,
Prop2, ColMajor, Allocator2>& B,
Vector<complex<float>,
VectFull, Allocator4>& alpha,
Vector<complex<float>,
VectFull, Allocator5>& beta,
Matrix<complex<float>,
Prop3, ColMajor, Allocator6>& V,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator3,
class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<double, Prop1, ColMajor, Allocator1>& A,
Matrix<double, Prop2, ColMajor, Allocator2>& B,
Vector<double, VectFull, Allocator3>& alpha_real,
Vector<double, VectFull, Allocator4>& alpha_imag,
Vector<double, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Allocator1,
class Allocator2, class Allocator3, class Allocator4,
class Allocator5, class Allocator6>
void GetEigenvaluesEigenvectors(Matrix<double, Prop1, ColMajor, Allocator1>& A,
Matrix<double, Prop2, ColMajor, Allocator2>& B,
Vector<double,
VectFull, Allocator3>& alpha_real,
Vector<double,
VectFull, Allocator4>& alpha_imag,
Vector<double, VectFull, Allocator5>& beta,
Matrix<double, Prop3, ColMajor, Allocator6>& V,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Allocator1,
class Allocator2, class Allocator4, class Allocator5>
void GetEigenvalues(Matrix<complex<double>, Prop1, ColMajor, Allocator1>& A,
Matrix<complex<double>, Prop2, ColMajor, Allocator2>& B,
Vector<complex<double>, VectFull, Allocator4>& alpha,
Vector<complex<double>, VectFull, Allocator5>& beta,
LapackInfo& info = lapack_info);
template<class Prop1, class Prop2, class Prop3, class Allocator1,
class Allocator2, class Allocator4,
class Allocator5, class Allocator6>
void GetEigenvaluesEigenvectors(Matrix<complex<double>,
Prop1, ColMajor, Allocator1>& A,
Matrix<complex<double>,
Prop2, ColMajor, Allocator2>& B,
Vector<complex<double>,
VectFull, Allocator4>& alpha,
Vector<complex<double>,
VectFull, Allocator5>& beta,
Matrix<complex<double>,
Prop3, ColMajor, Allocator6>& V,
LapackInfo& info = lapack_info);
// GENERALIZED EIGENVALUE PROBLEM //
////////////////////////////////////
//////////////////////////////////
// SINGULAR VALUE DECOMPOSITION //
/* RowMajor */
template<class Prop1, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetSVD(Matrix<float, Prop1, RowMajor, Allocator1>& A,
Vector<float, VectFull, Allocator4>& lambda,
Matrix<float, General, RowMajor, Allocator2>& u,
Matrix<float, General, RowMajor, Allocator3>& v,
LapackInfo& info = lapack_info);
template<class Prop1, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetSVD(Matrix<complex<float>, Prop1, RowMajor, Allocator1>& A,
Vector<float, VectFull, Allocator4>& lambda,
Matrix<complex<float>, General, RowMajor, Allocator2>& u,
Matrix<complex<float>, General, RowMajor, Allocator3>& v,
LapackInfo& info = lapack_info);
template<class Prop1, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetSVD(Matrix<double, Prop1, RowMajor, Allocator1>& A,
Vector<double, VectFull, Allocator4>& lambda,
Matrix<double, General, RowMajor, Allocator2>& u,
Matrix<double, General, RowMajor, Allocator3>& v,
LapackInfo& info = lapack_info);
template<class Prop1, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetSVD(Matrix<complex<double>, Prop1, RowMajor, Allocator1>& A,
Vector<double, VectFull, Allocator4>& lambda,
Matrix<complex<double>, General, RowMajor, Allocator2>& u,
Matrix<complex<double>, General, RowMajor, Allocator3>& v,
LapackInfo& info = lapack_info);
/* ColMajor */
template<class Prop1, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetSVD(Matrix<float, Prop1, ColMajor, Allocator1>& A,
Vector<float, VectFull, Allocator4>& lambda,
Matrix<float, General, ColMajor, Allocator2>& u,
Matrix<float, General, ColMajor, Allocator3>& v,
LapackInfo& info = lapack_info);
template<class Prop1, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetSVD(Matrix<complex<float>, Prop1, ColMajor, Allocator1>& A,
Vector<float, VectFull, Allocator4>& lambda,
Matrix<complex<float>, General, ColMajor, Allocator2>& u,
Matrix<complex<float>, General, ColMajor, Allocator3>& v,
LapackInfo& info = lapack_info);
template<class Prop1, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetSVD(Matrix<double, Prop1, ColMajor, Allocator1>& A,
Vector<double, VectFull, Allocator4>& lambda,
Matrix<double, General, ColMajor, Allocator2>& u,
Matrix<double, General, ColMajor, Allocator3>& v,
LapackInfo& info = lapack_info);
template<class Prop1, class Allocator1, class Allocator2,
class Allocator3, class Allocator4>
void GetSVD(Matrix<complex<double>, Prop1, ColMajor, Allocator1>& A,
Vector<double, VectFull, Allocator4>& sigma,
Matrix<complex<double>, General, ColMajor, Allocator2>& u,
Matrix<complex<double>, General, ColMajor, Allocator3>& v,
LapackInfo& info = lapack_info);
// pseudo inverse
template<class T, class Prop, class Storage, class Allocator>
void GetPseudoInverse(Matrix<T, Prop, Storage, Allocator>& A,
const T& epsilon, LapackInfo& info = lapack_info);
// SINGULAR VALUE DECOMPOSITION //
//////////////////////////////////
///////////////////////////////////
// RESOLUTION SYLVESTER EQUATION //
template<class T, class Prop, class Storage, class Allocator>
void GetPseudoInverse(Matrix<complex<T>, Prop, Storage, Allocator>& A,
const T& epsilon, LapackInfo& info = lapack_info);
template<class Alloc>
void GetHessenberg(Matrix<complex<double>, General, ColMajor, Alloc>& A,
Matrix<complex<double>, General, ColMajor, Alloc>& Q,
LapackInfo& info = lapack_info);
template<class Alloc>
void GetHessenberg(Matrix<complex<double>, General, ColMajor, Alloc>& A,
Matrix<complex<double>, General, ColMajor, Alloc>& B,
Matrix<complex<double>, General, ColMajor, Alloc>& Q,
Matrix<complex<double>, General, ColMajor, Alloc>& Z,
LapackInfo& info = lapack_info);
template<class Alloc>
void GetQZ(Matrix<complex<double>, General, ColMajor, Alloc>& A,
Matrix<complex<double>, General, ColMajor, Alloc>& B,
Matrix<complex<double>, General, ColMajor, Alloc>& Q,
Matrix<complex<double>, General, ColMajor, Alloc>& Z,
LapackInfo& info = lapack_info);
template<class Alloc>
void GetHessenberg(Matrix<complex<double>, General, RowMajor, Alloc>& A,
Matrix<complex<double>, General, RowMajor, Alloc>& Q,
LapackInfo& info = lapack_info);
template<class Alloc>
void GetHessenberg(Matrix<complex<double>, General, RowMajor, Alloc>& A,
Matrix<complex<double>, General, RowMajor, Alloc>& B,
Matrix<complex<double>, General, RowMajor, Alloc>& Q,
Matrix<complex<double>, General, RowMajor, Alloc>& Z,
LapackInfo& info = lapack_info);
template<class Alloc>
void GetQZ(Matrix<complex<double>, General, RowMajor, Alloc>& A,
Matrix<complex<double>, General, RowMajor, Alloc>& B,
Matrix<complex<double>, General, RowMajor, Alloc>& Q,
Matrix<complex<double>, General, RowMajor, Alloc>& Z,
LapackInfo& info = lapack_info);
template<class T, class Prop, class Storage, class Allocator, class Vector1>
void SolveHessenberg(Matrix<T, Prop, Storage, Allocator>& A, Vector1& B);
template<class T, class Prop, class Storage, class Allocator, class Vector1>
void SolveHessenbergTwo(Matrix<T, Prop, Storage, Allocator>& A, Vector1& B);
template<class Prop, class Storage, class Allocator>
void SolveSylvester(Matrix<complex<double>, Prop, Storage, Allocator>& A,
Matrix<complex<double>, Prop, Storage, Allocator>& B,
Matrix<complex<double>, Prop, Storage, Allocator>& C,
Matrix<complex<double>, Prop, Storage, Allocator>& D,
Matrix<complex<double>, Prop, Storage, Allocator>& E);
template<class Alloc>
void GetHessenberg(Matrix<double, General, ColMajor, Alloc>& A,
Matrix<double, General, ColMajor, Alloc>& Q,
LapackInfo& info = lapack_info);
template<class Alloc>
void GetHessenberg(Matrix<double, General, ColMajor, Alloc>& A,
Matrix<double, General, ColMajor, Alloc>& B,
Matrix<double, General, ColMajor, Alloc>& Q,
Matrix<double, General, ColMajor, Alloc>& Z,
LapackInfo& info = lapack_info);
template<class Alloc>
void GetQZ(Matrix<double, General, ColMajor, Alloc>& A,
Matrix<double, General, ColMajor, Alloc>& B,
Matrix<double, General, ColMajor, Alloc>& Q,
Matrix<double, General, ColMajor, Alloc>& Z,
LapackInfo& info = lapack_info);
template<class Alloc>
void GetHessenberg(Matrix<double, General, RowMajor, Alloc>& A,
Matrix<double, General, RowMajor, Alloc>& Q,
LapackInfo& info = lapack_info);
template<class Alloc>
void GetHessenberg(Matrix<double, General, RowMajor, Alloc>& A,
Matrix<double, General, RowMajor, Alloc>& B,
Matrix<double, General, RowMajor, Alloc>& Q,
Matrix<double, General, RowMajor, Alloc>& Z,
LapackInfo& info = lapack_info);
template<class Alloc>
void GetQZ(Matrix<double, General, RowMajor, Alloc>& A,
Matrix<double, General, RowMajor, Alloc>& B,
Matrix<double, General, RowMajor, Alloc>& Q,
Matrix<double, General, RowMajor>& Z,
LapackInfo& info = lapack_info);
template<class Prop, class Storage, class Allocator>
void SolveSylvester(Matrix<double, Prop, Storage, Allocator>& A,
Matrix<double, Prop, Storage, Allocator>& B,
Matrix<double, Prop, Storage, Allocator>& C,
Matrix<double, Prop, Storage, Allocator>& D,
Matrix<double, Prop, Storage, Allocator>& E);
// RESOLUTION SYLVESTER EQUATION //
///////////////////////////////////
} // end namespace
#define SELDON_FILE_LAPACK_EIGENVALUES_HXX
#endif
| 37.477859 | 84 | 0.694007 | [
"vector"
] |
0ae64bf9a4dc99b9b2107c22755078e6a4e670be | 5,738 | cpp | C++ | gui.shared/translator_base.cpp | Qt-Widgets/im-desktop-imported | 85fed419229597bc10de59de268f5d898f853405 | [
"Apache-2.0"
] | 524 | 2016-03-16T10:17:28.000Z | 2019-12-29T02:58:56.000Z | gui.shared/translator_base.cpp | Qt-Widgets/im-desktop-imported-widgets-collection | 85fed419229597bc10de59de268f5d898f853405 | [
"Apache-2.0"
] | 68 | 2016-03-16T16:23:17.000Z | 2019-09-20T22:37:28.000Z | gui.shared/translator_base.cpp | Qt-Widgets/im-desktop-imported-widgets-collection | 85fed419229597bc10de59de268f5d898f853405 | [
"Apache-2.0"
] | 142 | 2016-03-16T10:25:03.000Z | 2019-12-26T14:08:47.000Z | #include "stdafx.h"
#include "translator_base.h"
namespace translate
{
void translator_base::init()
{
installTranslator(getLang());
}
QString translator_base::formatDayOfWeek(const QDate& _date) const
{
switch (_date.dayOfWeek())
{
case Qt::Monday:
return QT_TRANSLATE_NOOP("date", "on Monday");
case Qt::Tuesday:
return QT_TRANSLATE_NOOP("date", "on Tuesday");
case Qt::Wednesday:
return QT_TRANSLATE_NOOP("date", "on Wednesday");
case Qt::Thursday:
return QT_TRANSLATE_NOOP("date", "on Thursday");
case Qt::Friday:
return QT_TRANSLATE_NOOP("date", "on Friday");
case Qt::Saturday:
return QT_TRANSLATE_NOOP("date", "on Saturday");
case Qt::Sunday:
return QT_TRANSLATE_NOOP("date", "on Sunday");
default:
return QT_TRANSLATE_NOOP("date", "recently");
}
}
QString translator_base::formatDate(const QDate& target, bool currentYear) const
{
const QString format = currentYear ? getCurrentYearDateFormat() : getOtherYearsDateFormat();
return QLocale().toString(target, format);
}
QString translator_base::getNumberString(int number, const QString& one, const QString& two, const QString& five, const QString& twentyOne) const
{
if (number == 1)
return one;
QString result;
int strCase = number % 10;
if (strCase == 1 && number % 100 != 11)
{
result = twentyOne;
}
else if (strCase > 4 || strCase == 0 || (number % 100 > 10 && number % 100 < 20))
{
result = five;
}
else
{
result = two;
}
return result;
}
QString translator_base::getCurrentYearDateFormat() const
{
const QString lang = getLang();
if (lang == ql1s("ru"))
return qsl("d MMM");
else if (lang == ql1s("de"))
return qsl("d. MMM");
else if (lang == ql1s("pt"))
return qsl("d 'de' MMMM");
else if (lang == ql1s("uk"))
return qsl("d MMM");
else if (lang == ql1s("cs"))
return qsl("d. MMM");
else if (lang == ql1s("fr"))
return qsl("Le d MMM");
else if (lang == ql1s("zh"))
return ql1s("MMMd'") % QT_TRANSLATE_NOOP("date", "day") % ql1c('\'');
else if (lang == ql1s("es"))
return qsl("d 'de' MMM");
else if (lang == ql1s("tr"))
return qsl("d MMM");
else if (lang == ql1s("vi"))
return ql1c('\'') % QT_TRANSLATE_NOOP("date", "day") % ql1s("' d MMM");
return qsl("MMM d");
}
QString translator_base::getOtherYearsDateFormat() const
{
const QString lang = getLang();
if (lang == ql1s("ru"))
return qsl("d MMM yyyy");
else if (lang == ql1s("de"))
return qsl("d. MMM yyyy");
else if (lang == ql1s("pt"))
return qsl("d 'de' MMMM 'de' yyyy");
else if (lang == ql1s("uk"))
return qsl("d MMM yyyy");
else if (lang == ql1s("cs"))
return qsl("d. MMM yyyy");
else if (lang == ql1s("fr"))
return qsl("Le d MMM yyyy");
else if (lang == ql1s("zh"))
return ql1s("yyyy'") % QT_TRANSLATE_NOOP("date", "year") % ql1s("'MMMd'") % QT_TRANSLATE_NOOP("date", "day") % ql1c('\'');
else if (lang == ql1s("es"))
return qsl("d 'de' MMM 'de' yyyy");
else if (lang == ql1s("tr"))
return qsl("d MMM yyyy");
else if (lang == ql1s("vi"))
return ql1c('\'') % QT_TRANSLATE_NOOP("date", "day") % ql1s("' d MMM '") % QT_TRANSLATE_NOOP("date", "year") % ql1s("' yyyy");
return qsl("MMM d, yyyy");
}
void translator_base::installTranslator(const QString& _lang)
{
QLocale::setDefault(QLocale(_lang));
static QTranslator translator;
translator.load(_lang, qsl(":/translations"));
QApplication::installTranslator(&translator);
}
const std::vector<QString>& translator_base::getLanguages() const
{
static const std::vector<QString> clist =
{
qsl("ru"),
qsl("en"),
qsl("uk"),
qsl("de"),
qsl("pt"),
qsl("cs"),
qsl("fr"),
qsl("zh"),
qsl("tr"),
qsl("vi"),
qsl("es")
};
return clist;
}
static QString getLocalLang()
{
if (platform::is_apple())
{
const auto uiLangs = QLocale().uiLanguages();
if (!uiLangs.isEmpty())
{
const auto& first = uiLangs.first();
const auto idx = first.indexOf(ql1c('-'));
if (idx == -1)
return first;
return first.left(idx);
}
else
{
return QString();
}
}
else
{
return QLocale::system().name().left(2);
}
}
QString translator_base::getLang() const
{
QString lang;
QString localLang = getLocalLang();
if (localLang.isEmpty())
lang = qsl("en");
else
lang = std::move(localLang);
const auto& langs = getLanguages();
if (std::all_of(langs.begin(), langs.end(), [&lang](const QString& _l) { return _l != lang; }))
lang = qsl("en");
return lang;
}
QLocale translator_base::getLocale() const
{
return QLocale(getLang());
}
}
| 29.73057 | 149 | 0.497386 | [
"vector"
] |
0aebc605f8ec4666a37a6b16bf52b28c62d577f7 | 7,906 | cpp | C++ | src/xmol/io/pdb/PDBReader.cpp | sizmailov/pyxmolpp2 | 9395ba1b1ddc957e0b33dc6decccdb711e720764 | [
"MIT"
] | 4 | 2020-06-24T11:07:57.000Z | 2022-01-15T23:00:30.000Z | src/xmol/io/pdb/PDBReader.cpp | sizmailov/pyxmolpp2 | 9395ba1b1ddc957e0b33dc6decccdb711e720764 | [
"MIT"
] | 84 | 2018-04-22T12:29:31.000Z | 2020-06-17T15:03:37.000Z | src/xmol/io/pdb/PDBReader.cpp | sizmailov/pyxmolpp2 | 9395ba1b1ddc957e0b33dc6decccdb711e720764 | [
"MIT"
] | 6 | 2018-06-04T09:16:26.000Z | 2022-03-12T11:05:54.000Z | #include "xmol/io/pdb/PdbReader.h"
#include "xmol/io/pdb/PdbLine.h"
#include "xmol/io/pdb/PdbRecord.h"
#include "xmol/io/pdb/exceptions.h"
#include "xmol/utils/string.h"
using namespace xmol::io::pdb;
using namespace xmol;
namespace {
struct PdbLineSentinel {};
struct PdbLineInputIterator {
private:
std::istream* sin_;
std::string str_;
int m_line_number = 0;
PdbLine pdbLine;
const basic_PdbRecords& db;
public:
PdbLineInputIterator(std::istream& sin, const basic_PdbRecords& db) : sin_(&sin), str_{}, db(db) {}
std::string& cached() noexcept { return str_; }
int line_number() noexcept { return m_line_number; }
PdbLineInputIterator& operator++() {
std::getline(*sin_, str_, '\n');
m_line_number++;
if (str_.size() > 0) {
pdbLine = PdbLine(str_, db);
} else {
pdbLine = PdbLine();
}
return *this;
}
const PdbLine* operator->() const { return &(this->pdbLine); }
const PdbLine& operator*() const { return this->pdbLine; }
bool operator!=(const PdbLineSentinel&) const { return !!(*sin_); }
};
template <typename Iterator> ResidueId to_resid(const Iterator& it) {
using xmol::utils::trim;
return ResidueId(it->getInt(FieldName("resSeq")), ResidueInsertionCode(trim(it->getString(FieldName("iCode")))));
}
struct AtomStub {
explicit AtomStub(AtomName name, AtomId serial, XYZ xyz) : name(name), serial(serial), xyz(xyz){};
AtomName name;
AtomId serial;
XYZ xyz;
};
struct ResidueStub {
explicit ResidueStub(ResidueName name, ResidueId serial) : name(name), serial(serial){};
ResidueName name;
ResidueId serial;
std::vector<AtomStub> atoms;
};
struct ChainStub {
explicit ChainStub(MoleculeName name) : name(name){};
MoleculeName name;
std::vector<ResidueStub> residues;
};
struct FrameStub {
int id;
std::vector<ChainStub> chains;
};
template <typename Iterator> AtomStub& readAtom(ResidueStub& res, Iterator& it) {
assert(it != PdbLineSentinel{});
assert(it->getRecordName() == RecordName("ATOM") || it->getRecordName() == RecordName("HETATM") ||
it->getRecordName() == RecordName("ANISOU"));
using xmol::utils::trim;
res.atoms.emplace_back(
AtomName(trim(it->getString(FieldName("name")))), it->getInt(FieldName("serial")),
XYZ{it->getDouble(FieldName("x")), it->getDouble(FieldName("y")), it->getDouble(FieldName("z"))});
AtomStub& atom = res.atoms.back();
++it;
// skip "ANISOU" records
while (it != PdbLineSentinel{} &&
(it->getRecordName() == RecordName("ANISOU") || it->getRecordName() == RecordName("SIGATM") ||
it->getRecordName() == RecordName("SIGUIJ"))) {
++it;
}
return atom;
}
template <typename Iterator> ResidueStub& readResidue(ChainStub& c, Iterator& it) {
assert(it != PdbLineSentinel{});
assert(it->getRecordName() == RecordName("ATOM") || it->getRecordName() == RecordName("HETATM") ||
it->getRecordName() == RecordName("ANISOU"));
using xmol::utils::trim;
auto residueId = to_resid(it);
int chainName = it->getChar(FieldName("chainID"));
c.residues.emplace_back(ResidueName(trim(it->getString(FieldName("resName")))), residueId);
ResidueStub& r = c.residues.back();
while (it != PdbLineSentinel{} &&
(it->getRecordName() == RecordName("ATOM") || it->getRecordName() == RecordName("HETATM") ||
it->getRecordName() == RecordName("ANISOU")) &&
it->getChar(FieldName("chainID")) == chainName && to_resid(it) == residueId) {
readAtom(r, it);
}
return r;
}
template <typename Iterator> ChainStub& readChain(FrameStub& frame, Iterator& it) {
assert(it->getRecordName() == RecordName("ATOM") || it->getRecordName() == RecordName("HETATM"));
std::string stringChainId = it->getString(FieldName("chainID"));
frame.chains.emplace_back(MoleculeName(stringChainId));
ChainStub& c = frame.chains.back();
while (it != PdbLineSentinel{} && it->getRecordName() != RecordName("TER") &&
(it->getRecordName() == RecordName("ATOM") || it->getRecordName() == RecordName("HETATM")) &&
it->getChar(FieldName("chainID")) == stringChainId[0]) {
readResidue(c, it);
}
if (it != PdbLineSentinel{} && it->getRecordName() == "TER") {
++it;
}
return c;
}
template <typename Iterator> Frame readFrame(Iterator& it) {
int id{0};
bool has_model = false;
if (it->getRecordName() == RecordName("MODEL")) {
id = it->getInt(FieldName("serial"));
has_model = true;
++it;
}
FrameStub frame_stub{id};
assert(it->getRecordName() == RecordName("ATOM") || it->getRecordName() == RecordName("HETATM"));
while (it != PdbLineSentinel{} &&
((has_model && it->getRecordName() != RecordName("ENDMDL")) || it->getRecordName() == RecordName("ATOM") ||
it->getRecordName() == RecordName("HETATM"))) {
readChain(frame_stub, it);
}
if (it != PdbLineSentinel{}) {
++it;
}
Frame result;
for (auto& chain_stub : frame_stub.chains) {
auto c = result.add_molecule().name(chain_stub.name);
for (auto& residue_stub : chain_stub.residues) {
auto r = c.add_residue().name(residue_stub.name).id(residue_stub.serial);
for (auto& atom_stub : residue_stub.atoms) {
r.add_atom().name(atom_stub.name).id(atom_stub.serial).r(atom_stub.xyz);
}
}
}
return result;
}
geom::UnitCell read_cell_from_cryst1_record(const PdbLine& line){
return geom::UnitCell(
line.getDouble(FieldName("a")),
line.getDouble(FieldName("b")),
line.getDouble(FieldName("c")),
geom::Degrees(line.getDouble(FieldName("alpha"))),
geom::Degrees(line.getDouble(FieldName("beta"))),
geom::Degrees(line.getDouble(FieldName("gamma")))
);
}
} // namespace
Frame PdbReader::read_frame() { return read_frame(StandardPdbRecords::instance()); }
Frame PdbReader::read_frame(const basic_PdbRecords& db) {
Frame result;
std::vector<Frame> frames;
auto it = PdbLineInputIterator(*is, db);
try {
while (it != PdbLineSentinel{}) {
if (it->getRecordName() == RecordName("MODEL") || it->getRecordName() == RecordName("ATOM") ||
it->getRecordName() == RecordName("HETATM")) {
return readFrame(it);
} else {
++it;
}
}
} catch (PdbFieldReadError& e) {
std::string filler(std::min(std::max(e.colon_l, 0), 80), '~');
std::string underline(std::min(e.colon_r - e.colon_l + 1, 80), '^');
throw PdbException(std::string(e.what()) + "\n" + "at line " + std::to_string(it.line_number()) + ":" +
std::to_string(e.colon_l) + "-" + std::to_string(e.colon_r) + "\n" + it.cached() + "\n" +
filler + underline);
}
return result;
}
std::vector<Frame> PdbReader::read_frames() { return read_frames(StandardPdbRecords::instance()); }
std::vector<Frame> PdbReader::read_frames(const basic_PdbRecords& db) {
std::vector<Frame> frames;
auto cell = geom::UnitCell::unit_cubic_cell(); // create dummy cell
auto it = PdbLineInputIterator(*is, db);
try {
while (it != PdbLineSentinel{}) {
if (it->getRecordName()== RecordName("CRYST1")) {
cell = read_cell_from_cryst1_record(*it);
} else if (it->getRecordName() == RecordName("MODEL") || it->getRecordName() == RecordName("ATOM") ||
it->getRecordName() == RecordName("HETATM")) {
frames.push_back(readFrame(it));
frames.back().cell = cell;
continue;
}
++it;
}
} catch (PdbFieldReadError& e) {
std::string filler(std::min(std::max(e.colon_l, 0), 80), '~');
std::string underline(std::min(e.colon_r - e.colon_l + 1, 80), '^');
throw PdbException(std::string(e.what()) + "\n" + "at line " + std::to_string(it.line_number()) + ":" +
std::to_string(e.colon_l) + "-" + std::to_string(e.colon_r) + "\n" + it.cached() + "\n" +
filler + underline);
}
return frames;
}
| 32.534979 | 116 | 0.634202 | [
"vector",
"model"
] |
e4005c5022ed8a1c361f1fc0008c43ceb647a5ec | 11,623 | cpp | C++ | TAO/tao/CORBALOC_Parser.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/tao/CORBALOC_Parser.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/tao/CORBALOC_Parser.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // -*- C++ -*-
// $Id: CORBALOC_Parser.cpp 96992 2013-04-11 18:07:48Z huangh $
#include "tao/CORBALOC_Parser.h"
#if (TAO_HAS_CORBALOC_PARSER == 1)
#include "tao/ORB_Core.h"
#include "tao/Stub.h"
#include "tao/MProfile.h"
#include "tao/Connector_Registry.h"
#include "tao/Transport_Connector.h"
#include "tao/Protocol_Factory.h"
#include "tao/debug.h"
#include "tao/SystemException.h"
#include "ace/Vector_T.h"
#include "ace/INET_Addr.h"
#include "ace/OS_NS_string.h"
#include "ace/os_include/os_netdb.h"
#if !defined(__ACE_INLINE__)
#include "tao/CORBALOC_Parser.inl"
#endif /* __ACE_INLINE__ */
static const char prefix[] = "corbaloc:";
static const size_t prefix_len = sizeof prefix - 1;
static const char rir_token[] = "rir:";
static const size_t rir_token_len = sizeof rir_token - 1;
static const char iiop_token[] = "iiop:";
static const char iiop_token_len = sizeof iiop_token - 1;
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
TAO_CORBALOC_Parser::~TAO_CORBALOC_Parser (void)
{
}
bool
TAO_CORBALOC_Parser::match_prefix (const char *ior_string) const
{
// Check if the prefix is 'corbaloc:' and return the result.
return (ACE_OS::strncmp (ior_string,
prefix,
prefix_len) == 0);
}
CORBA::Object_ptr
TAO_CORBALOC_Parser::make_stub_from_mprofile (CORBA::ORB_ptr orb,
TAO_MProfile &mprofile)
{
// Create a TAO_Stub.
TAO_Stub *data = orb->orb_core ()->create_stub ((const char *) 0, mprofile);
TAO_Stub_Auto_Ptr safe_data (data);
CORBA::Object_var obj = orb->orb_core ()->create_object (data);
if (!CORBA::is_nil (obj.in ()))
{
/// All is well, so release the stub object from its
/// auto_ptr.
(void) safe_data.release ();
/// Return the object reference to the application.
return obj._retn ();
}
/// Shouldnt come here: if so, return nil reference.
return CORBA::Object::_nil ();
}
CORBA::Object_ptr
TAO_CORBALOC_Parser::parse_string_rir_helper (const char * ior,
CORBA::ORB_ptr orb)
{
// Pass the key string as an argument to resolve_initial_references.
// NameService is the default if an empty key string is supplied.
const char *objkey = ior + rir_token_len;
if (*objkey == '/') // there is an explicit object key, which may
// validly be null.
objkey++;
CORBA::Object_var rir_obj =
orb->resolve_initial_references (*objkey == '\0' ? "NameService" : objkey);
return rir_obj._retn ();
}
CORBA::Object_ptr
TAO_CORBALOC_Parser::parse_string (const char * ior, CORBA::ORB_ptr orb)
{
// The decomposition of a corbaloc string is in Section 13.6.10.
//
// following the "corbaloc:"
// a comma separated list of <prot_addr> strings
// for each,
// Separate out the key, delimited by '/'
// Split out the various parts of our corbaloc string, comma-delimited
// For each part
// Determine the protocol
// If rir, defer to another function and return the object
// If iiop, make the profile with <endpoint>:<port>/<key>
// If another protocol, use <remainder>/<key>
// Search through the collection of protocols for the correct one
// If not found, throw exception
// If found, make our_connector from it.
// our_connector->make_mprofile_unchecked (...);
// object = this->make_stub_from_mprofile (...);
// Return the object
// Skip the prefix. We know it is there because this method is only
// called if match_prefix() returns 1.
ior += ACE_OS::strlen(prefix);
// First check for rir
if (ACE_OS::strncmp (ior,rir_token,rir_token_len) == 0)
return this->parse_string_rir_helper (ior,orb);
// set up space for parsed endpoints. there will be at least 1, and
// most likely commas will separate endpoints, although they could be
// part of an endpoint address for some protocols.
size_t max_endpoint_count = 1;
for (const char *comma = ACE_OS::strchr (ior,',');
comma;
comma = ACE_OS::strchr (comma+1,','))
++max_endpoint_count;
ACE_Array<parsed_endpoint> endpoints(max_endpoint_count);
endpoints.size (0);
// Get the Connector Registry from the ORB.
TAO_Connector_Registry *conn_reg =
orb->orb_core ()->connector_registry();
while (1) { // will loop on comma only.
size_t len = 0;
size_t ndx = endpoints.size();
endpoints.size(ndx+1);
int uiop_compatible = 0;
TAO_ConnectorSetIterator conn_iter = 0;
for (conn_iter = conn_reg->begin();
conn_iter != conn_reg->end() &&
endpoints[ndx].profile_ == 0;
conn_iter ++)
{
endpoints[ndx].profile_ =
(*conn_iter)->corbaloc_scan(ior,len);
if (endpoints[ndx].profile_)
{
endpoints[ndx].obj_key_sep_ =
(*conn_iter)->object_key_delimiter();
uiop_compatible = (endpoints[ndx].obj_key_sep_ == '|');
this->make_canonical (ior,len,endpoints[ndx].prot_addr_);
ior += len;
break;
}
}
if (endpoints[ndx].profile_ == 0)
{
if (TAO_debug_level)
TAOLIB_ERROR ((LM_ERROR,
ACE_TEXT("TAO (%P|%t) - TAO_CORBALOC_Parser::parse_string ")
ACE_TEXT("could not parse from %C\n"),
ior));
throw ::CORBA::BAD_PARAM (CORBA::OMGVMCID | 10, CORBA::COMPLETED_NO);
}
if (*ior == ',') // more endpoints follow
{
++ior;
continue;
}
if (*ior == '/') // found key separator
{
++ior;
break;
}
if (*ior == '\0') // no key separator appended, use default key
{
break;
}
if (uiop_compatible && *(ior - 1) == '|')
// Assume this is an old uiop style corbaloc. No need to warn here,
// the UIOP_Connector::corbaloc_scan already did.
break;
// anything else is a violation.
if (TAO_debug_level)
TAOLIB_ERROR ((LM_ERROR,
ACE_TEXT("TAO (%P|%t) - TAO_CORBALOC_Parser::parse_string ")
ACE_TEXT("could not parse from %C\n"),
ior));
throw ::CORBA::BAD_PARAM (CORBA::OMGVMCID | 10, CORBA::COMPLETED_NO);
} // end of while
// At this point, ior points at the start of the object key
ACE_CString obj_key (*ior ? ior : (const char *)"NameService");
// now take the collection of endpoints along with the decoded key and
// mix them together to get the mprofile.
TAO_MProfile mprofile (endpoints.size());
for (size_t i = 0; i < endpoints.size(); i++)
{
ACE_CString full_ep = endpoints[i].prot_addr_ +
endpoints[i].obj_key_sep_ +
obj_key;
const char * str = full_ep.c_str();
endpoints[i].profile_->parse_string (str);
int share = orb->orb_core()->orb_params()->shared_profile();
if (mprofile.give_profile(endpoints[i].profile_, share) != -1)
endpoints[i].profile_ = 0;
else
{
// Although this ought never happen, we want to make some
// indication back to the caller, more as an audit trail than
// anything else. The only failure possible is that there was
// insufficient heap to allocate the mprofile, hence the
// mprofile's size is 0, and give_profile fails.
if (TAO_debug_level)
TAOLIB_ERROR ((LM_ERROR,
ACE_TEXT("TAO (%P|%t) - TAO_CORBALOC_Parser::parse_string ")
ACE_TEXT("mprofile.give_profile failed for i = %d\n"),
i));
throw ::CORBA::BAD_PARAM (CORBA::OMGVMCID | 10, CORBA::COMPLETED_NO);
}
}
// Get an object stub out.
return this->make_stub_from_mprofile (orb, mprofile);
}
void
TAO_CORBALOC_Parser::make_canonical (const char *ior,
size_t prot_addr_len,
ACE_CString &canonical_endpoint)
{
const char *separator = ACE_OS::strchr (ior, ':');
// A special case for handling iiop
if (ior[0] != ':' && ACE_OS::strncmp (ior,iiop_token,iiop_token_len) != 0)
{
canonical_endpoint.set (separator+1,
prot_addr_len - (separator - ior) - 1,1);
return;
}
const char *addr_base = separator+1;
const char *addr_tail = ior + prot_addr_len;
// skip past version, if any
separator = ACE_OS::strchr (addr_base,'@');
if (separator != 0 && separator < addr_tail)
{
canonical_endpoint.set (addr_base,(separator - addr_base)+1,1);
addr_base = separator + 1;
}
else
canonical_endpoint.clear ();
ACE_CString raw_host;
ACE_CString raw_port;
separator = ACE_OS::strchr (addr_base,':');
#if defined (ACE_HAS_IPV6)
// IPv6 numeric address in host string?
// Check if this is an address containing a decimal IPv6 address representation.
if (addr_base < addr_tail && addr_base[0] == '[')
{
// In this case we have to find the end of the numeric address and
// start looking for the port separator from there.
const char *cp_pos = ACE_OS::strchr(addr_base, ']');
if (cp_pos == 0 || cp_pos >= addr_tail)
{
// No valid IPv6 address specified but that will come out later.
if (TAO_debug_level > 0)
{
TAOLIB_ERROR ((LM_ERROR,
ACE_TEXT ("TAO (%P|%t) - TAO_CORBALOC_Parser: ")
ACE_TEXT ("Invalid IPv6 decimal address specified.\n")));
}
separator = 0;
}
else
{
if (cp_pos[1] == ':') // Look for a port
separator = cp_pos + 1;
else
separator = 0;
}
}
#endif /* ACE_HAS_IPV6 */
if (separator != 0 && separator < addr_tail)
{
// we have a port number
raw_host.set (addr_base, (separator - addr_base), 1);
raw_port.set (separator, (addr_tail - separator), 1);
}
else
{
// we must default port #
if (addr_base < addr_tail)
raw_host.set (addr_base, (addr_tail - addr_base),1);
raw_port.set (":2809");
}
if (raw_host.length() == 0)
{
ACE_INET_Addr host_addr;
char tmp_host [MAXHOSTNAMELEN + 1];
// If no host is specified: assign the default host, i.e. the
// local host.
if (host_addr.get_host_name (tmp_host,
sizeof (tmp_host)) != 0)
{
// Can't get the IP address since the INET_Addr wasn't
// initialized. Just throw an exception.
if (TAO_debug_level > 0)
TAOLIB_DEBUG ((LM_DEBUG,
ACE_TEXT ("TAO (%P|%t) - ")
ACE_TEXT ("Cannot determine hostname.\n")));
throw ::CORBA::INV_OBJREF
(CORBA::SystemException::_tao_minor_code
(TAO::VMCID, EINVAL),
CORBA::COMPLETED_NO);
}
else
{
canonical_endpoint += tmp_host;
}
}
else
{
canonical_endpoint += raw_host;
}
canonical_endpoint += raw_port;
}
ACE_STATIC_SVC_DEFINE (TAO_CORBALOC_Parser,
ACE_TEXT ("CORBALOC_Parser"),
ACE_SVC_OBJ_T,
&ACE_SVC_NAME (TAO_CORBALOC_Parser),
ACE_Service_Type::DELETE_THIS |
ACE_Service_Type::DELETE_OBJ,
0)
ACE_FACTORY_DEFINE (TAO, TAO_CORBALOC_Parser)
TAO_END_VERSIONED_NAMESPACE_DECL
#endif /* TAO_HAS_CORBALOC_PARSER == 1 */
| 31.931319 | 84 | 0.597436 | [
"object"
] |
e4065b1e7d4e45d74df9daede34eae4fe2f93f5d | 924 | h++ | C++ | clauses/group_by_clause.h++ | snawaz/tagsql | 1b6d6c9eb9aa2d01ff3276414d714f3b6e6a9ee3 | [
"MIT"
] | 4 | 2018-03-03T13:45:35.000Z | 2021-05-22T12:11:08.000Z | clauses/group_by_clause.h++ | snawaz/tagsql | 1b6d6c9eb9aa2d01ff3276414d714f3b6e6a9ee3 | [
"MIT"
] | 1 | 2018-03-03T13:49:40.000Z | 2019-01-22T07:58:47.000Z | clauses/group_by_clause.h++ | snawaz/tagsql | 1b6d6c9eb9aa2d01ff3276414d714f3b6e6a9ee3 | [
"MIT"
] | 1 | 2018-03-03T13:45:36.000Z | 2018-03-03T13:45:36.000Z |
#pragma once
#include <tagsql/anatomy/column.h++>
namespace tagsql
{
template<typename SelectQuery>
class deferred_range;
template<typename SelectQuery>
class group_by_clause
{
public:
using is_null_t = typename std::conditional<is_null<typename SelectQuery::group_by>::value, std::true_type, std::false_type>::type;
template<typename ... Columns>
auto group_by(Columns ... ) -> deferred_range<typename SelectQuery::template add_group_by<::foam::meta::typelist<Columns...>>::type>
{
static const std::vector<std::string> names { qualify(typename get_tag<Columns>::type()) ... };
static const std::string clause = " GROUP BY " + ::tagsql::join(",", names) + " ";
auto range = static_cast<deferred_range<SelectQuery>*>(this);
range->_query_without_select += clause;
return { range->_connection, range->_query_without_select };
}
};
}
| 29.806452 | 144 | 0.672078 | [
"vector"
] |
e408464b134730e6fe6776a3bd7e448dd0779bee | 7,780 | cpp | C++ | source/MaterialXTest/RenderOgsFx.cpp | edgarv/MaterialX | b11267b2920c6645d44be6ff09de79a7eb853de2 | [
"BSD-3-Clause"
] | null | null | null | source/MaterialXTest/RenderOgsFx.cpp | edgarv/MaterialX | b11267b2920c6645d44be6ff09de79a7eb853de2 | [
"BSD-3-Clause"
] | null | null | null | source/MaterialXTest/RenderOgsFx.cpp | edgarv/MaterialX | b11267b2920c6645d44be6ff09de79a7eb853de2 | [
"BSD-3-Clause"
] | null | null | null | //
// TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd.
// All rights reserved. See LICENSE.txt for license.
//
#include <MaterialXTest/Catch/catch.hpp>
#include <MaterialXTest/RenderUtil.h>
#include <MaterialXGenOgsFx/MayaGlslPluginShaderGenerator.h>
#include <MaterialXGenShader/Shader.h>
#include <MaterialXGenShader/Util.h>
namespace mx = MaterialX;
//
// Render validation tester for the GLSL shading language
//
class OgsFxShaderRenderTester : public RenderUtil::ShaderRenderTester
{
public:
explicit OgsFxShaderRenderTester(mx::ShaderGeneratorPtr shaderGenerator) :
RenderUtil::ShaderRenderTester(shaderGenerator)
{
}
protected:
void loadAdditionalLibraries(mx::DocumentPtr document,
GenShaderUtil::TestSuiteOptions& options) override;
void registerLights(mx::DocumentPtr document, const GenShaderUtil::TestSuiteOptions &options,
mx::GenContext& context) override;
void createRenderer(std::ostream& log) override;
bool runRenderer(const std::string& shaderName,
mx::TypedElementPtr element,
mx::GenContext& context,
mx::DocumentPtr doc,
std::ostream& log,
const GenShaderUtil::TestSuiteOptions& testOptions,
RenderUtil::RenderProfileTimes& profileTimes,
const mx::FileSearchPath& imageSearchPath,
const std::string& outputPath = ".") override;
mx::LightHandlerPtr _lightHandler;
};
// In addition to standard texture and shader definition libraries, additional lighting files
// are loaded in. If no files are specifed in the input options, a sample
// compound light type and a set of lights in a "light rig" are loaded in to a given
// document.
void OgsFxShaderRenderTester::loadAdditionalLibraries(mx::DocumentPtr document,
GenShaderUtil::TestSuiteOptions& options)
{
mx::FilePath lightDir = mx::FilePath::getCurrentPath() / mx::FilePath("resources/Materials/TestSuite/Utilities/Lights");
for (const auto& lightFile : options.lightFiles)
{
loadLibrary(lightDir / mx::FilePath(lightFile), document);
}
}
// Create a light handler and populate it based on lights found in a given document
void OgsFxShaderRenderTester::registerLights(mx::DocumentPtr document,
const GenShaderUtil::TestSuiteOptions &/*options*/,
mx::GenContext& context)
{
_lightHandler = mx::LightHandler::create();
// Scan for lights
std::vector<mx::NodePtr> lights;
_lightHandler->findLights(document, lights);
_lightHandler->registerLights(document, lights, context);
// Set the list of lights on the with the generator
_lightHandler->setLightSources(lights);
}
void OgsFxShaderRenderTester::createRenderer(std::ostream& /*log*/)
{
}
bool OgsFxShaderRenderTester::runRenderer(const std::string& shaderName,
mx::TypedElementPtr element,
mx::GenContext& context,
mx::DocumentPtr doc,
std::ostream& log,
const GenShaderUtil::TestSuiteOptions& testOptions,
RenderUtil::RenderProfileTimes& profileTimes,
const mx::FileSearchPath& /*imageSearchPath*/,
const std::string& outputPath)
{
RenderUtil::AdditiveScopedTimer totalTime(profileTimes.languageTimes.totalTime, "OgsFx total time");
const mx::ShaderGenerator& shadergen = context.getShaderGenerator();
// Perform validation if requested
if (testOptions.validateElementToRender)
{
std::string message;
if (!element->validate(&message))
{
log << "Element is invalid: " << message << std::endl;
return false;
}
}
std::vector<mx::GenOptions> optionsList;
getGenerationOptions(testOptions, context.getOptions(), optionsList);
if (element && doc)
{
log << "------------ Run GLSL validation with element: " << element->getNamePath() << "-------------------" << std::endl;
for (auto options : optionsList)
{
profileTimes.elementsTested++;
mx::FilePath outputFilePath = outputPath;
// Use separate directory for reduced output
if (options.shaderInterfaceType == mx::SHADER_INTERFACE_REDUCED)
{
outputFilePath = outputFilePath / mx::FilePath("reduced");
}
// Note: mkdir will fail if the directory already exists which is ok.
{
RenderUtil::AdditiveScopedTimer ioDir(profileTimes.languageTimes.ioTime, "OgsFx dir time");
outputFilePath.createDirectory();
}
std::string shaderPath = mx::FilePath(outputFilePath) / mx::FilePath(shaderName);
mx::ShaderPtr shader;
try
{
RenderUtil::AdditiveScopedTimer transpTimer(profileTimes.languageTimes.transparencyTime, "OgsFx transparency time");
options.hwTransparency = mx::isTransparentSurface(element, shadergen);
transpTimer.endTimer();
RenderUtil::AdditiveScopedTimer generationTimer(profileTimes.languageTimes.generationTime, "OgsFx generation time");
mx::GenOptions& contextOptions = context.getOptions();
contextOptions = options;
contextOptions.targetColorSpaceOverride = "lin_rec709";
contextOptions.fileTextureVerticalFlip = true;
contextOptions.hwSpecularEnvironmentMethod = testOptions.specularEnvironmentMethod;
shader = shadergen.generate(shaderName, element, context);
generationTimer.endTimer();
}
catch (mx::Exception& e)
{
log << ">> " << e.what() << "\n";
shader = nullptr;
}
CHECK(shader != nullptr);
if (shader == nullptr)
{
log << ">> Failed to generate shader\n";
return false;
}
const std::string& fxSourceCode = shader->getSourceCode(mx::Stage::EFFECT);
CHECK(fxSourceCode.length() > 0);
if (testOptions.dumpGeneratedCode)
{
RenderUtil::AdditiveScopedTimer dumpTimer(profileTimes.languageTimes.ioTime, "OgsFx I/O time");
std::ofstream file;
file.open(shaderPath + ".ogsfx");
file << fxSourceCode;
file.close();
}
// TODO: Validate compilation.
// TODO: Validate rendering.
}
}
return true;
}
TEST_CASE("Render: OgsFx TestSuite", "[renderglsl]")
{
// Use the Maya version of the OgsFx generator,
// so we can render the shaders in Maya's viewport.
OgsFxShaderRenderTester renderTester(mx::MayaGlslPluginShaderGenerator::create());
const mx::FilePath testRootPath = mx::FilePath::getCurrentPath() / mx::FilePath("resources/Materials/TestSuite");
const mx::FilePath testRootPath2 = mx::FilePath::getCurrentPath() / mx::FilePath("resources/Materials/Examples/StandardSurface");
const mx::FilePath testRootPath3 = mx::FilePath::getCurrentPath() / mx::FilePath("resources/Materials/Examples/UsdPreviewSurface");
mx::FilePathVec testRootPaths;
testRootPaths.push_back(testRootPath);
testRootPaths.push_back(testRootPath2);
testRootPaths.push_back(testRootPath3);
mx::FilePath optionsFilePath = testRootPath / mx::FilePath("_options.mtlx");
renderTester.validate(testRootPaths, optionsFilePath);
}
| 39.095477 | 135 | 0.633033 | [
"render",
"vector"
] |
e40fbc7705a75be556bd2c1710c9fc129b3f357b | 1,928 | hpp | C++ | galaxy/src/galaxy/algorithm/RectPack.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | 6 | 2018-07-21T20:37:01.000Z | 2018-10-31T01:49:35.000Z | galaxy/src/galaxy/algorithm/RectPack.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | galaxy/src/galaxy/algorithm/RectPack.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | ///
/// RectPack.hpp
/// galaxy
///
/// Refer to LICENSE.txt for more details.
///
#ifndef GALAXY_ALGORITHM_RECTPACK_HPP_
#define GALAXY_ALGORITHM_RECTPACK_HPP_
#include <optional>
#include <vector>
#include "galaxy/graphics/Rect.hpp"
namespace galaxy
{
namespace algorithm
{
///
/// Rectangle 2D bin packing class.
///
class RectPack final
{
public:
///
/// Constructor.
///
RectPack() noexcept;
///
/// Destructor.
///
~RectPack() noexcept;
///
/// Set starting width and height of rectangle.
///
/// Generally should be a power of 2.
///
/// \param width Width of the master rectangle.
/// \param height Height of the master rectangle.
///
void init(const int width, const int height) noexcept;
///
/// Pack a rectangle into the master rectangle.
///
/// \param width Width of the rectangle to pack.
/// \param height Height of the rectangle to pack.
///
/// \return Returns the location of the packed rectangle on the master rectangle.
/// Otherwise, returns a std::nullopt.
///
[[nodiscard]] std::optional<graphics::iRect> pack(const int width, const int height) noexcept;
///
/// Clear all data.
///
void clear() noexcept;
///
/// Get total width.
///
[[nodiscard]] const int get_width() const noexcept;
///
/// Get total height.
///
[[nodiscard]] const int get_height() const noexcept;
///
/// Get free rectangles.
///
/// \return Const std::vector.
///
[[nodiscard]] const std::vector<graphics::iRect>& get_free_space() const noexcept;
private:
///
/// The starting width of the rectangle.
///
int m_width;
///
/// The starting width of the rectangle.
///
int m_height;
///
/// Free space in master rectangle.
///
std::vector<graphics::iRect> m_free_rects;
};
} // namespace algorithm
} // namespace galaxy
#endif | 19.673469 | 97 | 0.612552 | [
"vector"
] |
e411e88974a68e18776bf929ebd9bec6c4f7b643 | 362 | hpp | C++ | mrrc/src/mirror/ast/mrrexpr.hpp | nfwGytautas/mirror | 4e9a20f364076cd52abf3c358afebe7b10c08078 | [
"MIT"
] | null | null | null | mrrc/src/mirror/ast/mrrexpr.hpp | nfwGytautas/mirror | 4e9a20f364076cd52abf3c358afebe7b10c08078 | [
"MIT"
] | null | null | null | mrrc/src/mirror/ast/mrrexpr.hpp | nfwGytautas/mirror | 4e9a20f364076cd52abf3c358afebe7b10c08078 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <memory>
#include <vector>
#include "mirror/compiler/mrrc.hpp"
#include "mirror/utility/log.hpp"
#include "mirror/ast/expressions/base.hpp"
#include "mirror/ast/expressions/core.hpp"
#include "mirror/ast/expressions/control.hpp"
#include "mirror/ast/expressions/function.hpp"
#include "mirror/ast/expressions/type.hpp"
| 24.133333 | 46 | 0.773481 | [
"vector"
] |
e413f97952e21e62b228e5e137cbef6c33a70e79 | 697 | cpp | C++ | test/yosupo/shortest_path.test.cpp | shiomusubi496/library | 907f72eb6ee4ac6ef617bb359693588167f779e7 | [
"MIT"
] | 3 | 2021-11-04T08:45:12.000Z | 2021-11-29T08:44:26.000Z | test/yosupo/shortest_path.test.cpp | shiomusubi496/library | 907f72eb6ee4ac6ef617bb359693588167f779e7 | [
"MIT"
] | null | null | null | test/yosupo/shortest_path.test.cpp | shiomusubi496/library | 907f72eb6ee4ac6ef617bb359693588167f779e7 | [
"MIT"
] | null | null | null | #define PROBLEM "https://judge.yosupo.jp/problem/shortest_path"
#include "../../other/template.hpp"
#include "../../graph/Graph.hpp"
#include "../../graph/shortest-path/Dijkstra.hpp"
#include "../../graph/shortest-path/Restore.hpp"
using namespace std;
int main() {
int N, M, s, t; cin >> N >> M >> s >> t;
Graph<ll> G(N);
rep (M) {
int a, b, c; cin >> a >> b >> c;
G.add_edge(a, b, c, true);
}
vector<ll> D = Dijkstra(G, s);
if (D[t] == infinity<ll>::value) {
puts("-1");
return 0;
}
Edges<ll> R = RestorePath(G, D, s, t);
cout << D[t] << ' ' << R.size() << endl;
each_const (e : R) cout << e.from << ' ' << e.to << endl;
}
| 30.304348 | 63 | 0.51363 | [
"vector"
] |
e4156085a07439650fabcc7fc87776ff07c8617f | 4,645 | hpp | C++ | inference-engine/include/builders/ie_pooling_layer.hpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | 1 | 2021-07-30T17:03:50.000Z | 2021-07-30T17:03:50.000Z | inference-engine/include/builders/ie_pooling_layer.hpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | null | null | null | inference-engine/include/builders/ie_pooling_layer.hpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
/**
* @file
*/
#pragma once
#include <builders/ie_layer_decorator.hpp>
#include <ie_network.hpp>
#include <string>
#include <vector>
namespace InferenceEngine {
namespace Builder {
/**
* @deprecated Use ngraph API instead.
* @brief The class represents a builder for Pooling layer
*/
IE_SUPPRESS_DEPRECATED_START
class INFERENCE_ENGINE_NN_BUILDER_API_CLASS(PoolingLayer): public LayerDecorator {
public:
/**
* @brief The enum defines available pooling types
*/
enum PoolingType { MAX = 1, AVG = 2 };
/**
* @brief The enum defines available rounding types
*/
enum RoundingType { CEIL = 1, FLOOR = 2 };
/**
* @brief The constructor creates a builder with the name
* @param name Layer name
*/
explicit PoolingLayer(const std::string& name = "");
/**
* @brief The constructor creates a builder from generic builder
* @param layer pointer to generic builder
*/
explicit PoolingLayer(const Layer::Ptr& layer);
/**
* @brief The constructor creates a builder from generic builder
* @param layer constant pointer to generic builder
*/
explicit PoolingLayer(const Layer::CPtr& layer);
/**
* @brief Operator creates generic layer builder
* @return Generic layer builder
*/
operator Layer() const override;
/**
* @brief Sets the name for the layer
* @param name Layer name
* @return reference to layer builder
*/
PoolingLayer& setName(const std::string& name);
/**
* @brief Returns input port
* @return Input port
*/
const Port& getInputPort() const;
/**
* @brief Sets input port
* @param port Input port
* @return reference to layer builder
*/
PoolingLayer& setInputPort(const Port& port);
/**
* @brief Returns output port
* @return Output port
*/
const Port& getOutputPort() const;
/**
* @brief Sets output port
* @param port Output port
* @return reference to layer builder
*/
PoolingLayer& setOutputPort(const Port& port);
/**
* @brief Returns kernel size
* @return Kernel size
*/
const std::vector<size_t> getKernel() const;
/**
* @brief Sets kernel size
* @param kernel Kernel size
* @return reference to layer builder
*/
PoolingLayer& setKernel(const std::vector<size_t>& kernel);
/**
* @brief Returns vector of strides
* @return vector of strides
*/
const std::vector<size_t> getStrides() const;
/**
* @brief Sets strides
* @param strides vector of strides
* @return reference to layer builder
*/
PoolingLayer& setStrides(const std::vector<size_t>& strides);
/**
* @brief Returns begin paddings
* @return vector of paddings
*/
const std::vector<size_t> getPaddingsBegin() const;
/**
* @brief Sets begin paddings
* @param paddings Vector of paddings
* @return reference to layer builder
*/
PoolingLayer& setPaddingsBegin(const std::vector<size_t>& paddings);
/**
* @brief Return end paddings
* @return Vector of paddings
*/
const std::vector<size_t> getPaddingsEnd() const;
/**
* @brief Sets end paddings
* @param paddings Vector of paddings
* @return reference to layer builder
*/
PoolingLayer& setPaddingsEnd(const std::vector<size_t>& paddings);
/**
* @brief Returns pooling type
* @return Pooling type
*/
PoolingType getPoolingType() const;
/**
* @brief Sets pooling type
* @param type Pooling type
* @return reference to layer builder
*/
PoolingLayer& setPoolingType(PoolingType type);
/**
* @brief Returns rounding type
* @return Rounding type
*/
RoundingType getRoundingType() const;
/**
* @brief Sets rounding types
* @param type Rounding type
* @return reference to layer builder
*/
PoolingLayer& setRoundingType(RoundingType type);
/**
* @brief Returns a type of pooling strategy
* @return true if zero-values in the padding are not used
*/
bool getExcludePad() const;
/**
* @brief Sets a type of pooling strategy
* @param exclude zero-values in the padding are not used if true
* @return reference to layer builder
*/
PoolingLayer& setExcludePad(bool exclude);
private:
PoolingType type = MAX;
RoundingType roundingType = CEIL;
};
IE_SUPPRESS_DEPRECATED_END
} // namespace Builder
} // namespace InferenceEngine
| 27.163743 | 82 | 0.639182 | [
"vector"
] |
e4179bf6a6e65e7db475c6d2a5de20184be81ba6 | 514 | hpp | C++ | src/xml_clients.hpp | markkorput/raspi2030 | 4a918d240172b68634619567d47599fa02b8dd16 | [
"MIT"
] | null | null | null | src/xml_clients.hpp | markkorput/raspi2030 | 4a918d240172b68634619567d47599fa02b8dd16 | [
"MIT"
] | null | null | null | src/xml_clients.hpp | markkorput/raspi2030 | 4a918d240172b68634619567d47599fa02b8dd16 | [
"MIT"
] | null | null | null |
#ifndef xml_clients_hpp
#define xml_clients_hpp
#include "ofMain.h"
#include "setting_types.h"
namespace of2030{
class XmlClients{
public:
static XmlClients* instance();
private:
static XmlClients* singleton;
public:
XmlClients() : path("clients.xml"){};
~XmlClients(){ destroy(); }
void destroy();
void load();
//void save();
std::string path;
vector<ClientSetting*> clients;
};
}
#endif /* xml_clients_hpp */
| 17.724138 | 45 | 0.587549 | [
"vector"
] |
e419a80172775af08c05c314d265da6b407340e4 | 6,479 | cc | C++ | src/ui/SDL2/gui_modules/submodules/menu.cc | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 349 | 2017-11-15T22:51:00.000Z | 2022-03-21T13:43:57.000Z | src/ui/SDL2/gui_modules/submodules/menu.cc | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 12 | 2018-08-28T21:38:29.000Z | 2021-12-11T16:24:36.000Z | src/ui/SDL2/gui_modules/submodules/menu.cc | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 28 | 2018-06-10T07:31:13.000Z | 2022-03-21T10:54:26.000Z | #include "menu.h"
#include <algorithm>
#include <cute_files.h>
#include <SDL_inprint2.h>
#include <SDL.h>
#include "../../fs/util.h"
MenuSubModule::MenuSubModule(SharedState& gui, SDL_Window* window, SDL_Renderer* renderer)
: GUISubModule(gui, window, renderer)
{
fprintf(stderr, "[GUI][Menu] Initializing...\n");
// Update from config
strcpy(this->nav.directory, this->gui.config.roms_dir);
// Setup SDL2_inprint font
this->inprint = new SDL2_inprint(this->renderer);
}
MenuSubModule::~MenuSubModule() {
fprintf(stderr, "[GUI][Menu] Shutting down...\n");
// Update config
ANESE_fs::util::get_abs_path(this->gui.config.roms_dir, this->nav.directory, 260);
delete this->inprint;
// unload ROM
this->gui.unload_rom();
}
void MenuSubModule::input(const SDL_Event& event) {
// First, check if actions should even be recorded...
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
this->gui.status.in_menu = !this->gui.status.in_menu; break;
}
}
if (event.type == SDL_CONTROLLERBUTTONDOWN ||
event.type == SDL_CONTROLLERBUTTONUP) {
switch (event.cbutton.button) {
case SDL_CONTROLLER_BUTTON_LEFTSTICK:
this->gui.status.in_menu = !this->gui.status.in_menu; break;
}
}
if (!this->gui.status.in_menu) return;
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_RETURN: this->hit.enter = true; break;
case SDLK_DOWN: this->hit.down = true; break;
case SDLK_UP: this->hit.up = true; break;
case SDLK_LEFT: this->hit.left = true; break;
case SDLK_RIGHT: this->hit.right = true; break;
}
// support for basic "fast skipping" though file-names
const char* key_pressed = SDL_GetKeyName(event.key.keysym.sym);
bool is_valid_char = isalnum(key_pressed[0])
|| key_pressed[0] == '.';
if (is_valid_char && key_pressed[1] == '\0')
this->hit.last_ascii = key_pressed[0];
// Special case: space
if (event.key.keysym.sym == SDLK_SPACE)
this->hit.last_ascii = ' ';
}
if (event.type == SDL_CONTROLLERBUTTONDOWN ||
event.type == SDL_CONTROLLERBUTTONUP) {
switch (event.cbutton.button) {
case SDL_CONTROLLER_BUTTON_A: this->hit.enter = true; break;
case SDL_CONTROLLER_BUTTON_DPAD_UP: this->hit.up = true; break;
case SDL_CONTROLLER_BUTTON_DPAD_DOWN: this->hit.down = true; break;
case SDL_CONTROLLER_BUTTON_DPAD_LEFT: this->hit.left = true; break;
}
}
}
void MenuSubModule::update() {
std::vector<cf_file_t>& files = this->nav.files; // helpful alias
// First, check if the user wants to navigate / load a rom
if (this->hit.enter || this->hit.right) {
this->hit.enter = false;
this->hit.right = false;
const cf_file_t& file = files[this->nav.selected_i];
if (file.is_dir) {
// Navigate into directory
strcpy(this->nav.directory, file.path);
this->nav.selected_i = 0;
this->nav.should_update_dir = true;
} else {
// Load-up ROM (and close menu)
fprintf(stderr, "[Menu] Selected '%s'\n", file.name);
this->gui.unload_rom();
this->gui.load_rom(file.path);
this->gui.status.in_menu = false;
}
}
// Potentially update directory listing
if (this->nav.should_update_dir) {
this->nav.should_update_dir = false;
files.clear();
// Get file-listing
cf_dir_t dir;
cf_dir_open(&dir, this->nav.directory);
while (dir.has_next) {
cf_file_t file;
cf_read_file(&dir, &file);
files.push_back(file);
cf_dir_next(&dir);
}
cf_dir_close(&dir);
// Remove all file-types we don't care about
files.erase(
std::remove_if(files.begin(), files.end(), [](const cf_file_t& file) {
return file.is_dir == false &&
!(strcmp("nes", file.ext) == 0 || strcmp("zip", file.ext) == 0);
}),
files.end()
);
// Sort the directory by filename
std::sort(files.begin(), files.end(),
[](const cf_file_t& a, const cf_file_t& b){
return strcmp(a.name, b.name) < 0;
});
}
// Handle navigation...
if (this->hit.up) {
this->hit.up = false;
this->nav.selected_i -= this->nav.selected_i ? 1 : 0;
}
if (this->hit.down) {
this->hit.down = false;
this->nav.selected_i += (this->nav.selected_i < (files.size() - 1));
}
if (this->hit.left) {
this->hit.left = false;
strcpy(this->nav.directory, files[0].path);
this->nav.selected_i = 0;
}
if (this->nav.quicksel.timeout) { this->nav.quicksel.timeout--; }
else {
this->nav.quicksel.i = 0;
memset(this->nav.quicksel.buf, '\0', 16);
}
if (this->hit.last_ascii) {
// clear buffer in ~1s from last keypress
this->nav.quicksel.timeout = 30;
// buf[15] is always '\0'
this->nav.quicksel.buf[this->nav.quicksel.i++ % 15] = ::tolower(this->hit.last_ascii);
uint new_selection = std::distance(
files.begin(),
std::find_if(files.begin(), files.end(),
[=](const cf_file_t& f){
std::string fname = std::string(f.name).substr(0, this->nav.quicksel.i);
std::transform(fname.begin(), fname.end(), fname.begin(), ::tolower);
return strcmp(fname.c_str(), this->nav.quicksel.buf) == 0;
})
);
if (new_selection < files.size())
this->nav.selected_i = new_selection;
this->hit.last_ascii = '\0';
}
}
void MenuSubModule::output() {
if (!this->gui.status.in_menu) return;
// menu uses the EmuModule's rendering context
// Paint transparent bg
this->bg.x = this->bg.y = 0;
SDL_RenderGetLogicalSize(this->renderer, &this->bg.w, &this->bg.h);
if (this->bg.w == 0 && this->bg.h == 0)
SDL_GetWindowSize(this->window, &this->bg.w, &this->bg.h);
SDL_SetRenderDrawColor(this->renderer, 0, 0, 0, 200);
SDL_RenderFillRect(this->renderer, &this->bg);
// Paint menu
for (uint i = 0; i < this->nav.files.size(); i++) {
const cf_file_t& file = this->nav.files[i];
u32 color;
if (this->nav.selected_i == i) color = 0xff0000; // red - selected
else if (strcmp("nes", file.ext) == 0) color = 0x00ff00; // green - .nes
else if (strcmp("zip", file.ext) == 0) color = 0x00ffff; // cyan - .zip
else color = 0xffffff; // white - folder
this->inprint->set_color(color);
this->inprint->print(file.name, 10, this->bg.h / 2 + (i - this->nav.selected_i) * 12);
}
}
| 30.852381 | 90 | 0.619231 | [
"vector",
"transform"
] |
e41b916d71612cc9395448e80653a9d8363e173d | 27,344 | cpp | C++ | Client/src/TopNotebook.cpp | kluete/ddt3 | b8bf3b6daf275ec025b0c4a6401576560b671a3d | [
"Apache-2.0"
] | 6 | 2020-04-20T04:54:44.000Z | 2022-02-13T01:24:10.000Z | Client/src/TopNotebook.cpp | kluete/ddt3 | b8bf3b6daf275ec025b0c4a6401576560b671a3d | [
"Apache-2.0"
] | null | null | null | Client/src/TopNotebook.cpp | kluete/ddt3 | b8bf3b6daf275ec025b0c4a6401576560b671a3d | [
"Apache-2.0"
] | 1 | 2022-02-13T01:24:35.000Z | 2022-02-13T01:24:35.000Z | // Lua DDT top Notebook
#pragma GCC diagnostic ignored "-Wunused-private-field"
#include <cassert>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include "wx/panel.h"
#include "wx/notebook.h"
#include "wx/splitter.h"
#include "wx/statusbr.h"
#include "wx/statbmp.h"
#include "wx/numdlg.h" // for wxGetNumberFromUser()
#include "wx/laywin.h"
#include "TopFrame.h"
#include "Controller.h"
#include "logImp.h"
#include "SourceFileClass.h"
#include "StyledSourceCtrl.h"
#include "SearchBar.h"
#include "UIConst.h"
#include "sigImp.h"
#include "logImp.h"
#include "TopNotebook.h"
#include "WatchBag.h"
using namespace std;
using namespace LX;
using namespace DDT_CLIENT;
enum V_INDEX : size_t
{
SEARCHBAR = 0,
NOTE_TABS = 1,
EDITOR1 = 2,
};
void DumpFocusLL(const char *fn, const char *comment)
{
#if DDT_LOG_FOCUS_CHANGE
wxWindow *fw = wxWindow::FindFocus();
uLog(FOCUS, "focus = %p %d %s @ %s %S", fw, (int) fw->GetId(), fw->GetName(), string(fn), string(comment));
#endif
}
//---- top placeholder ------------------------------------------------
class TopPlaceholder : public wxPanel
{
public:
TopPlaceholder(wxWindow *parent_win, int id, ITopNotePanel &top_notebook)
: wxPanel(parent_win, id),
m_TopNotebook(top_notebook)
{
Show();
}
/*
m_TextCtrl(this, -1, "", wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_RICH | wxTE_NOHIDESEL | wxTE_DONTWRAP)
{
wxBoxSizer *top_v_sizer = new wxBoxSizer(wxVERTICAL);
top_v_sizer->Add(&m_TextCtrl, 1, wxALL | wxEXPAND, 1);
SetSizer(top_v_sizer);
m_TextCtrl.AppendText("bite au cul 1234\ncaca");
Show();
}
*/
virtual ~TopPlaceholder()
{
uLog(DTOR, "TopPlaceholder::DTOR");
}
private:
ITopNotePanel &m_TopNotebook;
// wxTextCtrl m_TextCtrl;
};
//---- top Notepage -----------------------------------------------------------
class Notepage : public wxPanel
{
public:
Notepage(wxWindow *parent, int id, ISourceFileClass *sfc)
: wxPanel(parent, id),
m_Sfc(sfc)
{
assert(sfc);
SetClientData(sfc);
}
virtual ~Notepage()
{
SetClientData(nil);
}
ISourceFileClass* GetSfc(void)
{
return m_Sfc;
}
private:
ISourceFileClass *m_Sfc;
};
//---- Top Notebook imp -------------------------------------------------------
class TopNotebookImp : public wxNotebook, private LX::SlotsMixin<LX::CTX_WX>
{
public:
TopNotebookImp(wxWindow *parent, int id, ITopNotePanel &top_notepanel, IEditorCtrl &editor, TopFrame &tf, Controller &controller)
: wxNotebook(parent, id, wxDefaultPosition, wxSize(-1, -1), wxNB_TOP),
m_TopNotePanel(top_notepanel),
m_Editor(editor),
m_TopFrame(tf), // used for var solving
m_Controller(controller)
{
m_LastDaemonTick = -1;
// use aux bitmaps (doesn't take ownership)
SetImageList(&controller.GetImageList());
ReIndex();
MixConnect(this, &TopNotebookImp::OnEditorDirtyChanged, m_Editor.GetSignals().OnEditorDirtyChanged);
}
virtual ~TopNotebookImp()
{
uLog(DTOR, "TopNotebookImp::DTOR");
}
EditorSignals& GetSignals(void) {return m_Editor.GetSignals();}
bool CanQueryDaemon(void) const
{
if (!m_Controller.IsLuaListening()) return false;
return true;
}
void OnEditorDirtyChanged(ISourceFileClass *sfc, bool dirty_f)
{
assert(sfc);
sfc->SetDirty(dirty_f);
UpdateEditorTitles();
}
// var hover resolution
bool SolveVar_ASYNC(const string &key, wxString &res); // returns [cached_f]
void SetSolvedVariable(const Collected &ce);
bool AddToWatches(const string &watch_name);
void NotifyPageChanged(void);
void OnCursorPosChanged(void);
void ShowSFC(ISourceFileClass *sfc);
void HideSFC(ISourceFileClass *sfc, const bool delete_f);
void HideAllSFCs(void)
{
for (auto &it : m_PageToSFCMap)
{
auto *sfc = it.second;
assert(sfc);
HideSFC(sfc, false/*delete?*/);
}
}
ISourceFileClass* GetEditSFC(void) const
{
return m_Editor.GetCurrentSFC();
}
void EscapeKeyCallback(void);
void UpdateEditorTitles(void)
{
for (auto &it : m_PageToSFCMap)
{
auto *sfc = it.second;
const bool dirty_f = sfc->IsDirty();
wxString title = sfc->GetShortName() + (dirty_f ? "*" : "");
const int index = m_SFCtoPageMap.at(sfc);
SetPageText(index, title);
}
// always set ???
m_Controller.SetDirtyProject();
}
private:
ISourceFileClass* GetSelectedSFC(void) const
{
const int page_index = GetSelection();
if (page_index == wxNOT_FOUND) return nil;
return m_PageToSFCMap.count(page_index) ? m_PageToSFCMap.at(page_index) : nil;
}
// events
void OnMouseLeftClick(wxMouseEvent &e);
void OnRightDown(wxMouseEvent &e);
void OnNotePageChanging(wxNotebookEvent &e);
void OnNotePageChanged(wxNotebookEvent &e);
// PRIVATE overloads
bool AddPage(wxWindow *page, const wxString &text, bool bSelect, int imageId) override;
bool RemovePage(size_t page_pos) override;
bool DeletePage(size_t page_pos) override;
int ChangeSelection(size_t page_index) override;
int SetSelection(size_t page_index) override;
void ReIndex(void);
ITopNotePanel &m_TopNotePanel;
IEditorCtrl &m_Editor;
TopFrame &m_TopFrame;
Controller &m_Controller;
unordered_map<int, ISourceFileClass*> m_PageToSFCMap;
unordered_map<ISourceFileClass*, int> m_SFCtoPageMap;
unordered_map<string, Collected> m_VarCache;
unordered_set<string> m_VarRequestedSet;
int m_LastDaemonTick;
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(TopNotebookImp, wxNotebook)
EVT_LEFT_DOWN( TopNotebookImp::OnMouseLeftClick)
EVT_NOTEBOOK_PAGE_CHANGED( -1, TopNotebookImp::OnNotePageChanged)
END_EVENT_TABLE()
void TopNotebookImp::NotifyPageChanged(void)
{
const int selected_page = GetSelection();
uLog(UI, "TopNotebookImp::NotifyPageChanged(selected page %d)", selected_page);
ISourceFileClass *sfc = GetSelectedSFC(); // may be nil
// assert(sfc);
m_TopNotePanel.SetEditSFC(sfc);
// const string shortname = sfc->GetShortName();
// m_TopNotePanel.GetSignals().OnEditorSourceChanged(CTX_WX, shortname);
m_TopNotePanel.RequestStatusBarRefresh();
}
void TopNotebookImp::OnNotePageChanged(wxNotebookEvent &e)
{
NotifyPageChanged();
e.Skip();
}
// PRIVATE OVERLOADS
bool TopNotebookImp::AddPage(wxWindow *page, const wxString &title, bool bSelect, int imageId)
{
uLog(UI, "TopNotebookImp::AddPage(%S)", title);
const bool f = wxNotebook::AddPage(page, title, bSelect, imageId);
assert(f);
ReIndex();
return f;
}
bool TopNotebookImp::RemovePage(size_t page_pos)
{
const bool f = wxNotebook::RemovePage(page_pos);
assert(f);
ReIndex();
return f;
}
bool TopNotebookImp::DeletePage(size_t page_pos)
{
uLog(DTOR, "TopNotebookImp::DeletePage(%zu)", page_pos);
const bool f = wxNotebook::DeletePage(page_pos);
assert(f);
ReIndex();
return f;
}
int TopNotebookImp::ChangeSelection(size_t page_index)
{
const int old_index = wxNotebook::ChangeSelection(page_index);
uLog(UI, "TopNotebookImp::ChangeSelection(%d -> %zu)", old_index, page_index);
NotifyPageChanged();
return old_index;
}
int TopNotebookImp::SetSelection(size_t page_index)
{
const int old_index = wxNotebook::SetSelection(page_index);
uLog(UI, "TopNotebookImp::SetSelection(%d -> %zu)", old_index, page_index);
NotifyPageChanged();
return old_index;
}
//---- re-Index SFC tables ----------------------------------------------------
void TopNotebookImp::ReIndex(void)
{
const size_t sz_bf = m_PageToSFCMap.size();
m_SFCtoPageMap.clear();
m_PageToSFCMap.clear();
for (int i = 0; i < GetPageCount(); i++)
{
wxWindow *win = GetPage(i);
assert(win);
Notepage *np = dynamic_cast<Notepage*>(win);
assert(np);
ISourceFileClass *sfc = np->GetSfc();
// cross-map
m_SFCtoPageMap.emplace(sfc, i);
m_PageToSFCMap.emplace(i, sfc);
}
const size_t sz_af = m_PageToSFCMap.size();
if ((sz_bf == 1) && (sz_af == 0))
{ // wx bug workaround for last removal
NotifyPageChanged();
}
}
//---- Show SFC ---------------------------------------------------------------
void TopNotebookImp::ShowSFC(ISourceFileClass *sfc)
{
assert(sfc);
int index = m_SFCtoPageMap.count(sfc) ? m_SFCtoPageMap.at(sfc) : -1;
if (-1 == index)
{ // wasn't visible, create
auto *np = new Notepage(this, -1, sfc);
const string title = sfc->GetShortName();
AddPage(np, title, false/*do NOT select here*/, BITMAP_ID_CLOSE_TAB);
np->Show();
assert(m_SFCtoPageMap.count(sfc));
index = m_SFCtoPageMap.at(sfc);
}
// *** wxSTC grabs the focus *** UNLESS use calls below
// bring to front
ChangeSelection(index);
}
//---- Hide or Delete SFC -----------------------------------------------------
void TopNotebookImp::HideSFC(ISourceFileClass *sfc, const bool delete_f)
{
assert(sfc);
if (!m_SFCtoPageMap.count(sfc))
{ // ignore if is delete op and isn't shown
if (delete_f) return;
uErr("TopNotebookImp::HideSFC(%S) wasn't shown", sfc->GetShortName());
return;
}
int index = m_SFCtoPageMap.at(sfc);
if (delete_f)
{ // deletes associated wxWindow
const bool ok = DeletePage(index);
assert(ok);
}
else
{ // close (don't delete)
// sfc->GetEditorCtrl()->Hide();
RemovePage(index);
}
}
//---- On Mouse Left-Click ---------------------------------------------------
void TopNotebookImp::OnMouseLeftClick(wxMouseEvent &e)
{
// skip event by default BUT unskip if needed
// e.Skip();
// hit test
long mask = 0;
const int page_index = HitTest(e.GetPosition(), &mask);
if (wxNOT_FOUND == page_index) return;
if (!(mask & wxBK_HITTEST_ONITEM)) return; // nowhere we care
assert(m_PageToSFCMap.count(page_index));
ISourceFileClass *sfc = m_PageToSFCMap.at(page_index);
assert(sfc);
if (mask & wxBK_HITTEST_ONICON)
{ // close button
HideSFC(sfc, false/*delete?*/);
// e.Skip(true);
}
else if (wxBK_HITTEST_ONLABEL & mask)
{ // notepage label -> raise
ChangeSelection(page_index); // wxSTC may capture FOCUS here?
// sfc->RestoreCursorPos();
// don't skip or cursor pos won't be restored!
e.Skip(false);
}
}
//---- Top Notepanel ----------------------------------------------------------
class DDT_CLIENT::TopNotePanel: public wxPanel, public ITopNotePanel, private SlotsMixin<CTX_WX>
{
public:
// ctor
TopNotePanel(wxWindow *parent, int id, TopFrame &tf, Controller &controller)
: wxPanel(parent, id, wxDefaultPosition, wxSize(0, 0), wxBORDER_SUNKEN),
m_TopFrame(tf),
m_Controller(controller),
m_SplitterTop(new BookSplitter(this, SPLITTER_ID_TOP, 0)),
m_TopPanel(m_SplitterTop.get(), CONTROL_ID_TOP_PANEL, wxDefaultPosition, wxSize(0, 0), wxBORDER_NONE),
m_EditorPtr(IEditorCtrl::CreateStyled(&m_TopPanel, CONTROL_ID_STC_EDITOR, *this, controller.GetImageList())),
m_Editor(*m_EditorPtr),
m_TopNotebookImp(&m_TopPanel, CONTROL_ID_TOP_NOTEBOOK_IMP, *this, m_Editor, tf, controller),
m_SearchBar(&m_TopPanel, CONTROL_ID_SEARCH_PANEL, *this, tf, controller),
m_EditorStatusBar(&m_TopPanel, CONTROL_ID_EDITOR_STATUSBAR, wxSTB_SHOW_TIPS | wxFULL_REPAINT_ON_RESIZE) // no size grip!
{
m_SearchBar.Show();
wxFont ft(wxFontInfo(9).Family(wxFONTFAMILY_SWISS).Encoding(wxFONTENCODING_DEFAULT));
m_EditorStatusBar.SetFont(ft);
m_EditorStatusBar.SetFieldsCount(NUM_EDIT_STATUS_FIELDS);
// EXPLICITLY set style on sub-fields on Gtk
int styles[NUM_EDIT_STATUS_FIELDS] = {0, 0, 0, 0};
m_EditorStatusBar.SetStatusStyles(NUM_EDIT_STATUS_FIELDS, styles);
m_EditorStatusBar.SetStatusText("dummy", 0);
m_EditorStatusBar.SetMinHeight(10);
m_EditorStatusBar.Show();
m_VSizer = new wxBoxSizer(wxVERTICAL);
m_VSizer->Add(&m_SearchBar, wxSizerFlags(0).Expand()); // .Border(wxALL, 0));
m_VSizer->Add(&m_TopNotebookImp, wxSizerFlags(0).Expand());
m_VSizer->Add(m_Editor.GetWxWindow(), wxSizerFlags(1).Expand());
// m_VSizer->Add(&m_Editor2Panel, wxSizerFlags(1).Expand());
m_VSizer->Add(&m_EditorStatusBar, wxSizerFlags(0).Border(wxLEFT | wxRIGHT, 1).Expand());
m_TopPanel.SetSizer(m_VSizer);
Layout();
Fit();
SetDropTarget(new ControllerDropTarget(controller));
// init unsplit (single pane)
m_SplitterTop->Initialize(&m_TopPanel);
wxBoxSizer *top_sizer = new wxBoxSizer(wxVERTICAL);
top_sizer->Add(m_SplitterTop.get(), wxSizerFlags(1).Expand());
SetSizer(top_sizer);
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnSaveFileMenu, this, EDIT_MENU_ID_SAVE_FILE);
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnRevertFileMenu, this, EDIT_MENU_ID_REVERT_FILE);
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnGotoLineNumber, this, MENU_ID_GOTO_LINE);
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnSetFindCommandEvent, this, TOOL_ID_SET_FIND_STRING); // CTRL-E
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnFindCommandEvent, this, TOOL_ID_FIND); // CTRL-F
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnFindCommandEvent, this, TOOL_ID_FIND_ALL); // CTRL-SHIFT-F
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnCycleResultCommandEvent, this, TOOL_ID_FIND_PREVIOUS); // CTRL-SHIFT-G
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnCycleResultCommandEvent, this, TOOL_ID_FIND_NEXT); // CTRL-G
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnToggleBookmark, this, TOOL_ID_BOOKMARK_TOOGLE);
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnPreviousBookmark, this, TOOL_ID_BOOKMARK_PREV);
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnNextBookmark, this, TOOL_ID_BOOKMARK_NEXT);
// m_TopFrame->Bind(wxEVT_CHAR_HOOK, &TopNotePanel::OnEscapeCharHook, this, -1);
// m_TopFrame->Bind(wxEVT_CHAR_HOOK, &TopNotePanel::OnEscapeCharHook, this);
tf.Bind(wxEVT_COMMAND_MENU_SELECTED, &TopNotePanel::OnToggleSelectedBreakpoint, this, TOOL_ID_TOGGLE_BREAKPOINT);
Bind(wxEVT_SIZE, &TopNotePanel::OnResizeEvent, this);
// hide search by default
ShowSearchBar(false);
MixConnect(this, &TopNotePanel::OnShowLocation, controller.GetSignals().OnShowLocation);
MixConnect(this, &TopNotePanel::OnRefreshSfcBreakpoints, controller.GetSignals().OnRefreshSfcBreakpoints);
MixConnect(this, &TopNotePanel::OnEditorCursorChanged, GetSignals().OnEditorCursorChanged);
controller.SetTopNotePanel(this);
// shouldn't call virtual in ctor ???
SetEditSFC(nil);
}
// dtor
virtual ~TopNotePanel()
{
uLog(DTOR, "TopNotePanel::DTOR");
Unbind(wxEVT_SIZE, &TopNotePanel::OnResizeEvent, this);
}
wxWindow* GetWxWindow(void) override {return this;}
EditorSignals& GetSignals(void) override {return m_TopNotebookImp.GetSignals();}
void RegisterCodeNavigator(LogicSignals &nav_signals) override
{
MixConnect(this, &TopNotePanel::OnShowLocation, nav_signals.OnShowLocation);
MixConnect(this, &TopNotePanel::OnShowMemory, nav_signals.OnShowMemory);
}
void ShowSFC(ISourceFileClass *sfc) override
{
m_TopNotebookImp.ShowSFC(sfc);
}
void HideSFC(ISourceFileClass *sfc, bool delete_f) override
{
m_TopNotebookImp.HideSFC(sfc, delete_f);
}
void HideAllSFCs(void) override
{
m_TopNotebookImp.HideAllSFCs();
}
void UnhighlightSFCs(void) override
{
m_Editor.RemoveAllHighlights();
m_Editor.ClearAnnotations();
}
bool CanQueryDaemon(void) const override
{
return m_TopNotebookImp.CanQueryDaemon();
}
bool SolveVar_ASYNC(const string &key, wxString &res) override // returns [cached_f]
{
return m_TopNotebookImp.SolveVar_ASYNC(key, res);
}
void SetSolvedVariable(const Collected &ce) override
{
m_TopNotebookImp.SetSolvedVariable(ce);
}
bool AddToWatches(const string &watch_name) override
{
return m_TopNotebookImp.AddToWatches(watch_name);
}
SearchBar& GetSearchBar(void) override
{
return m_SearchBar;
}
ISourceFileClass* GetEditSFC(void) const override
{
return m_TopNotebookImp.GetEditSFC();
}
void SetEditSFC(ISourceFileClass *sfc) override;
BookSplitter* GetSplitterTop(void) override {return m_SplitterTop.get();}
void EscapeKeyCallback(void) override;
void RequestStatusBarRefresh(void) override
{
MixDelay("statusbar_refresh", 100/*ms*/, this, &TopNotePanel::OnUpdateStatusBar);
}
IEditorCtrl& GetEditor(void) override
{
return m_Editor;
}
TopFrame& GetTopFrame(void) override
{
return m_Controller.GetTopFrame();
}
private:
// events
void OnShowLocation(const string shortname, int ln)
{
assert(!shortname.empty());
ISourceFileClass *sfc = m_Controller.GetSFC(shortname);
assert(sfc);
sfc->ShowNotebookPage(true);
m_Editor.ShowLine(ln, true/*focus?*/);
}
void OnShowMemory(const string key, const string val, const string type_s, const bool bin_data_f)
{
// relay (lame?)
m_Controller.GetSignals().OnShowMemory(CTX_WX, key, val, type_s, bin_data_f);
}
void OnEditorCursorChanged(int col, int row)
{
RequestStatusBarRefresh();
}
void OnRefreshSfcBreakpoints(ISourceFileClass *sfc, vector<int> bp_list)
{
uLog(BREAKPOINT_EDIT, "TopNotePanel::OnRefreshSfcBreakpoints(%zu breakpoints)", bp_list.size());
assert(sfc);
sfc->SetBreakpointLines(bp_list);
m_Editor.SetBreakpointLines(bp_list);
}
void OnResizeEvent(wxSizeEvent &e);
void OnGotoLineNumber(wxCommandEvent &e);
void OnToggleSelectedBreakpoint(wxCommandEvent &e);
void OnSaveFileMenu(wxCommandEvent &e)
{
m_Editor.SaveToDisk();
}
void OnRevertFileMenu(wxCommandEvent &e)
{
// caca
}
void OnSetFindCommandEvent(wxCommandEvent &e);
void OnFindCommandEvent(wxCommandEvent &e);
void OnCycleResultCommandEvent(wxCommandEvent &e);
void OnEscapeCharHook(wxKeyEvent &e);
void OnToggleBookmark(wxCommandEvent &e);
void OnPreviousBookmark(wxCommandEvent &e);
void OnNextBookmark(wxCommandEvent &e);
void OnUpdateStatusBar(void);
// functions
void ShowSearchBar(const bool f = true);
void CycleUserBookmark(const int &delta);
TopFrame &m_TopFrame;
Controller &m_Controller;
unique_ptr<BookSplitter> m_SplitterTop;
wxPanel m_TopPanel;
IEditorCtrl *m_EditorPtr;
IEditorCtrl &m_Editor;
TopNotebookImp m_TopNotebookImp;
SearchBar m_SearchBar;
wxStatusBar m_EditorStatusBar;
wxBoxSizer *m_VSizer;
};
//---- Show/Hide Search Bar ---------------------------------------------------
void TopNotePanel::ShowSearchBar(const bool f)
{
// use size_t to avoid compiler confusion
const bool is_shown_f = m_VSizer->IsShown(V_INDEX::SEARCHBAR);
// if state change
if (is_shown_f != f)
{ m_VSizer->Show(V_INDEX::SEARCHBAR, f);
m_VSizer->Layout();
}
// may crash (?)
// m_SearchBar.Reset();
}
//---- Set Edit SFC -----------------------------------------------------------
void TopNotePanel::SetEditSFC(ISourceFileClass *sfc)
{
m_Editor.LoadFromSFC(sfc);
const bool f = (sfc != nil);
m_VSizer->Show(V_INDEX::EDITOR1, f);
m_VSizer->Layout();
}
//---- On Resize event --------------------------------------------------------
void TopNotePanel::OnResizeEvent(wxSizeEvent &e)
{
RequestStatusBarRefresh();
e.Skip();
}
//---- On Update StatusBar ----------------------------------------------------
void TopNotePanel::OnUpdateStatusBar(void)
{
string status_strings[NUM_EDIT_STATUS_FIELDS];
ISourceFileClass *sfc = GetEditSFC();
if (sfc)
{ // cursor position
const iPoint pos = m_Editor.GetCursorPos();
const int ln = pos.y();
const int col = pos.x();
const int total_lines = m_Editor.GetTotalLines();
const bool writable_f = sfc->IsWritableFile();
const bool dirty_f = sfc->IsDirty();
status_strings[0] = xsprintf("line %d, column %d", ln, col);
status_strings[1] = xsprintf("%S: %d lines, %s %s", sfc->GetShortName(), total_lines, writable_f ? "r/w" : "READ-ONLY", dirty_f ? "DIRTY" : "clean");
// any search results
vector<SearchHit> hits;
const int result_ind = m_SearchBar.GetSearchStatus(hits/*&*/); // (search result NOT NECESSARILY in selected SFC)
if (result_ind != -1)
{ status_strings[3] = xsprintf("result %d / %zu", result_ind + 1, hits.size());
}
}
else
{ // repaint background or leaves smudge when no page shown - doesn't work?
// Refresh();
}
// set text fields
for (int i = 0; i < NUM_EDIT_STATUS_FIELDS; i++)
m_EditorStatusBar.SetStatusText(wxString(status_strings[i]), i);
}
//---- On Goto Line -----------------------------------------------------------
void TopNotePanel::OnGotoLineNumber(wxCommandEvent &e)
{
ISourceFileClass *sfc = GetEditSFC();
if (!sfc) return; // none selected?
const int max_ln = m_Editor.GetTotalLines();
int line_nbr = ::wxGetNumberFromUser(""/*message*/, "Goto Line:"/*prompt*/, "Goto Line Number", 0, 1/*min*/, max_ln, this/*parent*/);
if (line_nbr == -1) return; // canceled
m_Editor.ShowLine(line_nbr, true/*focus?*/);
}
//---- On Toggle Selected Breakpoint ------------------------------------------
// (only used on F9)
void TopNotePanel::OnToggleSelectedBreakpoint(wxCommandEvent &e)
{
ISourceFileClass *sfc = GetEditSFC();
if (!sfc) return; // no selected top tab?
const int ln = m_Editor.GetCursorPos().y();
if (ln == -1) return; // no selected line?
m_Controller.ToggleBreakpoint(*sfc, ln);
}
//---- On Set Find String command event ---------------------------------------
void TopNotePanel::OnSetFindCommandEvent(wxCommandEvent &e)
{
// e.Skip();
ISourceFileClass *sfc = GetEditSFC();
if (!sfc) return; // no selected top tab?
ShowSearchBar(true); // show
const string selection_s = m_Editor.GetUserSelection();
m_SearchBar.Reset(true, selection_s);
}
//---- On Keyboard/Menu CTRL-F command ----------------------------------------
void TopNotePanel::OnFindCommandEvent(wxCommandEvent &e)
{
// const int id = e.GetId();
// const bool find_all_f = (id == TOOL_ID_FIND_ALL);
// ISourceFileClass *sfc = GetEditSFC();
// if (!sfc) return; // no selected top tab?
ShowSearchBar(true); // show
m_SearchBar.Reset(true);
e.Skip();
}
//---- Escape Key Callback ----------------------------------------------------
void TopNotePanel::EscapeKeyCallback(void)
{
ShowSearchBar(false); // hide
m_SearchBar.Reset(false);
}
//---- On Keyboard/Menu CTRL-G-(shift) command --------------------------------
void TopNotePanel::OnCycleResultCommandEvent(wxCommandEvent &e)
{
const int id = e.GetId();
assert((id == TOOL_ID_FIND_PREVIOUS) || (id == TOOL_ID_FIND_NEXT));
const int delta = (id == TOOL_ID_FIND_PREVIOUS) ? -1 : 1;
m_SearchBar.CycleResultRelative(delta);
// e.Skip(); // not needed?
}
//---- On Toggle Bookmark -----------------------------------------------------
void TopNotePanel::OnToggleBookmark(wxCommandEvent &e)
{
ISourceFileClass *sfc = GetEditSFC();
if (!sfc) return; // no selected source
const int ln = m_Editor.GetCursorPos().y();
if (ln == -1) return; // no selected line?
#if 0
const bool f = sfc->HasLineMarker(ln, MARGIN_MARKER_T::USER_BOOKMARK);
uLog(BOOKMARK, "TopNotePanel::OnToggleBookmark(%s:%d) %c -> %c", sfc->GetShortName(), ln, f, !f);
sfc->SetLineMarker(ln, MARGIN_MARKER_T::USER_BOOKMARK, !f/*toggle*/);
#endif
}
//---- Cycle User Bookmark ----------------------------------------------------
void TopNotePanel::CycleUserBookmark(const int &delta)
{
uLog(BOOKMARK, "TopNotePanel::CycleUserBookmark(delta %d)", delta);
ISourceFileClass *selected_sfc = GetEditSFC();
if (!selected_sfc) return; // no selected source
const int selected_ln = m_Editor.GetCursorPos().y();
if (selected_ln == -1) return; // no selected line?
// add bookmarks from project sources
const vector<ISourceFileClass*> sfc_list = m_Controller.GetSFCInstances();
#if 0
vector<Bookmark> bmks;
// for (ISourceFileClass *sfc : sfc_list) sfc->AddUserBookmarks(bmks/*&*/);
if (bmks.empty()) return; // no bookmarks
for (size_t i = 0; i < bmks.size(); i++)
uLog(BOOKMARK, " [%d] %s:%d", i, bmks[i].Name(), bmks[i].Line());
const string fn = selected_sfc->GetShortName();
int ind = -1;
bool fn_crossed_f = false;
for (size_t i = 0; i < bmks.size(); i++)
{
const auto &it = bmks[i];
const bool fn_f = (it.Name() == fn);
if (!fn_f && fn_crossed_f)
{ // new sfc but source file was crossed earlier
ind = i;
break;
}
fn_crossed_f |= fn_f;
if (fn_f && (it.Line() >= selected_ln))
{ // sfc match, line equal or greater
ind = i;
break;
}
}
if (ind == -1)
{
uLog(BOOKMARK, "no bmk index found, get maxima");
ind = (delta > 0) ? 0 : (bmks.size() - 1);
}
else
{ uLog(BOOKMARK, "found bmk index %d (%s:%d)", ind, bmks[ind].Name(), bmks[ind].Line());
/*
if ((delta < 0) || selected_sfc->HasLineMarker(selected_ln, MARGIN_MARKER_T::USER_BOOKMARK)) // should show FIRST
{ ind = (ind + delta + bmks.size()) % bmks.size();
uLog(BOOKMARK, " bmk CYCLE");
}
*/
}
uLog(BOOKMARK, "new bmk index %d (%s:%d)", ind, bmks[ind].Name(), bmks[ind].Line());
ISourceFileClass *sfc = m_Controller.GetSFC(bmks[ind].Name());
assert(sfc);
// TOO MUCH CRAP?
sfc->ShowNotebookPage(true);
// sfc->ShowLine(bmks[ind].Line(), true/*center*/);
// sfc->SetFocus();
#endif
}
//---- On Previous Bookmark ---------------------------------------------------
void TopNotePanel::OnPreviousBookmark(wxCommandEvent &e)
{
CycleUserBookmark(-1/*prev*/);
}
//---- On Next Bookmark -------------------------------------------------------
void TopNotePanel::OnNextBookmark(wxCommandEvent &e)
{
CycleUserBookmark(1/*next*/);
}
//---- INSTANTIATE ------------------------------------------------------------
// static
ITopNotePanel* ITopNotePanel::Create(wxWindow *parent, int id, TopFrame &tf, Controller &controller)
{
return new TopNotePanel(parent, id, tf, controller);
}
//////////////////////////////////////////
//---- Request Solve Variable -------------------------------------------------
bool TopNotebookImp::SolveVar_ASYNC(const string &key, wxString &res)
{
res.clear();
// uMsg("TopNotebookImp::SolveVar(%S)", key);
if (m_Controller.GetDaemonTick() != m_LastDaemonTick)
{ m_LastDaemonTick = m_Controller.GetDaemonTick();
// uLog(WARNING, "var cache FLUSHED (had %zu entries)", m_VarCache.size());
m_VarCache.clear();
m_VarRequestedSet.clear();
}
const bool chached_f = (m_VarCache.count(key) > 0);
if (chached_f)
{ // get cached
const Collected &ce = m_VarCache.at(key);
string k = ce.GetDecoratedKey();
string v = ce.GetDecoratedVal();
res = wxString::Format("%s = %s", wxString(k), wxString(v));
}
else
{ // not cached
if (m_VarRequestedSet.count(key) > 0) return false; // already requested
// request
bool ok = m_TopFrame.SolveVar_ASYNC(VAR_SOLVE_REQUESTER::SOLVE_REQUESTER_HOVER, key);
if (ok) m_VarRequestedSet.insert(key);
else uErr("TopNotebookImp::SolveVar_ASYNC() failed");
}
return chached_f;
}
//---- Receive Solved Variable ------------------------------------------------
void TopNotebookImp::SetSolvedVariable(const Collected &ce)
{
const string key = ce.GetKey();
// uMsg("solved variable %S = %s", key, ce.GetVal());
m_VarCache[key] = ce;
m_VarRequestedSet.erase(key);
}
//---- Add To Watches ---------------------------------------------------------
bool TopNotebookImp::AddToWatches(const string &watch_name)
{
WatchBag &watches = m_TopFrame.GetWatchBag();
return watches.Add(watch_name);
}
// nada mas
| 25.459963 | 151 | 0.672469 | [
"vector"
] |
e41c421367afe230b5406aa74021b945b93c8d57 | 58,420 | cc | C++ | y2020/control_loops/superstructure/superstructure_lib_test.cc | AustinSchuh/971-Robot-Code | 99abc66fd2d899c0bdab338dc6f57dc5def9be8d | [
"Apache-2.0"
] | 39 | 2021-06-18T03:22:30.000Z | 2022-03-21T15:23:43.000Z | y2020/control_loops/superstructure/superstructure_lib_test.cc | AustinSchuh/971-Robot-Code | 99abc66fd2d899c0bdab338dc6f57dc5def9be8d | [
"Apache-2.0"
] | 10 | 2021-06-18T03:22:19.000Z | 2022-03-18T22:14:15.000Z | y2020/control_loops/superstructure/superstructure_lib_test.cc | AustinSchuh/971-Robot-Code | 99abc66fd2d899c0bdab338dc6f57dc5def9be8d | [
"Apache-2.0"
] | 4 | 2021-08-19T19:20:04.000Z | 2022-03-08T07:33:18.000Z | #include <unistd.h>
#include <chrono>
#include <memory>
#include "aos/events/logging/log_reader.h"
#include "aos/events/logging/log_writer.h"
#include "aos/network/team_number.h"
#include "frc971/control_loops/capped_test_plant.h"
#include "frc971/control_loops/control_loop_test.h"
#include "frc971/control_loops/position_sensor_sim.h"
#include "frc971/control_loops/team_number_test_environment.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "y2020/constants.h"
#include "y2020/control_loops/superstructure/accelerator/accelerator_plant.h"
#include "y2020/control_loops/superstructure/finisher/finisher_plant.h"
#include "y2020/control_loops/superstructure/hood/hood_plant.h"
#include "y2020/control_loops/superstructure/intake/intake_plant.h"
#include "y2020/control_loops/superstructure/superstructure.h"
DEFINE_string(output_file, "",
"If set, logs all channels to the provided logfile.");
DEFINE_string(replay_logfile, "external/superstructure_replay/",
"Name of the logfile to read from and replay.");
DEFINE_string(config, "y2020/config.json",
"Name of the config file to replay using.");
namespace y2020 {
namespace control_loops {
namespace superstructure {
namespace testing {
namespace {
constexpr double kNoiseScalar = 0.01;
} // namespace
namespace chrono = ::std::chrono;
using ::aos::monotonic_clock;
using ::frc971::CreateProfileParameters;
using ::frc971::control_loops::CappedTestPlant;
using ::frc971::control_loops::
CreateStaticZeroingSingleDOFProfiledSubsystemGoal;
using ::frc971::control_loops::PositionSensorSimulator;
using ::frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemGoal;
typedef ::frc971::control_loops::drivetrain::Status DrivetrainStatus;
typedef Superstructure::AbsoluteEncoderSubsystem AbsoluteEncoderSubsystem;
typedef Superstructure::AbsoluteAndAbsoluteEncoderSubsystem
AbsoluteAndAbsoluteEncoderSubsystem;
typedef Superstructure::PotAndAbsoluteEncoderSubsystem
PotAndAbsoluteEncoderSubsystem;
class FlywheelPlant : public StateFeedbackPlant<2, 1, 1> {
public:
explicit FlywheelPlant(StateFeedbackPlant<2, 1, 1> &&other, double bemf,
double resistance)
: StateFeedbackPlant<2, 1, 1>(::std::move(other)),
bemf_(bemf),
resistance_(resistance) {}
void CheckU(const Eigen::Matrix<double, 1, 1> &U) override {
EXPECT_LE(U(0, 0), U_max(0, 0) + 0.00001 + voltage_offset_);
EXPECT_GE(U(0, 0), U_min(0, 0) - 0.00001 + voltage_offset_);
}
double motor_current(const Eigen::Matrix<double, 1, 1> U) const {
return (U(0) - X(1) / bemf_) / resistance_;
}
double battery_current(const Eigen::Matrix<double, 1, 1> U) const {
return motor_current(U) * U(0) / 12.0;
}
double voltage_offset() const { return voltage_offset_; }
void set_voltage_offset(double voltage_offset) {
voltage_offset_ = voltage_offset;
}
private:
double voltage_offset_ = 0.0;
double bemf_;
double resistance_;
};
// Class which simulates the superstructure and sends out queue messages with
// the position.
class SuperstructureSimulation {
public:
SuperstructureSimulation(::aos::EventLoop *event_loop, chrono::nanoseconds dt)
: event_loop_(event_loop),
dt_(dt),
superstructure_position_sender_(
event_loop_->MakeSender<Position>("/superstructure")),
superstructure_status_fetcher_(
event_loop_->MakeFetcher<Status>("/superstructure")),
superstructure_output_fetcher_(
event_loop_->MakeFetcher<Output>("/superstructure")),
hood_plant_(new CappedTestPlant(hood::MakeHoodPlant())),
hood_encoder_(
constants::GetValues()
.hood.zeroing_constants.one_revolution_distance,
constants::GetValues()
.hood.zeroing_constants.single_turn_one_revolution_distance),
intake_plant_(new CappedTestPlant(intake::MakeIntakePlant())),
intake_encoder_(constants::GetValues()
.intake.zeroing_constants.one_revolution_distance),
turret_plant_(new CappedTestPlant(turret::MakeTurretPlant())),
turret_encoder_(constants::GetValues()
.turret.subsystem_params.zeroing_constants
.one_revolution_distance),
accelerator_left_plant_(
new FlywheelPlant(accelerator::MakeAcceleratorPlant(),
accelerator::kBemf, accelerator::kResistance)),
accelerator_right_plant_(
new FlywheelPlant(accelerator::MakeAcceleratorPlant(),
accelerator::kBemf, accelerator::kResistance)),
finisher_plant_(new FlywheelPlant(finisher::MakeFinisherPlant(),
finisher::kBemf,
finisher::kResistance)) {
InitializeHoodPosition(constants::Values::kHoodRange().upper);
InitializeIntakePosition(constants::Values::kIntakeRange().upper);
InitializeTurretPosition(constants::Values::kTurretRange().middle());
phased_loop_handle_ = event_loop_->AddPhasedLoop(
[this](int) {
// Skip this the first time.
if (!first_) {
Simulate();
}
first_ = false;
SendPositionMessage();
},
dt);
}
void InitializeHoodPosition(double start_pos) {
hood_plant_->mutable_X(0, 0) = start_pos;
hood_plant_->mutable_X(1, 0) = 0.0;
hood_encoder_.Initialize(
start_pos, kNoiseScalar, 0.0,
constants::GetValues()
.hood.zeroing_constants.measured_absolute_position,
constants::GetValues()
.hood.zeroing_constants.single_turn_measured_absolute_position);
}
void InitializeIntakePosition(double start_pos) {
intake_plant_->mutable_X(0, 0) = start_pos;
intake_plant_->mutable_X(1, 0) = 0.0;
intake_encoder_.Initialize(
start_pos, kNoiseScalar, 0.0,
constants::GetValues()
.intake.zeroing_constants.measured_absolute_position);
}
void InitializeTurretPosition(double start_pos) {
turret_plant_->mutable_X(0, 0) = start_pos;
turret_plant_->mutable_X(1, 0) = 0.0;
turret_encoder_.Initialize(start_pos, kNoiseScalar, 0.0,
constants::GetValues()
.turret.subsystem_params.zeroing_constants
.measured_absolute_position);
}
flatbuffers::Offset<ShooterPosition> shooter_pos_offset(
ShooterPositionBuilder *builder) {
builder->add_theta_finisher(finisher_plant_->Y(0, 0));
builder->add_theta_accelerator_left(accelerator_left_plant_->Y(0, 0));
builder->add_theta_accelerator_right(accelerator_right_plant_->Y(0, 0));
return builder->Finish();
}
// Sends a queue message with the position of the superstructure.
void SendPositionMessage() {
::aos::Sender<Position>::Builder builder =
superstructure_position_sender_.MakeBuilder();
frc971::AbsoluteAndAbsolutePosition::Builder hood_builder =
builder.MakeBuilder<frc971::AbsoluteAndAbsolutePosition>();
flatbuffers::Offset<frc971::AbsoluteAndAbsolutePosition> hood_offset =
hood_encoder_.GetSensorValues(&hood_builder);
frc971::AbsolutePosition::Builder intake_builder =
builder.MakeBuilder<frc971::AbsolutePosition>();
flatbuffers::Offset<frc971::AbsolutePosition> intake_offset =
intake_encoder_.GetSensorValues(&intake_builder);
frc971::PotAndAbsolutePosition::Builder turret_builder =
builder.MakeBuilder<frc971::PotAndAbsolutePosition>();
flatbuffers::Offset<frc971::PotAndAbsolutePosition> turret_offset =
turret_encoder_.GetSensorValues(&turret_builder);
ShooterPosition::Builder shooter_builder =
builder.MakeBuilder<ShooterPosition>();
flatbuffers::Offset<ShooterPosition> shooter_offset =
shooter_pos_offset(&shooter_builder);
Position::Builder position_builder = builder.MakeBuilder<Position>();
position_builder.add_hood(hood_offset);
position_builder.add_intake_joint(intake_offset);
position_builder.add_turret(turret_offset);
position_builder.add_shooter(shooter_offset);
position_builder.add_intake_beambreak_triggered(
intake_beambreak_triggered_);
CHECK_EQ(builder.Send(position_builder.Finish()),
aos::RawSender::Error::kOk);
}
double hood_position() const { return hood_plant_->X(0, 0); }
double hood_velocity() const { return hood_plant_->X(1, 0); }
double intake_position() const { return intake_plant_->X(0, 0); }
double intake_velocity() const { return intake_plant_->X(1, 0); }
double turret_position() const { return turret_plant_->X(0, 0); }
double turret_velocity() const { return turret_plant_->X(1, 0); }
double accelerator_left_velocity() const {
return accelerator_left_plant_->X(1, 0);
}
double accelerator_right_velocity() const {
return accelerator_right_plant_->X(1, 0);
}
double finisher_velocity() const { return finisher_plant_->X(1, 0); }
// Simulates the superstructure for a single timestep.
void Simulate() {
const double last_hood_velocity = hood_velocity();
const double last_intake_velocity = intake_velocity();
const double last_turret_velocity = turret_velocity();
EXPECT_TRUE(superstructure_output_fetcher_.Fetch());
EXPECT_TRUE(superstructure_status_fetcher_.Fetch());
const double voltage_check_hood =
(static_cast<AbsoluteAndAbsoluteEncoderSubsystem::State>(
superstructure_status_fetcher_->hood()->state()) ==
AbsoluteAndAbsoluteEncoderSubsystem::State::RUNNING)
? constants::GetValues().hood.operating_voltage
: constants::GetValues().hood.zeroing_voltage;
EXPECT_NEAR(superstructure_output_fetcher_->hood_voltage(), 0.0,
voltage_check_hood);
const double voltage_check_intake =
(static_cast<AbsoluteEncoderSubsystem::State>(
superstructure_status_fetcher_->intake()->state()) ==
AbsoluteEncoderSubsystem::State::RUNNING)
? constants::GetValues().intake.operating_voltage
: constants::GetValues().intake.zeroing_voltage;
EXPECT_NEAR(superstructure_output_fetcher_->intake_joint_voltage(), 0.0,
voltage_check_intake);
const double voltage_check_turret =
(static_cast<PotAndAbsoluteEncoderSubsystem::State>(
superstructure_status_fetcher_->turret()->state()) ==
PotAndAbsoluteEncoderSubsystem::State::RUNNING)
? constants::GetValues().turret.subsystem_params.operating_voltage
: constants::GetValues().turret.subsystem_params.zeroing_voltage;
EXPECT_NEAR(superstructure_output_fetcher_->turret_voltage(), 0.0,
voltage_check_turret);
// Invert the friction model.
::Eigen::Matrix<double, 1, 1> hood_U;
hood_U << superstructure_output_fetcher_->hood_voltage() +
hood_plant_->voltage_offset();
::Eigen::Matrix<double, 1, 1> intake_U;
intake_U << superstructure_output_fetcher_->intake_joint_voltage() +
intake_plant_->voltage_offset();
// Invert the friction model.
const double turret_velocity_sign =
turret_plant_->X(1) * Superstructure::kTurretFrictionGain;
::Eigen::Matrix<double, 1, 1> turret_U;
turret_U << superstructure_output_fetcher_->turret_voltage() +
turret_plant_->voltage_offset() -
std::clamp(turret_velocity_sign,
-Superstructure::kTurretFrictionVoltageLimit,
Superstructure::kTurretFrictionVoltageLimit);
::Eigen::Matrix<double, 1, 1> accelerator_left_U;
accelerator_left_U
<< superstructure_output_fetcher_->accelerator_left_voltage() +
accelerator_left_plant_->voltage_offset();
// Confirm that we aren't drawing too much current.
CHECK_NEAR(accelerator_left_plant_->battery_current(accelerator_left_U),
0.0, 75.0);
::Eigen::Matrix<double, 1, 1> accelerator_right_U;
accelerator_right_U
<< superstructure_output_fetcher_->accelerator_right_voltage() +
accelerator_right_plant_->voltage_offset();
// Confirm that we aren't drawing too much current.
CHECK_NEAR(accelerator_right_plant_->battery_current(accelerator_right_U),
0.0, 75.0);
::Eigen::Matrix<double, 1, 1> finisher_U;
finisher_U << superstructure_output_fetcher_->finisher_voltage() +
finisher_plant_->voltage_offset();
// Confirm that we aren't drawing too much current. 2 motors -> twice the
// lumped current since our model can't tell them apart.
CHECK_NEAR(finisher_plant_->battery_current(finisher_U), 0.0, 200.0);
hood_plant_->Update(hood_U);
intake_plant_->Update(intake_U);
turret_plant_->Update(turret_U);
accelerator_left_plant_->Update(accelerator_left_U);
accelerator_right_plant_->Update(accelerator_right_U);
finisher_plant_->Update(finisher_U);
const double position_hood = hood_plant_->Y(0, 0);
const double position_intake = intake_plant_->Y(0, 0);
const double position_turret = turret_plant_->Y(0, 0);
hood_encoder_.MoveTo(position_hood);
intake_encoder_.MoveTo(position_intake);
turret_encoder_.MoveTo(position_turret);
EXPECT_GE(position_hood, constants::Values::kHoodRange().lower_hard);
EXPECT_LE(position_hood, constants::Values::kHoodRange().upper_hard);
EXPECT_GE(position_intake, constants::Values::kIntakeRange().lower_hard);
EXPECT_LE(position_intake, constants::Values::kIntakeRange().upper_hard);
EXPECT_GE(position_turret, constants::Values::kTurretRange().lower_hard);
EXPECT_LE(position_turret, constants::Values::kTurretRange().upper_hard);
const double loop_time = ::aos::time::DurationInSeconds(dt_);
const double hood_acceleration =
(hood_velocity() - last_hood_velocity) / loop_time;
const double intake_acceleration =
(intake_velocity() - last_intake_velocity) / loop_time;
const double turret_acceleration =
(turret_velocity() - last_turret_velocity) / loop_time;
EXPECT_GE(peak_hood_acceleration_, hood_acceleration);
EXPECT_LE(-peak_hood_acceleration_, hood_acceleration);
EXPECT_GE(peak_hood_velocity_, hood_velocity());
EXPECT_LE(-peak_hood_velocity_, hood_velocity());
EXPECT_GE(peak_intake_acceleration_, intake_acceleration);
EXPECT_LE(-peak_intake_acceleration_, intake_acceleration);
EXPECT_GE(peak_intake_velocity_, intake_velocity());
EXPECT_LE(-peak_intake_velocity_, intake_velocity());
EXPECT_GE(peak_turret_acceleration_, turret_acceleration);
EXPECT_LE(-peak_turret_acceleration_, turret_acceleration);
EXPECT_GE(peak_turret_velocity_, turret_velocity());
EXPECT_LE(-peak_turret_velocity_, turret_velocity());
climber_voltage_ = superstructure_output_fetcher_->climber_voltage();
}
float climber_voltage() const { return climber_voltage_; }
void set_peak_hood_acceleration(double value) {
peak_hood_acceleration_ = value;
}
void set_peak_hood_velocity(double value) { peak_hood_velocity_ = value; }
void set_peak_intake_acceleration(double value) {
peak_intake_acceleration_ = value;
}
void set_peak_intake_velocity(double value) { peak_intake_velocity_ = value; }
void set_peak_turret_acceleration(double value) {
peak_turret_acceleration_ = value;
}
void set_peak_turret_velocity(double value) { peak_turret_velocity_ = value; }
void set_finisher_voltage_offset(double value) {
finisher_plant_->set_voltage_offset(value);
}
void set_intake_beambreak_triggered(bool triggered) {
intake_beambreak_triggered_ = triggered;
}
private:
::aos::EventLoop *event_loop_;
const chrono::nanoseconds dt_;
::aos::PhasedLoopHandler *phased_loop_handle_ = nullptr;
::aos::Sender<Position> superstructure_position_sender_;
::aos::Fetcher<Status> superstructure_status_fetcher_;
::aos::Fetcher<Output> superstructure_output_fetcher_;
bool first_ = true;
::std::unique_ptr<CappedTestPlant> hood_plant_;
PositionSensorSimulator hood_encoder_;
::std::unique_ptr<CappedTestPlant> intake_plant_;
PositionSensorSimulator intake_encoder_;
::std::unique_ptr<CappedTestPlant> turret_plant_;
PositionSensorSimulator turret_encoder_;
::std::unique_ptr<FlywheelPlant> accelerator_left_plant_;
::std::unique_ptr<FlywheelPlant> accelerator_right_plant_;
::std::unique_ptr<FlywheelPlant> finisher_plant_;
// The acceleration limits to check for while moving.
double peak_hood_acceleration_ = 1e10;
double peak_intake_acceleration_ = 1e10;
double peak_turret_acceleration_ = 1e10;
// The velocity limits to check for while moving.
double peak_hood_velocity_ = 1e10;
double peak_intake_velocity_ = 1e10;
double peak_turret_velocity_ = 1e10;
float climber_voltage_ = 0.0f;
bool intake_beambreak_triggered_ = false;
};
class SuperstructureTestEnvironment : public ::testing::Environment {
public:
void SetUp() override { constants::InitValues(); }
};
namespace {
const auto kTestEnv =
::testing::AddGlobalTestEnvironment(new SuperstructureTestEnvironment());
}
class SuperstructureTest : public ::frc971::testing::ControlLoopTest {
protected:
SuperstructureTest()
: ::frc971::testing::ControlLoopTest(
aos::configuration::ReadConfig("y2020/config.json"),
chrono::microseconds(5050)),
roborio_(aos::configuration::GetNode(configuration(), "roborio")),
test_event_loop_(MakeEventLoop("test", roborio_)),
superstructure_goal_fetcher_(
test_event_loop_->MakeFetcher<Goal>("/superstructure")),
superstructure_goal_sender_(
test_event_loop_->MakeSender<Goal>("/superstructure")),
superstructure_status_fetcher_(
test_event_loop_->MakeFetcher<Status>("/superstructure")),
superstructure_output_fetcher_(
test_event_loop_->MakeFetcher<Output>("/superstructure")),
superstructure_position_fetcher_(
test_event_loop_->MakeFetcher<Position>("/superstructure")),
drivetrain_status_sender_(
test_event_loop_->MakeSender<DrivetrainStatus>("/drivetrain")),
joystick_state_sender_(
test_event_loop_->MakeSender<aos::JoystickState>("/aos")),
superstructure_event_loop_(MakeEventLoop("superstructure", roborio_)),
superstructure_(superstructure_event_loop_.get()),
superstructure_plant_event_loop_(MakeEventLoop("plant", roborio_)),
superstructure_plant_(superstructure_plant_event_loop_.get(), dt()) {
set_team_id(::frc971::control_loops::testing::kTeamNumber);
if (!FLAGS_output_file.empty()) {
unlink(FLAGS_output_file.c_str());
logger_event_loop_ = MakeEventLoop("logger", roborio_);
logger_ = std::make_unique<aos::logger::Logger>(logger_event_loop_.get());
logger_->StartLoggingOnRun(FLAGS_output_file);
}
}
void VerifyNearGoal() {
superstructure_goal_fetcher_.Fetch();
superstructure_status_fetcher_.Fetch();
// Only check the goal if there is one.
if (superstructure_goal_fetcher_->has_hood()) {
EXPECT_NEAR(superstructure_goal_fetcher_->hood()->unsafe_goal(),
superstructure_status_fetcher_->hood()->position(), 0.001);
}
if (superstructure_goal_fetcher_->has_intake()) {
EXPECT_NEAR(superstructure_goal_fetcher_->intake()->unsafe_goal(),
superstructure_status_fetcher_->intake()->position(), 0.001);
}
if (superstructure_goal_fetcher_->has_turret()) {
EXPECT_NEAR(superstructure_goal_fetcher_->turret()->unsafe_goal(),
superstructure_status_fetcher_->turret()->position(), 0.001);
}
if (superstructure_goal_fetcher_->has_shooter()) {
EXPECT_NEAR(
superstructure_goal_fetcher_->shooter()->velocity_accelerator(),
superstructure_status_fetcher_->shooter()
->accelerator_left()
->angular_velocity(),
0.001);
EXPECT_NEAR(
superstructure_goal_fetcher_->shooter()->velocity_accelerator(),
superstructure_status_fetcher_->shooter()
->accelerator_right()
->angular_velocity(),
0.001);
EXPECT_NEAR(superstructure_goal_fetcher_->shooter()->velocity_finisher(),
superstructure_status_fetcher_->shooter()
->finisher()
->angular_velocity(),
0.001);
EXPECT_NEAR(
superstructure_goal_fetcher_->shooter()->velocity_accelerator(),
superstructure_status_fetcher_->shooter()
->accelerator_left()
->avg_angular_velocity(),
0.001);
EXPECT_NEAR(
superstructure_goal_fetcher_->shooter()->velocity_accelerator(),
superstructure_status_fetcher_->shooter()
->accelerator_right()
->avg_angular_velocity(),
0.001);
EXPECT_NEAR(superstructure_goal_fetcher_->shooter()->velocity_finisher(),
superstructure_status_fetcher_->shooter()
->finisher()
->avg_angular_velocity(),
0.001);
}
EXPECT_FALSE(superstructure_status_fetcher_->has_subsystems_not_ready());
}
void CheckIfZeroed() {
superstructure_status_fetcher_.Fetch();
ASSERT_TRUE(superstructure_status_fetcher_.get()->zeroed());
}
void WaitUntilZeroed() {
int i = 0;
do {
i++;
RunFor(dt());
superstructure_status_fetcher_.Fetch();
// 2 Seconds
ASSERT_LE(i, 2.0 / ::aos::time::DurationInSeconds(dt()));
// Since there is a delay when sending running, make sure we have a
// status before checking it.
} while (superstructure_status_fetcher_.get() == nullptr ||
!superstructure_status_fetcher_.get()->zeroed());
}
// Method for testing the intake_roller_voltage
void TestIntakeRollerVoltage(const float roller_voltage,
const float roller_speed_compensation,
const bool shooting,
const double expected_voltage) {
SetEnabled(true);
{
auto builder = superstructure_goal_sender_.MakeBuilder();
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_roller_voltage(roller_voltage);
goal_builder.add_roller_speed_compensation(roller_speed_compensation);
goal_builder.add_shooting(shooting);
ASSERT_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
RunFor(chrono::seconds(1));
superstructure_output_fetcher_.Fetch();
ASSERT_TRUE(superstructure_output_fetcher_.get() != nullptr);
EXPECT_EQ(superstructure_output_fetcher_->intake_roller_voltage(),
expected_voltage);
}
void StartSendingFinisherGoals() {
test_event_loop_->AddPhasedLoop(
[this](int) {
auto builder = superstructure_goal_sender_.MakeBuilder();
auto shooter_goal_builder = builder.MakeBuilder<ShooterGoal>();
shooter_goal_builder.add_velocity_finisher(finisher_goal_);
const auto shooter_goal_offset = shooter_goal_builder.Finish();
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_shooter(shooter_goal_offset);
builder.CheckOk(builder.Send(goal_builder.Finish()));
},
dt());
}
// Sets the finisher velocity goal (radians/s)
void SetFinisherGoalAfter(const double velocity_finisher,
const monotonic_clock::duration time_offset) {
test_event_loop_
->AddTimer(
[this, velocity_finisher] { finisher_goal_ = velocity_finisher; })
->Setup(test_event_loop_->monotonic_now() + time_offset);
}
// Simulates the friction of a ball in the flywheel
void ApplyFrictionToFinisherAfter(
const double voltage_offset, const bool ball_in_finisher,
const monotonic_clock::duration time_offset) {
test_event_loop_
->AddTimer([this, voltage_offset, ball_in_finisher] {
superstructure_plant_.set_finisher_voltage_offset(voltage_offset);
ball_in_finisher_ = ball_in_finisher;
})
->Setup(test_event_loop_->monotonic_now() + time_offset);
test_event_loop_
->AddTimer(
[this] { superstructure_plant_.set_finisher_voltage_offset(0); })
->Setup(test_event_loop_->monotonic_now() + time_offset +
chrono::seconds(1));
}
const aos::Node *const roborio_;
::std::unique_ptr<::aos::EventLoop> test_event_loop_;
::aos::Fetcher<Goal> superstructure_goal_fetcher_;
::aos::Sender<Goal> superstructure_goal_sender_;
::aos::Fetcher<Status> superstructure_status_fetcher_;
::aos::Fetcher<Output> superstructure_output_fetcher_;
::aos::Fetcher<Position> superstructure_position_fetcher_;
::aos::Sender<DrivetrainStatus> drivetrain_status_sender_;
::aos::Sender<aos::JoystickState> joystick_state_sender_;
// Create a control loop and simulation.
::std::unique_ptr<::aos::EventLoop> superstructure_event_loop_;
Superstructure superstructure_;
::std::unique_ptr<::aos::EventLoop> superstructure_plant_event_loop_;
SuperstructureSimulation superstructure_plant_;
std::unique_ptr<aos::EventLoop> logger_event_loop_;
std::unique_ptr<aos::logger::Logger> logger_;
double finisher_goal_ = 0;
bool ball_in_finisher_ = false;
};
// Tests that the superstructure does nothing when the goal is to remain
// still.
TEST_F(SuperstructureTest, DoesNothing) {
SetEnabled(true);
superstructure_plant_.InitializeHoodPosition(
constants::Values::kHoodRange().middle());
superstructure_plant_.InitializeIntakePosition(
constants::Values::kIntakeRange().middle());
WaitUntilZeroed();
{
auto builder = superstructure_goal_sender_.MakeBuilder();
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
hood_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kHoodRange().middle());
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
intake_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kIntakeRange().middle());
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
turret_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kTurretRange().middle() + 1.0);
flatbuffers::Offset<ShooterGoal> shooter_offset =
CreateShooterGoal(*builder.fbb(), 0.0, 0.0);
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_hood(hood_offset);
goal_builder.add_intake(intake_offset);
goal_builder.add_turret(turret_offset);
goal_builder.add_shooter(shooter_offset);
ASSERT_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
RunFor(chrono::seconds(10));
VerifyNearGoal();
EXPECT_TRUE(superstructure_output_fetcher_.Fetch());
}
// Tests that loops can reach a goal.
TEST_F(SuperstructureTest, ReachesGoal) {
SetEnabled(true);
// Set a reasonable goal.
superstructure_plant_.InitializeHoodPosition(
constants::Values::kHoodRange().middle());
superstructure_plant_.InitializeIntakePosition(
constants::Values::kIntakeRange().middle());
WaitUntilZeroed();
{
auto builder = superstructure_goal_sender_.MakeBuilder();
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
hood_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kHoodRange().upper,
CreateProfileParameters(*builder.fbb(), 1.0, 0.2));
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
intake_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kIntakeRange().upper,
CreateProfileParameters(*builder.fbb(), 1.0, 0.2));
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
turret_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kTurretRange().middle() + 1.0);
flatbuffers::Offset<ShooterGoal> shooter_offset =
CreateShooterGoal(*builder.fbb(), 300.0, 300.0);
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_hood(hood_offset);
goal_builder.add_intake(intake_offset);
goal_builder.add_turret(turret_offset);
goal_builder.add_shooter(shooter_offset);
ASSERT_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
// Give it a lot of time to get there.
RunFor(chrono::seconds(8));
VerifyNearGoal();
}
// Makes sure that the voltage on a motor is properly pulled back after
// saturation such that we don't get weird or bad (e.g. oscillating)
// behaviour.
TEST_F(SuperstructureTest, SaturationTest) {
SetEnabled(true);
// Zero it before we move.
WaitUntilZeroed();
{
auto builder = superstructure_goal_sender_.MakeBuilder();
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
hood_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kHoodRange().upper);
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
intake_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kIntakeRange().upper);
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
turret_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kTurretRange().middle() + 1.0);
flatbuffers::Offset<ShooterGoal> shooter_offset =
CreateShooterGoal(*builder.fbb(), 0.0, 0.0);
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_hood(hood_offset);
goal_builder.add_intake(intake_offset);
goal_builder.add_turret(turret_offset);
goal_builder.add_shooter(shooter_offset);
ASSERT_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
RunFor(chrono::seconds(8));
VerifyNearGoal();
// Try a low acceleration move with a high max velocity and verify the
// acceleration is capped like expected.
{
auto builder = superstructure_goal_sender_.MakeBuilder();
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
hood_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kHoodRange().lower,
CreateProfileParameters(*builder.fbb(), 20.0, 0.1));
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
intake_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kIntakeRange().lower,
CreateProfileParameters(*builder.fbb(), 20.0, 0.1));
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
turret_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kTurretRange().middle() + 1.0);
flatbuffers::Offset<ShooterGoal> shooter_offset =
CreateShooterGoal(*builder.fbb(), 0.0, 0.0);
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_hood(hood_offset);
goal_builder.add_intake(intake_offset);
goal_builder.add_turret(turret_offset);
goal_builder.add_shooter(shooter_offset);
ASSERT_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
superstructure_plant_.set_peak_hood_velocity(23.0);
// 30 hz sin wave on the hood causes acceleration to be ignored.
superstructure_plant_.set_peak_hood_acceleration(5.5);
superstructure_plant_.set_peak_intake_velocity(23.0);
superstructure_plant_.set_peak_intake_acceleration(0.2);
superstructure_plant_.set_peak_turret_velocity(23.0);
superstructure_plant_.set_peak_turret_acceleration(6.0);
// Intake needs over 9 seconds to reach the goal
RunFor(chrono::seconds(10));
VerifyNearGoal();
}
// Tests the shooter can spin up correctly.
TEST_F(SuperstructureTest, SpinUp) {
SetEnabled(true);
superstructure_plant_.InitializeHoodPosition(
constants::Values::kHoodRange().upper);
superstructure_plant_.InitializeIntakePosition(
constants::Values::kIntakeRange().upper);
WaitUntilZeroed();
{
auto builder = superstructure_goal_sender_.MakeBuilder();
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
hood_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kHoodRange().upper,
CreateProfileParameters(*builder.fbb(), 1.0, 0.2));
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
intake_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kIntakeRange().upper,
CreateProfileParameters(*builder.fbb(), 1.0, 0.2));
ShooterGoal::Builder shooter_builder = builder.MakeBuilder<ShooterGoal>();
// Start up the accelerator and make sure both run.
shooter_builder.add_velocity_accelerator(200.0);
shooter_builder.add_velocity_finisher(200.0);
flatbuffers::Offset<ShooterGoal> shooter_offset = shooter_builder.Finish();
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_hood(hood_offset);
goal_builder.add_intake(intake_offset);
goal_builder.add_shooter(shooter_offset);
goal_builder.add_shooting(true);
ASSERT_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
// In the beginning, the finisher and accelerator should not be ready
test_event_loop_
->AddTimer([&]() {
ASSERT_TRUE(superstructure_status_fetcher_.Fetch());
ASSERT_TRUE(superstructure_status_fetcher_->has_subsystems_not_ready());
const auto subsystems_not_ready =
superstructure_status_fetcher_->subsystems_not_ready();
ASSERT_EQ(subsystems_not_ready->size(), 2);
EXPECT_TRUE((subsystems_not_ready->Get(0) == Subsystem::FINISHER) !=
(subsystems_not_ready->Get(1) == Subsystem::FINISHER));
EXPECT_TRUE((subsystems_not_ready->Get(0) == Subsystem::ACCELERATOR) !=
(subsystems_not_ready->Get(1) == Subsystem::ACCELERATOR));
})
->Setup(test_event_loop_->monotonic_now() + chrono::milliseconds(1));
// Give it a lot of time to get there.
RunFor(chrono::seconds(8));
VerifyNearGoal();
{
auto builder = superstructure_goal_sender_.MakeBuilder();
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
hood_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kHoodRange().upper,
CreateProfileParameters(*builder.fbb(), 1.0, 0.2));
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
intake_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kIntakeRange().upper,
CreateProfileParameters(*builder.fbb(), 1.0, 0.2));
flatbuffers::Offset<ShooterGoal> shooter_offset =
CreateShooterGoal(*builder.fbb(), 0.0, 0.0);
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_hood(hood_offset);
goal_builder.add_intake(intake_offset);
goal_builder.add_shooter(shooter_offset);
ASSERT_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
// Give it a lot of time to get there.
RunFor(chrono::seconds(25));
VerifyNearGoal();
}
// Tests that the loop zeroes when run for a while without a goal.
TEST_F(SuperstructureTest, ZeroNoGoal) {
SetEnabled(true);
WaitUntilZeroed();
RunFor(chrono::seconds(2));
EXPECT_EQ(AbsoluteAndAbsoluteEncoderSubsystem::State::RUNNING,
superstructure_.hood().state());
EXPECT_EQ(AbsoluteEncoderSubsystem::State::RUNNING,
superstructure_.intake_joint().state());
EXPECT_EQ(PotAndAbsoluteEncoderSubsystem::State::RUNNING,
superstructure_.turret().state());
}
// Tests that running disabled works
TEST_F(SuperstructureTest, DisableTest) {
RunFor(chrono::seconds(2));
CheckIfZeroed();
}
// Tests that the climber passes through per the design.
TEST_F(SuperstructureTest, Climber) {
SetEnabled(true);
// Set a reasonable goal.
WaitUntilZeroed();
{
auto builder = superstructure_goal_sender_.MakeBuilder();
// Since there is a turret lockout, we need to set a turret goal...
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
turret_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), M_PI / 2.0);
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_climber_voltage(-10.0);
goal_builder.add_turret(turret_offset);
ASSERT_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
// The turret needs to move out of the way first. This takes some time.
RunFor(chrono::milliseconds(100));
EXPECT_EQ(superstructure_plant_.climber_voltage(), 0.0);
// Now, we should be far enough that it should work.
RunFor(chrono::seconds(10));
EXPECT_EQ(superstructure_plant_.climber_voltage(), -10.0);
{
auto builder = superstructure_goal_sender_.MakeBuilder();
// Since there is a turret lockout, we need to set a turret goal...
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
turret_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), M_PI / 2.0);
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_climber_voltage(10.0);
goal_builder.add_turret(turret_offset);
ASSERT_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
RunFor(chrono::seconds(1));
// And forwards too.
EXPECT_EQ(superstructure_plant_.climber_voltage(), 10.0);
VerifyNearGoal();
}
// Tests that preserializing balls works.
TEST_F(SuperstructureTest, Preserializing) {
SetEnabled(true);
// Set a reasonable goal.
WaitUntilZeroed();
{
auto builder = superstructure_goal_sender_.MakeBuilder();
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_intake_preloading(true);
builder.CheckOk(builder.Send(goal_builder.Finish()));
}
superstructure_plant_.set_intake_beambreak_triggered(false);
// Give it time to stabilize.
RunFor(chrono::seconds(1));
// Preloads balls.
superstructure_output_fetcher_.Fetch();
ASSERT_TRUE(superstructure_output_fetcher_.get() != nullptr);
EXPECT_EQ(superstructure_output_fetcher_->feeder_voltage(), 12.0);
EXPECT_EQ(superstructure_output_fetcher_->washing_machine_spinner_voltage(),
5.0);
VerifyNearGoal();
superstructure_plant_.set_intake_beambreak_triggered(true);
// Give it time to stabilize.
RunFor(chrono::seconds(1));
// Stops preloading balls once one ball is in place
superstructure_output_fetcher_.Fetch();
ASSERT_TRUE(superstructure_output_fetcher_.get() != nullptr);
EXPECT_EQ(superstructure_output_fetcher_->feeder_voltage(), 0.0);
EXPECT_EQ(superstructure_output_fetcher_->washing_machine_spinner_voltage(),
0.0);
VerifyNearGoal();
}
// Makes sure that a negative number is not added to the to the
// roller_voltage
TEST_F(SuperstructureTest, NegativeRollerSpeedCompensation) {
constexpr float kRollerVoltage = 12.0f;
TestIntakeRollerVoltage(kRollerVoltage, -10.0f, false, kRollerVoltage);
}
// Makes sure that intake_roller_voltage is correctly being calculated
// based on the velocity when the roller_speed_compensation is positive
TEST_F(SuperstructureTest, PositiveRollerSpeedCompensation) {
constexpr float kRollerVoltage = 12.0f;
constexpr float kRollerSpeedCompensation = 10.0f;
TestIntakeRollerVoltage(kRollerVoltage, kRollerSpeedCompensation, false,
kRollerVoltage + (superstructure_.robot_speed() *
kRollerSpeedCompensation));
}
// Makes sure that the intake_roller_voltage is 3.0
// when the robot should be shooting balls (after the hood, turret, and
// shooter at at the goal)
TEST_F(SuperstructureTest, WhenShooting) {
TestIntakeRollerVoltage(0.0f, 0.0f, true, 3.0);
}
// Tests that we detect that a ball was shot whenever the average angular
// velocity is lower than a certain threshold compared to the goal.
TEST_F(SuperstructureTest, BallsShot) {
SetEnabled(true);
WaitUntilZeroed();
int balls_shot = 0;
// When there is a ball in the flywheel, the finisher velocity should drop
// below the goal
bool finisher_velocity_below_goal = false;
StartSendingFinisherGoals();
test_event_loop_->AddPhasedLoop(
[&](int) {
ASSERT_TRUE(superstructure_status_fetcher_.Fetch());
const double finisher_velocity =
superstructure_status_fetcher_->shooter()
->finisher()
->angular_velocity();
const double finisher_velocity_dip = finisher_goal_ - finisher_velocity;
if (ball_in_finisher_ &&
finisher_velocity_dip >=
shooter::Shooter::kVelocityToleranceFinisher) {
finisher_velocity_below_goal = true;
}
if (ball_in_finisher_ && finisher_velocity_below_goal &&
finisher_velocity_dip <
shooter::Shooter::kVelocityToleranceFinisher) {
ball_in_finisher_ = false;
finisher_velocity_below_goal = false;
balls_shot++;
LOG(INFO) << "Shot a ball at " << test_event_loop_->monotonic_now();
}
// Since here we are calculating the dip from the goal instead of the
// local maximum, the shooter could have calculated that a ball was shot
// slightly before we did if the local maximum was slightly below the
// goal.
if (superstructure_status_fetcher_->shooter()->balls_shot() !=
balls_shot) {
EXPECT_EQ(superstructure_status_fetcher_->shooter()->balls_shot(),
balls_shot + 1)
<< ": Failed at " << test_event_loop_->monotonic_now();
EXPECT_LT(finisher_velocity_dip,
0.2 + shooter::Shooter::kVelocityToleranceFinisher)
<< ": Failed at " << test_event_loop_->monotonic_now();
}
},
dt());
constexpr int kFastShootingSpeed = 500;
constexpr int kSlowShootingSpeed = 300;
// Maximum (since it is negative) flywheel voltage offsets for simulating the
// friction of a ball at different finisher speeds.
// Slower speeds require a higher magnitude of voltage offset.
static constexpr double kFastSpeedVoltageOffsetWithBall = -3.1;
static constexpr double kSlowSpeedVoltageOffsetWithBall = -3.5;
SetFinisherGoalAfter(kFastShootingSpeed, chrono::seconds(1));
// Simulate shooting balls by applying friction to the finisher
ApplyFrictionToFinisherAfter(kFastSpeedVoltageOffsetWithBall, true,
chrono::seconds(3));
ApplyFrictionToFinisherAfter(kFastSpeedVoltageOffsetWithBall, true,
chrono::seconds(6));
SetFinisherGoalAfter(0, chrono::seconds(10));
SetFinisherGoalAfter(kFastShootingSpeed, chrono::seconds(15));
ApplyFrictionToFinisherAfter(kFastSpeedVoltageOffsetWithBall, true,
chrono::seconds(18));
ApplyFrictionToFinisherAfter(kFastSpeedVoltageOffsetWithBall, true,
chrono::seconds(21));
SetFinisherGoalAfter(kSlowShootingSpeed, chrono::seconds(25));
ApplyFrictionToFinisherAfter(kSlowSpeedVoltageOffsetWithBall, true,
chrono::seconds(28));
ApplyFrictionToFinisherAfter(kSlowSpeedVoltageOffsetWithBall, true,
chrono::seconds(31));
// This smaller decrease in velocity shouldn't be counted as a ball
ApplyFrictionToFinisherAfter(kSlowSpeedVoltageOffsetWithBall / 10.0, false,
chrono::seconds(34));
SetFinisherGoalAfter(kFastShootingSpeed, chrono::seconds(38));
ApplyFrictionToFinisherAfter(kFastSpeedVoltageOffsetWithBall, true,
chrono::seconds(41));
ApplyFrictionToFinisherAfter(kFastSpeedVoltageOffsetWithBall, true,
chrono::seconds(44));
// This slow positive voltage offset that speeds up the flywheel instead of
// slowing it down shouldn't be counted as a ball.
// We wouldn't expect a positive voltage offset of more than ~2 volts.
ApplyFrictionToFinisherAfter(1, false, chrono::seconds(47));
RunFor(chrono::seconds(50));
ASSERT_TRUE(superstructure_status_fetcher_.Fetch());
EXPECT_EQ(superstructure_status_fetcher_->shooter()->balls_shot(), 8);
}
class SuperstructureReplayTest : public ::testing::Test {
public:
SuperstructureReplayTest()
: reader_(aos::logger::SortParts(
aos::logger::FindLogs(FLAGS_replay_logfile))) {
aos::network::OverrideTeamNumber(971);
reader_.RemapLoggedChannel("/superstructure",
"y2020.control_loops.superstructure.Status");
reader_.RemapLoggedChannel("/superstructure",
"y2020.control_loops.superstructure.Output");
reader_.Register();
roborio_ = aos::configuration::GetNode(reader_.configuration(), "roborio");
superstructure_event_loop_ =
reader_.event_loop_factory()->MakeEventLoop("superstructure", roborio_);
superstructure_event_loop_->SkipTimingReport();
test_event_loop_ = reader_.event_loop_factory()->MakeEventLoop(
"superstructure_replay_test", roborio_);
drivetrain_status_sender_ =
test_event_loop_->MakeSender<DrivetrainStatus>("/drivetrain");
superstructure_status_fetcher_ =
test_event_loop_->MakeFetcher<Status>("/superstructure");
if (!FLAGS_output_file.empty()) {
unlink(FLAGS_output_file.c_str());
logger_event_loop_ =
reader_.event_loop_factory()->MakeEventLoop("logger", roborio_);
logger_ = std::make_unique<aos::logger::Logger>(logger_event_loop_.get());
logger_->StartLoggingOnRun(FLAGS_output_file);
}
}
aos::logger::LogReader reader_;
const aos::Node *roborio_;
std::unique_ptr<aos::EventLoop> superstructure_event_loop_;
std::unique_ptr<aos::EventLoop> test_event_loop_;
std::unique_ptr<aos::EventLoop> logger_event_loop_;
std::unique_ptr<aos::logger::Logger> logger_;
aos::Sender<DrivetrainStatus> drivetrain_status_sender_;
aos::Fetcher<Status> superstructure_status_fetcher_;
};
// Tests that balls_shot is updated correctly with a real log.
TEST_F(SuperstructureReplayTest, BallsShotReplay) {
Superstructure superstructure(superstructure_event_loop_.get());
constexpr double kShotAngle = 1.0;
constexpr double kShotDistance = 2.5;
const auto target = turret::OuterPortPose(aos::Alliance::kRed);
// There was no target when this log was taken so send a position within range
// of the interpolation table.
test_event_loop_->AddPhasedLoop(
[&](int) {
auto builder = drivetrain_status_sender_.MakeBuilder();
const auto localizer_offset =
builder
.MakeBuilder<
frc971::control_loops::drivetrain::LocalizerState>()
.Finish();
auto drivetrain_status_builder =
builder.MakeBuilder<DrivetrainStatus>();
// Set the robot up at kShotAngle off from the target, kShotDistance
// away.
drivetrain_status_builder.add_x(target.abs_pos().x() +
std::cos(kShotAngle) * kShotDistance);
drivetrain_status_builder.add_y(target.abs_pos().y() +
std::sin(kShotAngle) * kShotDistance);
drivetrain_status_builder.add_localizer(localizer_offset);
builder.CheckOk(builder.Send(drivetrain_status_builder.Finish()));
},
frc971::controls::kLoopFrequency);
reader_.event_loop_factory()->Run();
ASSERT_TRUE(superstructure_status_fetcher_.Fetch());
EXPECT_EQ(superstructure_status_fetcher_->shooter()->balls_shot(), 3);
}
class SuperstructureAllianceTest
: public SuperstructureTest,
public ::testing::WithParamInterface<aos::Alliance> {
protected:
void SendAlliancePosition() {
auto builder = joystick_state_sender_.MakeBuilder();
aos::JoystickState::Builder joystick_builder =
builder.MakeBuilder<aos::JoystickState>();
joystick_builder.add_alliance(GetParam());
ASSERT_EQ(builder.Send(joystick_builder.Finish()),
aos::RawSender::Error::kOk);
}
};
// Tests that the turret switches to auto-aiming when we set turret_tracking to
// true.
TEST_P(SuperstructureAllianceTest, TurretAutoAim) {
SetEnabled(true);
// Set a reasonable goal.
const frc971::control_loops::Pose target = turret::OuterPortPose(GetParam());
WaitUntilZeroed();
constexpr double kShotAngle = 1.0;
SendAlliancePosition();
{
auto builder = superstructure_goal_sender_.MakeBuilder();
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_turret_tracking(true);
ASSERT_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
{
auto builder = drivetrain_status_sender_.MakeBuilder();
frc971::control_loops::drivetrain::LocalizerState::Builder
localizer_builder = builder.MakeBuilder<
frc971::control_loops::drivetrain::LocalizerState>();
localizer_builder.add_left_velocity(0.0);
localizer_builder.add_right_velocity(0.0);
const auto localizer_offset = localizer_builder.Finish();
DrivetrainStatus::Builder status_builder =
builder.MakeBuilder<DrivetrainStatus>();
// Set the robot up at kShotAngle off from the target, 1m away.
status_builder.add_x(target.abs_pos().x() + std::cos(kShotAngle));
status_builder.add_y(target.abs_pos().y() + std::sin(kShotAngle));
status_builder.add_theta(0.0);
status_builder.add_localizer(localizer_offset);
ASSERT_EQ(builder.Send(status_builder.Finish()),
aos::RawSender::Error::kOk);
}
// Give it time to stabilize.
RunFor(chrono::seconds(1));
superstructure_status_fetcher_.Fetch();
EXPECT_NEAR(kShotAngle, superstructure_status_fetcher_->turret()->position(),
5e-4);
EXPECT_FLOAT_EQ(kShotAngle,
superstructure_status_fetcher_->aimer()->turret_position());
EXPECT_FLOAT_EQ(0,
superstructure_status_fetcher_->aimer()->turret_velocity());
}
// Test a manual goal
TEST_P(SuperstructureAllianceTest, ShooterInterpolationManualGoal) {
SetEnabled(true);
WaitUntilZeroed();
{
auto builder = superstructure_goal_sender_.MakeBuilder();
auto shooter_goal = CreateShooterGoal(*builder.fbb(), 400.0, 500.0);
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
hood_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kHoodRange().lower);
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_shooter(shooter_goal);
goal_builder.add_hood(hood_offset);
CHECK_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
RunFor(chrono::seconds(10));
superstructure_status_fetcher_.Fetch();
EXPECT_DOUBLE_EQ(superstructure_status_fetcher_->shooter()
->accelerator_left()
->angular_velocity_goal(),
400.0);
EXPECT_DOUBLE_EQ(superstructure_status_fetcher_->shooter()
->accelerator_right()
->angular_velocity_goal(),
400.0);
EXPECT_DOUBLE_EQ(superstructure_status_fetcher_->shooter()
->finisher()
->angular_velocity_goal(),
500.0);
EXPECT_NEAR(superstructure_status_fetcher_->hood()->position(),
constants::Values::kHoodRange().lower, 0.001);
}
// Test an out of range value with auto tracking
TEST_P(SuperstructureAllianceTest, ShooterInterpolationOutOfRange) {
SetEnabled(true);
const frc971::control_loops::Pose target = turret::OuterPortPose(GetParam());
WaitUntilZeroed();
constexpr double kShotAngle = 1.0;
{
auto builder = drivetrain_status_sender_.MakeBuilder();
frc971::control_loops::drivetrain::LocalizerState::Builder
localizer_builder = builder.MakeBuilder<
frc971::control_loops::drivetrain::LocalizerState>();
localizer_builder.add_left_velocity(0.0);
localizer_builder.add_right_velocity(0.0);
const auto localizer_offset = localizer_builder.Finish();
DrivetrainStatus::Builder status_builder =
builder.MakeBuilder<DrivetrainStatus>();
// Set the robot up at kShotAngle off from the target, 100m away.
status_builder.add_x(target.abs_pos().x() + std::cos(kShotAngle) * 100);
status_builder.add_y(target.abs_pos().y() + std::sin(kShotAngle) * 100);
status_builder.add_theta(0.0);
status_builder.add_localizer(localizer_offset);
ASSERT_EQ(builder.Send(status_builder.Finish()),
aos::RawSender::Error::kOk);
}
{
auto builder = superstructure_goal_sender_.MakeBuilder();
// Add a goal, this should be ignored with auto tracking
auto shooter_goal = CreateShooterGoal(*builder.fbb(), 400.0, 500.0);
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
hood_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kHoodRange().lower);
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_shooter(shooter_goal);
goal_builder.add_hood(hood_offset);
goal_builder.add_shooter_tracking(true);
goal_builder.add_hood_tracking(true);
CHECK_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
RunFor(chrono::seconds(10));
superstructure_status_fetcher_.Fetch();
EXPECT_DOUBLE_EQ(superstructure_status_fetcher_->shooter()
->accelerator_left()
->angular_velocity_goal(),
0.0);
EXPECT_DOUBLE_EQ(superstructure_status_fetcher_->shooter()
->accelerator_right()
->angular_velocity_goal(),
0.0);
EXPECT_DOUBLE_EQ(superstructure_status_fetcher_->shooter()
->finisher()
->angular_velocity_goal(),
0.0);
EXPECT_NEAR(superstructure_status_fetcher_->hood()->position(),
constants::Values::kHoodRange().upper, 0.001);
}
// Test a value in range with auto tracking
TEST_P(SuperstructureAllianceTest, ShooterInterpolationInRange) {
SetEnabled(true);
const frc971::control_loops::Pose target = turret::OuterPortPose(GetParam());
WaitUntilZeroed();
constexpr double kShotAngle = 1.0;
SendAlliancePosition();
// Test an in range value returns a reasonable result
{
auto builder = drivetrain_status_sender_.MakeBuilder();
frc971::control_loops::drivetrain::LocalizerState::Builder
localizer_builder = builder.MakeBuilder<
frc971::control_loops::drivetrain::LocalizerState>();
localizer_builder.add_left_velocity(0.0);
localizer_builder.add_right_velocity(0.0);
const auto localizer_offset = localizer_builder.Finish();
DrivetrainStatus::Builder status_builder =
builder.MakeBuilder<DrivetrainStatus>();
// Set the robot up at kShotAngle off from the target, 2.5m away.
status_builder.add_x(target.abs_pos().x() + std::cos(kShotAngle) * 2.5);
status_builder.add_y(target.abs_pos().y() + std::sin(kShotAngle) * 2.5);
status_builder.add_theta(0.0);
status_builder.add_localizer(localizer_offset);
ASSERT_EQ(builder.Send(status_builder.Finish()),
aos::RawSender::Error::kOk);
}
{
auto builder = superstructure_goal_sender_.MakeBuilder();
// Add a goal, this should be ignored with auto tracking
auto shooter_goal = CreateShooterGoal(*builder.fbb(), 400.0, 500.0);
flatbuffers::Offset<StaticZeroingSingleDOFProfiledSubsystemGoal>
hood_offset = CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*builder.fbb(), constants::Values::kHoodRange().lower);
Goal::Builder goal_builder = builder.MakeBuilder<Goal>();
goal_builder.add_shooter(shooter_goal);
goal_builder.add_hood(hood_offset);
goal_builder.add_shooter_tracking(true);
goal_builder.add_hood_tracking(true);
CHECK_EQ(builder.Send(goal_builder.Finish()),
aos::RawSender::Error::kOk);
}
RunFor(chrono::seconds(10));
superstructure_status_fetcher_.Fetch();
EXPECT_GE(superstructure_status_fetcher_->shooter()
->accelerator_left()
->angular_velocity_goal(),
250.0);
EXPECT_GE(superstructure_status_fetcher_->shooter()
->accelerator_right()
->angular_velocity_goal(),
250.0);
EXPECT_GE(superstructure_status_fetcher_->shooter()
->finisher()
->angular_velocity_goal(),
250.0);
EXPECT_GE(superstructure_status_fetcher_->hood()->position(),
constants::Values::kHoodRange().lower);
}
INSTANTIATE_TEST_SUITE_P(ShootAnyAlliance, SuperstructureAllianceTest,
::testing::Values(aos::Alliance::kRed,
aos::Alliance::kBlue,
aos::Alliance::kInvalid));
} // namespace testing
} // namespace superstructure
} // namespace control_loops
} // namespace y2020
| 38.408941 | 80 | 0.703304 | [
"model"
] |
e4254c28a84f62ccf412a53c2196cbb4821657a0 | 2,250 | cpp | C++ | Triangle.cpp | rahul0324/Computer-Graphics-Lab | eeff1749c32a1cbd3e1e481a40e280c8b945688e | [
"MIT"
] | null | null | null | Triangle.cpp | rahul0324/Computer-Graphics-Lab | eeff1749c32a1cbd3e1e481a40e280c8b945688e | [
"MIT"
] | null | null | null | Triangle.cpp | rahul0324/Computer-Graphics-Lab | eeff1749c32a1cbd3e1e481a40e280c8b945688e | [
"MIT"
] | null | null | null | #include <GL/glut.h>
void initGL() {
// Set "clearing" or background color
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black and opaque
}
void display() {
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
// Define shapes enclosed within a pair of glBegin and glEnd
glBegin(GL_QUADS);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2f(-0.8f, 0.1f);
glVertex2f(-0.2f, 0.1f);
glVertex2f(-0.2f, 0.7f);
glVertex2f(-0.8f, 0.7f);
// glColor3f(0.0f, 1.0f, 0.0f); // Green
// glVertex2f(-0.7f, -0.6f);
// glVertex2f(-0.1f, -0.6f);
// glVertex2f(-0.1f, 0.0f);
// glVertex2f(-0.7f, 0.0f);
// glColor3f(0.2f, 0.2f, 0.2f); // Dark Gray
// glVertex2f(-0.9f, -0.7f);
// glColor3f(1.0f, 1.0f, 1.0f); // White
// glVertex2f(-0.5f, -0.7f);
// glColor3f(0.2f, 0.2f, 0.2f); // Dark Gray
// glVertex2f(-0.5f, -0.3f);
// glColor3f(1.0f, 1.0f, 1.0f); // White
// glVertex2f(-0.9f, -0.3f);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.0f, 0.0f, 1.0f); // Blue
glVertex2f(0.1f, -0.6f);
glVertex2f(0.7f, -0.6f);
glVertex2f(0.4f, -0.1f);
// glColor3f(1.0f, 0.0f, 0.0f); // Red
// glVertex2f(0.3f, -0.4f);
// glColor3f(0.0f, 1.0f, 0.0f); // Green
// glVertex2f(0.9f, -0.4f);
// glColor3f(0.0f, 0.0f, 1.0f); // Blue
// glVertex2f(0.6f, -0.9f);
glEnd();
glBegin(GL_POLYGON); // These vertices form a closed polygon
glColor3f(1.0f, 1.0f, 0.0f); // Yellow
glVertex2f(0.4f, 0.2f);
glVertex2f(0.6f, 0.2f);
glVertex2f(0.7f, 0.4f);
glVertex2f(0.6f, 0.6f);
glVertex2f(0.4f, 0.6f);
glVertex2f(0.3f, 0.4f);
glEnd();
glFlush(); // Render now
}
/* Main function: GLUT runs as a console application starting at main() */
int main(int argc, char** argv) {
glutInit(&argc, argv); // Initialize GLUT
glutCreateWindow("Vertex, Primitive & Color");
glutInitWindowSize(320, 320);
glutInitWindowPosition(50, 50);
glutDisplayFunc(display);
initGL();
glutMainLoop();
return 0;
} | 31.25 | 88 | 0.536 | [
"render"
] |
e42c766b56bd4b6ccb19b34ec683711f7c6b4ce7 | 1,212 | cpp | C++ | Recursion and Backtracking/NQueensBranchAndBound.cpp | Ankitlenka26/IP2021 | 99322c9c84a8a9c9178a505afbffdcebd312b059 | [
"MIT"
] | null | null | null | Recursion and Backtracking/NQueensBranchAndBound.cpp | Ankitlenka26/IP2021 | 99322c9c84a8a9c9178a505afbffdcebd312b059 | [
"MIT"
] | null | null | null | Recursion and Backtracking/NQueensBranchAndBound.cpp | Ankitlenka26/IP2021 | 99322c9c84a8a9c9178a505afbffdcebd312b059 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void nqueens(vector<vector<int>> &board, vector<bool> column, vector<bool> ndiag, vector<bool> rdiag, string psf, int row)
{
if (row == board.size())
{
cout << psf + "." << endl;
return;
}
for (int col = 0; col < column.size(); col++)
{
if (column[col] == false && ndiag[row + col] == false && rdiag[row - col + board.size() - 1] == false)
{
board[row][col] = 1;
column[col] = true;
ndiag[row + col] = true;
rdiag[row - col + board.size() - 1] = true;
nqueens(board, column, ndiag, rdiag, psf + to_string(row) + "-" + to_string(col) + ", ", row + 1);
board[row][col] = 0;
column[col] = false;
ndiag[row + col] = false;
rdiag[row - col + board.size() - 1] = false;
}
}
}
int main()
{
int n;
cin >> n;
vector<vector<int>> board(n, vector<int>(n, 0));
vector<bool> col(n, false);
vector<bool> ndiag(2 * n - 1, false);
vector<bool> rdiag(2 * n - 1, false);
nqueens(board, col, ndiag, rdiag, "", 0);
return 0;
} | 28.186047 | 122 | 0.509901 | [
"vector"
] |
e4300a55a4fe9d21bbf869ec644efc3a90ceb3b4 | 2,306 | cc | C++ | apf/apfTagData.cc | Thomas-Ulrich/core | 1c7bc7ff994c3570ab22b96d37be0c4c993e5940 | [
"BSD-3-Clause"
] | 138 | 2015-01-05T15:50:20.000Z | 2022-02-25T01:09:58.000Z | apf/apfTagData.cc | Thomas-Ulrich/core | 1c7bc7ff994c3570ab22b96d37be0c4c993e5940 | [
"BSD-3-Clause"
] | 337 | 2015-08-07T18:24:58.000Z | 2022-03-31T14:39:03.000Z | apf/apfTagData.cc | Thomas-Ulrich/core | 1c7bc7ff994c3570ab22b96d37be0c4c993e5940 | [
"BSD-3-Clause"
] | 70 | 2015-01-17T00:58:41.000Z | 2022-02-13T04:58:20.000Z | /*
* Copyright 2011 Scientific Computation Research Center
*
* This work is open source software, licensed under the terms of the
* BSD license as described in the LICENSE file in the top-level directory.
*/
#include "apfTagData.h"
#include "apfShape.h"
#include <pcu_util.h>
namespace apf {
void TagData::init(
const char* name,
Mesh* m,
FieldShape* s,
TagMaker* mk,
int c)
{
mesh = m;
shape = s;
maker = mk;
createTags(name,c);
}
TagData::~TagData()
{
detachTags();
destroyTags();
}
bool TagData::hasEntity(MeshEntity* e)
{
MeshTag* tag = getTag(e);
if (!tag) return false;
return mesh->hasTag(e,tag);
}
void TagData::removeEntity(MeshEntity* e)
{
MeshTag* tag = this->getTag(e);
if (!tag) return;
mesh->removeTag(e,this->getTag(e));
}
MeshTag* TagData::getTag(MeshEntity* e)
{
return tags[mesh->getType(e)];
}
MeshTag* TagData::makeOrFindTag(const char* name, int size)
{
MeshTag* tag = mesh->findTag(name);
if (tag) return tag;
return maker->make(mesh,name,size);
}
static const char* typePostfix[Mesh::TYPES] =
{"ver","edg","tri","qua","tet","hex","pri","pyr"};
void TagData::createTags(const char* name, int components)
{
PCU_ALWAYS_ASSERT(name);
PCU_ALWAYS_ASSERT(shape);
for (int type=Mesh::VERTEX; type < Mesh::TYPES; ++type)
{
int n = shape->countNodesOn(type);
if (n)
{
std::string tagName(name);
tagName += '_';
tagName += typePostfix[type];
tags[type] = makeOrFindTag(tagName.c_str(),n*components);
}
else
tags[type] = 0;
}
}
void TagData::detachTags()
{
for (int dim=0; dim <= 3; ++dim)
if (shape->hasNodesIn(dim))
{
MeshEntity* entity;
MeshIterator* entities = mesh->begin(dim);
while ((entity = mesh->iterate(entities)))
this->removeEntity(entity);
mesh->end(entities);
}
}
void TagData::destroyTags()
{
for (int type=Mesh::VERTEX; type < Mesh::TYPES; ++type)
if (tags[type])
mesh->destroyTag(tags[type]);
}
void TagData::rename(const char* newName)
{
for (int type=Mesh::VERTEX; type < Mesh::TYPES; ++type)
if (tags[type]) {
std::string newTagName(newName);
newTagName += '_';
newTagName += typePostfix[type];
mesh->renameTag(tags[type], newTagName.c_str());
}
}
}
| 20.22807 | 75 | 0.630095 | [
"mesh",
"shape"
] |
e430f57aa46a89262f31a4b0d2c5eacc40c247fd | 8,300 | cc | C++ | ui/aura/mus/input_method_mus_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/aura/mus/input_method_mus_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/aura/mus/input_method_mus_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 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 "ui/aura/mus/input_method_mus.h"
#include <utility>
#include "services/ui/public/interfaces/ime/ime.mojom.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/test/mus/input_method_mus_test_api.h"
#include "ui/aura/window.h"
#include "ui/base/ime/dummy_text_input_client.h"
#include "ui/base/ime/input_method_delegate.h"
namespace aura {
namespace {
// Empty implementation of InputMethodDelegate.
class TestInputMethodDelegate : public ui::internal::InputMethodDelegate {
public:
TestInputMethodDelegate() {}
~TestInputMethodDelegate() override {}
// ui::internal::InputMethodDelegate:
ui::EventDispatchDetails DispatchKeyEventPostIME(ui::KeyEvent* key) override {
return ui::EventDispatchDetails();
}
private:
DISALLOW_COPY_AND_ASSIGN(TestInputMethodDelegate);
};
using ProcessKeyEventCallback = base::OnceCallback<void(bool)>;
using ProcessKeyEventCallbacks = std::vector<ProcessKeyEventCallback>;
using EventResultCallback = base::Callback<void(ui::mojom::EventResult)>;
// InputMethod implementation that queues up the callbacks supplied to
// ProcessKeyEvent().
class TestInputMethod : public ui::mojom::InputMethod {
public:
TestInputMethod() {}
~TestInputMethod() override {}
ProcessKeyEventCallbacks* process_key_event_callbacks() {
return &process_key_event_callbacks_;
}
// ui::ime::InputMethod:
void OnTextInputTypeChanged(ui::TextInputType text_input_type) override {}
void OnCaretBoundsChanged(const gfx::Rect& caret_bounds) override {}
void ProcessKeyEvent(std::unique_ptr<ui::Event> key_event,
ProcessKeyEventCallback callback) override {
process_key_event_callbacks_.push_back(std::move(callback));
}
void CancelComposition() override {}
private:
ProcessKeyEventCallbacks process_key_event_callbacks_;
DISALLOW_COPY_AND_ASSIGN(TestInputMethod);
};
} // namespace
using InputMethodMusTest = test::AuraTestBaseMus;
namespace {
// Used in closure supplied to processing the event.
void RunFunctionWithEventResult(bool* was_run, ui::mojom::EventResult result) {
*was_run = true;
}
} // namespace
TEST_F(InputMethodMusTest, PendingCallbackRunFromDestruction) {
aura::Window window(nullptr);
window.Init(ui::LAYER_NOT_DRAWN);
bool was_event_result_callback_run = false;
// Create an InputMethodMus and foward an event to it.
{
TestInputMethodDelegate input_method_delegate;
InputMethodMus input_method_mus(&input_method_delegate, &window);
TestInputMethod test_input_method;
InputMethodMusTestApi::SetInputMethod(&input_method_mus,
&test_input_method);
std::unique_ptr<EventResultCallback> callback =
base::MakeUnique<EventResultCallback>(base::Bind(
&RunFunctionWithEventResult, &was_event_result_callback_run));
ui::EventDispatchDetails details =
InputMethodMusTestApi::CallSendKeyEventToInputMethod(
&input_method_mus,
ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, 0),
std::move(callback));
ASSERT_TRUE(!details.dispatcher_destroyed && !details.target_destroyed);
// Add a null callback as well, to make sure null is deal with.
details = InputMethodMusTestApi::CallSendKeyEventToInputMethod(
&input_method_mus, ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, 0),
nullptr);
ASSERT_TRUE(!details.dispatcher_destroyed && !details.target_destroyed);
// The event should have been queued.
EXPECT_EQ(2u, test_input_method.process_key_event_callbacks()->size());
// Callback should not have been run yet.
EXPECT_FALSE(was_event_result_callback_run);
}
// When the destructor is run the callback should be run.
EXPECT_TRUE(was_event_result_callback_run);
}
TEST_F(InputMethodMusTest, PendingCallbackRunFromOnDidChangeFocusedClient) {
aura::Window window(nullptr);
window.Init(ui::LAYER_NOT_DRAWN);
bool was_event_result_callback_run = false;
ui::DummyTextInputClient test_input_client;
// Create an InputMethodMus and foward an event to it.
TestInputMethodDelegate input_method_delegate;
InputMethodMus input_method_mus(&input_method_delegate, &window);
TestInputMethod test_input_method;
InputMethodMusTestApi::SetInputMethod(&input_method_mus, &test_input_method);
std::unique_ptr<EventResultCallback> callback =
base::MakeUnique<EventResultCallback>(base::Bind(
&RunFunctionWithEventResult, &was_event_result_callback_run));
ui::EventDispatchDetails details =
InputMethodMusTestApi::CallSendKeyEventToInputMethod(
&input_method_mus,
ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, 0),
std::move(callback));
ASSERT_TRUE(!details.dispatcher_destroyed && !details.target_destroyed);
// The event should have been queued.
EXPECT_EQ(1u, test_input_method.process_key_event_callbacks()->size());
// Callback should not have been run yet.
EXPECT_FALSE(was_event_result_callback_run);
InputMethodMusTestApi::CallOnDidChangeFocusedClient(
&input_method_mus, nullptr, &test_input_client);
// Changing the focused client should trigger running the callback.
EXPECT_TRUE(was_event_result_callback_run);
}
// See description of ChangeTextInputTypeWhileProcessingCallback for details.
class TestInputMethodDelegate2 : public ui::internal::InputMethodDelegate {
public:
TestInputMethodDelegate2() {}
~TestInputMethodDelegate2() override {}
void SetInputMethodAndClient(InputMethodMus* input_method_mus,
ui::TextInputClient* text_input_client) {
input_method_mus_ = input_method_mus;
text_input_client_ = text_input_client;
}
bool was_dispatch_key_event_post_ime_called() const {
return was_dispatch_key_event_post_ime_called_;
}
// ui::internal::InputMethodDelegate:
ui::EventDispatchDetails DispatchKeyEventPostIME(ui::KeyEvent* key) override {
was_dispatch_key_event_post_ime_called_ = true;
input_method_mus_->SetFocusedTextInputClient(text_input_client_);
return ui::EventDispatchDetails();
}
private:
InputMethodMus* input_method_mus_ = nullptr;
ui::TextInputClient* text_input_client_ = nullptr;
bool was_dispatch_key_event_post_ime_called_ = false;
DISALLOW_COPY_AND_ASSIGN(TestInputMethodDelegate2);
};
// This test setups the scenario where during processing an unhandled event
// SetFocusedTextInputClient() is called. This verifies we don't crash in this
// scenario and the callback is correctly called.
TEST_F(InputMethodMusTest, ChangeTextInputTypeWhileProcessingCallback) {
aura::Window window(nullptr);
window.Init(ui::LAYER_NOT_DRAWN);
bool was_event_result_callback_run = false;
ui::DummyTextInputClient test_input_client;
// Create an InputMethodMus and foward an event to it.
TestInputMethodDelegate2 input_method_delegate;
InputMethodMus input_method_mus(&input_method_delegate, &window);
input_method_delegate.SetInputMethodAndClient(&input_method_mus,
&test_input_client);
TestInputMethod test_input_method;
InputMethodMusTestApi::SetInputMethod(&input_method_mus, &test_input_method);
std::unique_ptr<EventResultCallback> callback =
base::MakeUnique<EventResultCallback>(base::Bind(
&RunFunctionWithEventResult, &was_event_result_callback_run));
const ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, 0);
ui::EventDispatchDetails details =
InputMethodMusTestApi::CallSendKeyEventToInputMethod(
&input_method_mus, key_event, std::move(callback));
ASSERT_TRUE(!details.dispatcher_destroyed && !details.target_destroyed);
// The event should have been queued.
ASSERT_EQ(1u, test_input_method.process_key_event_callbacks()->size());
// Callback should not have been run yet.
EXPECT_FALSE(was_event_result_callback_run);
std::move((*test_input_method.process_key_event_callbacks())[0]).Run(false);
// Callback should have been run.
EXPECT_TRUE(was_event_result_callback_run);
EXPECT_TRUE(input_method_delegate.was_dispatch_key_event_post_ime_called());
}
} // namespace aura
| 39.52381 | 80 | 0.766747 | [
"vector"
] |
e435ba37e0dfb897d07fe5fcc8c963f94b615388 | 14,125 | cpp | C++ | instrumentor/PrepareCSI.cpp | pohmann/csi-cc | 08d103f09a647874a99349339721e1a33135468e | [
"Apache-2.0"
] | 2 | 2018-05-02T06:12:34.000Z | 2019-07-02T03:25:57.000Z | instrumentor/PrepareCSI.cpp | pohmann/csi-cc | 08d103f09a647874a99349339721e1a33135468e | [
"Apache-2.0"
] | null | null | null | instrumentor/PrepareCSI.cpp | pohmann/csi-cc | 08d103f09a647874a99349339721e1a33135468e | [
"Apache-2.0"
] | 1 | 2021-12-20T06:59:36.000Z | 2021-12-20T06:59:36.000Z | //===-------------------------- PrepareCSI.cpp ----------------------------===//
//
// This module pass replicates functions to allow multiple possible
// instrumentation schemes. Note that, presently, this causes enormous code
// bloat.
//
//===----------------------------------------------------------------------===//
//
// Copyright (c) 2016 Peter J. Ohmann and Benjamin R. Liblit
//
// 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.
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "csi-prep"
#include "PrepareCSI.h"
#include "InstrumentationData.h"
#include "Utils.hpp"
#include "Versions.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <llvm/Support/Debug.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Transforms/Utils/Cloning.h>
#pragma GCC diagnostic pop
#include "llvm_proxy/CommandLine.h"
#include "llvm_proxy/Module.h"
#include "llvm_proxy/InstIterator.h"
#include "llvm_proxy/IntrinsicInst.h"
#include <algorithm>
#include <climits>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace csi_inst;
using namespace llvm;
using namespace std;
static cl::opt<bool> SilentInternal("csi-silent", cl::desc("Silence internal "
"warnings. Will still print errors which "
"cause CSI to fail."));
static cl::opt<string> VariantsFile("csi-variants-file", cl::desc("The path to "
"the instrumentation variants output file."),
cl::value_desc("file_path"));
static cl::opt<bool> NoFilter("csi-no-filter", cl::desc("Do not filter "
"instrumentation schemes. All schemes are used "
"verbatim for function replication."));
// Register CSI prep as a pass
char PrepareCSI::ID = 0;
static RegisterPass<PrepareCSI> X("csi",
"Necessary preparation for any CSI instrumentation",
false, false);
// Output the bitcode if we want to observe instrumentation changess
#define PRINT_MODULE dbgs() << \
"\n\n============= MODULE BEGIN ===============\n" << M << \
"\n============== MODULE END ================\n"
bool PrepareCSI::hasInstrumentationType(const Function &F, const string &type) const {
#if LLVM_VERSION < 30300
const map<const Function*, set<string> >::const_iterator found =
functionSchemes.find(&F);
if (found == functionSchemes.end())
return false;
else
return found->second.count(type);
#else
return F.hasFnAttribute(type);
#endif
}
void PrepareCSI::addInstrumentationType(Function &F, const string &type) {
#if LLVM_VERSION < 30300
functionSchemes[&F].insert(type);
#else
F.addFnAttr(type);
#endif
}
Function* PrepareCSI::switchIndirect(Function* F, GlobalVariable* switcher,
vector<Function*>& replicas){
F->dropAllReferences();
BasicBlock* newEntry = BasicBlock::Create(*Context, "newEntry", F);
vector<Value*> callArgs;
for(Function::arg_iterator k = F->arg_begin(), ke = F->arg_end(); k != ke; ++k)
callArgs.push_back(&*k);
// set up the switch
LoadInst* whichCall = new LoadInst(switcher, "chooseCall", true, newEntry);
SwitchInst* callSwitch = NULL;
// stuff we need
IntegerType* tInt = Type::getInt32Ty(*Context);
// create one bb for each possible call (instrumentation scheme)
bool aZero = false;
for(unsigned int i = 0; i < replicas.size(); ++i){
Function* newF = replicas[i];
BasicBlock* bb = BasicBlock::Create(*Context, "call", F);
if(callSwitch == NULL){
callSwitch = SwitchInst::Create(whichCall, bb, replicas.size(),
newEntry);
}
string funcName = newF->getName().str();
if(funcName.length() > 5 &&
funcName.substr(funcName.length()-5, 5) == "$none"){
callSwitch->addCase(ConstantInt::get(tInt, 0), bb);
if(aZero)
report_fatal_error("multiple defaults for function '" +
F->getName() + "'");
aZero = true;
}
else
callSwitch->addCase(ConstantInt::get(tInt, i+1), bb);
CallInst* oneCall = CallInst::Create(newF, callArgs,
(F->getReturnType()->isVoidTy()) ? "" : "theCall", bb);
oneCall->setTailCall(true);
if(F->getReturnType()->isVoidTy())
ReturnInst::Create(*Context, bb);
else
ReturnInst::Create(*Context, oneCall, bb);
}
// note that we intentionally started numbering the cases from 1 so that the
// zero case is reserved for the uninstrumented variant (if there is one)
if(!aZero)
switcher->setInitializer(ConstantInt::get(tInt, 1));
return(F);
}
void printScheme(vector<pair<string, set<set<string> > > >& schemeData){
dbgs() << "------Scheme------\n";
for(vector<pair<string, set<set<string> > > >::iterator i = schemeData.begin(), e = schemeData.end(); i != e; ++i){
pair<string, set<set<string> > > entry = *i;
dbgs() << entry.first << ": ";
for(set<set<string> >::iterator j = entry.second.begin(), je = entry.second.end(); j != je; ++j){
set<string> jentry = *j;
if(j != entry.second.begin())
dbgs() << ",";
dbgs() << "{";
for(set<string>::iterator k = jentry.begin(), ke = jentry.end(); k != ke; ++k){
if(k != jentry.begin())
dbgs() << ",";
dbgs() << *k;
}
dbgs() << "}";
}
dbgs() << "\n";
}
dbgs() << "------------------\n";
}
static vector<string> split(string s, char delim){
vector<string> result;
stringstream lineStream(s);
string entry;
while(getline(lineStream, entry, delim)){
result.push_back(entry);
if(lineStream.fail() || lineStream.eof())
break;
}
if(lineStream.bad())
report_fatal_error("internal error encountered parsing scheme input");
return(result);
}
static bool patternMatch(const string &text, const string &pattern){
return pattern == text || pattern == "*";
}
static void verifyScheme(const vector<pair<string, set<set<string> > > >& scheme) {
for(vector<pair<string, set<set<string> > > >::const_iterator i = scheme.begin(), e = scheme.end(); i != e; ++i){
for(set<set<string> >::const_iterator j = i->second.begin(), je = i->second.end(); j != je; ++j){
for(set<string>::const_iterator k = j->begin(), ke = j->end(); k != ke; ++k){
if(Instrumentors.count(*k) < 1)
report_fatal_error("invalid instrumentor '" + *k + "' in scheme");
}
}
}
}
static vector<pair<string, set<set<string> > > > readScheme(istream& in){
vector<string> lines;
string s;
while(getline(in, s)){
s.erase(remove_if(s.begin(), s.end(), ::isspace), s.end());
if(!s.empty())
lines.push_back(s);
if(in.fail() || in.eof())
break;
}
if(in.bad())
report_fatal_error("error encountered reading schema input");
vector<pair<string, set<set<string> > > > result;
for(vector<string>::iterator i = lines.begin(), e = lines.end(); i != e; ++i){
vector<string> entries = split(*i, ';');
if(entries.size() < 2)
report_fatal_error("invalid formatting for line '" + *i + "' in instrumentation schema");
string fnPattern = entries[0];
set<set<string> > schemes;
for(vector<string>::iterator j = ++entries.begin(), je = entries.end(); j != je; ++j){
string scheme = *j;
transform(scheme.begin(), scheme.end(), scheme.begin(), ::toupper);
if(scheme[0] != '{' || scheme[scheme.length()-1] != '}')
report_fatal_error("invalid formatting for entry '" + scheme + "' in instrumentation schema", false);
scheme.erase(0, 1);
scheme.erase(scheme.length()-1, 1);
const vector<string> methods = split(scheme, ',');
set<string> methodsSet;
for(vector<string>::const_iterator k = methods.begin(), ke = methods.end(); k != ke; ++k){
if(!k->empty())
methodsSet.insert(*k);
}
schemes.insert(methodsSet);
}
result.push_back(make_pair(fnPattern, schemes));
}
return(result);
}
static void labelInstructions(Function& F){
unsigned int label = 1;
for(inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
attachCSILabelToInstruction(*i, csi_inst::to_string(label++));
}
// Entry point of the module
bool PrepareCSI::runOnModule(Module &M){
// first, label all instructions in all functions in the module (so later
// passes can have a unique identifier for each instruction)
for(Module::iterator F = M.begin(), e = M.end(); F != e; ++F)
labelInstructions(*F);
// then, proceed with reading in scheme data
vector<pair<string, set<set<string> > > > schemeData;
if(VariantsFile.empty()){
outs() << "Reading stdin for instrumentation scheme...\n";
schemeData = readScheme(cin);
outs() << "Finished reading stdin for scheme\n";
}
else{
ifstream inFile(VariantsFile.c_str(), ios::in);
if(!inFile || !inFile.is_open())
report_fatal_error("cannot open specified instrumentation scheme file: " +
VariantsFile);
schemeData = readScheme(inFile);
}
DEBUG(printScheme(schemeData));
// verify that all passes provided exist
DEBUG(dbgs() << "verifying...\n");
verifyScheme(schemeData);
DEBUG(printScheme(schemeData));
Context = &M.getContext();
// Find the matching pattern for each function
map<Function*, set<set<string> > > matches;
for(Module::iterator F = M.begin(), E = M.end(); F != E; ++F){
if(F->isDeclaration() || F->isIntrinsic())
continue;
bool found = false;
for(vector<pair<string, set<set<string> > > >::iterator i = schemeData.begin(), e = schemeData.end(); i != e; ++i){
if(patternMatch(F->getName(), i->first)){
matches[&*F] = i->second;
found = true;
break;
}
}
if(!found){
errs() << "WARNING: No scheme match found for function '"
<< F->getName() << "'. Skipping.\n";
continue;
}
}
// Filter patterns matched to each function, and replicate
for(map<Function*, set<set<string> > >::iterator i = matches.begin(), e = matches.end(); i != e; ++i){
Function* F = i->first;
// go through all filters for each possible scheme. after passing through
// all filters, make a replica of this function with those tags on it,
// and add that replica to the "replicas" set. else, print warning
set<set<string> > replicas;
for(set<set<string> >::iterator j = i->second.begin(), je = i->second.end(); j != je; ++j){
set<string> testing = *j;
bool passed = true;
if(!NoFilter){
for(vector<FilterFn>::const_iterator fi = Filters.begin(), fe = Filters.end(); fi != fe; ++fi){
if((*fi)(testing, F))
passed = false;
}
}
replicas.insert(testing);
if(!passed){
outs() << "WARNING: filtered scheme '";
for(set<string>::iterator k = j->begin(), ke = j->end(); k != ke; ++k){
if(k != j->begin())
outs() << ",";
outs() << *k;
}
outs() << "' for function '" << F->getName().str() << "'\n";
continue;
}
}
switch (replicas.size()) {
case 0:
continue;
case 1: {
// instrument the original body (don't replicate and trampoline)
const set<string>& scheme = *(replicas.begin());
for(set<string>::iterator j = scheme.begin(), je = scheme.end(); j != je; ++j)
addInstrumentationType(*F, *j);
break;
}
default:
// if the function is variable-argument, currently don't support
if(F->isVarArg()){
outs() << "WARNING: cannot instrument variable-argument function '"
<< F->getName() << "'\n";
continue;
}
// make a function for each scheme
vector<Function*> funcReplicas;
for(set<set<string> >::iterator j = replicas.begin(), je = replicas.end(); j != je; ++j){
ValueToValueMapTy valueMap;
SmallVector<ReturnInst*, 1> returns;
Function* newF = CloneFunction(F, valueMap,
#if LLVM_VERSION < 30900
false,
#endif
NULL);
string name = F->getName().str();
if(j->begin() == j->end())
name += "$none";
for(set<string>::iterator k = j->begin(), ke = j->end(); k != ke; ++k){
name += "$" + *k;
addInstrumentationType(*newF, *k);
}
newF->setName(name);
// NOTE: this does not preserve function ordering, thus it could
// randomly slightly impact performance positively or negatively
F->getParent()->getFunctionList().push_back(newF);
funcReplicas.push_back(newF);
}
// assign this function a global switcher variable
IntegerType* tInt = Type::getInt32Ty(*Context);
string globalName = "__CSI_inst_"+getUniqueCFunctionName(*F);
const GlobalValue::LinkageTypes linkage =
F->hasAvailableExternallyLinkage()
? GlobalValue::WeakAnyLinkage
: GlobalValue::ExternalLinkage;
GlobalVariable * const functionGlobal =
new GlobalVariable(M, tInt, true, linkage,
ConstantInt::get(tInt, 0), globalName);
functionGlobal->setSection("__CSI_func_inst");
// set up the trampoline call for this function
switchIndirect(F, functionGlobal, funcReplicas);
}
}
return(true);
}
| 34.876543 | 119 | 0.594619 | [
"vector",
"transform"
] |
e4384de87ae479e320eaef1db17e5528dba3c335 | 5,772 | cpp | C++ | src/ContextManager.cpp | yxonic/ycc1 | 01ecf01d0e069fa9e976387164c80ee171913915 | [
"MIT"
] | 1 | 2016-09-28T02:14:30.000Z | 2016-09-28T02:14:30.000Z | src/ContextManager.cpp | yxonic/ycc1 | 01ecf01d0e069fa9e976387164c80ee171913915 | [
"MIT"
] | null | null | null | src/ContextManager.cpp | yxonic/ycc1 | 01ecf01d0e069fa9e976387164c80ee171913915 | [
"MIT"
] | null | null | null | #include "ContextManager.h"
#include "llvm/IR/IRBuilder.h"
using namespace llvm;
void ContextManager::enterBlock(Function *f)
{
_sym_table.emplace_back(std::map<std::string, std::pair<Value *, ElemType>>());
_func.push(f);
}
void ContextManager::exitBlock()
{
_sym_table.pop_back();
_func.pop();
}
Value *ContextManager::get(std::string name) const
{
for (auto i = _sym_table.rbegin(), e = _sym_table.rend();
i != e; ++i) {
auto x = i->find(name);
if (x != i->end())
return x->second.first;
}
return nullptr;
}
ContextManager::ElemType ContextManager::getType(std::string name) const
{
for (auto i = _sym_table.rbegin(), e = _sym_table.rend();
i != e; ++i) {
auto x = i->find(name);
if (x != i->end())
return x->second.second;
}
return Error;
}
Value *ContextManager::defConstant(std::string name, int value)
{
if (_sym_table.size() == 1) {
GlobalVariable* gvar =
new GlobalVariable(*_module, IntegerType::get(_module->getContext(), 32),
/*isConstant=*/true, GlobalValue::ExternalLinkage, 0, name);
gvar->setInitializer(ConstantInt::get(getGlobalContext(), APInt(32, value)));
_sym_table.back()[name] = {gvar, Constant};
return gvar;
} else {
IRBuilder<> tmpB(&_func.top()->getEntryBlock(),
_func.top()->getEntryBlock().begin());
AllocaInst *rv = tmpB.CreateAlloca(Type::getInt32Ty(getGlobalContext()), 0,
name);
tmpB.CreateStore(ConstantInt::get(getGlobalContext(), APInt(32, value)), rv);
_sym_table.back()[name] = {rv, Constant};
return rv;
}
}
Value *ContextManager::defVariable(std::string name)
{
if (_sym_table.size() == 1) {
GlobalVariable* gvar =
new GlobalVariable(*_module, IntegerType::get(_module->getContext(), 32),
/*isConstant=*/false, GlobalValue::ExternalLinkage, 0, name);
gvar->setInitializer(ConstantInt::get(getGlobalContext(), APInt(32, 0)));
_sym_table.back()[name] = {gvar, Int};
return gvar;
} else {
IRBuilder<> tmpB(&_func.top()->getEntryBlock(),
_func.top()->getEntryBlock().begin());
AllocaInst *rv = tmpB.CreateAlloca(Type::getInt32Ty(getGlobalContext()), 0,
name);
_sym_table.back()[name] = {rv, Int};
return rv;
}
}
Value *ContextManager::defVariable(std::string name, int value)
{
if (_sym_table.size() == 1) {
GlobalVariable* gvar =
new GlobalVariable(*_module, IntegerType::get(getGlobalContext(), 32),
/*isConstant=*/false, GlobalValue::ExternalLinkage, 0, name);
gvar->setInitializer(ConstantInt::get(getGlobalContext(), APInt(32, value)));
_sym_table.back()[name] = {gvar, Int};
return gvar;
} else {
IRBuilder<> tmpB(&_func.top()->getEntryBlock(),
_func.top()->getEntryBlock().begin());
AllocaInst *rv = tmpB.CreateAlloca(Type::getInt32Ty(getGlobalContext()), 0,
name);
tmpB.CreateStore(ConstantInt::get(getGlobalContext(), APInt(32, value)), rv);
_sym_table.back()[name] = {rv, Int};
return rv;
}
}
Value *ContextManager::defPointer(std::string name)
{
IRBuilder<> tmpB(&_func.top()->getEntryBlock(),
_func.top()->getEntryBlock().begin());
AllocaInst *rv = tmpB.CreateAlloca(Type::getInt32PtrTy(getGlobalContext()), 0,
name);
_sym_table.back()[name] = {rv, Pointer};
return rv;
}
Value *ContextManager::defArray(std::string name, int size)
{
if (_sym_table.size() == 1) {
ArrayType *arrayTy = ArrayType::get(Type::getInt32Ty(getGlobalContext()), size);
GlobalVariable *gvar =
new GlobalVariable(*_module, arrayTy,
/*isConstant=*/false, GlobalValue::ExternalLinkage, 0, name);
_sym_table.back()[name] = {gvar, Array};
ConstantAggregateZero* values = ConstantAggregateZero::get(arrayTy);
gvar->setInitializer(values);
return gvar;
} else {
IRBuilder<> tmpB(&_func.top()->getEntryBlock(),
_func.top()->getEntryBlock().begin());
AllocaInst *rv =
tmpB.CreateAlloca(ArrayType::get(Type::getInt32Ty(getGlobalContext()), size),
0, name);
_sym_table.back()[name] = {rv, Array};
return rv;
}
}
Value *ContextManager::defArray(std::string name, int size, std::vector<int> values)
{
if (_sym_table.size() == 1) {
ArrayType *arrayTy = ArrayType::get(Type::getInt32Ty(getGlobalContext()), size);
GlobalVariable *gvar =
new GlobalVariable(*_module, arrayTy,
/*isConstant=*/false, GlobalValue::ExternalLinkage, 0, name);
_sym_table.back()[name] = {gvar, Array};
std::vector<llvm::Constant*> consts;
for (int v : values)
consts.push_back(ConstantInt::get(getGlobalContext(), APInt(32, v)));
gvar->setInitializer(ConstantArray::get(arrayTy, ArrayRef<llvm::Constant*>(consts)));
return gvar;
} else {
IRBuilder<> tmpB(&_func.top()->getEntryBlock(),
_func.top()->getEntryBlock().begin());
AllocaInst *rv =
tmpB.CreateAlloca(ArrayType::get(Type::getInt32Ty(getGlobalContext()), size),
0, name);
_sym_table.back()[name] = {rv, Array};
return rv;
}
}
| 37.23871 | 93 | 0.568087 | [
"vector"
] |
e43ce52f6e4e43cd20cf6c6609efae48dd09e68b | 13,772 | cpp | C++ | examples/solarsystem/openglwindow.cpp | EduardaMeirinhos/abcg | 8d2018c519b2752d4df53d5e50cc70dcf7d074a3 | [
"MIT"
] | null | null | null | examples/solarsystem/openglwindow.cpp | EduardaMeirinhos/abcg | 8d2018c519b2752d4df53d5e50cc70dcf7d074a3 | [
"MIT"
] | null | null | null | examples/solarsystem/openglwindow.cpp | EduardaMeirinhos/abcg | 8d2018c519b2752d4df53d5e50cc70dcf7d074a3 | [
"MIT"
] | null | null | null | #include "openglwindow.hpp"
#include <imgui.h>
#include <cppitertools/itertools.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include <fmt/core.h>
#include <string>
void OpenGLWindow::handleEvent(SDL_Event& ev) {
if (ev.type == SDL_KEYDOWN) {
if (ev.key.keysym.sym == SDLK_UP || ev.key.keysym.sym == SDLK_w)
m_dollySpeed = 0.3f;
if (ev.key.keysym.sym == SDLK_DOWN || ev.key.keysym.sym == SDLK_s)
m_dollySpeed = -0.3f;
if (ev.key.keysym.sym == SDLK_LEFT || ev.key.keysym.sym == SDLK_a)
m_panSpeed = -0.5f;
if (ev.key.keysym.sym == SDLK_RIGHT || ev.key.keysym.sym == SDLK_d)
m_panSpeed = 0.5f;
if (ev.key.keysym.sym == SDLK_q) m_truckSpeed = -0.3f;
if (ev.key.keysym.sym == SDLK_e) m_truckSpeed = 0.3f;
if (ev.key.keysym.sym == SDLK_r) m_liftSpeed = -0.3f;
if (ev.key.keysym.sym == SDLK_f) m_liftSpeed = 0.3f;
}
if (ev.type == SDL_KEYUP) {
if ((ev.key.keysym.sym == SDLK_UP || ev.key.keysym.sym == SDLK_w) &&
m_dollySpeed > 0)
m_dollySpeed = 0.0f;
if ((ev.key.keysym.sym == SDLK_DOWN || ev.key.keysym.sym == SDLK_s) &&
m_dollySpeed < 0)
m_dollySpeed = 0.0f;
if ((ev.key.keysym.sym == SDLK_LEFT || ev.key.keysym.sym == SDLK_a) &&
m_panSpeed < 0)
m_panSpeed = 0.0f;
if ((ev.key.keysym.sym == SDLK_RIGHT || ev.key.keysym.sym == SDLK_d) &&
m_panSpeed > 0)
m_panSpeed = 0.0f;
if (ev.key.keysym.sym == SDLK_q && m_truckSpeed < 0) m_truckSpeed = 0.0f;
if (ev.key.keysym.sym == SDLK_e && m_truckSpeed > 0) m_truckSpeed = 0.0f;
if (ev.key.keysym.sym == SDLK_r && m_liftSpeed < 0) m_liftSpeed = 0.0f;
if (ev.key.keysym.sym == SDLK_f && m_liftSpeed > 0 ) m_liftSpeed = 0.0f;
}
}
void OpenGLWindow::initializeGL() {
glClearColor(0, 0, 0, 1);
glEnable(GL_DEPTH_TEST);
auto path{getAssetsPath() + "shaders/texture"};
auto program{createProgramFromFile(path + ".vert", path + ".frag")};
m_program = program;
loadModel();
}
void OpenGLWindow::loadModel() {
for (int i = 0; i < 10; i++){
planets[i].m_model.loadFromFile(getAssetsPath() + filenames[i][0]);
planets[i].m_model.loadDiffuseTexture(getAssetsPath() + "maps/" + filenames[i][1]);
if (i == 6){
planets[i].m_model.loadDiffuseTexture(getAssetsPath() + "maps/uranus_rings.map");
}
planets[i].m_model.setupVAO(m_program);
planets[i].m_trianglesToDraw = planets[i].m_model.getNumTriangles();
}
// Use material properties from the loaded model
m_Ka = planets[0].m_model.getKa();
m_Kd = planets[0].m_model.getKd();
m_Ks = planets[0].m_model.getKs();
m_shininess = 13.0f;
}
void OpenGLWindow::paintGL() {
update();
glEnable(GL_CULL_FACE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, m_viewportWidth, m_viewportHeight);
glUseProgram(m_program);
GLint viewMatrixLoc{glGetUniformLocation(m_program, "viewMatrix")};
GLint projMatrixLoc{glGetUniformLocation(m_program, "projMatrix")};
GLint modelMatrixLoc{glGetUniformLocation(m_program, "modelMatrix")};
GLint normalMatrixLoc{glGetUniformLocation(m_program, "normalMatrix")};
GLint lightDirLoc{glGetUniformLocation(m_program, "lightDirWorldSpace")};
GLint shininessLoc{glGetUniformLocation(m_program, "shininess")};
GLint IaLoc{glGetUniformLocation(m_program, "Ia")};
GLint IdLoc{glGetUniformLocation(m_program, "Id")};
GLint IsLoc{glGetUniformLocation(m_program, "Is")};
GLint KaLoc{glGetUniformLocation(m_program, "Ka")};
GLint KdLoc{glGetUniformLocation(m_program, "Kd")};
GLint KsLoc{glGetUniformLocation(m_program, "Ks")};
GLint diffuseTexLoc{glGetUniformLocation(m_program, "diffuseTex")};
GLint normalTexLoc{glGetUniformLocation(m_program, "normalTex")};
GLint mappingModeLoc{glGetUniformLocation(m_program, "mappingMode")};
glUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, &m_camera.m_viewMatrix[0][0]);
glUniformMatrix4fv(projMatrixLoc, 1, GL_FALSE, &m_camera.m_projMatrix[0][0]);
glUniform1i(diffuseTexLoc, 0);
glUniform1i(normalTexLoc, 1);
glUniform1i(mappingModeLoc, 3);
glUniform4fv(lightDirLoc, 1, &m_lightDir.x);
glUniform4fv(IaLoc, 1, &m_Ia.x);
glUniform4fv(IdLoc, 1, &m_Id.x);
glUniform4fv(IsLoc, 1, &m_Is.x);
float mat[4] = {1.0f, 1.0f, 1.0f, 1.0f};
glUniform1f(shininessLoc, 5000.0f);
glUniform4fv(KaLoc, 1, mat);
glUniform4fv(KdLoc, 1, mat);
glUniform4fv(KsLoc, 1, mat);
// Sun
planets[9].m_modelMatrix = glm::mat4(1.0);
planets[9].m_modelMatrix = glm::translate(planets[9].m_modelMatrix, glm::vec3(-3.5f, 0.0f, 0.0f));
planets[9].m_modelMatrix = glm::rotate(planets[9].m_modelMatrix, glm::radians(0.005f * numberFramers), glm::vec3(0, 0, 1));
planets[9].m_modelMatrix = glm::scale(planets[9].m_modelMatrix, glm::vec3(2.0f));
glUniformMatrix4fv(modelMatrixLoc, 1, GL_FALSE, &planets[9].m_modelMatrix[0][0]);
auto modelViewMatrix{glm::mat3(m_camera.m_viewMatrix * planets[9].m_modelMatrix)};
glm::mat3 normalMatrix{glm::inverseTranspose(modelViewMatrix)};
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, &normalMatrix[0][0]);
planets[9].m_model.render(planets[9].m_trianglesToDraw);
//------
glUniform1f(shininessLoc, m_shininess);
glUniform4fv(KaLoc, 1, &m_Ka.x);
glUniform4fv(KdLoc, 1, &m_Kd.x);
glUniform4fv(KsLoc, 1, &m_Ks.x);
// Mercury
planets[0].m_modelMatrix = glm::mat4(1.0);
planets[0].m_modelMatrix = glm::translate(planets[0].m_modelMatrix, glm::vec3(-2.15f, 0.0f, 0.0f));
planets[0].m_modelMatrix = glm::rotate(planets[0].m_modelMatrix, glm::radians(0.1f * numberFramers), glm::vec3(0, 1, 0));
planets[0].m_modelMatrix = glm::scale(planets[0].m_modelMatrix, glm::vec3(0.2f));
glUniformMatrix4fv(modelMatrixLoc, 1, GL_FALSE, &planets[0].m_modelMatrix[0][0]);
modelViewMatrix = glm::mat3(m_camera.m_viewMatrix * planets[0].m_modelMatrix);
normalMatrix = glm::inverseTranspose(modelViewMatrix);
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, &normalMatrix[0][0]);
planets[0].m_model.render(planets[0].m_trianglesToDraw);
//------
// Venus
planets[1].m_modelMatrix = glm::mat4(1.0);
planets[1].m_modelMatrix = glm::translate(planets[1].m_modelMatrix, glm::vec3(-1.75f, 0.0f, 0.0f));
planets[1].m_modelMatrix = glm::rotate(planets[1].m_modelMatrix, glm::radians(0.03f * numberFramers), glm::vec3(0, 1, 0));
planets[1].m_modelMatrix = glm::scale(planets[1].m_modelMatrix, glm::vec3(0.35f));
glUniformMatrix4fv(modelMatrixLoc, 1, GL_FALSE, &planets[1].m_modelMatrix[0][0]);
modelViewMatrix = glm::mat3(m_camera.m_viewMatrix * planets[1].m_modelMatrix);
normalMatrix = glm::inverseTranspose(modelViewMatrix);
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, &normalMatrix[0][0]);
planets[1].m_model.render(planets[1].m_trianglesToDraw);
//------
// Earth
planets[2].m_modelMatrix = glm::mat4(1.0);
planets[2].m_modelMatrix = glm::translate(planets[2].m_modelMatrix, glm::vec3(-1.25f, 0.0f, 0.0f));
planets[2].m_modelMatrix = glm::rotate(planets[2].m_modelMatrix, glm::radians(0.05f * numberFramers), glm::vec3(0, 1, 0));
planets[2].m_modelMatrix = glm::scale(planets[2].m_modelMatrix, glm::vec3(0.4f));
glUniformMatrix4fv(modelMatrixLoc, 1, GL_FALSE, &planets[2].m_modelMatrix[0][0]);
modelViewMatrix = glm::mat3(m_camera.m_viewMatrix * planets[2].m_modelMatrix);
normalMatrix = glm::inverseTranspose(modelViewMatrix);
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, &normalMatrix[0][0]);
planets[2].m_model.render(planets[2].m_trianglesToDraw);
//------
// Mars
planets[3].m_modelMatrix = glm::mat4(1.0);
planets[3].m_modelMatrix = glm::translate(planets[3].m_modelMatrix, glm::vec3(-0.75f, 0.0f, 0.0f));
planets[3].m_modelMatrix = glm::rotate(planets[3].m_modelMatrix, glm::radians(90.0f), glm::vec3(1, 0, 0));
planets[3].m_modelMatrix = glm::rotate(planets[3].m_modelMatrix, glm::radians(0.12f * numberFramers), glm::vec3(0, 0, -1));
planets[3].m_modelMatrix = glm::scale(planets[3].m_modelMatrix, glm::vec3(0.35f));
glUniformMatrix4fv(modelMatrixLoc, 1, GL_FALSE, &planets[3].m_modelMatrix[0][0]);
modelViewMatrix = glm::mat3(m_camera.m_viewMatrix * planets[3].m_modelMatrix);
normalMatrix = glm::inverseTranspose(modelViewMatrix);
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, &normalMatrix[0][0]);
planets[3].m_model.render(planets[3].m_trianglesToDraw);
//------
// Jupyter
planets[4].m_modelMatrix = glm::mat4(1.0);
planets[4].m_modelMatrix = glm::translate(planets[4].m_modelMatrix, glm::vec3(0.11f, 0.0f, 0.0f));
planets[4].m_modelMatrix = glm::rotate(planets[4].m_modelMatrix, glm::radians(90.0f), glm::vec3(1, 0, 0));
planets[4].m_modelMatrix = glm::rotate(planets[4].m_modelMatrix, glm::radians(0.07f * numberFramers), glm::vec3(0, 0, -1));
planets[4].m_modelMatrix = glm::scale(planets[4].m_modelMatrix, glm::vec3(1.0f));
glUniformMatrix4fv(modelMatrixLoc, 1, GL_FALSE, &planets[4].m_modelMatrix[0][0]);
modelViewMatrix = glm::mat3(m_camera.m_viewMatrix * planets[4].m_modelMatrix);
normalMatrix = glm::inverseTranspose(modelViewMatrix);
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, &normalMatrix[0][0]);
planets[4].m_model.render(planets[4].m_trianglesToDraw);
//------
// Saturn
planets[5].m_modelMatrix = glm::mat4(1.0);
planets[5].m_modelMatrix = glm::translate(planets[5].m_modelMatrix, glm::vec3(1.5f, 0.0f, 0.0f));
planets[5].m_modelMatrix = glm::rotate(planets[5].m_modelMatrix, glm::radians(0.002f * numberFramers), glm::vec3(1, 0, 0));
planets[5].m_modelMatrix = glm::scale(planets[5].m_modelMatrix, glm::vec3(1.1f));
glUniformMatrix4fv(modelMatrixLoc, 1, GL_FALSE, &planets[5].m_modelMatrix[0][0]);
modelViewMatrix = glm::mat3(m_camera.m_viewMatrix * planets[5].m_modelMatrix);
normalMatrix = glm::inverseTranspose(modelViewMatrix);
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, &normalMatrix[0][0]);
planets[5].m_model.render(planets[5].m_trianglesToDraw);
//------
// Uranus
planets[6].m_modelMatrix = glm::mat4(1.0);
planets[6].m_modelMatrix = glm::translate(planets[6].m_modelMatrix, glm::vec3(2.5f, 0.0f, 0.0f));
planets[6].m_modelMatrix = glm::rotate(planets[6].m_modelMatrix, glm::radians(180.0f), glm::vec3(0, 1, 0));
planets[6].m_modelMatrix = glm::rotate(planets[6].m_modelMatrix, glm::radians(0.004f * numberFramers), glm::vec3(1, 0, 0));
planets[6].m_modelMatrix = glm::scale(planets[6].m_modelMatrix, glm::vec3(0.7f));
glUniformMatrix4fv(modelMatrixLoc, 1, GL_FALSE, &planets[6].m_modelMatrix[0][0]);
modelViewMatrix = glm::mat3(m_camera.m_viewMatrix * planets[6].m_modelMatrix);
normalMatrix = glm::inverseTranspose(modelViewMatrix);
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, &normalMatrix[0][0]);
planets[6].m_model.render(planets[6].m_trianglesToDraw);
//------
// Neptune
planets[7].m_modelMatrix = glm::mat4(1.0);
planets[7].m_modelMatrix = glm::translate(planets[7].m_modelMatrix, glm::vec3(3.2f, 0.0f, 0.0f));
planets[7].m_modelMatrix = glm::rotate(planets[7].m_modelMatrix, glm::radians(0.075f * numberFramers), glm::vec3(0, 1, 0));
planets[7].m_modelMatrix = glm::scale(planets[7].m_modelMatrix, glm::vec3(0.45f));
glUniformMatrix4fv(modelMatrixLoc, 1, GL_FALSE, &planets[7].m_modelMatrix[0][0]);
modelViewMatrix = glm::mat3(m_camera.m_viewMatrix * planets[7].m_modelMatrix);
normalMatrix = glm::inverseTranspose(modelViewMatrix);
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, &normalMatrix[0][0]);
planets[7].m_model.render(planets[7].m_trianglesToDraw);
//------
// Pluto
planets[8].m_modelMatrix = glm::mat4(1.0);
planets[8].m_modelMatrix = glm::translate(planets[8].m_modelMatrix, glm::vec3(3.7f, 0.0f, 0.0f));
planets[8].m_modelMatrix = glm::rotate(planets[8].m_modelMatrix, glm::radians(0.4f * numberFramers), glm::vec3(0, 1, 0));
planets[8].m_modelMatrix = glm::scale(planets[8].m_modelMatrix, glm::vec3(0.15f));
glUniformMatrix4fv(modelMatrixLoc, 1, GL_FALSE, &planets[8].m_modelMatrix[0][0]);
modelViewMatrix = glm::mat3(m_camera.m_viewMatrix * planets[8].m_modelMatrix);
normalMatrix = glm::inverseTranspose(modelViewMatrix);
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, &normalMatrix[0][0]);
planets[8].m_model.render(planets[8].m_trianglesToDraw);
//------
numberFramers++;
glUseProgram(0);
}
void OpenGLWindow::paintUI() {
/*
{
// Header window
auto windowWidth{m_viewportWidth * 1.0f};
auto windowHeight{80};
ImGui::SetNextWindowSize(ImVec2(windowWidth, windowHeight));
ImGui::SetNextWindowPos(ImVec2((m_viewportWidth - windowWidth) / 2, 0));
auto flags{ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoCollapse};
std::string text;
text = fmt::format("{}:{}:{}\n{}:{}:{}\n{}:{}:{}\n{}",
m_camera.m_eye[0], m_camera.m_eye[1], m_camera.m_eye[2],
m_camera.m_at[0], m_camera.m_at[1], m_camera.m_at[2],
m_camera.m_up[0], m_camera.m_up[1], m_camera.m_up[2],
numberFramers);
ImGui::SetCursorPosX((windowWidth - ImGui::CalcTextSize(text.c_str()).x) /2);
ImGui::Text("%s", text.c_str());
}
*/
{
auto aspect{static_cast<float>(m_viewportWidth) / static_cast<float>(m_viewportHeight)};
m_projMatrix = glm::perspective(glm::radians(45.0f), aspect, 0.1f, 5.0f);
}
}
void OpenGLWindow::resizeGL(int width, int height) {
m_viewportWidth = width;
m_viewportHeight = height;
m_camera.computeProjectionMatrix(width, height);
}
void OpenGLWindow::terminateGL() {
glDeleteProgram(m_program);
}
void OpenGLWindow::update() {
float deltaTime{static_cast<float>(getDeltaTime())};
m_camera.dolly(m_dollySpeed * deltaTime);
m_camera.truck(m_truckSpeed * deltaTime);
m_camera.pan(m_panSpeed * deltaTime);
m_camera.lift(m_liftSpeed * deltaTime);
} | 43.444795 | 125 | 0.702658 | [
"render",
"model"
] |
e449d546ca20d6cb08918e52c745428c07bce69a | 45,831 | cpp | C++ | YCAIRO/ycairo.cpp | Youlean/wdl-ol | 0291d9f634bd2e180a402ccf9b652b4a91e00451 | [
"Zlib"
] | 36 | 2017-03-12T20:16:42.000Z | 2022-02-09T21:40:52.000Z | YCAIRO/ycairo.cpp | Youlean/wdl-ol | 0291d9f634bd2e180a402ccf9b652b4a91e00451 | [
"Zlib"
] | 1 | 2017-08-09T13:27:55.000Z | 2017-08-12T21:48:03.000Z | YCAIRO/ycairo.cpp | Youlean/wdl-ol | 0291d9f634bd2e180a402ccf9b652b4a91e00451 | [
"Zlib"
] | 9 | 2017-04-18T14:24:04.000Z | 2018-11-14T18:03:35.000Z | #include "ycairo.h"
#define NANOSVG_ALL_COLOR_KEYWORDS // Include full list of color keywords.
#define NANOSVG_IMPLEMENTATION // Expands implementation
#include "nanosvg.h"
// ycairo_background ------------------------------------------------------------------------------------------------------------------------------------
ycairo_background::ycairo_background(IPlugBase * pPlug, ycairo_base * ycairo_base, IGraphics * pGraphics, double red, double green, double blue)
: IControl(pPlug, IRECT(0, 0, pGraphics->Width(), pGraphics->Height()))
{
bg_red = red;
bg_green = green;
bg_blue = blue;
ycairo = ycairo_base;
mGraphics = pGraphics;
}
void ycairo_background::AfterGUIResize(double guiScaleRatio)
{
}
bool ycairo_background::Draw(IGraphics * pGraphics)
{
//pGraphics->FillIRect(&IColor(255,255,255,255), &mDrawRECT);
bg_surface = ycairo->get_surface();
bg_cr = ycairo->get_cr();
if (GetGUIResize())
{
cairo_surface_set_device_scale(bg_surface, GetGUIResize()->GetGUIScaleRatio(), GetGUIResize()->GetGUIScaleRatio());
}
cairo_reset_clip(bg_cr);
cairo_new_path(bg_cr);
//pGraphics->MarkAllIntersectingControlsDirty();
//IRECT dirtyR;
//if (pGraphics->IsDirty(&dirtyR))
//{
// cairo_rectangle(bg_cr, dirtyR.L, dirtyR.T, dirtyR.W(), dirtyR.H());
//}
if (true)
{
cairo_rectangle(bg_cr, mNonScaledDrawRECT.L, mNonScaledDrawRECT.T, mNonScaledDrawRECT.W(), mNonScaledDrawRECT.H());
}
else
{
for (int i = 1; i < pGraphics->GetNControls(); i++)
{
if (pGraphics->GetControl(i)->IsDirty() && !pGraphics->GetControl(i)->IsHidden())
{
IRECT tmpRECT = *pGraphics->GetControl(i)->GetNonScaledDrawRECT();
if (i == 1)
{
cairo_move_to(bg_cr, tmpRECT.L, tmpRECT.T);
cairo_rel_line_to(bg_cr, tmpRECT.W(), 0);
cairo_rel_line_to(bg_cr, 0, tmpRECT.H());
cairo_rel_line_to(bg_cr, -tmpRECT.W(), 0);
}
else if (i > 1)
{
cairo_new_sub_path(bg_cr);
cairo_line_to(bg_cr, tmpRECT.L, tmpRECT.T);
cairo_rel_line_to(bg_cr, tmpRECT.W(), 0);
cairo_rel_line_to(bg_cr, 0, tmpRECT.H());
cairo_rel_line_to(bg_cr, -tmpRECT.W(), 0);
}
}
}
}
cairo_set_source_rgb(bg_cr, bg_red, bg_green, bg_blue);
cairo_fill(bg_cr);
return true;
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------
ycairo_base::ycairo_base(IPlugBase * pPlug)
{
ycairo_iplug_base = pPlug;
}
ycairo_base::~ycairo_base()
{
if (cr) cairo_destroy(cr);
if (surface) cairo_surface_destroy(surface);
// If global font was initialized, destroy font on exit
if (global_font)
{
FT_Done_Face(ft_face);
FT_Done_FreeType(ft_library);
}
}
#ifdef _WIN32
void ycairo_base::set_HINSTANCE(HINSTANCE hinstance)
{
hinstance_handle = hinstance;
}
HINSTANCE ycairo_base::get_HINSTANCE()
{
return hinstance_handle;
}
#elif defined(__APPLE__)
void ycairo_base::set_BUNDLE_ID(const char* _bundleID)
{
bundleID = _bundleID;
}
const char* ycairo_base::get_BUNDLE_ID()
{
return bundleID;
}
#endif
void ycairo_base::create_global_font_from_path(const char * path)
{
// If global font was initialized, destroy old font
if (global_font)
{
FT_Done_Face(ft_face);
FT_Done_FreeType(ft_library);
}
FT_Init_FreeType(&ft_library);
FT_New_Face(ft_library, path, 0, &ft_face);
global_font = true;
}
void ycairo_base::create_global_font_from_memory(int name, int type, const char * relative_path)
{
// If global font was initialized, destroy old font
if (global_font)
{
FT_Done_Face(ft_face);
FT_Done_FreeType(ft_library);
}
#ifdef _WIN32
HRSRC rc = ::FindResource(hinstance_handle, MAKEINTRESOURCE(name), MAKEINTRESOURCE(type));
HGLOBAL rcData = ::LoadResource(hinstance_handle, rc);
int size = ::SizeofResource(hinstance_handle, rc);
const FT_Byte* data = static_cast<const FT_Byte*>(::LockResource(rcData));
FT_Init_FreeType(&ft_library);
FT_New_Memory_Face(ft_library, data, size, 0, &ft_face);
#elif defined(__APPLE__)
CFStringRef CFBundleID = __CFStringMakeConstantString(bundleID);
CFBundleRef requestedBundle = CFBundleGetBundleWithIdentifier(CFBundleID);
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(requestedBundle);
char path[PATH_MAX];
CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX);
CFRelease(resourcesURL);
chdir(path);
std::string font_path = path;
std::string font_name = relative_path;
int lastindex = font_name.find_last_of("/");
font_path.append(font_name.substr(lastindex, font_name.size() - lastindex));
FT_Init_FreeType(&ft_library);
FT_New_Face(ft_library, font_path.c_str(), 0, &ft_face);
#endif
global_font = true;
}
void ycairo_base::bind_to_lice(IGraphics * pGraphics)
{
base_width = pGraphics->GetDrawBitmap()->getWidth();
base_height = pGraphics->GetDrawBitmap()->getHeight();
surface = cairo_image_surface_create_for_data((unsigned char*)pGraphics->GetBits(),
CAIRO_FORMAT_RGB24, base_width, base_height, cairo_format_stride_for_width(CAIRO_FORMAT_RGB24, pGraphics->GetDrawBitmap()->getRowSpan()));
cr = cairo_create(surface);
cairo_set_source_rgb(cr, red, green, blue);
cairo_rectangle(cr, 0, 0, base_width, base_height);
cairo_fill(cr);
}
void ycairo_base::attach_background(IGraphics * pGraphics, IColor color)
{
base_width = pGraphics->Width();
base_height = pGraphics->Height();
red = (double)color.R / 255.0;
green = (double)color.G / 255.0;
blue = (double)color.B / 255.0;
IControl* pBG = new ycairo_background(ycairo_iplug_base, this, pGraphics, red, green, blue);
pGraphics->AttachControl(pBG);
}
cairo_t * ycairo_base::get_cr()
{
return cr;
}
cairo_surface_t * ycairo_base::get_surface()
{
return surface;
}
int ycairo_base::get_width()
{
return base_width;
}
int ycairo_base::get_height()
{
return base_height;
}
FT_Library * ycairo_base::get_global_ft_lib()
{
return &ft_library;
}
FT_Face * ycairo_base::get_global_ft_face()
{
return &ft_face;
}
bool ycairo_base::global_font_initialized()
{
return global_font;
}
IPlugBase * ycairo_base::GetIPlugBase()
{
return ycairo_iplug_base;
}
ycairo_gui::ycairo_gui(ycairo_base * ycairo_base, IControl *pControl)
{
if (ycairo_base->GetIPlugBase()->GetGUIResize())
{
non_scaled_draw_rect = pControl->GetNonScaledDrawRECT();
}
else
{
draw_rect = pControl->GetDrawRECT();
}
ycairo = ycairo_base;
}
void ycairo_gui::ycairo_reset_clip(cairo_t * cr)
{
if (ycairo->GetIPlugBase()->GetGUIResize())
{
ycairo_reset_clip_to(cr, *non_scaled_draw_rect);
}
else
{
ycairo_reset_clip_to(cr, *draw_rect);
}
}
void ycairo_helper::ycairo_reset_clip_to(cairo_t *cr, IRECT rect)
{
cairo_new_path(cr);
cairo_reset_clip(cr);
cairo_rectangle(cr, rect.L, rect.T, rect.W(), rect.H());
cairo_clip(cr);
}
void ycairo_helper::ycairo_rounded_rectangle(cairo_t * cr, double x, double y, double width, double height, double corner)
{
cairo_new_path(cr);
cairo_arc(cr, x + width - corner, y + corner, corner, -1.5707963267948966192313216916398, 0);
cairo_arc(cr, x + width - corner, y + height - corner, corner, 0, 1.5707963267948966192313216916398);
cairo_arc(cr, x + corner, y + height - corner, corner, 1.5707963267948966192313216916398, 3.1415926535897932384626433832796);
cairo_arc(cr, x + corner, y + corner, corner, 3.1415926535897932384626433832796, 4.7123889803846898576939650749193);
cairo_close_path(cr);
}
void ycairo_helper::ycairo_circle(cairo_t * cr, double x, double y, double radius)
{
cairo_arc(cr, x, y, radius, 0, 6.283185307179586476925286766559);
}
void ycairo_helper::ycairo_set_source_rgba(cairo_t * cr, IColor color)
{
cairo_set_source_rgba(cr, color.R / 255.0, color.G / 255.0, color.B / 255.0, color.A / 255.0);
}
void ycairo_helper::ycairo_set_source_rgba(cairo_t * cr, IColor *color)
{
cairo_set_source_rgba(cr, color->R / 255.0, color->G / 255.0, color->B / 255.0, color->A / 255.0);
}
void ycairo_helper::ycairo_set_source_rgba_fast(cairo_t * cr, IColor color)
{
cairo_set_source_rgba(cr, color.R / 256.0, color.G / 256.0, color.B / 256.0, color.A / 256.0);
}
void ycairo_helper::ycairo_set_source_rgba_fast(cairo_t * cr, IColor *color)
{
cairo_set_source_rgba(cr, color->R / 256.0, color->G / 256.0, color->B / 256.0, color->A / 256.0);
}
void ycairo_helper::ycairo_anchor_rotate(cairo_t * cr, double x, double y, double angle)
{
cairo_translate(cr, x, y);
cairo_rotate(cr, angle);
cairo_translate(cr, -x, -y);
}
void ycairo_helper::ycairo_anchor_scale(cairo_t * cr, double x, double y, double sx, double sy)
{
cairo_translate(cr, x, y);
cairo_scale(cr, sx, sy);
cairo_translate(cr, -x, -y);
}
void ycairo_drop_shadow::_ycairo_draw_drop_shadow_fast(cairo_t * cr, bool stroke)
{
int props_index = _get_props_index(cr);
cairo_path_t *path = cairo_copy_path(cr);
cairo_pattern_t *source_pattern = cairo_pattern_reference(cairo_get_source(cr));
double cx1, cy1, cx2, cy2;
cairo_clip_extents(cr, &cx1, &cy1, &cx2, &cy2);
double x1, y1, x2, y2;
if (stroke)
{
cairo_set_line_width(cr, props[props_index].shadow_radius);
cairo_stroke_extents(cr, &x1, &y1, &x2, &y2);
}
else cairo_path_extents(cr, &x1, &y1, &x2, &y2);
x1 = IPMAX(x1, cx1);
y1 = IPMAX(y1, cy1);
x2 = IPMIN(x2, cx2);
y2 = IPMIN(y2, cy2);
double surface_width = IPMAX(x2 - x1, 0.0) / props[props_index].shadow_radius;
double surface_height = IPMAX(y2 - y1, 0.0) / props[props_index].shadow_radius;
if (surface_width - int(surface_width) > 0) surface_width++;
if (surface_height - int(surface_height) > 0) surface_height++;
if (surface_width < 1) surface_width++;
if (surface_height < 1) surface_height++;
cairo_surface_t *shadow_surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, (int)surface_width, (int)surface_height);
cairo_t *shadow_cr = cairo_create(shadow_surface);
cairo_translate(shadow_cr, -x1 / props[props_index].shadow_radius, -y1 / props[props_index].shadow_radius);
cairo_scale(shadow_cr, 1 / props[props_index].shadow_radius, 1 / props[props_index].shadow_radius);
cairo_set_source_rgba(shadow_cr, 0, 0, 0, props[props_index].shadow_opacity);
cairo_append_path(shadow_cr, path);
if (stroke)
{
cairo_set_line_width(shadow_cr, props[props_index].shadow_radius);
cairo_stroke(shadow_cr);
}
else cairo_fill(shadow_cr);
cairo_scale(shadow_cr, props[props_index].shadow_radius, props[props_index].shadow_radius);
cairo_translate(shadow_cr, x1 / props[props_index].shadow_radius, y1 / props[props_index].shadow_radius);
// Destination surface
cairo_scale(cr, props[props_index].shadow_radius, props[props_index].shadow_radius);
cairo_set_source_surface(cr, shadow_surface, (x1 + props[props_index].shadow_offset_x) / props[props_index].shadow_radius, (y1 + props[props_index].shadow_offset_y) / props[props_index].shadow_radius);
cairo_paint(cr);
cairo_scale(cr, 1 / props[props_index].shadow_radius, 1 / props[props_index].shadow_radius);
cairo_set_source(cr, source_pattern);
if (!stroke)
{
cairo_new_path(cr);
cairo_append_path(cr, path);
}
cairo_pattern_destroy(source_pattern);
cairo_path_destroy(path);
cairo_destroy(shadow_cr);
cairo_surface_destroy(shadow_surface);
}
void ycairo_drop_shadow::_ycairo_draw_drop_shadow(cairo_t * cr, bool stroke, double downsample)
{
int props_index = _get_props_index(cr);
cairo_path_t *path = cairo_copy_path(cr);
cairo_pattern_t *source_pattern = cairo_pattern_reference(cairo_get_source(cr));
double cx1, cy1, cx2, cy2;
cairo_clip_extents(cr, &cx1, &cy1, &cx2, &cy2);
double x1, y1, x2, y2;
if (stroke)
{
cairo_set_line_width(cr, props[props_index].shadow_radius);
cairo_stroke_extents(cr, &x1, &y1, &x2, &y2);
}
else cairo_path_extents(cr, &x1, &y1, &x2, &y2);
x1 = IPMAX(x1, cx1);
y1 = IPMAX(y1, cy1);
x2 = IPMIN(x2, cx2);
y2 = IPMIN(y2, cy2);
double surface_width = (IPMAX(x2 - x1, 0.0) + props[props_index].shadow_radius * 2) / downsample;
double surface_height = (IPMAX(y2 - y1, 0.0) + props[props_index].shadow_radius * 2) / downsample;
if (surface_width - int(surface_width) > 0) surface_width++;
if (surface_height - int(surface_height) > 0) surface_height++;
if (surface_width < 1) surface_width++;
if (surface_height < 1) surface_height++;
cairo_surface_t *shadow_surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, (int)surface_width, (int)surface_height);
cairo_t *shadow_cr = cairo_create(shadow_surface);
cairo_translate(shadow_cr, (-x1 + props[props_index].shadow_radius) / downsample, (-y1 + props[props_index].shadow_radius) / downsample);
cairo_scale(shadow_cr, 1.0 / downsample, 1.0 / downsample);
cairo_set_source_rgb(shadow_cr, 0, 0, 0);
cairo_append_path(shadow_cr, path);
if (stroke)
{
cairo_set_line_width(shadow_cr, props[props_index].shadow_radius);
cairo_stroke(shadow_cr);
}
else cairo_fill(shadow_cr);
cairo_scale(shadow_cr, downsample, downsample);
cairo_translate(shadow_cr, (x1 - props[props_index].shadow_radius) / downsample, (y1 - props[props_index].shadow_radius) / downsample);
// Destination surface
_ycairo_blur_surface_channel_offseted_minus_radius(shadow_surface, int(props[props_index].shadow_radius / downsample), 3);
cairo_scale(cr, downsample, downsample);
cairo_set_source_surface(cr, shadow_surface, ((x1 + props[props_index].shadow_offset_x) - props[props_index].shadow_radius / 2) / downsample, ((y1 + props[props_index].shadow_offset_y) - props[props_index].shadow_radius / 2) / downsample);
cairo_paint_with_alpha(cr, props[props_index].shadow_opacity);
cairo_scale(cr, 1.0 / downsample, 1.0 / downsample);
cairo_new_path(cr);
cairo_append_path(cr, path);
cairo_set_source(cr, source_pattern);
cairo_pattern_destroy(source_pattern);
cairo_path_destroy(path);
cairo_destroy(shadow_cr);
cairo_surface_destroy(shadow_surface);
}
void ycairo_helper::ycairo_triangle(cairo_t * cr, double x0, double y0, double x1, double y1, double x2, double y2)
{
cairo_new_sub_path(cr);
cairo_move_to(cr, x0, y0);
cairo_line_to(cr, x1, y1);
cairo_line_to(cr, x2, y2);
cairo_close_path(cr);
}
void ycairo_gui::ycairo_prepare_draw()
{
//Getting surface
surface = ycairo->get_surface();
cr = ycairo->get_cr();
// Set anti aliasing method
//cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE); // 10x faster than GOOD
cairo_set_antialias(cr, CAIRO_ANTIALIAS_FAST); // 3x faster than GOOD
//cairo_set_antialias(cr, CAIRO_ANTIALIAS_GOOD);
//Adding new path and new clip region
cairo_new_path(cr);
if (ycairo->GetIPlugBase()->GetGUIResize())
{
cairo_rectangle(cr, non_scaled_draw_rect->L, non_scaled_draw_rect->T, non_scaled_draw_rect->W(), non_scaled_draw_rect->H());
}
else
{
cairo_rectangle(cr, draw_rect->L, draw_rect->T, draw_rect->W(), draw_rect->H());
}
cairo_clip(cr);
}
void ycairo_gui::ycairo_draw()
{
//cairo_surface_flush(surface);
cairo_reset_clip(cr);
}
ycairo_text::ycairo_text(ycairo_base * ycairo_base)
{
#ifdef _WIN32
hinstance_handle = ycairo_base->get_HINSTANCE();
#elif defined(__APPLE__)
bundleID = ycairo_base->get_BUNDLE_ID();
#endif
ext_height = new cairo_text_extents_t;
text_extents = new cairo_text_extents_t;
font_extents = new cairo_font_extents_t;
global_font_initialized = ycairo_base->global_font_initialized();
if (global_font_initialized)
{
global_ft_library = ycairo_base->get_global_ft_lib();
global_ft_face = ycairo_base->get_global_ft_face();
}
}
ycairo_text::~ycairo_text()
{
delete ext_height;
delete text_extents;
delete font_extents;
// If local font was initialized destroy font on exit
if (local_font_initialized)
{
FT_Done_Face(local_ft_face);
FT_Done_FreeType(local_ft_library);
}
}
void ycairo_text::ycairo_create_font_from_path(const char * path)
{
// If local font was initialized destroy old font
if (local_font_initialized)
{
FT_Done_Face(local_ft_face);
FT_Done_FreeType(local_ft_library);
}
FT_Init_FreeType(&local_ft_library);
FT_New_Face(local_ft_library, path, 0, &local_ft_face);
local_font_initialized = true;
}
void ycairo_text::ycairo_create_font_from_memory(int name, int type, const char * relative_path)
{
// If local font was initialized destroy old font
if (local_font_initialized)
{
FT_Done_Face(local_ft_face);
FT_Done_FreeType(local_ft_library);
}
#ifdef _WIN32
HRSRC rc = ::FindResource(hinstance_handle, MAKEINTRESOURCE(name), MAKEINTRESOURCE(type));
HGLOBAL rcData = ::LoadResource(hinstance_handle, rc);
int size = ::SizeofResource(hinstance_handle, rc);
const FT_Byte* data = static_cast<const FT_Byte*>(::LockResource(rcData));
FT_Init_FreeType(&local_ft_library);
FT_New_Memory_Face(local_ft_library, data, size, 0, &local_ft_face);
#elif defined(__APPLE__)
CFStringRef CFBundleID = __CFStringMakeConstantString(bundleID);
CFBundleRef requestedBundle = CFBundleGetBundleWithIdentifier(CFBundleID);
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(requestedBundle);
char path[PATH_MAX];
CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX);
CFRelease(resourcesURL);
chdir(path);
std::string font_path = path;
std::string font_name = relative_path;
int lastindex = font_name.find_last_of("/");
font_path.append(font_name.substr(lastindex, font_name.size() - lastindex));
FT_Init_FreeType(&local_ft_library);
FT_New_Face(local_ft_library, font_path.c_str(), 0, &local_ft_face);
#endif
local_font_initialized = true;
}
void ycairo_text::ycairo_initialize_font_face(cairo_t * cr)
{
if (local_font_initialized)
{
current_font_face = cairo_ft_font_face_create_for_ft_face(local_ft_face, 0);
cairo_set_font_face(cr, current_font_face);
}
else if (global_font_initialized)
{
current_font_face = cairo_ft_font_face_create_for_ft_face(*global_ft_face, 0);
cairo_set_font_face(cr, current_font_face);
}
else
{
return;
}
}
void ycairo_text::ycairo_destroy_font_face()
{
cairo_font_face_destroy(current_font_face);
}
void ycairo_text::ycairo_set_text(cairo_t * cr, const string &text)
{
single_line_text = text;
}
void ycairo_text::ycairo_set_multiline_text(cairo_t * cr, const string &text)
{
multi_line_text = text;
}
void ycairo_text::ycairo_set_text_position(cairo_t * cr, DRECT rect, ycairo_text_w_aligement w_aligement, ycairo_text_h_aligement h_aligement)
{
width_aligement = w_aligement;
height_aligement = h_aligement;
text_rect = rect;
ycairo_calculate_extents(cr);
double x, y;
switch (width_aligement)
{
case YCAIRO_TEXT_W_ALIGN_LEFT:
x = text_rect.L;
break;
case YCAIRO_TEXT_W_ALIGN_RIGHT:
x = text_rect.R - text_extents->width - text_extents->x_bearing;
break;
case YCAIRO_TEXT_W_ALIGN_CENTER:
x = text_rect.L + ((text_rect.W() - text_extents->width - text_extents->x_bearing) / 2.0);
break;
default:
break;
}
switch (height_aligement)
{
case YCAIRO_TEXT_H_ALIGN_TOP:
y = text_rect.T + font_extents->ascent;
break;
case YCAIRO_TEXT_H_ALIGN_BOTTOM:
y = text_rect.B - font_extents->descent;
break;
case YCAIRO_TEXT_H_ALIGN_CENTER:
y = text_rect.B - ((text_rect.H() - font_extents->height) / 2.0) - font_extents->descent;
break;
default:
break;
}
cairo_move_to(cr, x, y);
}
void ycairo_text::ycairo_set_multiline_text_position(cairo_t * cr, DRECT rect, ycairo_text_w_aligement w_aligement, ycairo_text_h_aligement h_aligement)
{
multiline_width_aligement = w_aligement;
multiline_height_aligement = h_aligement;
multiline_text_rect = rect;
CreateTextLinesVector(cr, rect);
}
void ycairo_text::ycairo_calculate_extents(cairo_t * cr)
{
cairo_font_extents(cr, font_extents);
cairo_text_extents(cr, single_line_text.c_str(), text_extents);
}
cairo_font_extents_t * ycairo_text::ycairo_get_font_extents(cairo_t * cr)
{
return font_extents;
}
cairo_text_extents_t * ycairo_text::ycairo_get_text_extents(cairo_t * cr)
{
return text_extents;
}
void ycairo_text::ycairo_show_text(cairo_t * cr, const char * text, double size, IColor color, IRECT rect, ycairo_text_w_aligement w_aligement, ycairo_text_h_aligement h_aligement)
{
cairo_set_source_rgba(cr, color.R / 255.0, color.G / 255.0, color.B / 255.0, color.A / 255.0);
ycairo_initialize_font_face(cr);
cairo_set_font_size(cr, size);
ycairo_set_text(cr, text);
ycairo_set_text_position(cr, rect, w_aligement, h_aligement);
//// Adding subpixel rendering improves rendering speed by 10% on my system
//cairo_font_options_t *options;
//cairo_get_font_options(cr, options);
//cairo_font_options_set_antialias(options, CAIRO_ANTIALIAS_SUBPIXEL);
//cairo_set_font_options(cr, options);
//// -----------------------------------------------------------------------
ycairo_show_text(cr);
ycairo_destroy_font_face();
}
void ycairo_text::ycairo_text_path(cairo_t * cr, const char * text, double size, IRECT rect, ycairo_text_w_aligement w_aligement, ycairo_text_h_aligement h_aligement)
{
ycairo_initialize_font_face(cr);
cairo_set_font_size(cr, size);
ycairo_set_text(cr, text);
ycairo_set_text_position(cr, rect, w_aligement, h_aligement);
//// Adding subpixel rendering improves rendering speed by 10% on my system
//cairo_font_options_t *options;
//cairo_get_font_options(cr, options);
//cairo_font_options_set_antialias(options, CAIRO_ANTIALIAS_SUBPIXEL);
//cairo_set_font_options(cr, options);
//// -----------------------------------------------------------------------
ycairo_text_path(cr);
ycairo_destroy_font_face();
}
void ycairo_text::ycairo_show_multiline_text(cairo_t * cr, const string &text, double size, IColor color, IRECT rect, ycairo_text_w_aligement w_aligement, ycairo_text_h_aligement h_aligement)
{
cairo_set_source_rgba(cr, color.R / 255.0, color.G / 255.0, color.B / 255.0, color.A / 255.0);
ycairo_initialize_font_face(cr);
cairo_set_font_size(cr, size);
ycairo_set_multiline_text(cr, text);
ycairo_set_multiline_text_position(cr, rect, w_aligement, h_aligement);
ycairo_show_multiline_text(cr);
ycairo_destroy_font_face();
}
void ycairo_text::ycairo_multiline_text_path(cairo_t * cr, const string &text, double size, IRECT rect, ycairo_text_w_aligement w_aligement, ycairo_text_h_aligement h_aligement)
{
ycairo_initialize_font_face(cr);
cairo_set_font_size(cr, size);
ycairo_set_multiline_text(cr, text);
ycairo_set_multiline_text_position(cr, rect, w_aligement, h_aligement);
ycairo_multiline_text_path(cr);
ycairo_destroy_font_face();
}
void ycairo_text::ycairo_show_text(cairo_t * cr, const string &text, double size, IColor color, IRECT rect, ycairo_text_w_aligement w_aligement, ycairo_text_h_aligement h_aligement)
{
ycairo_show_text(cr, text.c_str(), size, color, rect, w_aligement, h_aligement);
}
void ycairo_text::ycairo_text_path(cairo_t * cr, const string &text, double size, IRECT rect, ycairo_text_w_aligement w_aligement, ycairo_text_h_aligement h_aligement)
{
ycairo_text_path(cr, text.c_str(), size, rect, w_aligement, h_aligement);
}
void ycairo_text::ycairo_show_multiline_text(cairo_t * cr)
{
cairo_font_extents(cr, font_extents);
double fontHeight = font_extents->height;
int lineNumber = text_lines.size();
switch (multiline_height_aligement)
{
case YCAIRO_TEXT_H_ALIGN_TOP:
{
for (int i = 0; i < lineNumber; i++)
{
DRECT textRect = multiline_text_rect;
textRect.B = multiline_text_rect.T + (i + 1) * fontHeight;
textRect.T = textRect.B - fontHeight;
ycairo_set_text(cr, text_lines[i]);
ycairo_set_text_position(cr, textRect, multiline_width_aligement, ycairo_text_h_aligement::YCAIRO_TEXT_H_ALIGN_CENTER);
cairo_show_text(cr, text_lines[i].c_str());
}
break;
}
case YCAIRO_TEXT_H_ALIGN_BOTTOM:
{
for (int i = 0; i < lineNumber; i++)
{
int indexInv = (lineNumber - 1) - i;
DRECT textRect = multiline_text_rect;
textRect.T = multiline_text_rect.B - (i + 1) * fontHeight;
textRect.B = textRect.T + fontHeight;
ycairo_set_text(cr, text_lines[indexInv]);
ycairo_set_text_position(cr, textRect, multiline_width_aligement, ycairo_text_h_aligement::YCAIRO_TEXT_H_ALIGN_CENTER);
cairo_show_text(cr, text_lines[indexInv].c_str());
}
break;
}
case YCAIRO_TEXT_H_ALIGN_CENTER:
{
for (int i = 0; i < lineNumber; i++)
{
double top = (multiline_text_rect.H() - lineNumber * fontHeight) / 2 + multiline_text_rect.T;
DRECT textRect = multiline_text_rect;
textRect.B = top + (i + 1) * fontHeight;
textRect.T = textRect.B - fontHeight;
ycairo_set_text(cr, text_lines[i]);
ycairo_set_text_position(cr, textRect, multiline_width_aligement, ycairo_text_h_aligement::YCAIRO_TEXT_H_ALIGN_CENTER);
cairo_show_text(cr, text_lines[i].c_str());
}
break;
}
default:
break;
}
}
void ycairo_text::ycairo_multiline_text_path(cairo_t * cr)
{
cairo_font_extents(cr, font_extents);
double fontHeight = font_extents->height;
int lineNumber = text_lines.size();
switch (multiline_height_aligement)
{
case YCAIRO_TEXT_H_ALIGN_TOP:
{
for (int i = 0; i < lineNumber; i++)
{
DRECT textRect = multiline_text_rect;
textRect.B = multiline_text_rect.T + (i + 1) * fontHeight;
textRect.T = textRect.B - fontHeight;
ycairo_set_text(cr, text_lines[i]);
ycairo_set_text_position(cr, textRect, multiline_width_aligement, ycairo_text_h_aligement::YCAIRO_TEXT_H_ALIGN_CENTER);
cairo_text_path(cr, text_lines[i].c_str());
}
break;
}
case YCAIRO_TEXT_H_ALIGN_BOTTOM:
{
for (int i = 0; i < lineNumber; i++)
{
int indexInv = (lineNumber - 1) - i;
DRECT textRect = multiline_text_rect;
textRect.T = multiline_text_rect.B - (i + 1) * fontHeight;
textRect.B = textRect.T + fontHeight;
ycairo_set_text(cr, text_lines[indexInv]);
ycairo_set_text_position(cr, textRect, multiline_width_aligement, ycairo_text_h_aligement::YCAIRO_TEXT_H_ALIGN_CENTER);
cairo_text_path(cr, text_lines[indexInv].c_str());
}
break;
}
case YCAIRO_TEXT_H_ALIGN_CENTER:
{
for (int i = 0; i < lineNumber; i++)
{
double top = (multiline_text_rect.H() - lineNumber * fontHeight) / 2 + multiline_text_rect.T;
DRECT textRect = multiline_text_rect;
textRect.B = top + (i + 1) * fontHeight;
textRect.T = textRect.B - fontHeight;
ycairo_set_text(cr, text_lines[i]);
ycairo_set_text_position(cr, textRect, multiline_width_aligement, ycairo_text_h_aligement::YCAIRO_TEXT_H_ALIGN_CENTER);
cairo_text_path(cr, text_lines[i].c_str());
}
break;
}
default:
break;
}
}
void ycairo_text::ycairo_show_text(cairo_t * cr)
{
cairo_show_text(cr, single_line_text.c_str());
}
void ycairo_text::ycairo_text_path(cairo_t * cr)
{
cairo_text_path(cr, single_line_text.c_str());
}
void ycairo_text::CreateTextLinesVector(cairo_t * cr, DRECT rect)
{
text_lines.resize(0);
text_lines.push_back(string());
double stringSize = 0;
string tmpString;
double tmpStringSize = 0;
// Find space or new line or tab
for (int i = 0; i < multi_line_text.size(); i++)
{
string c;
c.push_back(multi_line_text[i]);
if (c == " ")
{
if (stringSize + tmpStringSize > rect.W())
{
text_lines.push_back(string());
stringSize = 0;
}
text_lines.back().append(tmpString);
stringSize += tmpStringSize;
tmpString.resize(0);
tmpStringSize = 0;
cairo_text_extents(cr, c.c_str(), text_extents);
stringSize += text_extents->x_advance;
if (stringSize <= rect.W())
text_lines.back().append(" ");
}
else if (c == "\t")
{
if (stringSize + tmpStringSize > rect.W())
{
text_lines.push_back(string());
stringSize = 0;
}
text_lines.back().append(tmpString);
stringSize += tmpStringSize;
tmpString.resize(0);
tmpStringSize = 0;
cairo_text_extents(cr, " ", text_extents);
stringSize += text_extents->x_advance;
if (stringSize <= rect.W())
text_lines.back().append(" ");
}
else if (c == "\n")
{
if (stringSize + tmpStringSize > rect.W())
{
text_lines.push_back(string());
stringSize = 0;
}
text_lines.back().append(tmpString);
stringSize += tmpStringSize;
tmpString.resize(0);
tmpStringSize = 0;
text_lines.push_back(string());
stringSize = 0;
}
else
{
if (stringSize > rect.W())
{
text_lines.push_back(string());
stringSize = 0;
}
cairo_text_extents(cr, c.c_str(), text_extents);
tmpStringSize += text_extents->x_advance;
tmpString.append(c);
}
}
if (stringSize + tmpStringSize > rect.W())
{
text_lines.push_back(string());
stringSize = 0;
}
text_lines.back().append(tmpString);
stringSize += tmpStringSize;
tmpString.resize(0);
tmpStringSize = 0;
}
void ycairo_blur::_ycairo_blur_surface_offseted(cairo_surface_t * src_surface, unsigned int radius, unsigned int channels_num)
{
unsigned char* src = cairo_image_surface_get_data(src_surface);
unsigned int src_width = cairo_image_surface_get_width(src_surface);
unsigned int src_stride = cairo_image_surface_get_stride(src_surface);
unsigned int src_height = cairo_image_surface_get_height(src_surface);
unsigned int src_excess_w_stride = src_stride - src_width * channels_num;
cairo_surface_flush(src_surface);
unsigned int w_radius_stride = radius * channels_num;
unsigned int h_radius_stride = radius * src_stride;
unsigned char *src_c = src;
// Blur horizontaly
for (unsigned int h = 0; h < src_height; h++)
{
_reset();
for (unsigned int w = 0; w < src_width; w++)
{
_average_pixel(src_c, w, radius, w_radius_stride);
src_c += channels_num;
}
src_c += src_excess_w_stride;
}
// Blur vertically
for (unsigned int s = 0; s < src_stride - src_excess_w_stride; s += channels_num)
{
src_c = src + s;
_reset();
for (unsigned int h = 0; h < src_height; h++)
{
_average_pixel(src_c, h, radius, h_radius_stride);
src_c += src_stride;
}
}
}
void ycairo_blur::_ycairo_blur_surface_channel_offseted(cairo_surface_t * src_surface, unsigned int radius, unsigned int channel, unsigned int channels_num)
{
unsigned char* src = cairo_image_surface_get_data(src_surface);
unsigned int src_width = cairo_image_surface_get_width(src_surface);
unsigned int src_stride = cairo_image_surface_get_stride(src_surface);
unsigned int src_height = cairo_image_surface_get_height(src_surface);
unsigned int src_excess_w_stride = src_stride - src_width * channels_num;
cairo_surface_flush(src_surface);
unsigned int w_radius_stride = radius * channels_num;
unsigned int h_radius_stride = radius * src_stride;
unsigned char *src_c = src + channel;
// Blur horizontaly
for (unsigned int h = 0; h < src_height; h++)
{
_reset();
for (unsigned int w = 0; w < src_width; w++)
{
_average_channel(src_c, w, radius, w_radius_stride);
src_c += channels_num;
}
src_c += src_excess_w_stride;
}
// Blur vertically
for (unsigned int s = 0; s < src_stride - src_excess_w_stride; s += channels_num)
{
src_c = src + s;
_reset();
for (unsigned int h = 0; h < src_height; h++)
{
_average_channel(src_c, h, radius, h_radius_stride);
src_c += src_stride;
}
}
}
void ycairo_blur::_ycairo_blur_surface_offseted_minus_radius(cairo_surface_t * src_surface, unsigned int radius, unsigned int channels_num)
{
unsigned int shift = _get_bit_shift(radius);
unsigned char* src = cairo_image_surface_get_data(src_surface);
unsigned int src_width = cairo_image_surface_get_width(src_surface);
unsigned int src_stride = cairo_image_surface_get_stride(src_surface);
unsigned int src_height = cairo_image_surface_get_height(src_surface);
unsigned int src_excess_w_stride = src_stride - src_width * channels_num;
cairo_surface_flush(src_surface);
unsigned int w_radius_stride = radius * channels_num;
unsigned int h_radius_stride = radius * src_stride;
unsigned char *src_c = src + h_radius_stride + w_radius_stride;
if (shift > 0)
{
// Blur horizontaly
for (unsigned int h = radius; h < src_height; h++)
{
_reset();
for (unsigned int w = radius; w < src_width; w++)
{
_average_pixel_bit_shift(src_c, shift, w_radius_stride);
src_c += channels_num;
}
src_c += w_radius_stride;
src_c += src_excess_w_stride;
}
// Blur vertically
for (unsigned int s = 0; s < src_stride - src_excess_w_stride; s += channels_num)
{
src_c = src + s + h_radius_stride;
_reset();
for (unsigned int h = radius; h < src_height; h++)
{
_average_pixel_bit_shift(src_c, shift, h_radius_stride);
src_c += src_stride;
}
}
}
else
{
// Blur horizontaly
for (unsigned int h = radius; h < src_height; h++)
{
_reset();
for (unsigned int w = radius; w < src_width; w++)
{
_average_pixel_minus_radius(src_c, radius, w_radius_stride);
src_c += channels_num;
}
src_c += w_radius_stride;
src_c += src_excess_w_stride;
}
// Blur vertically
for (unsigned int s = 0; s < src_stride - src_excess_w_stride; s += channels_num)
{
src_c = src + s + h_radius_stride;
_reset();
for (unsigned int h = radius; h < src_height; h++)
{
_average_pixel_minus_radius(src_c, radius, h_radius_stride);
src_c += src_stride;
}
}
}
cairo_surface_mark_dirty(src_surface);
}
void ycairo_blur::_ycairo_blur_surface_channel_offseted_minus_radius(cairo_surface_t * src_surface, unsigned int radius, unsigned int channel, int unsigned channels_num)
{
unsigned int shift = _get_bit_shift(radius);
unsigned char* src = cairo_image_surface_get_data(src_surface);
unsigned int src_width = cairo_image_surface_get_width(src_surface);
unsigned int src_stride = cairo_image_surface_get_stride(src_surface);
unsigned int src_height = cairo_image_surface_get_height(src_surface);
unsigned int src_excess_w_stride = src_stride - src_width * channels_num;
cairo_surface_flush(src_surface);
unsigned int w_radius_stride = radius * channels_num;
unsigned int h_radius_stride = radius * src_stride;
unsigned char *src_c = src + channel + h_radius_stride + w_radius_stride;
unsigned int max_sum = radius * 255;
if (shift > 0)
{
// Blur horizontaly
for (unsigned int h = radius; h < src_height; h++)
{
_reset();
for (int w = radius; w < src_width; w++)
{
_average_channel_bit_shift(src_c, shift, w_radius_stride, max_sum);
src_c += channels_num;
}
src_c += w_radius_stride;
src_c += src_excess_w_stride;
}
// Blur vertically
for (unsigned int s = 0; s < src_stride - src_excess_w_stride; s += channels_num)
{
src_c = src + s + channel + h_radius_stride;
_reset();
for (unsigned int h = radius; h < src_height; h++)
{
_average_channel_bit_shift(src_c, shift, h_radius_stride, max_sum);
src_c += src_stride;
}
}
}
else
{
// Blur horizontaly
for (unsigned int h = radius; h < src_height; h++)
{
_reset();
for (int w = radius; w < src_width; w++)
{
_average_channel_minus_radius(src_c, radius, w_radius_stride, max_sum);
src_c += channels_num;
}
src_c += w_radius_stride;
src_c += src_excess_w_stride;
}
// Blur vertically
for (unsigned int s = 0; s < src_stride - src_excess_w_stride; s += channels_num)
{
src_c = src + s + channel + h_radius_stride;
_reset();
for (unsigned int h = radius; h < src_height; h++)
{
_average_channel_minus_radius(src_c, radius, h_radius_stride, max_sum);
src_c += src_stride;
}
}
}
cairo_surface_mark_dirty(src_surface);
}
inline unsigned int ycairo_blur::_get_bit_shift(unsigned int radius)
{
switch (radius)
{
case 2: return 1;
case 4: return 2;
case 8: return 3;
case 16: return 4;
case 32: return 5;
case 64: return 6;
case 128: return 7;
case 256: return 8;
case 512: return 9;
case 1024: return 10;
}
return 0;
}
inline void _ycairo_pixel_average::_average_channel_minus_radius(unsigned char *in, unsigned int size, unsigned int delay_stride, unsigned int max_sum)
{
unsigned char *delayed = in - delay_stride;
out = out + *in - *delayed;
//// Prevent drawing same over one another
//if (out == max_sum && *delayed == 255) return; // Prevent overdrawing 255
//if (out < size && *delayed == 0) return; // Prevent overdrawing 0
*delayed = (unsigned char)(out / size);
}
inline void _ycairo_pixel_average::_average_pixel_minus_radius(unsigned char * in, unsigned int size, unsigned int delay_stride)
{
unsigned char *delayed = in - delay_stride;
out1 = (out1 + *(in + 0) - *(delayed + 0));
out2 = (out2 + *(in + 1) - *(delayed + 1));
out3 = (out3 + *(in + 2) - *(delayed + 2));
out4 = (out4 + *(in + 3) - *(delayed + 3));
*delayed = (unsigned char)(out1 / size);
*(delayed + 1) = (unsigned char)(out2 / size);
*(delayed + 2) = (unsigned char)(out3 / size);
*(delayed + 3) = (unsigned char)(out4 / size);
}
inline void _ycairo_pixel_average::_average_pixel(unsigned char * in, unsigned int start_index, unsigned int size, unsigned int delay_stride)
{
if (start_index < size)
{
out1 = (out1 + *(in + 0));
out2 = (out2 + *(in + 1));
out3 = (out3 + *(in + 2));
out4 = (out4 + *(in + 3));
}
else
{
unsigned char *delayed = in - delay_stride;
out1 = ((out1 + *(in + 0)) - *(delayed + 0));
out2 = (out2 + *(in + 1) - *(delayed + 1));
out3 = (out3 + *(in + 2) - *(delayed + 2));
out4 = (out4 + *(in + 3) - *(delayed + 3));
*delayed = (unsigned char)(out1 / size);
*(delayed + 1) = (unsigned char)(out2 / size);
*(delayed + 2) = (unsigned char)(out3 / size);
*(delayed + 3) = (unsigned char)(out4 / size);
}
}
inline void _ycairo_pixel_average::_average_channel(unsigned char * in, unsigned int start_index, unsigned int size, unsigned int delay_stride)
{
if (start_index < size)
{
out1 = (out1 + *(in + 0));
}
else
{
unsigned char *delayed = in - delay_stride;
out1 = ((out1 + *(in + 0)) - *(delayed + 0));
*delayed = (unsigned char)(out1 / size);
}
}
inline void _ycairo_pixel_average::_average_channel_bit_shift(unsigned char *in, unsigned int shift, unsigned int delay_stride, unsigned int max_sum)
{
unsigned char *delayed = in - delay_stride;
out = out - *delayed + *in;
//// Prevent drawing same over one another
//if (out == max_sum && *delayed == 255) return; // Prevent overdrawing 255
//if (out < shift && *delayed == 0) return; // Prevent overdrawing 0
*delayed = (unsigned char)(out >> shift);
}
inline void _ycairo_pixel_average::_average_pixel_bit_shift(unsigned char * in, unsigned int shift, unsigned int delay_stride)
{
unsigned char *delayed = in - delay_stride;
out1 = (out1 + *(in + 0) - *(delayed + 0));
out2 = (out2 + *(in + 1) - *(delayed + 1));
out3 = (out3 + *(in + 2) - *(delayed + 2));
out4 = (out4 + *(in + 3) - *(delayed + 3));
*delayed = (unsigned char)(out1 >> shift);
*(delayed + 1) = (unsigned char)(out2 >> shift);
*(delayed + 2) = (unsigned char)(out3 >> shift);
*(delayed + 3) = (unsigned char)(out4 >> shift);
}
inline void _ycairo_pixel_average::_reset()
{
out = 0;
out1 = 0;
out2 = 0;
out3 = 0;
out4 = 0;
}
void ycairo_drop_shadow::ycairo_drop_shadow_set_opacity(cairo_t * cr, double opacity)
{
int props_index = _get_props_index(cr);
props[props_index].shadow_opacity = opacity;
}
void ycairo_drop_shadow::ycairo_drop_shadow_set_radius(cairo_t * cr, double radius)
{
int props_index = _get_props_index(cr);
props[props_index].shadow_radius = IPMAX(radius, 1.0);
}
void ycairo_drop_shadow::ycairo_drop_shadow_set_distance(cairo_t * cr, double distance)
{
int props_index = _get_props_index(cr);
props[props_index].shadow_distance = distance;
_calculate_shadow_offset(props_index);
}
void ycairo_drop_shadow::ycairo_drop_shadow_set_angle(cairo_t * cr, double angle)
{
int props_index = _get_props_index(cr);
props[props_index].shadow_angle = IPMAX(IPMIN(angle, 180.0), -180.0);
_calculate_shadow_offset(props_index);
}
void ycairo_drop_shadow::_calculate_shadow_offset(int props_index)
{
props[props_index].shadow_offset_x = props[props_index].shadow_distance * cos((1 - (props[props_index].shadow_angle / 180)) * 3.14159265359);
props[props_index].shadow_offset_y = props[props_index].shadow_distance * sin((1 - (props[props_index].shadow_angle / 180)) * 3.14159265359);
}
int ycairo_drop_shadow::_get_props_index(cairo_t * cr)
{
// If there is no cairo_t* inside vector, create new
for (int i = 0; i < props.size(); i++)
{
if (props[i].cr == cr) return i;
}
props.push_back(shadow_properties());
int index = props.size() - 1;
props[index].cr = cr;
_calculate_shadow_offset(index);
return index;
}
void ycairo_drop_shadow::ycairo_drop_shadow_fill(cairo_t * cr, double downsample)
{
_ycairo_draw_drop_shadow(cr, false, downsample);
cairo_new_path(cr);
}
void ycairo_drop_shadow::ycairo_drop_shadow_fill_fast(cairo_t * cr)
{
_ycairo_draw_drop_shadow_fast(cr, false);
cairo_new_path(cr);
}
void ycairo_drop_shadow::ycairo_drop_shadow_stroke(cairo_t * cr, double downsample)
{
_ycairo_draw_drop_shadow(cr, true, downsample);
cairo_new_path(cr);
}
void ycairo_drop_shadow::ycairo_drop_shadow_stroke_fast(cairo_t * cr)
{
_ycairo_draw_drop_shadow_fast(cr, true);
cairo_new_path(cr);
}
// NanoSVG stuff
void setSource(cairo_t * cr, const NSVGpaint & paint, double opacity)
{
switch (paint.type)
{
case NSVG_PAINT_COLOR:
{
double r = ((paint.color >> 0) & 0xFF) / 255.0;
double g = ((paint.color >> 8) & 0xFF) / 255.0;
double b = ((paint.color >> 16) & 0xFF) / 255.0;
cairo_set_source_rgba(cr, r, g, b, opacity);
break;
}
//case NSVG_PAINT_LINEAR_GRADIENT:
//case NSVG_PAINT_RADIAL_GRADIENT:
default:
cairo_set_source_rgba(cr, 0, 0, 0, opacity);
}
}
void RenderNanoSVG(cairo_t * cr, NSVGimage * image)
{
for (NSVGshape* shape = image->shapes; shape; shape = shape->next)
{
if (!(shape->flags & NSVG_FLAGS_VISIBLE))
continue;
for (NSVGpath* path = shape->paths; path; path = path->next)
{
cairo_move_to(cr, path->pts[0], path->pts[1]);
for (int i = 0; i < path->npts - 1; i += 3)
{
float* p = path->pts + i * 2 + 2;
cairo_curve_to(cr, p[0], p[1], p[2], p[3], p[4], p[5]);
}
if (path->closed)
cairo_close_path(cr);
}
// Fill
if (shape->fill.type != NSVG_PAINT_NONE)
{
if (shape->fillRule == NSVG_FILLRULE_EVENODD)
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
else
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
setSource(cr, shape->fill, shape->opacity);
if (shape->stroke.type != NSVG_PAINT_NONE)
cairo_fill_preserve(cr);
else
cairo_fill(cr);
}
// Stroke
if (shape->stroke.type != NSVG_PAINT_NONE)
{
cairo_set_line_width(cr, shape->strokeWidth);
cairo_set_miter_limit(cr, shape->miterLimit);
switch (shape->strokeLineCap)
{
case NSVG_CAP_BUTT: cairo_set_line_cap(cr, CAIRO_LINE_CAP_BUTT); break;
case NSVG_CAP_ROUND: cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND); break;
case NSVG_CAP_SQUARE: cairo_set_line_cap(cr, CAIRO_LINE_CAP_SQUARE); break;
}
switch (shape->strokeLineJoin)
{
case NSVG_JOIN_MITER: cairo_set_line_join(cr, CAIRO_LINE_JOIN_MITER); break;
case NSVG_JOIN_ROUND: cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND); break;
case NSVG_JOIN_BEVEL: cairo_set_line_join(cr, CAIRO_LINE_JOIN_BEVEL); break;
}
double dashArray[8];
for (int i = 0; i < shape->strokeDashCount; i++)
dashArray[i] = shape->strokeDashArray[i];
cairo_set_dash(cr, dashArray, shape->strokeDashCount, shape->strokeDashOffset);
setSource(cr, shape->stroke, shape->opacity);
cairo_stroke(cr);
}
}
}
void ycairo_helper::ycairo_draw_svg(cairo_t * cr, string path)
{
NSVGimage *SVG = nsvgParseFromFile(path.c_str(), "px", 96);
RenderNanoSVG(cr, SVG);
nsvgDelete(SVG);
}
void ycairo_grayscale::ycairo_begin_grayscale(cairo_t * cr)
{
cairo_push_group_with_content(cr, CAIRO_CONTENT_COLOR_ALPHA);
}
void ycairo_grayscale::ycairo_end_grayscale_slow(cairo_t * cr, double alpha)
{
cairo_pattern_t *mask = cairo_pop_group(cr);
cairo_set_source(cr, mask);
cairo_operator_t op = cairo_get_operator(cr);
cairo_set_operator(cr, cairo_operator_t::CAIRO_OPERATOR_HSL_LUMINOSITY);
if (alpha == 1.0)
cairo_paint_with_alpha(cr, alpha);
else
cairo_paint(cr);
cairo_pattern_destroy(mask);
cairo_set_operator(cr, op);
}
void ycairo_grayscale::ycairo_end_grayscale(cairo_t * cr, double intensity, double alpha, bool using_luminosity, bool skip_transparent)
{
cairo_surface_t *surface = cairo_get_group_target(cr);
cairo_surface_type_t type = cairo_surface_get_type(surface);
// If backend if not image surface use luminosity type
if (type != cairo_surface_type_t::CAIRO_SURFACE_TYPE_IMAGE)
{
ycairo_end_grayscale_slow(cr, alpha);
return;
}
int img_width = cairo_image_surface_get_width(surface);
int img_height = cairo_image_surface_get_height(surface);
int stride = cairo_image_surface_get_stride(surface);
unsigned char* data = cairo_image_surface_get_data(surface);
for (int y = 0; y < img_height; y++)
{
for (int x = 0; x < img_width; x++)
{
unsigned int* pixel = (unsigned int*)(data);
pixel += x;
int B = ((*pixel) >> 0) & 0xff;
int G = ((*pixel) >> 8) & 0xff;
int R = ((*pixel) >> 16) & 0xff;
int A = ((*pixel) >> 24) & 0xff;
if (skip_transparent && A == 0) continue;
unsigned char average;
if (using_luminosity)
average = (unsigned char)((double)R * 0.3 + (double)G * 0.59 + (double)B * 0.11);
else
average = (unsigned char)((R + G + B) / 3);
if (intensity != 1.0)
{
double double_average = average;
double_average *= intensity;
double_average = IPMAX(double_average, 0);
double_average = IPMIN(double_average, 255);
average = (unsigned char)double_average;
}
unsigned char *char_data = (unsigned char*)pixel;
*char_data = average;
char_data++;
*char_data = average;
char_data++;
*char_data = average;
}
data += stride;
}
cairo_surface_flush(surface);
cairo_pattern_t *mask = cairo_pop_group(cr);
cairo_set_source(cr, mask);
if (alpha == 1.0)
cairo_paint_with_alpha(cr, alpha);
else
cairo_paint(cr);
cairo_pattern_destroy(mask);
}
| 27.361791 | 240 | 0.719251 | [
"shape",
"vector"
] |
e44cb60a6ee0c680240559bad175982deeaf024f | 7,425 | cpp | C++ | src/PathFinder/PathFinderGui.cpp | Person-93/aima-cpp | 08d062dcb971edeaddb9a10083cf6da5a1b869f7 | [
"MIT"
] | null | null | null | src/PathFinder/PathFinderGui.cpp | Person-93/aima-cpp | 08d062dcb971edeaddb9a10083cf6da5a1b869f7 | [
"MIT"
] | null | null | null | src/PathFinder/PathFinderGui.cpp | Person-93/aima-cpp | 08d062dcb971edeaddb9a10083cf6da5a1b869f7 | [
"MIT"
] | null | null | null | #include "PathFinderGui.hpp"
#include <utility>
#include "util/define_logger.hpp"
#include "core/Exception.hpp"
#include "util/parseTitle.hpp"
#include "util/AssetManager.hpp"
#include "util/random_string.hpp"
#include "PathFinderAgent.hpp"
#include "SearchNode.hpp"
using namespace aima::core;
using namespace aima::path_finder;
DEFINE_LOGGER( PathFinderGui )
namespace {
PathFinderGui::AssetHandles assetLoader() { return {}; }
const ImColor& color() {
static std::array<ImColor, 3> colors{
ImColor{ ImVec4{ 0, 100, 255, .5 }},
ImColor{ ImVec4{ 255, 0, 100, .5 }},
ImColor{ ImVec4{ 100, 255, 0, .5 }},
};
static size_t colorsIndex{};
if ( colorsIndex >= colors.size()) colorsIndex = 0;
return colors[ colorsIndex++ ];
}
}
PathFinderGui::PathFinderGui( std::string_view title, bool* open, std::string_view str_id ) :
GraphicViewer{ assetLoader, title, open, str_id },
childWindowConfig{
.str_id = str_id.empty() ? util::random_string( 10 ) : std::string{ str_id },
.size = { 850, 350 },
.border = true
} { TRACE; }
void PathFinderGui::setEnvironment( const std::shared_ptr<Environment>& environment ) {
TRACE;
auto p = std::dynamic_pointer_cast<PathFinderEnvironment>( environment );
if ( !p ) {
using namespace aima::core::exception;
AIMA_THROW_EXCEPTION( Exception{} << EnvironmentViewType( util::parseTitle<PathFinderGui>())
<< Because( "Received unrecognized environment" ));
}
GraphicViewer::setEnvironment( environment );
}
void PathFinderGui::agentAdded( const aima::core::Agent& agent, const aima::core::Environment& source ) {
agentColors.insert( { agent, color() } );
}
void PathFinderGui::renderDisplay( aima::gui::ImGuiWrapper& imGuiWrapper, std::shared_ptr<Environment>& environment ) {
if ( !environment ) {
ImGui::Text( "The environment has not been set" );
return;
}
auto env = std::dynamic_pointer_cast<PathFinderEnvironment>( environment );
if ( !env ) {
using namespace aima::core::exception;
AIMA_THROW_EXCEPTION( Exception{} << EnvironmentViewType( util::parseTitle<PathFinderGui>())
<< Because( "Received unrecognized environment" ));
}
renderInfo( *env, imGuiWrapper );
renderPathArea( *env, imGuiWrapper );
}
void PathFinderGui::renderInfo( const PathFinderEnvironment& env, gui::ImGuiWrapper& imGuiWrapper ) const {
for ( const core::Agent& agent: env.getAgents()) {
const auto& pathFinderAgent = dynamic_cast<const PathFinderAgent&>(agent);
const auto& status = pathFinderAgent.getStatus();
ImGui::TextColored( agentColors.at( agent ), "%s:", util::parseTitle( agent ).data());
ImGui::Text( " Nodes in memory: %zu", status.nodesInMemory );
ImGui::Text( " Max nodes in memory: %zu", status.maxNodesInMemory );
ImGui::Text( " Nodes generated: %zu", status.nodesGenerated );
ImGui::Text( " Path length: %.0f", status.pathLength );
ImGui::Text( " Time spent thinking: %zu", status.timeSpent );
}
}
void PathFinderGui::renderPathArea( const PathFinderEnvironment& env, gui::ImGuiWrapper& imGuiWrapper ) {
auto region = ImGui::GetContentRegionAvail();
float xScaleFactor = region.x / 800;
float yScaleFactor = region.y / 350;
float scaleFactor = std::min( xScaleFactor, yScaleFactor );
childWindowConfig.size = { 800 * scaleFactor, 350 * scaleFactor };
imGuiWrapper.childWindow( childWindowConfig, [ & ]() {
renderObstacles( env, scaleFactor );
renderAgents( env, scaleFactor );
renderGoal( env, scaleFactor );
renderPlans( env, scaleFactor );
} );
}
void PathFinderGui::renderObstacles( const PathFinderEnvironment& env, float scaleFactor ) const {
static const ImU32 color = ImColor{ ImVec4{ 0.4f, 0.4f, 0.4f, 1.0f }};
const ImVec2 position = ImGui::GetCursorScreenPos();
ImDrawList* drawList = ImGui::GetWindowDrawList();
std::vector<ImVec2> vertices;
for ( const auto& obstacle : env.getObstacles()) {
std::transform( obstacle.getPoints().begin(), obstacle.getPoints().end(), std::back_inserter( vertices ),
[ & ]( const util::geometry::Point& point ) {
return ImVec2{ point.x * scaleFactor + position.x,
point.y * scaleFactor + position.y };
} );
drawList->AddConvexPolyFilled( vertices.data(), static_cast<const int>(vertices.size()), color );
vertices.clear();
}
}
void PathFinderGui::renderAgents( const PathFinderEnvironment& env, float scaleFactor ) const {
static const ImU32 color = ImColor{ ImVec4{ 0.0f, 1.0f, 0.2f, 1.0f }};
const ImVec2 position = ImGui::GetCursorScreenPos();
ImDrawList* draw_list = ImGui::GetWindowDrawList();
for ( const auto&[agent, location] : env.getAgentLocations()) {
draw_list->AddCircleFilled( ImVec2{ location.x * scaleFactor + position.x,
location.y * scaleFactor + position.y },
5 * scaleFactor,
color );
}
}
void PathFinderGui::renderGoal( const PathFinderEnvironment& env, float scaleFactor ) const {
static const ImU32 color = ImColor{ ImVec4{ 1.0f, 0.0f, 0.0f, 1.0f }};
const ImVec2 position = ImGui::GetCursorScreenPos();
ImDrawList* draw_list = ImGui::GetWindowDrawList();
const auto& goal = env.getGoal();
draw_list->AddCircleFilled( ImVec2{ goal.x * scaleFactor + position.x,
goal.y * scaleFactor + position.y },
5 * scaleFactor,
color );
}
void PathFinderGui::renderPlans( const PathFinderEnvironment& env, float scaleFactor ) const {
static float thickness = 2.5 * scaleFactor;
const ImVec2 position = ImGui::GetCursorScreenPos();
ImDrawList * drawList = ImGui::GetWindowDrawList();
for ( const Agent& agent : env.getAgents()) {
auto p = dynamic_cast<const PathFinderAgent*>(&agent);
if ( !p ) {
using namespace aima::core::exception;
AIMA_THROW_EXCEPTION( Exception{} << EnvironmentViewType( util::parseTitle<PathFinderGui>())
<< Because( "Received unrecognized agent" ));
}
auto previous = p->getPlan();
if ( !previous ) continue;
const auto& color = agentColors.at( agent );
for ( auto current = previous->parent.lock();
current;
previous = current, current = current->parent.lock()) {
drawList->AddLine( ImVec2{ previous->location.x * scaleFactor + position.x,
previous->location.y * scaleFactor + position.y },
ImVec2{ current->location.x * scaleFactor + position.x,
current->location.y * scaleFactor + position.y },
color,
thickness );
}
}
}
| 44.461078 | 119 | 0.59771 | [
"geometry",
"vector",
"transform"
] |
e44e0028d0f56710068e09fc6e0946303d0ec2cc | 23,704 | cpp | C++ | cresis-toolbox/+tomo/stereo.cpp | CReSIS/CRESIS-TOOLBOX | b8c5de57a7a95137e543e202c6a473a958129b04 | [
"MIT"
] | 14 | 2019-12-04T19:48:11.000Z | 2022-02-07T18:53:49.000Z | cresis-toolbox/+tomo/stereo.cpp | CReSIS/CRESIS-TOOLBOX | b8c5de57a7a95137e543e202c6a473a958129b04 | [
"MIT"
] | 10 | 2020-06-23T17:22:38.000Z | 2021-05-11T18:41:53.000Z | cresis-toolbox/+tomo/stereo.cpp | CReSIS/CRESIS-TOOLBOX | b8c5de57a7a95137e543e202c6a473a958129b04 | [
"MIT"
] | 7 | 2019-12-14T04:47:46.000Z | 2021-09-17T13:47:01.000Z | #include "SImage.h"
#include <vector>
#include <iostream>
#include <fstream>
#include <map>
#include <math.h>
#include <limits>
#ifdef STANDALONE
#include <SImageIO.h>
#endif
//#define STANDALONE
//#define INFINITY numeric_limits<double>::infinity()
using namespace std;
typedef vector< pair<int, int> > PathType;
const char *basename_g = 0;
double top_smoothness_g = 1e3, bottom_smoothness_g = 1e3;
double top_peak_g = 0.5, bottom_peak_g = 0.5;
double repulse_g = 10;
SDoublePlane resample(const SDoublePlane &input, int newRow, int newCol)
{
SDoublePlane output(newRow, newCol);
int oldRow = input.rows();
int oldCol = input.cols();
for (int i=0;i<newRow;i++)
{
for (int j=0;j<newCol;j++)
{
double src_i = ((double)i)*oldRow/newRow;
double src_j = ((double)j)*oldCol/newCol;
int fi0 = int(src_i);
int fi1 = fi0+1;
int fj0 = int(src_j);
int fj1 = fj0+1;
double a = src_i - int(src_i);
double b = src_j - int(src_j);
output[i][j] = (1-b)*(1-a)*input[fi0][fj0]+(1-b)*a*input[fi1][fj0]+b*(1-a)*input[fi0][fj1]+b*a*input[fi1][fj1];
}
}
return output;
}
inline double potts(int x, int y)
{
return fabs(x-y)<=3?0:10000;
}
//convert a (i,j) label to index in storing matrix
int ij2index(int i, int j, int n)
{
return (2*n-i+1)*i/2+j-i;
}
//convert storing matrix index back to a (i,j) label
void index2ij(int index, int n, int &i, int &j)
{
i=0;
j=0;
int col_num=n;
while (index - col_num >= 0)
{
index-=col_num;
col_num--;
i++;
}
j = index+i;
return;
}
/*
double calc_u(int col, int i, int j, SDoublePlane &gradients)
{
double cost = 20000.0;
double min_cost=1000.0;
double scale = 1000.0;
cost -= gradients[i][col]+gradients[j][col];
//cost += 50000/(j-i+1);
double vert_penal = 10000.0-fabs((j-i)*scale);
if (vert_penal<min_cost)
{
vert_penal = min_cost;
}
cost += vert_penal;
return cost;
}
*/
double calc_u(int col, int i, int j, SDoublePlane &gradients, double cost, double gradScale)
{
//double cost = 20000.0;
cost -= gradients[i][col]+gradients[j][col];
//cost += 50000/(j-i+1);
cost += gradScale/(j-i+1);
return cost;
}
/*
double calc_u(int col, int i, int j, SDoublePlane &gradients, SDoublePlane &cumulativeGradients)
{
double cost = 20000.0;
double middle_scale=20.0;
cost -= gradients[i][col]+gradients[j][col];
cost += 50000/(j-i+1);
cost += cumulativeGradients[j][col];
return cost;
}
*/
double calc_h(int rows, int i1, int j1, int i2, int j2, double label_diff_1, double label_diff_2)
{
double cost = 0.0;
//double label_diff_1 = 200.0, label_diff_2 = 1000.0;
if (i1<i2)
{
if(j1<i2)
{
cost = (j1-i1+j2-i2)*label_diff_1+(i2-j1)*label_diff_2;
}
else
{
if(j1<j2)
{//t=1
cost = (i2-i1+j2-j1)*label_diff_1;
}
else
{//t=2
cost = (i2-i1+j1-j2)*label_diff_1;
}
}
}
else
{
if(i1>j2)
{
cost = (i2-j2+j1-i1)*label_diff_1+(i1-j2)*label_diff_2;
}
else
{
if(j1<j2)
{//t=3
cost = (i1-i2+j2-j1)*label_diff_1;
}
else
{//t=4
cost = (i1-i2+j1-j2)*label_diff_1;
}
}
}
// printf("i1=%d,i2=%d,j1=%d,j2=%d, h smooth cost = %f\n",i1,i2,j1,j2,cost);
// getchar();
return cost;
}
SDoublePlane calc_uk(const SDoublePlane &input, int num_label, double cost, double gradScale, SDoublePlane &gradients)
{
int rows = input.rows();
SDoublePlane Uk(input.cols(), num_label);
printf("Calculating Uk...\n");
gradients=SDoublePlane(input.rows(),input.cols());
//SDoublePlane cumulativeGradients(input.rows(),input.cols());
double scale=100;
int grade = 1;
for (int i=0;i<input.rows();i++)
{
int low_i = i;
int high_i = i+grade<rows?i+grade:rows-1;
for (int k=0;k<input.cols();k++)
{
double gradient = 0.0;
for (int j=low_i+1;j<=high_i;j++)
{
gradient+=fabs(input[j-1][k]-input[j][k])*scale;
}
gradients[i][k]=gradient;
/*
if (i==0)
cumulativeGradients[i][k]=gradient;
else
cumulativeGradients[i][k]=gradient+cumulativeGradients[i-1][k];
*/
}
}
int index = 0;
for (int i=0;i<input.rows();i++)
{
for (int j=i;j<input.rows();j++)
{
for (int k=0;k<input.cols();k++)
{
//Uk[k][index]=calc_u(k, i, j, gradients, cumulativeGradients);
Uk[k][index]=calc_u(k, i, j, gradients, cost, gradScale);
}
index++;
}
}
return Uk;
}
inline double sqr(double x) { return x * x; }
// dt with quadratic distance
void dt(const double *src, double *dst, double *dst_ind, int s1, int s2, int d1, int d2, double scale, int off=0)
{
int d = (d1+d2) >> 1;
int s = s1;
for (int p = s1; p <= s2; p++)
if (src[s] + sqr(s-d-off) * scale> src[p] + sqr(p-d-off) * scale)
s = p;
dst[d] = src[s] + sqr(s-d-off) * scale;
dst_ind[d] = s;
if(d-1 >= d1)
dt(src, dst, dst_ind, s1, s, d1, d-1, scale, off);
if(d2>=d+1)
dt(src, dst, dst_ind, s, s2, d+1, d2, scale, off);
}
void dt_1d(const double *f, double scale, double *result, double *dst_ind, int beg, int end, int off=0)
{
dt(f, result, dst_ind, beg, end-1, beg, end-1, scale, off);
}
PathType find_single_path(const SDoublePlane &unary, double lambda)
{
// SDoublePlane Ek1(unary.rows(), unary.cols()), path(unary.rows(), unary.cols());
SDoublePlane Ek1(unary.cols(), unary.rows()), path(unary.cols(), unary.rows());
for (int i=0;i<unary.rows();i++)
Ek1[0][i] = (unary[i][0]);
/*
for (int k=1; k<unary.cols(); k++)
{
for(int new_i=0; new_i < unary.rows(); new_i++)
{
int min_i = -1;
double min_cost = INFINITY;
double my_unary = unary[new_i][k];
for(int old_i=0; old_i < unary.rows(); old_i++)
{
double cost = lambda * sqr(old_i-new_i);
cost += Ek1[old_i][k-1] + my_unary;
if(cost < min_cost)
min_i = old_i, min_cost = cost;
}
Ek1[new_i][k] = min_cost;
path[new_i][k] = min_i;
}
}
*/
// use DT
// D(j) = v(j) + min_i d(i) + v(i,j)
for (int k=1; k<unary.cols(); k++)
{
// double unary_old[unary.rows()], dt_result[unary.rows()];
// int dt_result_ind[unary.rows()];
// for(int i=0; i<unary.rows(); i++)
// unary_old[i] = Ek1[i][k-1];
double *Ek1_k = Ek1[k];
dt_1d(Ek1[k-1], lambda, Ek1_k, path[k], 0, unary.rows()-1);
for(int i=0; i<unary.rows(); i++)
Ek1_k[i] += unary[i][k];
// for(int i=0; i<unary.rows(); i++)
// {
// Ek1[k][i] = dt_result[i] + unary[i][k];
// path[k] = dt_result_ind[i];
// }
}
int min_s = -1;
double min_cost = INFINITY;
double *last_ek1 = Ek1[unary.cols()-1];
for (int s = 0 ; s<unary.rows();s++)
{
if (last_ek1[s]<min_cost)
{
min_cost=last_ek1[s];
min_s = s;
}
}
cout << "Cost of path = " << min_cost << endl;
cout << "Final state = " << min_s << endl;
// min_s=173*2;
PathType Path(unary.cols());
for (int k=unary.cols()-1; k>=0; k--)
{
int c1, c2;
// index2ij(min_s, rows, c1, c2);
Path[k].first = min_s; Path[k].second = min_s;
min_s = (int)path[k][min_s];
}
return Path;
}
void write_plane(const SDoublePlane &unary_top, const char *fname, const char *bn)
{
return;
SDoublePlane g = unary_top;
double x=-INFINITY, n=INFINITY;
for(int i=0; i<g.rows(); i++)
for(int j=0; j<g.cols(); j++)
{
if(!isinf(g[i][j]))
x = max(x, g[i][j]), n=min(n, g[i][j]);
}
for(int i=0; i<g.rows(); i++)
for(int j=0; j<g.cols(); j++)
{
if(!isinf(g[i][j]))
g[i][j] = (g[i][j] - n) / (x-n) * 255.0;
else if(isinf(g[i][j]) > 0)
g[i][j] = 255;
else
g[i][j] = 0;
}
#ifdef STANDALONE
SImageIO::write_png_file((string(bn) + "-" + fname).c_str(), g, g, g);
#endif
}
inline void set_both_to_max(double &A, double &B)
{
if(A > B) B=A; else A=B;
}
PathType scene_labeling_1(const SDoublePlane &input, double cost, double gradeScale, const PathType &pts1, const PathType &pts2)
{
cerr << "computing unary terms..." << endl;
int rows = input.rows();
int num_label = (input.rows()+1)*input.rows()/2;
SDoublePlane gradients(input.rows(), input.cols());
const int kk=5;
/* for(int i=0; i<input.rows(); i++)
for(int j=0; j<input.cols(); j++)
if(i >= kk && i < input.rows()-kk && j >= kk && j < input.cols()-kk)
// gradients[i][j] = fabs(input[i+kk][j]-input[i-kk][j]) + fabs(input[i][j+kk] - input[i][j-kk]);
gradients[i][j] = sqrt(sqr(input[i+kk][j]-input[i-kk][j]) + sqr(input[i][j+kk] - input[i][j-kk]));
// gradients[i][j] = max(0.0, input[i-kk][j]-input[i+kk][j]); // + fabs(input[i][j+kk] - input[i][j-kk]);
else
gradients[i][j] = 0;
*/
for(int i=0; i<input.rows(); i++)
for(int j=0; j<input.cols(); j++)
if(i >= kk && i < input.rows()-kk)
{
double acc = 0;
for(int k=-kk; k<=-1; k++)
acc += sqr(255-input[i+k][j]);
for(int k=1; k<=kk; k++)
acc += sqr(input[i+k][j]);
// gradients[i][j] = -sqr(acc);
gradients[i][j] = -(acc);
}
else
gradients[i][j] = -INFINITY;
/*
const int kk=2;
for(int i=0; i<input.rows(); i++)
for(int j=0; j<input.cols(); j++)
if(i >= kk && i < input.rows()-kk)
{
double acc = 0;
for(int k=-kk; k<=-1; k++)
acc += sqr(input[i+k][j]);
for(int k=1; k<=kk; k++)
acc += sqr(input[i+k][j]);
// acc += sqr(input[i+k][j]);
gradients[i][j] = -(acc);
}
else
gradients[i][j] = -INFINITY;
*/
cerr << "1" << endl;
// for gradients, higher values are good
SDoublePlane cumulative_fromtop_grad = gradients, cumulative_frombottom_grad = gradients;
for(int j=0; j<input.cols(); j++)
{
double top_acc=-INFINITY, bottom_acc=-INFINITY;
for(int i=0; i<input.rows(); i++)
set_both_to_max(cumulative_fromtop_grad[i][j], top_acc);
for(int i=input.rows()-1; i >= 0; i--)
set_both_to_max(cumulative_fromtop_grad[i][j], bottom_acc);
}
// for cumulative gradients, higher values are bad
cerr << "2" << endl;
SDoublePlane unary_bottom(input.rows(), input.cols());
SDoublePlane unary_top(input.rows(), input.cols());
for(int i=0; i<input.rows(); i++)
for(int j=0; j<input.cols(); j++)
{
if(i < input.rows() - 5*2)
unary_bottom[i][j] = -gradients[i][j] + cumulative_frombottom_grad[i+5][j] * bottom_peak_g;
else
unary_bottom[i][j] = INFINITY;
if(i >= 5*2)
unary_top[i][j] = -gradients[i][j] + cumulative_fromtop_grad[i-5][j] * top_peak_g;
else
unary_top[i][j] = INFINITY;
}
cerr << "3" << endl;
if(pts2.size() > 0)
{
for(int i=0; i<pts2.size(); i++)
unary_bottom[pts2[i].second][pts2[i].first] = -1e10;
}
if(pts1.size() > 0)
{
for(int i=0; i<pts1.size(); i++)
unary_top[pts1[i].second][pts1[i].first] = -1e10;
}
write_plane(unary_top, "unary_top.png", basename_g);
write_plane(unary_bottom, "unary_bottom.png", basename_g);
write_plane(gradients, "grad.png", basename_g);
write_plane(cumulative_frombottom_grad, "cum_bottom.png", basename_g);
write_plane(cumulative_fromtop_grad, "cum_top.png", basename_g);
printf("Doing inference...\n");
// SDoublePlane Ek(input.cols(),num_label);
// SDoublePlane Path(input.cols(),num_label);
PathType top_path = find_single_path(unary_top, top_smoothness_g);
// make bottom path be far away from top path
for(int i=0; i<input.cols(); i++)
for(int j=0; j<top_path[i].first+repulse_g; j++)
if(j < unary_bottom.rows())
unary_bottom[j][i] = INFINITY;
PathType bottom_path = find_single_path(unary_bottom, bottom_smoothness_g);
PathType final_path(input.cols());
for(int j=0; j<input.cols(); j++)
final_path[j] = make_pair(top_path[j].first, bottom_path[j].first);
return final_path;
}
PathType scene_labeling(const SDoublePlane &input, double cost, double gradeScale)
{
int rows = input.rows();
double label_diff_1 = 300.0, label_diff_2 = 2000.0;
int num_label = (input.rows()+1)*input.rows()/2;
SDoublePlane grad;
SDoublePlane Uk = calc_uk(input, num_label, cost, gradeScale, grad);
printf("Calculating Ek...\n");
SDoublePlane Ek(input.cols(),num_label);
SDoublePlane Path(input.cols(),num_label);
for (int i=0;i<num_label;i++)
{
Ek[0][i] = Uk[0][i];
Path[0][i] = -1;
}
//t=1, i1<=i2<=j1<=j2
double **Ep1 = new double*[rows];
double **F1 = new double*[rows];
//t=2, i1<=i2<=j2<=i1
double **Ep2 = new double*[rows];
double **F2 = new double*[rows];
//t=3, i2<=i1<=j1<=j2
double **Ep3 = new double*[rows];
double **F3 = new double*[rows];
//t=4, i2<=i1<=j2<=j1
double **Ep4 = new double*[rows];
double **F4 = new double*[rows];
for (int k=1; k< input.cols();k++)
{
printf("calculating t=%d %d\n", k, input.cols());
int **min_ip_t1 = new int*[rows];
for (int jp=0;jp<rows;jp++)// for each jp
{
double *g = new double[jp+1];
Ep1[jp] = new double[jp+1];
min_ip_t1[jp] = new int[jp+1];
for (int i = 0;i<=jp;i++)
{
g[i] = Ek[k-1][ij2index(i,jp,rows)]-i*label_diff_1;
if (i==0)
{
Ep1[jp][i] = g[i];
min_ip_t1[jp][i] = 0;
}
else if(g[i]<Ep1[jp][i-1])
{
Ep1[jp][i] = g[i];
min_ip_t1[jp][i]=i;
}
else
{
Ep1[jp][i]=Ep1[jp][i-1];
min_ip_t1[jp][i]=min_ip_t1[jp][i-1];
}
}
delete[] g;
}
int **min_jp_t1 = new int*[rows];
for (int i=0;i<rows;i++)
{
min_jp_t1[i] = new int[rows-i+1];
double *g = new double[rows-i+1];
F1[i] = new double[rows-i+1];
double *h = new double[rows-i+1];
for (int j=i;j<rows;j++)
{
g[j-i]=-j*label_diff_1+Ep1[j][i];
if(j-i==0)
{
h[0]=g[0];
min_jp_t1[i][j-i] = j;
}
else if(g[j-i]<h[j-i-1])
{
h[j-i]=g[j-i];
min_jp_t1[i][j-i] = j;
}
else
{
h[j-i] = h[j-i-1];
min_jp_t1[i][j-i] = min_jp_t1[i][j-i-1];
}
F1[i][j-i] = (i+j)*label_diff_1+h[j-i];
}
delete[] g;
delete[] h;
}
// printf("calculating t=2\n");
int **min_ip_t2 = new int*[rows];
// printf("calculating Ep2\n");
for (int jp=0;jp<rows;jp++)// for each jp
{
double *g = new double[jp+1];
Ep2[jp] = new double[jp+1];
min_ip_t2[jp] = new int[jp+1];
for (int i = 0;i<=jp;i++)
{
g[i] = Ek[k-1][ij2index(i,jp,rows)]-i*label_diff_1;
if (i==0)
{
Ep2[jp][i] = g[i];
min_ip_t2[jp][i] = 0;
}
else if(g[i]<Ep2[jp][i-1])
{
Ep2[jp][i] = g[i];
min_ip_t2[jp][i]=i;
}
else
{
Ep2[jp][i]=Ep2[jp][i-1];
min_ip_t2[jp][i]=min_ip_t2[jp][i-1];
}
}
delete[] g;
}
// printf("calculating F2\n");
int **min_jp_t2 = new int*[rows];
for (int i=0;i<rows;i++)
{
min_jp_t2[i] = new int[rows-i+1];
double *g = new double[rows-i+1];
F2[i] = new double[rows-i+1];
double *h = new double[rows-i+1];
for (int j=rows-1;j>=i;j--)
{
g[j-i]=j*label_diff_1+Ep2[j][i];
if(j==rows-1)
{
h[j-i]=g[j-i];
min_jp_t2[i][j-i] = j;
}
else if(g[j-i]<h[j-i+1])
{
h[j-i]=g[j-i];
min_jp_t2[i][j-i] = j;
}
else
{
h[j-i] = h[j-i+1];
min_jp_t2[i][j-i] = min_jp_t2[i][j-i+1];
}
F2[i][j-i] = (i-j)*label_diff_1+h[j-i];
}
delete[] g;
delete[] h;
}
// printf("calculating t=3\n");
int **min_ip_t3 = new int*[rows];
// printf("calculating Ep3\n");
for (int jp=0;jp<rows;jp++)// for each jp
{
double *g = new double[jp+1];
Ep3[jp] = new double[jp+1];
min_ip_t3[jp] = new int[jp+1];
for (int i = jp;i>=0;i--)
{
g[i] = Ek[k-1][ij2index(i,jp,rows)]+i*label_diff_1;
if (i==jp)
{
Ep3[jp][i] = g[i];
min_ip_t3[jp][i] = jp;
}
else if(g[i]<Ep3[jp][i+1])
{
Ep3[jp][i] = g[i];
min_ip_t3[jp][i]=i;
}
else
{
Ep3[jp][i]=Ep3[jp][i+1];
min_ip_t3[jp][i]=min_ip_t3[jp][i+1];
}
}
delete[] g;
}
// printf("calculating F3\n");
int **min_jp_t3 = new int*[rows];
for (int i=0;i<rows;i++)
{
min_jp_t3[i] = new int[rows-i+1];
double *g = new double[rows-i+1];
F3[i] = new double[rows-i+1];
double *h = new double[rows-i+1];
for (int j=i;j<rows;j++)
{
g[j-i]=-j*label_diff_1+Ep3[j][i];
if(j-i==0)
{
h[0]=g[0];
min_jp_t3[i][j-i] = j;
}
else if(g[j-i]<h[j-i-1])
{
h[j-i]=g[j-i];
min_jp_t3[i][j-i] = j;
}
else
{
h[j-i] = h[j-i-1];
min_jp_t3[i][j-i] = min_jp_t3[i][j-i-1];
}
F3[i][j-i] = (j-i)*label_diff_1+h[j-i];
}
delete[] g;
delete[] h;
}
// printf("calculating t=4\n");
int **min_ip_t4 = new int*[rows];
// printf("calculating Ep4\n");
for (int jp=0;jp<rows;jp++)// for each jp
{
double *g = new double[jp+1];
Ep4[jp] = new double[jp+1];
min_ip_t4[jp] = new int[jp+1];
for (int i = jp;i>=0;i--)
{
g[i] = Ek[k-1][ij2index(i,jp,rows)]+i*label_diff_1;
if (i==jp)
{
Ep4[jp][i] = g[i];
min_ip_t4[jp][i] = jp;
}
else if(g[i]<Ep4[jp][i+1])
{
Ep4[jp][i] = g[i];
min_ip_t4[jp][i]=i;
}
else
{
Ep4[jp][i]=Ep4[jp][i+1];
min_ip_t4[jp][i]=min_ip_t4[jp][i+1];
}
}
delete[] g;
}
// printf("calculating F4\n");
int **min_jp_t4 = new int*[rows];
for (int i=0;i<rows;i++)
{
min_jp_t4[i] = new int[rows-i+1];
double *g = new double[rows-i+1];
F4[i] = new double[rows-i+1];
double *h = new double[rows-i+1];
for (int j=rows-1;j>=i;j--)
{
g[j-i]=j*label_diff_1+Ep4[j][i];
if(j==rows-1)
{
h[j-i]=g[j-i];
min_jp_t4[i][j-i] = j;
}
else if(g[j-i]<h[j-i+1])
{
h[j-i]=g[j-i];
min_jp_t4[i][j-i] = j;
}
else
{
h[j-i] = h[j-i+1];
min_jp_t4[i][j-i] = min_jp_t4[i][j-i+1];
}
F4[i][j-i] = (-i-j)*label_diff_1+h[j-i];
}
delete[] g;
delete[] h;
}
// printf("calculating minimum ip jp\n");
for (int index=0;index<num_label;index++)
{
int i,j, ip, jp;
index2ij(index,rows,i,j);
int min_t = 1;
double min_F = F1[i][j-i];
if (F2[i][j-i]<min_F)
{
min_F = F2[i][j-i];
min_t = 2;
}
if (F3[i][j-i]<min_F)
{
min_F = F3[i][j-i];
min_t = 3;
}
if (F4[i][j-i]<min_F)
{
min_F = F4[i][j-i];
min_t = 4;
}
switch(min_t)
{
case 1:
jp = min_jp_t1[i][j-i];
ip = min_ip_t1[jp][i];
break;
case 2:
jp = min_jp_t2[i][j-i];
ip = min_ip_t2[jp][i];
break;
case 3:
jp = min_jp_t3[i][j-i];
ip = min_ip_t3[jp][i];
break;
case 4:
jp = min_jp_t4[i][j-i];
ip = min_ip_t4[jp][i];
break;
}
Ek[k][index]=Uk[k][index]+min_F;
Path[k][index]=ij2index(ip,jp,rows);
}
}
int min_s = -1;
double min_cost = 1e32;
for (int s = 0;s<num_label;s++)
{
if (Ek[input.cols()-1][s]<min_cost)
{
min_cost=Ek[input.cols()-1][s];
min_s = s;
}
}
PathType path(input.cols());
for (int k=input.cols()-1; k>=0; k--)
{
int c1, c2;
index2ij(min_s, rows, c1, c2);
path[k].first = c1; path[k].second = c2;
min_s = (int)Path[k][min_s];
}
return path;
}
#ifdef STANDALONE
int main(int argc, char *argv[])
{
if(argc != 5)
{
cerr << "usage: " << argv[0] << " input_image_file output_image_file, cost, gradScale" << endl;
return 1;
}
printf("Reading image...\n");
string input_filename = argv[1], output_filename = argv[2];
basename_g = output_filename.c_str();
double cost = atof(argv[3]), gradScale = atof(argv[4]);
SDoublePlane input = SImageIO::read_png_file(input_filename.c_str());
PathType path = scene_labeling_1(input, cost, gradScale, PathType(), PathType());
printf("Writing output...\n");
SDoublePlane R, G, B;
R = input; G = input; B = input;
for (int k=input.cols()-1; k>=0; k--)
{
int c1 = path[k].first, c2=path[k].second;
R[c1][k]=255.0; G[c1][k]=0; B[c1][k]=0;
R[c2][k]=0; B[c2][k]=0; G[c2][k]=255.0;
}
printf("png...\n");
SImageIO::write_png_file(output_filename.c_str(), R, G, B);
return 0;
}
#else
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
if(nlhs != 2 || nrhs < 3)
{
cerr << nlhs << " " << nrhs << endl;
mexErrMsgTxt("input or output variable problem");
}
if(mxGetM(prhs[0]) != 1 || mxGetN(prhs[0]) != 1)
mexErrMsgTxt("first param must be a scalar");
double *input = mxGetPr(prhs[1]);
int rows= mxGetM(prhs[1]), cols = mxGetN(prhs[1]);
cerr << rows << " " << cols << endl;
SDoublePlane P(rows, cols);
cerr << "init" << endl;
for(int j=0, cp=0; j<cols; j++)
for(int i=0; i<rows; i++, cp++)
{
P[i][j] = input[cp];
}
// get parameters
double *params = mxGetPr(prhs[2]);
if(mxGetM(prhs[2])*mxGetN(prhs[2]) != 5)
mexErrMsgTxt("need two params");
top_smoothness_g = params[0];
bottom_smoothness_g = params[1];
top_peak_g = params[2];
bottom_peak_g = params[3];
repulse_g = params[4];
PathType pts1, pts2;
if(nrhs > 3)
{
int m = mxGetN(prhs[3]);
double *t = mxGetPr(prhs[3]);
for(int i=0; i<m; i++)
// if(t[i*2] != -1)
pts1.push_back( pair<int, int>((int)t[i*2], (int)t[i*2+1]) );
m = mxGetN(prhs[4]);
t = mxGetPr(prhs[4]);
for(int i=0; i<m; i++)
// if(t[i*2] != -1)
pts2.push_back( pair<int, int>((int)t[i*2], (int)t[i*2+1]) );
cerr << pts1.size() << " " << pts2.size() << endl;
}
cerr << "scene labeling" << endl;
PathType path = scene_labeling_1(P, 1, 1, pts1, pts2);
/* printf("Writing output...\n");
SDoublePlane R, G, B;
R = P; G = P; B = P;
for (int k=P.cols()-1; k>=0; k--)
{
int c1 = path[k].first, c2=path[k].second;
R[c1][k]=255.0; G[c1][k]=0; B[c1][k]=0;
R[c2][k]=0; B[c2][k]=0; G[c2][k]=255.0;
}
*/
// printf("png...\n");
// SImageIO::write_png_file("aa.png", R, G, B);
mwSize dims[] = {rows, cols, 3};
plhs[0] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
/* double *P_ptr = mxGetPr(plhs[0]);
int cp=0;
for(int j=0; j<cols; j++)
for(int i=0; i<rows; i++, cp++)
P_ptr[cp] = R[i][j];
for(int j=0; j<cols; j++)
for(int i=0; i<rows; i++, cp++)
P_ptr[cp] = G[i][j];
for(int j=0; j<cols; j++)
for(int i=0; i<rows; i++, cp++)
P_ptr[cp] = B[i][j];
*/
plhs[1] = mxCreateDoubleMatrix(2, cols, mxREAL);
double *P_ptr = mxGetPr(plhs[1]);
for(int i=0; i<cols; i++)
P_ptr[i*2] = path[i].first, P_ptr[i*2+1] = path[i].second;
}
#endif
| 25.217021 | 129 | 0.519659 | [
"vector"
] |
e44fe399da4a0ba71c60ec0bec512d78006007c0 | 4,716 | cpp | C++ | source/direct3d9/ExtendedMaterial.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 85 | 2015-04-06T05:37:10.000Z | 2022-03-22T19:53:03.000Z | source/direct3d9/ExtendedMaterial.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 10 | 2016-03-17T11:18:24.000Z | 2021-05-11T09:21:43.000Z | source/direct3d9/ExtendedMaterial.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 45 | 2015-09-14T03:54:01.000Z | 2022-03-22T19:53:09.000Z | #include "stdafx.h"
/*
* Copyright (c) 2007-2012 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <d3d9.h>
#include <d3dx9.h>
#include "../Utilities.h"
#include "ExtendedMaterial.h"
using namespace System;
namespace SlimDX
{
namespace Direct3D9
{
// Utility function to convert from D3D color to SlimDX color. Can't put it in Color4 because
// that thing is shared between D3D 9 and D3D 10.
Color4 ConvertColor( const D3DCOLORVALUE& color )
{
Color4 cv;
cv.Red = color.r;
cv.Green = color.g;
cv.Blue = color.b;
cv.Alpha = color.a;
return cv;
}
D3DCOLORVALUE ConvertColor( Color4 color )
{
D3DCOLORVALUE cv;
cv.r = color.Red;
cv.g = color.Green;
cv.b = color.Blue;
cv.a = color.Alpha;
return cv;
}
D3DXMATERIAL ExtendedMaterial::ToUnmanaged( ExtendedMaterial material )
{
D3DXMATERIAL result;
result.pTextureFilename = Utilities::AllocateNativeString( material.TextureFileName );
result.MatD3D.Ambient = ConvertColor( material.MaterialD3D.Ambient );
result.MatD3D.Diffuse = ConvertColor( material.MaterialD3D.Diffuse );
result.MatD3D.Specular = ConvertColor( material.MaterialD3D.Specular );
result.MatD3D.Emissive = ConvertColor( material.MaterialD3D.Emissive );
result.MatD3D.Power = material.MaterialD3D.Power;
return result;
}
ExtendedMaterial ExtendedMaterial::FromUnmanaged( const D3DXMATERIAL &material )
{
ExtendedMaterial result;
Material mat;
mat.Diffuse = ConvertColor( material.MatD3D.Diffuse );
mat.Ambient = ConvertColor( material.MatD3D.Ambient );
mat.Specular = ConvertColor( material.MatD3D.Specular );
mat.Emissive = ConvertColor( material.MatD3D.Emissive );
mat.Power = material.MatD3D.Power;
result.MaterialD3D = mat;
result.TextureFileName = gcnew String( material.pTextureFilename );
return result;
}
array<ExtendedMaterial>^ ExtendedMaterial::FromBuffer( ID3DXBuffer* buffer, unsigned int count )
{
const D3DXMATERIAL* source = reinterpret_cast<const D3DXMATERIAL*>( buffer->GetBufferPointer() );
array<ExtendedMaterial>^ destination = gcnew array<ExtendedMaterial>( count );
for( unsigned int i = 0; i < count; ++i )
{
Material m;
m.Diffuse = ConvertColor( source[i].MatD3D.Diffuse );
m.Ambient = ConvertColor( source[i].MatD3D.Ambient );
m.Specular = ConvertColor( source[i].MatD3D.Specular );
m.Emissive = ConvertColor( source[i].MatD3D.Emissive );
m.Power = source[i].MatD3D.Power;
destination[i].MaterialD3D = m;
destination[i].TextureFileName = gcnew String( source[i].pTextureFilename );
}
return destination;
}
bool ExtendedMaterial::operator == ( ExtendedMaterial left, ExtendedMaterial right )
{
return ExtendedMaterial::Equals( left, right );
}
bool ExtendedMaterial::operator != ( ExtendedMaterial left, ExtendedMaterial right )
{
return !ExtendedMaterial::Equals( left, right );
}
int ExtendedMaterial::GetHashCode()
{
return MaterialD3D.GetHashCode() + TextureFileName->GetHashCode();
}
bool ExtendedMaterial::Equals( Object^ value )
{
if( value == nullptr )
return false;
if( value->GetType() != GetType() )
return false;
return Equals( safe_cast<ExtendedMaterial>( value ) );
}
bool ExtendedMaterial::Equals( ExtendedMaterial value )
{
return ( MaterialD3D == value.MaterialD3D && TextureFileName == value.TextureFileName );
}
bool ExtendedMaterial::Equals( ExtendedMaterial% value1, ExtendedMaterial% value2 )
{
return ( value1.MaterialD3D == value2.MaterialD3D && value1.TextureFileName == value2.TextureFileName );
}
}
} | 32.75 | 107 | 0.718193 | [
"object"
] |
e45051e85e2557a517d286ae3d756935fc8917c8 | 6,015 | cpp | C++ | src/SFML/Graphics/RenderImage.cpp | yoyonel/sflm2-custom | 1ebeabe7cfe6605590b341f7b415b24bed1f50d1 | [
"Zlib"
] | null | null | null | src/SFML/Graphics/RenderImage.cpp | yoyonel/sflm2-custom | 1ebeabe7cfe6605590b341f7b415b24bed1f50d1 | [
"Zlib"
] | null | null | null | src/SFML/Graphics/RenderImage.cpp | yoyonel/sflm2-custom | 1ebeabe7cfe6605590b341f7b415b24bed1f50d1 | [
"Zlib"
] | null | null | null | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
//
// 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.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/RenderImage.hpp>
#include <SFML/Graphics/RenderImageImplFBO.hpp>
#include <SFML/Graphics/RenderImageImplPBuffer.hpp>
#include <SFML/System/Err.hpp>
#include <iostream>
namespace sf
{
////////////////////////////////////////////////////////////
RenderImage::RenderImage() :
myRenderImage(NULL)
{
}
////////////////////////////////////////////////////////////
RenderImage::~RenderImage()
{
SetActive(false);
delete myRenderImage;
}
////////////////////////////////////////////////////////////
bool RenderImage::Create(unsigned int width, unsigned int height, bool depthBuffer, bool stencilBuffer)
{
std::cout<<"RenderImage::Create"<<std::endl;
// Make sure that render-images are supported
if (!IsAvailable())
{
Err() << "Impossible to create render image (your system doesn't support this feature)" << std::endl;
return false;
}
// Create the image
if (!myImage.Create(width, height))
{
Err() << "Impossible to create render image (failed to create the target image)" << std::endl;
return false;
}
// We disable smoothing by default for render images
SetSmooth(false);
// Create the implementation
delete myRenderImage;
if (priv::RenderImageImplFBO::IsSupported())
{
// Use FBO
myRenderImage = new priv::RenderImageImplFBO;
}
/*
else if (priv::RenderImageImplPBuffer::IsSupported())
{
// Use P-Buffer
myRenderImage = new priv::RenderImageImplPBuffer;
}
*/
// Initialize the render image
if (!myRenderImage->Create(width, height, myImage.myTexture, depthBuffer, stencilBuffer))
return false;
// We can now initialize the render target part
RenderTarget::Initialize();
return true;
}
/*
////////////////////////////////////////////////////////////
bool RenderImage::Create(unsigned int width, unsigned int height, bool depthBuffer)
{
// Make sure that render-images are supported
if (!IsAvailable())
{
Err() << "Impossible to create render image (your system doesn't support this feature)" << std::endl;
return false;
}
// Create the image
if (!myImage.Create(width, height))
{
Err() << "Impossible to create render image (failed to create the target image)" << std::endl;
return false;
}
// We disable smoothing by default for render images
SetSmooth(false);
// Create the implementation
delete myRenderImage;
if (priv::RenderImageImplFBO::IsSupported())
{
// Use FBO
myRenderImage = new priv::RenderImageImplFBO;
}
else if (priv::RenderImageImplPBuffer::IsSupported())
{
// Use P-Buffer
myRenderImage = new priv::RenderImageImplPBuffer;
}
// Initialize the render image
if (!myRenderImage->Create(width, height, myImage.myTexture, depthBuffer))
return false;
// We can now initialize the render target part
RenderTarget::Initialize();
return true;
}
*/
////////////////////////////////////////////////////////////
void RenderImage::SetSmooth(bool smooth)
{
myImage.SetSmooth(smooth);
}
////////////////////////////////////////////////////////////
bool RenderImage::IsSmooth() const
{
return myImage.IsSmooth();
}
////////////////////////////////////////////////////////////
bool RenderImage::SetActive(bool active)
{
return myRenderImage && myRenderImage->Activate(active);
}
////////////////////////////////////////////////////////////
void RenderImage::Display()
{
// Update the target image
if (SetActive(true))
{
myRenderImage->UpdateTexture(myImage.myTexture);
myImage.myPixelsFlipped = true;
myImage.myArrayUpdated = false;
myImage.myTextureUpdated = true;
}
}
////////////////////////////////////////////////////////////
unsigned int RenderImage::GetWidth() const
{
return myImage.GetWidth();
}
////////////////////////////////////////////////////////////
unsigned int RenderImage::GetHeight() const
{
return myImage.GetHeight();
}
////////////////////////////////////////////////////////////
const Image& RenderImage::GetImage() const
{
return myImage;
}
////////////////////////////////////////////////////////////
bool RenderImage::IsAvailable()
{
return priv::RenderImageImplFBO::IsSupported() ||
priv::RenderImageImplPBuffer::IsSupported();
}
////////////////////////////////////////////////////////////
bool RenderImage::Activate(bool active)
{
return SetActive(active);
}
} // namespace sf
| 27.847222 | 110 | 0.542643 | [
"render"
] |
e4550f3dacfe299ad104c896553376578a434415 | 62,477 | cc | C++ | src/scanner.cc | carlthuringer/tree-sitter-tlaplus | d7d8c73035028edeb07cd3d9a50bcc635a186877 | [
"MIT"
] | null | null | null | src/scanner.cc | carlthuringer/tree-sitter-tlaplus | d7d8c73035028edeb07cd3d9a50bcc635a186877 | [
"MIT"
] | null | null | null | src/scanner.cc | carlthuringer/tree-sitter-tlaplus | d7d8c73035028edeb07cd3d9a50bcc635a186877 | [
"MIT"
] | null | null | null | #include <tree_sitter/parser.h>
#include <cassert>
#include <climits>
#include <cstring>
#include <cwctype>
#include <vector>
/**
* Macro; goes to the lexer state without consuming any codepoints.
*
* @param state_value The new lexer state.
*/
#define GO_TO_STATE(state_value) \
{ \
state = state_value; \
goto start; \
}
/**
* Macro; marks the given lexeme as accepted.
*
* @param lexeme The lexeme to mark as accepted.
*/
#define ACCEPT_LEXEME(lexeme) \
{ \
result_lexeme = lexeme; \
}
/**
* Macro; marks the given token as accepted without also marking the
* current position as its end.
*
* @param token The token to mark as accepted.
*/
#define ACCEPT_LOOKAHEAD_TOKEN(token) \
{ \
result = true; \
lexer->result_symbol = token; \
}
/**
* Macro; ends a lexer state by returning any accepted lexeme.
*/
#define END_LEX_STATE() \
{ \
return result_lexeme; \
}
namespace {
// Tokens emitted by this external scanner.
enum TokenType {
EXTRAMODULAR_TEXT, // Freeform text between modules.
BLOCK_COMMENT_TEXT, // Text inside block comments.
INDENT, // Marks beginning of junction list.
BULLET_CONJ, // New item of a conjunction list.
BULLET_DISJ, // New item of a disjunction list.
DEDENT, // Marks end of junction list.
BEGIN_PROOF, // Marks the beginning of an entire proof.
BEGIN_PROOF_STEP, // Marks the beginning of a proof step.
PROOF_KEYWORD, // The PROOF keyword.
BY_KEYWORD, // The BY keyword.
OBVIOUS_KEYWORD, // The OBVIOUS keyword.
OMITTED_KEYWORD, // The OMITTED keyword.
QED_KEYWORD, // The QED keyword.
ERROR_SENTINEL // Only valid if in error recovery mode.
};
// Datatype used to record length of nested proofs & jlists.
using nest_address = int16_t;
// Datatype used to record column index of jlists.
using column_index = int16_t;
// Datatype used to record proof levels.
using proof_level = int32_t;
/**
* Advances the scanner while marking the codepoint as non-whitespace.
*
* @param lexer The tree-sitter lexing control structure.
*/
void advance(TSLexer* const lexer) {
lexer->advance(lexer, false);
}
/**
* Checks whether the next codepoint is the one given.
*
* @param lexer The tree-sitter lexing control structure.
* @param codepoint The codepoint to check.
* @return Whether the next codepoint is the one given.
*/
bool is_next_codepoint(
const TSLexer* const lexer,
int32_t const codepoint
) {
return codepoint == lexer->lookahead;
}
/**
* Checks whether there are any codepoints left in the string.
*
* @param lexer The tree-sitter lexing control structure.
* @return Whether there are any codepoints left in the string.
*/
bool has_next(const TSLexer* const lexer) {
return !lexer->eof(lexer);
}
/**
* Checks whether the given codepoint could be used in an identifier,
* which consist of capital ASCII letters, lowercase ASCII letters,
* and underscores.
*
* @param codepoint The codepoint to check.
* @return Whether the given codepoint could be used in an identifier.
*/
bool is_identifier_char(int32_t const codepoint) {
return iswalnum(codepoint) || ('_' == codepoint);
}
/**
* Consumes codepoints as long as they are the one given.
*
* @param lexer The tree-sitter lexing control structure.
* @param codepoint The codepoint to consume.
* @return The number of codepoints consumed.
*/
void consume_codepoint(TSLexer* const lexer, const int32_t codepoint) {
while (has_next(lexer) && is_next_codepoint(lexer, codepoint)) {
advance(lexer);
}
}
/**
* Checks whether the next codepoint sequence is the one given.
* This function can change the state of the lexer.
*
* @param lexer The tree-sitter lexing control structure.
* @param token The codepoint sequence to check for.
* @return Whether the next codepoint sequence is the one given.
*/
bool is_next_codepoint_sequence(
TSLexer* const lexer,
const char codepoint_sequence[]
) {
size_t sequence_length = strlen(codepoint_sequence);
for (size_t i = 0; i < sequence_length; i++) {
int32_t codepoint = codepoint_sequence[i];
if (!is_next_codepoint(lexer, codepoint)) {
return false;
} else if (i + 1 < sequence_length) {
advance(lexer);
}
}
return true;
}
// Possible states for the extramodular text lexer to enter.
enum EMTLexState {
EMTLexState_CONSUME,
EMTLexState_DASH,
EMTLexState_SINGLE_LINE,
EMTLexState_MODULE,
EMTLexState_BLANK_BEFORE_MODULE,
EMTLexState_END_OF_FILE,
EMTLexState_BLANK_BEFORE_END_OF_FILE
};
/**
* Scans for extramodular text, the freeform text that can be present
* outside of TLA+ modules. This function skips any leading whitespace
* to avoid extraneous extramodular text tokens given newlines at the
* beginning or end of the file. It will consume any text up to the
* point it performs lookahead that captures the following regex:
* /----[-]*[ ]*MODULE/
* or EOF, which marks the end of the extramodular text. It is important
* that the extramodular text does not itself include the captured module
* start sequence, which is why this is in an external scanner rather
* than a regex in the grammar itself.
*
* @param lexer The tree-sitter lexing control structure
* @return Whether any extramodular text was detected.
*/
bool scan_extramodular_text(TSLexer* const lexer) {
bool has_consumed_any = false;
EMTLexState state = EMTLexState_CONSUME;
START_LEXER();
eof = !has_next(lexer);
switch (state) {
case EMTLexState_CONSUME:
if (eof) ADVANCE(EMTLexState_END_OF_FILE);
if (iswspace(lookahead) && !has_consumed_any) SKIP(EMTLexState_CONSUME);
if (iswspace(lookahead) && has_consumed_any) ADVANCE(EMTLexState_CONSUME);
lexer->mark_end(lexer);
if ('-' == lookahead) ADVANCE(EMTLexState_DASH);
has_consumed_any = true;
ADVANCE(EMTLexState_CONSUME);
END_STATE();
case EMTLexState_DASH:
if (is_next_codepoint_sequence(lexer, "---")) ADVANCE(EMTLexState_SINGLE_LINE);
has_consumed_any = true;
GO_TO_STATE(EMTLexState_CONSUME);
END_STATE();
case EMTLexState_SINGLE_LINE:
consume_codepoint(lexer, '-');
consume_codepoint(lexer, ' ');
if (is_next_codepoint_sequence(lexer, "MODULE")) ADVANCE(EMTLexState_MODULE);
has_consumed_any = true;
GO_TO_STATE(EMTLexState_CONSUME);
END_STATE();
case EMTLexState_MODULE:
if (!has_consumed_any) GO_TO_STATE(EMTLexState_BLANK_BEFORE_MODULE);
ACCEPT_LOOKAHEAD_TOKEN(EXTRAMODULAR_TEXT);
END_STATE();
case EMTLexState_BLANK_BEFORE_MODULE:
END_STATE();
case EMTLexState_END_OF_FILE:
if (!has_consumed_any) GO_TO_STATE(EMTLexState_BLANK_BEFORE_END_OF_FILE);
ACCEPT_TOKEN(EXTRAMODULAR_TEXT);
END_STATE();
case EMTLexState_BLANK_BEFORE_END_OF_FILE:
END_STATE();
default:
END_STATE();
}
}
// Possible states for the comment lexer to enter.
enum CLexState {
CLexState_CONSUME,
CLexState_ASTERISK,
CLexState_L_PAREN,
CLexState_LEFT_COMMENT_DELIMITER,
CLexState_RIGHT_COMMENT_DELIMITER,
CLexState_LOOKAHEAD,
CLexState_LOOKAHEAD_NEWLINE,
CLexState_LOOKAHEAD_L_PAREN,
CLexState_END_OF_FILE
};
/**
* Scans for block comment text. This scanner function supports nested
* block comments, so (* text (* text *) text *) will all be parsed as
* a single block comment. Also, multiple block comments separated
* only by spaces, tabs, or a single newline will be parsed as a single
* block comment for convenience; for example, the following is a
* single comment:
*
* (***********************)
* (* text text text text *)
* (* text text text text *)
* (* text text text text *)
* (***********************)
*
* Although the following constitutes two separate block comments:
*
* (***********************)
* (* text text text text *)
* (***********************)
*
* (***********************)
* (* text text text text *)
* (***********************)
*
* A block comment will also be emitted if EOF is reached.
*
* @param lexer The tree-sitter lexing control structure.
* @return Whether any block comment text was detected.
*/
bool scan_block_comment_text(TSLexer* const lexer) {
uint32_t nest_level = 0;
CLexState state = CLexState_CONSUME;
START_LEXER();
eof = !has_next(lexer);
switch (state) {
case CLexState_CONSUME:
if (eof) ADVANCE(CLexState_END_OF_FILE);
if ('*' == lookahead) ADVANCE(CLexState_ASTERISK);
if ('(' == lookahead) ADVANCE(CLexState_L_PAREN);
ADVANCE(CLexState_CONSUME);
END_STATE();
case CLexState_ASTERISK:
if ('*' == lookahead) ADVANCE(CLexState_ASTERISK);
if ('(' == lookahead) ADVANCE(CLexState_L_PAREN);
if (')' == lookahead) ADVANCE(CLexState_RIGHT_COMMENT_DELIMITER);
ADVANCE(CLexState_CONSUME);
END_STATE();
case CLexState_L_PAREN:
if ('*' == lookahead) {ADVANCE(CLexState_LEFT_COMMENT_DELIMITER);}
if ('(' == lookahead) ADVANCE(CLexState_L_PAREN);
ADVANCE(CLexState_CONSUME);
END_STATE();
case CLexState_LEFT_COMMENT_DELIMITER:
nest_level++;
GO_TO_STATE(CLexState_CONSUME);
END_STATE();
case CLexState_RIGHT_COMMENT_DELIMITER:
if (nest_level > 0) {
nest_level--;
GO_TO_STATE(CLexState_CONSUME);
} else {
ACCEPT_TOKEN(BLOCK_COMMENT_TEXT);
if (iswspace(lookahead)) GO_TO_STATE(CLexState_LOOKAHEAD);
if ('(' == lookahead) ADVANCE(CLexState_LOOKAHEAD_L_PAREN);
}
END_STATE();
case CLexState_LOOKAHEAD:
if (' ' == lookahead) ADVANCE(CLexState_LOOKAHEAD);
if ('\t' == lookahead) ADVANCE(CLexState_LOOKAHEAD);
if ('\r' == lookahead) ADVANCE(CLexState_LOOKAHEAD);
if ('\n' == lookahead) ADVANCE(CLexState_LOOKAHEAD_NEWLINE);
if ('(' == lookahead) ADVANCE(CLexState_LOOKAHEAD_L_PAREN);
END_STATE();
case CLexState_LOOKAHEAD_NEWLINE:
if (' ' == lookahead) ADVANCE(CLexState_LOOKAHEAD);
if ('\t' == lookahead) ADVANCE(CLexState_LOOKAHEAD);
if ('(' == lookahead) ADVANCE(CLexState_LOOKAHEAD_L_PAREN);
END_STATE();
case CLexState_LOOKAHEAD_L_PAREN:
if ('*' == lookahead) ADVANCE(CLexState_CONSUME);
END_STATE();
case CLexState_END_OF_FILE:
ACCEPT_TOKEN(BLOCK_COMMENT_TEXT);
END_STATE();
default:
END_STATE();
}
}
// Types of proof step IDs.
enum ProofStepIdType {
ProofStepIdType_STAR, // <*>
ProofStepIdType_PLUS, // <+>
ProofStepIdType_NUMBERED // <1234>
};
// Data about a proof step ID.
struct ProofStepId {
// The proof step ID type.
ProofStepIdType type;
// The proof step ID level (-1 if not NUMBERED).
proof_level level;
/**
* Initializes a new instance of the ProofStepId class.
*
* @param raw_level The unparsed contents of the <...> lexeme.
*/
ProofStepId(const std::vector<char>& raw_level) {
level = -1;
if ('*' == raw_level.at(0)) {
type = ProofStepIdType_STAR;
} else if ('+' == raw_level.at(0)) {
type = ProofStepIdType_PLUS;
} else {
type = ProofStepIdType_NUMBERED;
// We can't use std::stoi because it isn't included in the emcc
// build so will cause errors; thus we roll our own. raw_level
// should also be a std::string but that isn't included either.
// level = std::stoi(raw_level);
level = 0;
int32_t multiplier = 1;
for (size_t i = 0; i < raw_level.size(); i++) {
const size_t index = raw_level.size() - i - 1;
int8_t digit_value = raw_level.at(index) - 48;
level += digit_value * multiplier;
multiplier *= 10;
}
}
}
};
// Lexemes recognized by this lexer.
enum Lexeme {
Lexeme_FORWARD_SLASH,
Lexeme_BACKWARD_SLASH,
Lexeme_GT,
Lexeme_EQ,
Lexeme_DASH,
Lexeme_COMMA,
Lexeme_LAND,
Lexeme_LOR,
Lexeme_L_PAREN,
Lexeme_R_PAREN,
Lexeme_R_SQUARE_BRACKET,
Lexeme_R_CURLY_BRACE,
Lexeme_R_ANGLE_BRACKET,
Lexeme_RIGHT_ARROW,
Lexeme_COMMENT_START,
Lexeme_BLOCK_COMMENT_START,
Lexeme_SINGLE_LINE,
Lexeme_DOUBLE_LINE,
Lexeme_ASSUME_KEYWORD,
Lexeme_ASSUMPTION_KEYWORD,
Lexeme_AXIOM_KEYWORD,
Lexeme_BY_KEYWORD,
Lexeme_CONSTANT_KEYWORD,
Lexeme_CONSTANTS_KEYWORD,
Lexeme_COROLLARY_KEYWORD,
Lexeme_ELSE_KEYWORD,
Lexeme_IN_KEYWORD,
Lexeme_LEMMA_KEYWORD,
Lexeme_LOCAL_KEYWORD,
Lexeme_OBVIOUS_KEYWORD,
Lexeme_OMITTED_KEYWORD,
Lexeme_PROOF_KEYWORD,
Lexeme_PROPOSITION_KEYWORD,
Lexeme_QED_KEYWORD,
Lexeme_THEN_KEYWORD,
Lexeme_THEOREM_KEYWORD,
Lexeme_VARIABLE_KEYWORD,
Lexeme_VARIABLES_KEYWORD,
Lexeme_PROOF_STEP_ID,
Lexeme_IDENTIFIER,
Lexeme_OTHER,
Lexeme_END_OF_FILE
};
// Possible states for the lexer to enter.
enum LexState {
LexState_CONSUME_LEADING_SPACE,
LexState_FORWARD_SLASH,
LexState_BACKWARD_SLASH,
LexState_LT,
LexState_GT,
LexState_EQ,
LexState_DASH,
LexState_COMMA,
LexState_LAND,
LexState_LOR,
LexState_L_PAREN,
LexState_R_PAREN,
LexState_R_SQUARE_BRACKET,
LexState_R_CURLY_BRACE,
LexState_R_ANGLE_BRACKET,
LexState_RIGHT_ARROW,
LexState_COMMENT_START,
LexState_BLOCK_COMMENT_START,
LexState_SINGLE_LINE,
LexState_DOUBLE_LINE,
LexState_A, LexState_ASSUM, LexState_ASSUME, LexState_ASSUMPTION, LexState_AX, LexState_AXIOM,
LexState_B, LexState_BY,
LexState_C, LexState_CO, LexState_CON, LexState_COR, LexState_CONSTANT, LexState_CONSTANTS, LexState_COROLLARY,
LexState_E, LexState_ELSE,
LexState_I, LexState_IN,
LexState_L, LexState_LE, LexState_LEMMA, LexState_LO, LexState_LOCAL,
LexState_O, LexState_OB, LexState_OBVIOUS, LexState_OM, LexState_OMITTED,
LexState_P, LexState_PRO, LexState_PROO, LexState_PROOF, LexState_PROP, LexState_PROPOSITION,
LexState_Q, LexState_QED,
LexState_T, LexState_THE, LexState_THEN, LexState_THEOREM,
LexState_V, LexState_VARIABLE, LexState_VARIABLES,
LexState_IDENTIFIER,
LexState_PROOF_LEVEL_NUMBER,
LexState_PROOF_LEVEL_STAR,
LexState_PROOF_LEVEL_PLUS,
LexState_PROOF_NAME,
LexState_PROOF_ID,
LexState_OTHER,
LexState_END_OF_FILE
};
/**
* Looks ahead to identify the next lexeme. Consumes all leading
* whitespace. Out parameters include column of first non-whitespace
* codepoint and the level of the proof step ID lexeme if encountered.
*
* @param lexer The tree-sitter lexing control structure.
* @param lexeme_start_col The starting column of the first lexeme.
* @param proof_step_id_level The level of the proof step ID.
* @return The lexeme encountered.
*/
Lexeme lex_lookahead(
TSLexer* const lexer,
column_index& lexeme_start_col,
std::vector<char>& proof_step_id_level
) {
LexState state = LexState_CONSUME_LEADING_SPACE;
Lexeme result_lexeme = Lexeme_OTHER;
START_LEXER();
eof = !has_next(lexer);
switch (state) {
case LexState_CONSUME_LEADING_SPACE:
if (iswspace(lookahead)) SKIP(LexState_CONSUME_LEADING_SPACE);
lexeme_start_col = lexer->get_column(lexer);
lexer->mark_end(lexer);
if (eof) ADVANCE(LexState_END_OF_FILE);
if ('/' == lookahead) ADVANCE(LexState_FORWARD_SLASH);
if ('\\' == lookahead) ADVANCE(LexState_BACKWARD_SLASH);
if ('<' == lookahead) ADVANCE(LexState_LT);
if ('>' == lookahead) ADVANCE(LexState_GT);
if ('=' == lookahead) ADVANCE(LexState_EQ);
if ('-' == lookahead) ADVANCE(LexState_DASH);
if (',' == lookahead) ADVANCE(LexState_COMMA);
if ('(' == lookahead) ADVANCE(LexState_L_PAREN);
if (')' == lookahead) ADVANCE(LexState_R_PAREN);
if (']' == lookahead) ADVANCE(LexState_R_SQUARE_BRACKET);
if ('}' == lookahead) ADVANCE(LexState_R_CURLY_BRACE);
if ('A' == lookahead) ADVANCE(LexState_A);
if ('B' == lookahead) ADVANCE(LexState_B);
if ('C' == lookahead) ADVANCE(LexState_C);
if ('E' == lookahead) ADVANCE(LexState_E);
if ('I' == lookahead) ADVANCE(LexState_I);
if ('L' == lookahead) ADVANCE(LexState_L);
if ('O' == lookahead) ADVANCE(LexState_O);
if ('P' == lookahead) ADVANCE(LexState_P);
if ('Q' == lookahead) ADVANCE(LexState_Q);
if ('T' == lookahead) ADVANCE(LexState_T);
if ('V' == lookahead) ADVANCE(LexState_V);
if (L'∧' == lookahead) ADVANCE(LexState_LAND);
if (L'∨' == lookahead) ADVANCE(LexState_LOR);
if (L'〉' == lookahead) ADVANCE(LexState_R_ANGLE_BRACKET);
if (L'⟩' == lookahead) ADVANCE(LexState_R_ANGLE_BRACKET);
if (L'⟶' == lookahead) ADVANCE(LexState_RIGHT_ARROW);
ADVANCE(LexState_OTHER);
END_LEX_STATE();
case LexState_FORWARD_SLASH:
ACCEPT_LEXEME(Lexeme_FORWARD_SLASH);
if ('\\' == lookahead) ADVANCE(LexState_LAND);
END_LEX_STATE();
case LexState_BACKWARD_SLASH:
ACCEPT_LEXEME(Lexeme_BACKWARD_SLASH);
if ('/' == lookahead) ADVANCE(LexState_LOR);
if ('*' == lookahead) ADVANCE(LexState_COMMENT_START);
END_LEX_STATE();
case LexState_LT:
proof_step_id_level.push_back(static_cast<char>(lookahead & CHAR_MAX));
if (iswdigit(lookahead)) ADVANCE(LexState_PROOF_LEVEL_NUMBER);
if ('*' == lookahead) ADVANCE(LexState_PROOF_LEVEL_STAR);
if ('+' == lookahead) ADVANCE(LexState_PROOF_LEVEL_PLUS);
ADVANCE(LexState_OTHER);
END_LEX_STATE();
case LexState_GT:
ACCEPT_LEXEME(Lexeme_GT);
if ('>' == lookahead) ADVANCE(LexState_R_ANGLE_BRACKET);
END_LEX_STATE();
case LexState_EQ:
ACCEPT_LEXEME(Lexeme_EQ);
if (is_next_codepoint_sequence(lexer, "===")) ADVANCE(LexState_DOUBLE_LINE);
END_LEX_STATE();
case LexState_DASH:
ACCEPT_LEXEME(Lexeme_DASH);
if ('>' == lookahead) ADVANCE(LexState_RIGHT_ARROW);
if (is_next_codepoint_sequence(lexer, "---")) ADVANCE(LexState_SINGLE_LINE);
END_LEX_STATE();
case LexState_COMMA:
ACCEPT_LEXEME(Lexeme_COMMA);
END_LEX_STATE();
case LexState_LAND:
ACCEPT_LEXEME(Lexeme_LAND);
END_LEX_STATE();
case LexState_LOR:
ACCEPT_LEXEME(Lexeme_LOR);
END_LEX_STATE();
case LexState_L_PAREN:
ACCEPT_LEXEME(Lexeme_L_PAREN);
if ('*' == lookahead) ADVANCE(LexState_BLOCK_COMMENT_START);
END_LEX_STATE();
case LexState_R_PAREN:
ACCEPT_LEXEME(Lexeme_R_PAREN);
END_LEX_STATE();
case LexState_R_SQUARE_BRACKET:
ACCEPT_LEXEME(Lexeme_R_SQUARE_BRACKET);
END_LEX_STATE();
case LexState_R_CURLY_BRACE:
ACCEPT_LEXEME(Lexeme_R_CURLY_BRACE);
END_LEX_STATE();
case LexState_R_ANGLE_BRACKET:
ACCEPT_LEXEME(Lexeme_R_ANGLE_BRACKET);
END_LEX_STATE();
case LexState_RIGHT_ARROW:
ACCEPT_LEXEME(Lexeme_RIGHT_ARROW);
END_LEX_STATE();
case LexState_COMMENT_START:
ACCEPT_LEXEME(Lexeme_COMMENT_START);
END_LEX_STATE();
case LexState_BLOCK_COMMENT_START:
ACCEPT_LEXEME(Lexeme_BLOCK_COMMENT_START);
END_LEX_STATE();
case LexState_SINGLE_LINE:
ACCEPT_LEXEME(Lexeme_SINGLE_LINE);
END_LEX_STATE();
case LexState_DOUBLE_LINE:
ACCEPT_LEXEME(Lexeme_DOUBLE_LINE);
END_LEX_STATE();
case LexState_A:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if ('X' == lookahead) ADVANCE(LexState_AX);
if (is_next_codepoint_sequence(lexer, "SSUM")) ADVANCE(LexState_ASSUM);
END_LEX_STATE();
case LexState_ASSUM:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if ('E' == lookahead) ADVANCE(LexState_ASSUME);
if (is_next_codepoint_sequence(lexer, "PTION")) ADVANCE(LexState_ASSUMPTION);
END_LEX_STATE();
case LexState_ASSUME:
ACCEPT_LEXEME(Lexeme_ASSUME_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_ASSUMPTION:
ACCEPT_LEXEME(Lexeme_ASSUMPTION_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_AX:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "IOM")) ADVANCE(LexState_AXIOM);
END_LEX_STATE();
case LexState_AXIOM:
ACCEPT_LEXEME(Lexeme_AXIOM_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_B:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if ('Y' == lookahead) ADVANCE(LexState_BY);
END_LEX_STATE();
case LexState_BY:
ACCEPT_LEXEME(Lexeme_BY_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_C:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if ('O' == lookahead) ADVANCE(LexState_CO);
END_LEX_STATE();
case LexState_CO:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if ('N' == lookahead) ADVANCE(LexState_CON);
if ('R' == lookahead) ADVANCE(LexState_COR);
END_LEX_STATE();
case LexState_CON:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "STANT")) ADVANCE(LexState_CONSTANT);
END_LEX_STATE();
case LexState_CONSTANT:
ACCEPT_LEXEME(Lexeme_CONSTANT_KEYWORD);
if ('S' == lookahead) ADVANCE(LexState_CONSTANTS);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_CONSTANTS:
ACCEPT_LEXEME(Lexeme_CONSTANTS_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_COR:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "OLLARY")) ADVANCE(LexState_COROLLARY);
END_LEX_STATE();
case LexState_COROLLARY:
ACCEPT_LEXEME(Lexeme_COROLLARY_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_E:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "LSE")) ADVANCE(LexState_ELSE);
END_LEX_STATE();
case LexState_ELSE:
ACCEPT_LEXEME(Lexeme_ELSE_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_I:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if ('N' == lookahead) ADVANCE(LexState_IN);
END_LEX_STATE();
case LexState_IN:
ACCEPT_LEXEME(Lexeme_IN_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_L:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if ('E' == lookahead) ADVANCE(LexState_LE);
if ('O' == lookahead) ADVANCE(LexState_LO);
END_LEX_STATE();
case LexState_LE:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "MMA")) ADVANCE(LexState_LEMMA);
END_LEX_STATE();
case LexState_LEMMA:
ACCEPT_LEXEME(Lexeme_LEMMA_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_LO:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "CAL")) ADVANCE(LexState_LOCAL);
END_LEX_STATE();
case LexState_LOCAL:
ACCEPT_LEXEME(Lexeme_LOCAL_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_O:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if ('B' == lookahead) ADVANCE(LexState_OB);
if ('M' == lookahead) ADVANCE(LexState_OM);
END_LEX_STATE();
case LexState_OB:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "VIOUS")) ADVANCE(LexState_OBVIOUS);
END_LEX_STATE();
case LexState_OBVIOUS:
ACCEPT_LEXEME(Lexeme_OBVIOUS_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_OM:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "ITTED")) ADVANCE(LexState_OMITTED);
END_LEX_STATE();
case LexState_OMITTED:
ACCEPT_LEXEME(Lexeme_OMITTED_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_P:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "RO")) ADVANCE(LexState_PRO);
END_LEX_STATE();
case LexState_PRO:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if ('O' == lookahead) ADVANCE(LexState_PROO);
if ('P' == lookahead) ADVANCE(LexState_PROP);
END_LEX_STATE();
case LexState_PROO:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if ('F' == lookahead) ADVANCE(LexState_PROOF);
END_LEX_STATE();
case LexState_PROOF:
ACCEPT_LEXEME(Lexeme_PROOF_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_PROP:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "OSITION")) ADVANCE(LexState_PROPOSITION);
END_LEX_STATE();
case LexState_PROPOSITION:
ACCEPT_LEXEME(Lexeme_PROPOSITION_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_Q:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "ED")) ADVANCE(LexState_QED);
END_LEX_STATE();
case LexState_QED:
ACCEPT_LEXEME(Lexeme_QED_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_T:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "HE")) ADVANCE(LexState_THE);
END_LEX_STATE();
case LexState_THE:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if ('N' == lookahead) ADVANCE(LexState_THEN);
if (is_next_codepoint_sequence(lexer, "OREM")) ADVANCE(LexState_THEOREM);
END_LEX_STATE();
case LexState_THEN:
ACCEPT_LEXEME(Lexeme_THEN_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_THEOREM:
ACCEPT_LEXEME(Lexeme_THEOREM_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_V:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
if (is_next_codepoint_sequence(lexer, "ARIABLE")) ADVANCE(LexState_VARIABLE);
END_LEX_STATE();
case LexState_VARIABLE:
ACCEPT_LEXEME(Lexeme_VARIABLE_KEYWORD);
if ('S' == lookahead) ADVANCE(LexState_VARIABLES);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_VARIABLES:
ACCEPT_LEXEME(Lexeme_VARIABLES_KEYWORD);
if (is_identifier_char(lookahead)) ADVANCE(LexState_IDENTIFIER);
END_LEX_STATE();
case LexState_PROOF_LEVEL_NUMBER:
if (iswdigit(lookahead)) {
proof_step_id_level.push_back(static_cast<char>(lookahead & CHAR_MAX));
ADVANCE(LexState_PROOF_LEVEL_NUMBER);
}
if ('>' == lookahead) ADVANCE(LexState_PROOF_NAME);
ADVANCE(LexState_OTHER);
END_LEX_STATE();
case LexState_PROOF_LEVEL_STAR:
if ('>' == lookahead) ADVANCE(LexState_PROOF_NAME);
ADVANCE(LexState_OTHER);
END_LEX_STATE();
case LexState_PROOF_LEVEL_PLUS:
if ('>' == lookahead) ADVANCE(LexState_PROOF_NAME);
ADVANCE(LexState_OTHER);
END_LEX_STATE();
case LexState_PROOF_NAME:
ACCEPT_LEXEME(Lexeme_PROOF_STEP_ID);
if (iswalnum(lookahead)) ADVANCE(LexState_PROOF_NAME);
if ('.' == lookahead) ADVANCE(LexState_PROOF_ID);
END_LEX_STATE();
case LexState_PROOF_ID:
ACCEPT_LEXEME(Lexeme_PROOF_STEP_ID);
if ('.' == lookahead) ADVANCE(LexState_PROOF_ID);
END_LEX_STATE();
case LexState_IDENTIFIER:
ACCEPT_LEXEME(Lexeme_IDENTIFIER);
END_LEX_STATE();
case LexState_OTHER:
ACCEPT_LEXEME(Lexeme_OTHER);
END_LEX_STATE();
case LexState_END_OF_FILE:
ACCEPT_LEXEME(Lexeme_END_OF_FILE);
END_LEX_STATE();
default:
ACCEPT_LEXEME(Lexeme_OTHER);
END_LEX_STATE();
}
}
// Tokens recognized by this scanner.
enum Token {
Token_LAND,
Token_LOR,
Token_RIGHT_DELIMITER,
Token_COMMENT_START,
Token_TERMINATOR,
Token_PROOF_STEP_ID,
Token_PROOF_KEYWORD,
Token_BY_KEYWORD,
Token_OBVIOUS_KEYWORD,
Token_OMITTED_KEYWORD,
Token_QED_KEYWORD,
Token_OTHER
};
/**
* Maps the given lexeme to a token.
*
* @param lexeme The lexeme to map to a token.
* @return The token corresponding to the given lexeme.
*/
Token tokenize_lexeme(Lexeme lexeme) {
switch (lexeme) {
case Lexeme_FORWARD_SLASH: return Token_OTHER;
case Lexeme_BACKWARD_SLASH: return Token_OTHER;
case Lexeme_GT: return Token_OTHER;
case Lexeme_EQ: return Token_OTHER;
case Lexeme_DASH: return Token_OTHER;
case Lexeme_COMMA: return Token_RIGHT_DELIMITER;
case Lexeme_LAND: return Token_LAND;
case Lexeme_LOR: return Token_LOR;
case Lexeme_L_PAREN: return Token_OTHER;
case Lexeme_R_PAREN: return Token_RIGHT_DELIMITER;
case Lexeme_R_SQUARE_BRACKET: return Token_RIGHT_DELIMITER;
case Lexeme_R_CURLY_BRACE: return Token_RIGHT_DELIMITER;
case Lexeme_R_ANGLE_BRACKET: return Token_RIGHT_DELIMITER;
case Lexeme_RIGHT_ARROW: return Token_RIGHT_DELIMITER;
case Lexeme_COMMENT_START: return Token_COMMENT_START;
case Lexeme_BLOCK_COMMENT_START: return Token_COMMENT_START;
case Lexeme_SINGLE_LINE: return Token_TERMINATOR;
case Lexeme_DOUBLE_LINE: return Token_TERMINATOR;
case Lexeme_ASSUME_KEYWORD: return Token_TERMINATOR;
case Lexeme_ASSUMPTION_KEYWORD: return Token_TERMINATOR;
case Lexeme_AXIOM_KEYWORD: return Token_TERMINATOR;
case Lexeme_BY_KEYWORD: return Token_BY_KEYWORD;
case Lexeme_CONSTANT_KEYWORD: return Token_TERMINATOR;
case Lexeme_CONSTANTS_KEYWORD: return Token_TERMINATOR;
case Lexeme_COROLLARY_KEYWORD: return Token_TERMINATOR;
case Lexeme_ELSE_KEYWORD: return Token_RIGHT_DELIMITER;
case Lexeme_IN_KEYWORD: return Token_RIGHT_DELIMITER;
case Lexeme_LEMMA_KEYWORD: return Token_TERMINATOR;
case Lexeme_LOCAL_KEYWORD: return Token_TERMINATOR;
case Lexeme_OBVIOUS_KEYWORD: return Token_OBVIOUS_KEYWORD;
case Lexeme_OMITTED_KEYWORD: return Token_OMITTED_KEYWORD;
case Lexeme_PROOF_KEYWORD: return Token_PROOF_KEYWORD;
case Lexeme_PROPOSITION_KEYWORD: return Token_TERMINATOR;
case Lexeme_THEN_KEYWORD: return Token_RIGHT_DELIMITER;
case Lexeme_THEOREM_KEYWORD: return Token_TERMINATOR;
case Lexeme_VARIABLE_KEYWORD: return Token_TERMINATOR;
case Lexeme_VARIABLES_KEYWORD: return Token_TERMINATOR;
case Lexeme_PROOF_STEP_ID: return Token_PROOF_STEP_ID;
case Lexeme_QED_KEYWORD: return Token_QED_KEYWORD;
case Lexeme_IDENTIFIER: return Token_OTHER;
case Lexeme_OTHER: return Token_OTHER;
case Lexeme_END_OF_FILE: return Token_TERMINATOR;
default: return Token_OTHER;
}
}
// Possible types of junction list.
enum JunctType {
JunctType_CONJUNCTION,
JunctType_DISJUNCTION
};
// Data about a jlist.
struct JunctList {
// The type of jlist.
JunctType type;
// The starting alignment columnt of the jlist.
column_index alignment_column;
JunctList() { }
JunctList(JunctType const type, column_index const alignment_column) {
this->type = type;
this->alignment_column = alignment_column;
}
unsigned serialize(char* buffer) {
unsigned offset = 0;
unsigned byte_count = 0;
unsigned copied = 0;
// Serialize junction type
copied = sizeof(uint8_t);
buffer[offset] = static_cast<uint8_t>(type);
offset += copied;
byte_count += copied;
// Serialize alignment column
copied = sizeof(column_index);
memcpy(&buffer[offset], (char*)&alignment_column, copied);
offset += copied;
byte_count += copied;
return byte_count;
}
unsigned deserialize(const char* const buffer, unsigned const length) {
assert(length > 0);
unsigned byte_count = 0;
unsigned offset = 0;
unsigned copied = 0;
// Deserialize junction type
copied = sizeof(uint8_t);
type = JunctType(buffer[offset]);
offset += copied;
byte_count += copied;
// Deserialize alignment column
copied = sizeof(column_index);
memcpy((char*)&alignment_column, &buffer[offset], copied);
offset += copied;
byte_count += copied;
return byte_count;
}
};
/**
* A stateful scanner used to parse junction lists.
*/
struct Scanner {
//The nested junction lists at the current lexer position.
std::vector<JunctList> jlists;
// The nested proofs at the current lexer position.
std::vector<proof_level> proofs;
// The level of the last proof.
proof_level last_proof_level;
// Whether we have seen a PROOF token.
bool have_seen_proof_keyword;
/**
* Initializes a new instance of the Scanner object.
*/
Scanner() {
deserialize(NULL, 0);
}
/**
* Serializes the Scanner state into the given buffer.
*
* @param buffer The buffer into which to serialize the scanner state.
* @return Number of bytes written into the buffer.
*/
unsigned serialize(char* const buffer) {
unsigned offset = 0;
unsigned byte_count = 0;
unsigned copied = 0;
const nest_address jlist_depth = static_cast<nest_address>(jlists.size());
copied = sizeof(nest_address);
memcpy(&buffer[offset], &jlist_depth, copied);
offset += copied;
byte_count += copied;
for (nest_address i = 0; i < jlist_depth; i++) {
copied = jlists[i].serialize(&buffer[offset]);
offset += copied;
byte_count += copied;
}
const nest_address proof_depth = static_cast<nest_address>(proofs.size());
copied = sizeof(nest_address);
memcpy(&buffer[offset], &proof_depth, copied);
offset += copied;
byte_count += copied;
copied = proof_depth * sizeof(proof_level);
memcpy(&buffer[offset], proofs.data(), copied);
offset += copied;
byte_count += copied;
copied = sizeof(proof_level);
memcpy(&buffer[offset], &last_proof_level, copied);
offset += copied;
byte_count += copied;
copied = sizeof(uint8_t);
buffer[offset] = static_cast<uint8_t>(have_seen_proof_keyword);
offset += copied;
byte_count += copied;
return byte_count;
}
/**
* Deserializes the Scanner state from the given buffer.
*
* @param buffer The buffer from which to deserialize the state.
* @param length The bytes available to read from the buffer.
*/
void deserialize(const char* const buffer, unsigned const length) {
// Very important to clear values of all fields here!
// Scanner object is reused; if a variable isn't cleared, it can
// lead to extremely strange & impossible-to-debug behavior.
jlists.clear();
proofs.clear();
last_proof_level = -1;
have_seen_proof_keyword = false;
if (length > 0) {
unsigned offset = 0;
unsigned copied = 0;
nest_address jlist_depth = 0;
copied = sizeof(nest_address);
memcpy(&jlist_depth, &buffer[offset], copied);
jlists.resize(jlist_depth);
offset += copied;
for (nest_address i = 0; i < jlist_depth; i++) {
assert(offset < length);
copied = jlists[i].deserialize(&buffer[offset], length - offset);
offset += copied;
}
nest_address proof_depth = 0;
copied = sizeof(nest_address);
memcpy(&proof_depth, &buffer[offset], copied);
proofs.resize(proof_depth);
offset += copied;
copied = proof_depth * sizeof(proof_level);
memcpy(proofs.data(), &buffer[offset], copied);
offset += copied;
copied = sizeof(proof_level);
memcpy(&last_proof_level, &buffer[offset], copied);
offset += copied;
copied = sizeof(uint8_t);
have_seen_proof_keyword = static_cast<bool>(buffer[offset] & 1);
offset += copied;
assert(offset == length);
}
}
/**
* Whether the Scanner state indicates we are currently in a jlist.
*
* @return Whether we are in a jlist.
*/
bool is_in_jlist() const {
return !jlists.empty();
}
/**
* The column index of the current jlist. Returns negative number if
* we are not currently in a jlist.
*
* @return The column index of the current jlist.
*/
column_index get_current_jlist_column_index() const {
return is_in_jlist() ? this->jlists.back().alignment_column : -1;
}
/**
* Whether the given jlist type matches the current jlist.
*
* @param type The jlist type to check.
* @return Whether the given jlist type matches the current jlist.
*/
bool current_jlist_type_is(JunctType const type) const {
return is_in_jlist() && type == this->jlists.back().type;
}
/**
* Emits an INDENT token, recording the new jlist in the Scanner state.
*
* @param lexer The tree-sitter lexing control structure.
* @param type The type of the new jlist.
* @param col The column position of the new jlist.
* @return Whether an INDENT token was emitted.
*/
bool emit_indent(
TSLexer* const lexer,
JunctType const type,
column_index const col
) {
lexer->result_symbol = INDENT;
JunctList new_list(type, col);
this->jlists.push_back(new_list);
return true;
}
/**
* Emits a BULLET_CONJ or BULLET_DISJ token, marking the start of a
* new item in the current jlist.
*
* @param lexer The tree-sitter lexing control structure.
* @param type The type of junction token to emit.
* @return Whether a BULLET token was emitted.
*/
bool emit_bullet(TSLexer* const lexer, const JunctType type) {
switch (type) {
case JunctType_CONJUNCTION:
lexer->result_symbol = BULLET_CONJ;
break;
case JunctType_DISJUNCTION:
lexer->result_symbol = BULLET_DISJ;
break;
default:
return false;
}
lexer->mark_end(lexer);
return true;
}
/**
* Emits a DEDENT token, removing a jlist from the Scanner state.
*
* @param lexer The tree-sitter lexing control structure.
* @return Whether a DEDENT token was emitted.
*/
bool emit_dedent(TSLexer* const lexer) {
lexer->result_symbol = DEDENT;
this->jlists.pop_back();
return true;
}
/**
* Jlists are identified with the column position (cpos) of the first
* junct token in the list, and the junction type. For a given junct
* token there are five possible interpretations:
* 1. The junct is after the cpos of the current jlist, and an
* INDENT token is expected
* -> this is a new nested jlist, emit INDENT token
* 2. The junct is after the cpos of the current jlist, and an
* INDENT token is *not* expected
* -> this is an infix junct operator; emit nothing
* 3. The junct is equal to the cpos of the current jlist, and is
* the same junct type (conjunction or disjunction)
* -> this is an item of the current jlist; emit BULLET token
* 4. The junct is equal to the cpos of the current jlist, and is
* a DIFFERENT junct type (conjunction vs. disjunction)
* -> this is an infix operator that also ends the current list
* 5. The junct is prior to the cpos of the current jlist
* -> this ends the current jlist, emit DEDENT token
*
* @param lexer The tree-sitter lexing control structure.
* @param valid_symbols Tokens possibly expected in this spot.
* @param type The type of junction encountered.
* @param next The column position of the junct token encountered.
* @return Whether a jlist-relevant token should be emitted.
*/
bool handle_junct_token(
TSLexer* const lexer,
const bool* const valid_symbols,
JunctType const next_type,
column_index const next_col
) {
const column_index current_col = get_current_jlist_column_index();
if (current_col < next_col) {
if (valid_symbols[INDENT]) {
/**
* The start of a new junction list!
*/
return emit_indent(lexer, next_type, next_col);
} else {
/**
* This is an infix junction symbol. Tree-sitter will only look for
* a new jlist at the start of an expression rule; infix operators
* occur when joining two expression rules together, so tree-sitter
* is only looking for either BULLET or DEDENT rules. Examples:
*
* /\ a /\ b
* ^ tree-sitter will NEVER look for an INDENT here
*
* /\ a
* /\ b
* ^ tree-sitter WILL look for a BULLET here
*
* /\ /\ a
* ^ tree-sitter WILL look for an INDENT here
*/
return false;
}
} else if (current_col == next_col) {
if (current_jlist_type_is(next_type)) {
/**
* This is another entry in the jlist.
*/
return emit_bullet(lexer, next_type);
} else {
/**
* Disjunct in alignment with conjunct list or vice-versa; treat
* this as an infix operator by terminating the current list.
*/
return emit_dedent(lexer);
}
} else {
/**
* Junct found prior to the alignment column of the current jlist.
* This marks the end of the jlist.
*/
return emit_dedent(lexer);
}
}
/**
* If a given right delimiter matches some left delimiter that occurred
* *before* the beginning of the current jlist, then that ends the
* current jlist. The concept of a delimiter is not limited (hah) to
* (), [], <<>>, and {}; it also includes IF/THEN, THEN/ELSE, CASE/->,
* and basically every other language construct where an expression is
* squeezed between a known start & end token.
*
* Previously I implemented complicated logic using a stack to keep
* track of all the delimiters that have been seen (and their
* pairs) but found that tree-sitter would never trigger the
* external scanner before encountering a right delimiter matching
* a left delimiter that started within the scope of a jlist. Thus
* we can assume that when we *do* see a right delimiter, it
* matches a left delimiter that occurred prior to the start of the
* jlist, so we can emit a DEDENT token to end the jlist. Example:
*
* /\ ( a + b )
* ^ tree-sitter will never look for an INDENT,
* BULLET, or DEDENT token here; it is only
* looking for another infix operator or the
* right-delimiter.
*
* ( /\ a + b )
* ^ tree-sitter WILL look for an INDENT, BULLET, or
* DEDENT token here in addition to looking for an
* infix operator; it also wants to see a DEDENT
* token before seeing the right delimiter, although
* error recovery is simple enough that it would
* barely notice its absence.
*
* There are a few notable exceptions to this rule; for example, the
* empty set or empty sequence:
*
* /\ { }
* ^
* /\ << >>
* ^ there is the option for an expression here, so tree-sitter
* looks for INDENT tokens and we will see a right delimiter
* in this external scanner.
*
* Another example when the code is in a non-parseable state which we
* nonetheless wish to handle gracefully:
*
* /\ [x \in S |-> ]
* ^ user is about to write an expression here, but
* there is a time when the code is non-parseable;
* tree-sitter will again look for an INDENT token
* and we will see a right delimiter in this
* external scanner.
*
* The easy solution to these cases is to simply check whether
* tree-sitter is looking for a DEDENT token. If so, emit one; if not,
* emit nothing. Tree-sitter will not look for a DEDENT token inside
* enclosing delimiters within the scope of a jlist.
*
* One side-effect of all this is that tree-sitter parses certain
* arrangements of jlists and delimiters that are actually illegal
* according to TLA+ syntax rules; that is okay since tree-sitter's
* use case of error-tolerant editor tooling ensures its design
* errs on the side of being overly-permissive. For a concrete
* example here, tree-sitter will parse this illegal expression
* without complaint:
*
* /\ A
* /\ (B + C
* )
* /\ D
*
* This should simply be detected as an error at the semantic level.
*
* @param lexer The tree-sitter lexing control structure.
* @param valid_symbols Tokens possibly expected in this spot.
* @return Whether a jlist-relevant token should be emitted.
*/
bool handle_right_delimiter_token(
TSLexer* const lexer,
const bool* const valid_symbols
) {
return is_in_jlist()
&& valid_symbols[DEDENT]
&& emit_dedent(lexer);
}
/**
* Emits a dedent token if are in jlist and have encountered a token that
* unconditionally ends a jlist regardless of column position; these
* include:
* 1. New unit definition (op == expr, etc.)
* 2. End-of-module token (====)
* 3. End-of-file (this shouldn't happen but we will end the jlist to
* improve error reporting since the end-of-module token is missing)
*
* @param lexer The tree-sitter lexing control structure.
* @param valid_symbols Tokens possibly expected in this spot.
* @return Whether a jlist-relevant token should be emitted.
*/
bool handle_terminator_token(
TSLexer* const lexer,
const bool* const valid_symbols
) {
return is_in_jlist()
&& emit_dedent(lexer);
}
/**
* Non-junct tokens could possibly indicate the end of a jlist. Rules:
* - If the token cpos is leq to the current jlist cpos, the jlist
* has ended; emit a DEDENT token (possibly multiple); example:
* IF /\ P
* /\ Q
* THEN R
* ELSE S
* - Otherwise the token is treated as part of the expression in that
* junct; for example:
* /\ IF e THEN P
* ELSE Q
* /\ R
* so emit no token.
*
* @param lexer The tree-sitter lexing control structure.
* @param next The column position of the encountered token.
* @return Whether a jlist-relevant token should be emitted.
*/
bool handle_other_token(
TSLexer* const lexer,
const bool* const valid_symbols,
column_index const next
) {
return is_in_jlist()
&& next <= get_current_jlist_column_index()
&& emit_dedent(lexer);
}
/**
* Gets whether we are currently in a proof.
*
* @return Whether we are currently in a proof.
*/
bool is_in_proof() const {
return !proofs.empty();
}
/**
* Gets the current proof level; -1 if none.
*
* @return The current proof level.
*/
proof_level get_current_proof_level() const {
return is_in_proof() ? proofs.back() : -1;
}
/**
* Emits a token indicating the start of a new proof.
*
* @param lexer The tree-sitter lexing control structure.
* @param level The level of the new proof.
* @return Whether a token should be emitted.
*/
bool emit_begin_proof(TSLexer* const lexer, proof_level level) {
lexer->result_symbol = BEGIN_PROOF;
proofs.push_back(level);
last_proof_level = level;
have_seen_proof_keyword = false;
return true;
}
/**
* Emits a token indicating the start of a new proof step.
*
* @param lexer The tree-sitter lexing control structure.
* @param level The level of the new proof step.
* @return Whether a token should be emitted.
*/
bool emit_begin_proof_step(TSLexer* const lexer, proof_level level) {
last_proof_level = level;
lexer->result_symbol = BEGIN_PROOF_STEP;
return true;
}
/**
* Handle encountering a new proof step ID. This probably marks the
* beginning of a new proof step, but could also be a reference to a
* prior proof step as part of an expression. There are also various
* interactions between the proof step ID and jlists. Cases:
* 1. A proof step token is expected
* -> This is a new proof step; see proof step logic below
* 2. A proof step token is *not* expected, and a DEDENT token *is*
* -> This is the beginning of a proof step but there is an open
* jlist which must first be closed; emit a DEDENT token.
* 3. A proof step token is not expected, and neither is a DEDENT
* -> This is a proof step reference, so treat as other token.
* P => <1>b
* ^ tree-sitter will only look for INDENT here
*
* For handling proof steps alone, there are the following cases:
* 1. The new proof token level is greater than the current level
* -> This is the start of a new proof; emit BEGIN_PROOF token
* and push level to proof stack. Set last_proof_level to
* the new proof level.
* 2. The new proof token level is equal to the current level
* -> This is another proof step; emit BEGIN_PROOF_STEP token.
* 3. The new proof token level is less than the current level
* -> This is an error, which we will try to recover from.
*
* There are also rules to handle proof step IDs where the level is
* inferred, like <+> and <*>. They are as follows:
* 1. The proof step ID is <+>
* -> This is the start of a new proof; its level is one higher
* than last_proof_level.
* 2. The proof step ID is <*> and we are not inside a proof
* -> This is the start of the very first proof; its level is one
* higher than last_proof_level, which should be -1; thus the
* proof level should be 0.
* 3. The proof step ID is <*> and it directly follows a PROOF keyword
* -> This is the start of a new proof; its level is one higher
* than last_proof_level.
* 4. The proof step ID is <*> and it *does not* follow a PROOF keyword
* -> This is another step in the same proof; its level is the
* same as last_proof_level.
*
* Proofs are ended upon encountering a QED step, which is handled
* elsewhere.
*
* @param lexer The tree-sitter lexing control structure.
* @param valid_symbols Tokens possibly expected in this spot.
* @param next The column position of the encountered token.
* @return Whether a token should be emitted.
*/
bool handle_proof_step_id_token(
TSLexer* const lexer,
const bool* const valid_symbols,
column_index const next,
const std::vector<char>& proof_step_id_level
) {
ProofStepId proof_step_id_token(proof_step_id_level);
if (valid_symbols[BEGIN_PROOF] || valid_symbols[BEGIN_PROOF_STEP]) {
proof_level next_proof_level = -1;
const proof_level current_proof_level = get_current_proof_level();
switch (proof_step_id_token.type) {
case ProofStepIdType_STAR:
/**
* <*> can start a new proof only at the very first level,
* or directly following a PROOF keyword.
*/
next_proof_level =
!is_in_proof() || have_seen_proof_keyword
? last_proof_level + 1
: current_proof_level;
break;
case ProofStepIdType_PLUS:
/**
* This keeps us from entering an infinite loop when we see
* a <+> proof step ID; the first time we encounter the <+>,
* we will increase the level and emit a BEGIN_PROOF token.
* The second time, we mark it as the same level and emit a
* BEGIN_PROOF_STEP token.
*/
next_proof_level = valid_symbols[BEGIN_PROOF]
? last_proof_level + 1
: current_proof_level;
break;
case ProofStepIdType_NUMBERED:
next_proof_level = proof_step_id_token.level;
break;
default:
return false;
}
if (next_proof_level > current_proof_level) {
return emit_begin_proof(lexer, next_proof_level);
} else if (next_proof_level == current_proof_level) {
if (have_seen_proof_keyword) {
// This has been declared a new proof using the PROOF keyword
// but does not have a level greater than the old; thus we've
// detected a syntax error.
// TODO: handle this.
return false;
} else {
return emit_begin_proof_step(lexer, next_proof_level);
}
} else {
// The next proof level is lower than the current. This is
// invalid syntax.
// TODO: handle this.
return false;
}
} else {
if (valid_symbols[DEDENT]) {
// End all jlists before start of proof.
return handle_terminator_token(lexer, valid_symbols);
} else {
// This is a reference to a proof step in an expression.
return handle_other_token(lexer, valid_symbols, next);
}
}
}
/**
* Handles the PROOF keyword token. We record that we've seen the
* PROOF keyword, which modifies the interpretation of the subsequent
* proof step ID. The PROOF token also terminates any current jlist.
*
* @param lexer The tree-sitter lexing control structure.
* @param valid_symbols Tokens possibly expected in this spot.
* @return Whether a token should be emitted.
*/
bool handle_proof_keyword_token(
TSLexer* const lexer,
const bool* const valid_symbols
) {
if (valid_symbols[PROOF_KEYWORD]) {
have_seen_proof_keyword = true;
lexer->result_symbol = PROOF_KEYWORD;
lexer->mark_end(lexer);
return true;
} else {
return handle_terminator_token(lexer, valid_symbols);
}
}
/**
* Handles the BY, OBVIOUS, and OMITTED keyword tokens. We record
* that we've seen the keyword, which negates any PROOF keyword
* previously encountered. These tokens also terminate any current
* jlist.
*
* @param lexer The tree-sitter lexing control structure.
* @param valid_symbols Tokens possibly expected in this spot.
* @param keyword_type The specific keyword being handled.
* @return Whether a token should be emitted.
*/
bool handle_terminal_proof_keyword_token(
TSLexer* const lexer,
const bool* const valid_symbols,
TokenType keyword_type
) {
if (valid_symbols[keyword_type]) {
have_seen_proof_keyword = false;
lexer->result_symbol = keyword_type;
lexer->mark_end(lexer);
return true;
} else {
return handle_terminator_token(lexer, valid_symbols);
}
}
/**
* Handles the QED keyword token. The QED token indicates this is the
* final step of a proof, so we modify the state accordingly. First
* we record the current proof level in case there is a child proof
* of this step that uses <+> or PROOF <*> for its first step. Then
* we pop the top proof level off the stack.
*
* @param lexer The tree-sitter lexing control structure.
* @param valid_symbols Tokens possibly expected in this spot.
* @return Whether a token should be emitted.
*/
bool handle_qed_keyword_token(
TSLexer* const lexer,
const bool* const valid_symbols
) {
last_proof_level = get_current_proof_level();
proofs.pop_back();
lexer->result_symbol = QED_KEYWORD;
lexer->mark_end(lexer);
return true;
}
/**
* Scans for various possible external tokens.
*
* @param lexer The tree-sitter lexing control structure.
* @param valid_symbols Tokens possibly expected in this spot.
* @return Whether a token was encountered.
*/
bool scan(TSLexer* const lexer, const bool* const valid_symbols) {
// All symbols are marked as valid during error recovery.
// We can check for this by looking at the validity of the final
// (unused) external symbol, ERROR_SENTINEL.
const bool is_error_recovery = valid_symbols[ERROR_SENTINEL];
// TODO: actually function during error recovery
// https://github.com/tlaplus-community/tree-sitter-tlaplus/issues/19
if (is_error_recovery) {
return false;
}
if(valid_symbols[EXTRAMODULAR_TEXT]) {
return scan_extramodular_text(lexer);
} else if (valid_symbols[BLOCK_COMMENT_TEXT]) {
return scan_block_comment_text(lexer);
} else {
column_index col;
std::vector<char> proof_step_id_level;
switch (tokenize_lexeme(lex_lookahead(lexer, col, proof_step_id_level))) {
case Token_LAND:
return handle_junct_token(lexer, valid_symbols, JunctType_CONJUNCTION, col);
case Token_LOR:
return handle_junct_token(lexer, valid_symbols, JunctType_DISJUNCTION, col);
case Token_RIGHT_DELIMITER:
return handle_right_delimiter_token(lexer, valid_symbols);
case Token_COMMENT_START:
return false;
case Token_TERMINATOR:
return handle_terminator_token(lexer, valid_symbols);
case Token_PROOF_STEP_ID:
return handle_proof_step_id_token(lexer, valid_symbols, col, proof_step_id_level);
case Token_PROOF_KEYWORD:
return handle_proof_keyword_token(lexer, valid_symbols);
case Token_BY_KEYWORD:
return handle_terminal_proof_keyword_token(lexer, valid_symbols, BY_KEYWORD);
case Token_OBVIOUS_KEYWORD:
return handle_terminal_proof_keyword_token(lexer, valid_symbols, OBVIOUS_KEYWORD);
case Token_OMITTED_KEYWORD:
return handle_terminal_proof_keyword_token(lexer, valid_symbols, OMITTED_KEYWORD);
case Token_QED_KEYWORD:
return handle_qed_keyword_token(lexer, valid_symbols);
case Token_OTHER:
return handle_other_token(lexer, valid_symbols, col);
default:
return false;
}
}
}
};
}
extern "C" {
// Called once when language is set on a parser.
// Allocates memory for storing scanner state.
void* tree_sitter_tlaplus_external_scanner_create() {
return new Scanner();
}
// Called once parser is deleted or different language set.
// Frees memory storing scanner state.
void tree_sitter_tlaplus_external_scanner_destroy(void* const payload) {
Scanner* const scanner = static_cast<Scanner*>(payload);
delete scanner;
}
// Called whenever this scanner recognizes a token.
// Serializes scanner state into buffer.
unsigned tree_sitter_tlaplus_external_scanner_serialize(
void* const payload,
char* const buffer
) {
Scanner* scanner = static_cast<Scanner*>(payload);
return scanner->serialize(buffer);
}
// Called when handling edits and ambiguities.
// Deserializes scanner state from buffer.
void tree_sitter_tlaplus_external_scanner_deserialize(
void* const payload,
const char* const buffer,
unsigned const length
) {
Scanner* const scanner = static_cast<Scanner*>(payload);
scanner->deserialize(buffer, length);
}
// Scans for tokens.
bool tree_sitter_tlaplus_external_scanner_scan(
void* const payload,
TSLexer* const lexer,
const bool* const valid_symbols
) {
Scanner* const scanner = static_cast<Scanner*>(payload);
return scanner->scan(lexer, valid_symbols);
}
}
| 36.600469 | 115 | 0.64699 | [
"object",
"vector"
] |
e467d9d961353140c21c19fd817c45f4f6cf3258 | 3,174 | cpp | C++ | UVa/UVa12171.cpp | Insouciant21/solution | 8f241ec2076c9c29c0d39c2c285ee12eac1dee9e | [
"Apache-2.0"
] | 1 | 2020-09-11T13:17:28.000Z | 2020-09-11T13:17:28.000Z | UVa/UVa12171.cpp | Insouciant21/solution | 8f241ec2076c9c29c0d39c2c285ee12eac1dee9e | [
"Apache-2.0"
] | 1 | 2020-10-22T13:36:23.000Z | 2020-10-22T13:36:23.000Z | UVa/UVa12171.cpp | Insouciant21/solution | 8f241ec2076c9c29c0d39c2c285ee12eac1dee9e | [
"Apache-2.0"
] | 1 | 2020-10-22T13:33:11.000Z | 2020-10-22T13:33:11.000Z | #include <bits/stdc++.h>
using namespace std;
const int maxn = 110;
int vis[maxn][maxn][maxn];
long long v = 0;
long long s = 0;
int dx[] = {0, 0, -1, 1, 0, 0};
int dy[] = {1, -1, 0, 0, 0, 0};
int dz[] = {0, 0, 0, 0, 1, -1};
vector<int> x, y, z;
struct Sculpture {
int x, y, z;
int x0, y0, z0;
};
vector<Sculpture> g;
struct Point {
int x, y, z;
void move(int i) { x += dx[i], y += dy[i], z += dz[i]; }
};
inline int calcVolume(Point f) {
return (x[f.x + 1] - x[f.x]) * (y[f.y + 1] - y[f.y]) * (z[f.z + 1] - z[f.z]);
}
inline int calcArea(Point f, int d) {
return (!dx[d] ? x[f.x + 1] - x[f.x] : 1) * (!dy[d] ? y[f.y + 1] - y[f.y] : 1) * (!dz[d] ? z[f.z + 1] - z[f.z] : 1);
}
void bfs() {
vis[0][0][0] = 2;
queue<Point> q;
q.push({0, 0, 0});
while (!q.empty()) {
Point prs = q.front();
q.pop();
v += calcVolume(prs);
for (int i = 0; i < 6; i++) {
Point ftr = prs;
ftr.move(i);
if (ftr.x < 0 || ftr.y < 0 || ftr.z < 0 || ftr.x >= x.size() - 1 || ftr.y >= y.size() - 1 ||
ftr.z >= z.size() - 1)
continue;
if (vis[ftr.x][ftr.y][ftr.z] == 1) {
s += calcArea(prs, i);
continue;
}
if (vis[ftr.x][ftr.y][ftr.z] == 2) continue;
vis[ftr.x][ftr.y][ftr.z] = 2;
q.push(ftr);
}
}
v = 1001 * 1001 * 1001 - v;
}
int main() {
int T;
cin >> T;
while (T--) {
memset(vis, 0, sizeof vis);
x.clear(), y.clear(), z.clear(), g.clear();
s = v = 0;
int n;
cin >> n;
x.push_back(0), y.push_back(0), z.push_back(0);
for (int i = 0; i < n; i++) {
Sculpture t {};
cin >> t.x >> t.y >> t.z;
cin >> t.x0 >> t.y0 >> t.z0;
t.x0 += t.x, t.y0 += t.y, t.z0 += t.z;
x.push_back(t.x), x.push_back(t.x0);
y.push_back(t.y), y.push_back(t.y0);
z.push_back(t.z), z.push_back(t.z0);
g.push_back(t);
}
x.push_back(1001), y.push_back(1001), z.push_back(1001);
sort(x.begin(), x.end()), sort(y.begin(), y.end()), sort(z.begin(), z.end());
x.erase(unique(x.begin(), x.end()), x.end());
y.erase(unique(y.begin(), y.end()), y.end());
z.erase(unique(z.begin(), z.end()), z.end());
for (auto item : g) {
Sculpture t {};
t.x = int(lower_bound(x.begin(), x.end(), item.x) - x.begin());
t.x0 = int(lower_bound(x.begin(), x.end(), item.x0) - x.begin());
t.y = int(lower_bound(y.begin(), y.end(), item.y) - y.begin());
t.y0 = int(lower_bound(y.begin(), y.end(), item.y0) - y.begin());
t.z = int(lower_bound(z.begin(), z.end(), item.z) - z.begin());
t.z0 = int(lower_bound(z.begin(), z.end(), item.z0) - z.begin());
for (int i = t.x; i < t.x0; i++)
for (int j = t.y; j < t.y0; j++)
for (int k = t.z; k < t.z0; k++) vis[i][j][k] = 1;
}
bfs();
cout << s << " " << v << endl;
}
return 0;
}
| 30.228571 | 120 | 0.41966 | [
"vector"
] |
e476e1f6cea55b2b9cc43c30365cd31900aa5401 | 21,438 | cc | C++ | src/mesh/mesh_mstk/test/test_extract_surface.cc | cannsudemir/amanzi | c6cd3287bdc2c6cf26c6f8b79e34799751385f9e | [
"RSA-MD"
] | 1 | 2021-02-23T18:34:47.000Z | 2021-02-23T18:34:47.000Z | src/mesh/mesh_mstk/test/test_extract_surface.cc | cannsudemir/amanzi | c6cd3287bdc2c6cf26c6f8b79e34799751385f9e | [
"RSA-MD"
] | null | null | null | src/mesh/mesh_mstk/test/test_extract_surface.cc | cannsudemir/amanzi | c6cd3287bdc2c6cf26c6f8b79e34799751385f9e | [
"RSA-MD"
] | null | null | null | #include <UnitTest++.h>
#include <fstream>
#include "../Mesh_MSTK.hh"
#include "Epetra_Map.h"
#include "AmanziComm.hh"
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_XMLParameterListHelpers.hpp"
#include "Teuchos_Array.hpp"
#include "mpi.h"
// startup function
// Extract some surfaces as-is from 3D mesh, generated mesh.
TEST(Extract_Surface_MSTK1)
{
auto comm = Amanzi::getDefaultComm();
Teuchos::ParameterList parameterlist;
// create a sublist name Regions and put a reference to it in
// reg_spec and other sublists as references. Turns out it is
// important to define reg_spec and other lists below as references
// - otherwise, a new copy is made of the sublist that is retrieved
Teuchos::ParameterList& reg_spec = parameterlist.sublist("regions");
Teuchos::ParameterList& top_surface = reg_spec.sublist("Top Surface");
Teuchos::ParameterList& top_surface_def = top_surface.sublist("region: plane");
Teuchos::Array<double> loc1 = Teuchos::tuple(0.0,0.0,1.0);
Teuchos::Array<double> dir1 = Teuchos::tuple(0.0,0.0,-1.0);
top_surface_def.set< Teuchos::Array<double> >("point",loc1);
top_surface_def.set< Teuchos::Array<double> >("normal",dir1);
Teuchos::ParameterList& right_surface = reg_spec.sublist("Right Surface");
Teuchos::ParameterList& right_surface_def = right_surface.sublist("region: plane");
Teuchos::Array<double> loc2 = Teuchos::tuple(1.0,0.0,0.0);
Teuchos::Array<double> dir2 = Teuchos::tuple(1.0,0.0,0.0);
right_surface_def.set< Teuchos::Array<double> >("point",loc2);
right_surface_def.set< Teuchos::Array<double> >("normal",dir2);
// Teuchos::writeParameterListToXmlOStream(parameterlist,std::cout);
Teuchos::RCP<Amanzi::AmanziGeometry::GeometricModel> gm =
Teuchos::rcp(new Amanzi::AmanziGeometry::GeometricModel(3, reg_spec, *comm));
// Generate a mesh consisting of 3x3x3 elements
auto mesh = Teuchos::rcp(new Amanzi::AmanziMesh::Mesh_MSTK(0,0,0,1,1,1,3,3,3,comm,gm));
std::vector<std::string> setnames;
setnames.push_back(std::string("Top Surface"));
setnames.push_back(std::string("Right Surface"));
Amanzi::AmanziMesh::Entity_ID_List ids1, ids2;
mesh->get_set_entities(setnames[0], Amanzi::AmanziMesh::FACE, Amanzi::AmanziMesh::Parallel_type::OWNED, &ids1);
mesh->get_set_entities(setnames[1], Amanzi::AmanziMesh::FACE, Amanzi::AmanziMesh::Parallel_type::OWNED, &ids2);
ids1.insert(ids1.end(), ids2.begin(), ids2.end());
Amanzi::AmanziMesh::Mesh_MSTK surfmesh(mesh,ids1,Amanzi::AmanziMesh::FACE, false, mesh->get_comm());
// Number of cells (quadrilaterals) in surface mesh
int ncells_surf = surfmesh.get_set_size(setnames[0],Amanzi::AmanziMesh::CELL,Amanzi::AmanziMesh::Parallel_type::OWNED);
ncells_surf += surfmesh.get_set_size(setnames[1],Amanzi::AmanziMesh::CELL,Amanzi::AmanziMesh::Parallel_type::OWNED);
// int ncells_surf = surfmesh.num_entities(Amanzi::AmanziMesh::CELL,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(18,ncells_surf);
// Number of "faces" (edges) in surface mesh
int nfaces_surf = surfmesh.num_entities(Amanzi::AmanziMesh::FACE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(45,nfaces_surf);
// Number of nodes in surface mesh
int nnodes_surf = surfmesh.num_entities(Amanzi::AmanziMesh::NODE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(28,nnodes_surf);
int exp_parent_faces[18] = {27,28,29,30,31,32,33,34,35,99,100,101,102,103,104,105,106,107};
int *found = new int[ncells_surf];
for (int k = 0; k < ncells_surf; k++) {
Amanzi::AmanziMesh::Entity_ID parent = surfmesh.entity_get_parent(Amanzi::AmanziMesh::CELL,k);
found[k] = 0;
for (int kk = 0; kk < ncells_surf; kk++) {
if (exp_parent_faces[kk] == parent) {
Amanzi::AmanziGeometry::Point centroid1 = mesh->face_centroid(parent);
Amanzi::AmanziGeometry::Point centroid2 = surfmesh.cell_centroid(k);
CHECK_ARRAY_EQUAL(centroid1,centroid2,3);
found[k]++;
}
}
}
for (int k = 0; k < ncells_surf; k++)
CHECK_EQUAL(1,found[k]);
delete [] found;
}
// Extract a surface of a 3D mesh and flatten it to 2D to make new mesh
TEST(Extract_Surface_MSTK2)
{
auto comm = Amanzi::getDefaultComm();
Teuchos::ParameterList parameterlist;
// create a sublist name Regions and put a reference to it in
// reg_spec and other sublists as references. Turns out it is
// important to define reg_spec and other lists below as references
// - otherwise, a new copy is made of the sublist that is retrieved
Teuchos::ParameterList& reg_spec = parameterlist.sublist("regions");
Teuchos::ParameterList& top_surface = reg_spec.sublist("Top Surface");
Teuchos::ParameterList& top_surface_def = top_surface.sublist("region: plane");
Teuchos::Array<double> loc1 = Teuchos::tuple(0.0,0.0,1.0);
Teuchos::Array<double> dir1 = Teuchos::tuple(-1/sqrt(2.0),0.0,1/sqrt(2.0));
top_surface_def.set< Teuchos::Array<double> >("point",loc1);
top_surface_def.set< Teuchos::Array<double> >("normal",dir1);
// Teuchos::writeParameterListToXmlOStream(parameterlist,std::cout);
Teuchos::RCP<Amanzi::AmanziGeometry::GeometricModel> gm =
Teuchos::rcp(new Amanzi::AmanziGeometry::GeometricModel(3, reg_spec, *comm));
// Generate a mesh consisting of 3x3x3 elements
auto mesh = Teuchos::rcp(new Amanzi::AmanziMesh::Mesh_MSTK(0.0,0.0,0.0,1.0,1.0,1.0,4,4,4,comm,gm));
// Perturb some nodes
int nv = mesh->num_entities(Amanzi::AmanziMesh::NODE,Amanzi::AmanziMesh::Parallel_type::OWNED);
for (int i = 0; i < nv; i++) {
Amanzi::AmanziGeometry::Point pt;
mesh->node_get_coordinates(i,&pt);
if (pt[2] == 1.0) {
pt[2] = pt[2]+pt[0];
mesh->node_set_coordinates(i,pt);
}
}
// get a list of the top surface
std::vector<std::string> setnames;
setnames.push_back(std::string("Top Surface"));
Amanzi::AmanziMesh::Entity_ID_List ids1;
mesh->get_set_entities(setnames[0], Amanzi::AmanziMesh::FACE, Amanzi::AmanziMesh::Parallel_type::OWNED, &ids1);
// Extract surface mesh while projecting to 2D
Amanzi::AmanziMesh::Mesh_MSTK surfmesh(mesh,ids1,Amanzi::AmanziMesh::FACE,true,mesh->get_comm());
CHECK_EQUAL(surfmesh.space_dimension(),2);
// Number of cells (quadrilaterals) in surface mesh
int ncells_surf = surfmesh.num_entities(Amanzi::AmanziMesh::CELL,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(16,ncells_surf);
// Number of "faces" (edges) in surface mesh
int nfaces_surf = surfmesh.num_entities(Amanzi::AmanziMesh::FACE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(40,nfaces_surf);
// Number of nodes in surface mesh
int nnodes_surf = surfmesh.num_entities(Amanzi::AmanziMesh::NODE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(25,nnodes_surf);
// parent entities
int exp_parent_faces[16] = {224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239};
int *found = new int[ncells_surf];
for (int k = 0; k < ncells_surf; k++) {
Amanzi::AmanziMesh::Entity_ID parent = surfmesh.entity_get_parent(Amanzi::AmanziMesh::CELL,k);
found[k] = 0;
for (int kk = 0; kk < ncells_surf; kk++) {
if (exp_parent_faces[kk] == parent) {
Amanzi::AmanziGeometry::Point centroid1 = mesh->face_centroid(parent);
Amanzi::AmanziGeometry::Point centroid2 = surfmesh.cell_centroid(k);
CHECK_EQUAL(2,centroid2.dim());
CHECK_CLOSE(centroid1[0],centroid1[0],1.0e-10);
CHECK_CLOSE(centroid1[1],centroid1[1],1.0e-10);
found[k]++;
}
}
}
for (int k = 0; k < ncells_surf; k++)
CHECK_EQUAL(1,found[k]);
delete [] found;
}
// Doing these as a test suite to really see what breaks. Failures all throw unfortunately.
SUITE(Extract_Surface_MSTK_Sets) {
struct test_fixture {
test_fixture() {
std::string filename("test/hex_3x3x3_sets.exo");
comm = Amanzi::getDefaultComm();
Teuchos::ParameterList parameterlist;
// create a sublist name Regions and put a reference to it in
// reg_spec and other sublists as references. Turns out it is
// important to define reg_spec and other lists below as references
// - otherwise, a new copy is made of the sublist that is retrieved
Teuchos::ParameterList& reg_spec = parameterlist.sublist("regions");
Teuchos::ParameterList& top_surface = reg_spec.sublist("Top Surface");
Teuchos::ParameterList& top_surface_def = top_surface.sublist("region: labeled set");
top_surface_def.set<std::string>("label","106");
top_surface_def.set<std::string>("file",filename.c_str());
top_surface_def.set<std::string>("format","Exodus II");
top_surface_def.set<std::string>("entity","face");
Teuchos::ParameterList& side_surface = reg_spec.sublist("Side Surface");
Teuchos::ParameterList& side_surface_def = side_surface.sublist("region: labeled set");
side_surface_def.set<std::string>("label","102");
side_surface_def.set<std::string>("file",filename.c_str());
side_surface_def.set<std::string>("format","Exodus II");
side_surface_def.set<std::string>("entity","face");
Teuchos::ParameterList& r1_surface = reg_spec.sublist("Region 1");
Teuchos::ParameterList& r1_surface_def = r1_surface.sublist("region: labeled set");
r1_surface_def.set<std::string>("label","30000");
r1_surface_def.set<std::string>("file",filename.c_str());
r1_surface_def.set<std::string>("format","Exodus II");
r1_surface_def.set<std::string>("entity","cell");
Teuchos::ParameterList& r2_surface = reg_spec.sublist("Region 2");
Teuchos::ParameterList& r2_surface_def = r2_surface.sublist("region: labeled set");
r2_surface_def.set<std::string>("label","20000");
r2_surface_def.set<std::string>("file",filename.c_str());
r2_surface_def.set<std::string>("format","Exodus II");
r2_surface_def.set<std::string>("entity","cell");
gm = Teuchos::rcp(new Amanzi::AmanziGeometry::GeometricModel(3, reg_spec, *comm));
mesh = Teuchos::rcp(new Amanzi::AmanziMesh::Mesh_MSTK(filename.c_str(), comm, gm));
}
Teuchos::RCP<Amanzi::AmanziMesh::Mesh> extract(bool flatten) {
// get the surface set
std::vector<std::string> setnames;
setnames.push_back(std::string("Top Surface"));
Amanzi::AmanziMesh::Entity_ID_List ids1;
mesh->get_set_entities(setnames[0], Amanzi::AmanziMesh::FACE, Amanzi::AmanziMesh::Parallel_type::OWNED, &ids1);
// extract a surface mesh from the 3D mesh using the set
surfmesh = Teuchos::rcp(new Amanzi::AmanziMesh::Mesh_MSTK(mesh,ids1,Amanzi::AmanziMesh::FACE, flatten, mesh->get_comm()));
return surfmesh;
}
Amanzi::Comm_ptr_type comm;
Teuchos::RCP<Amanzi::AmanziGeometry::GeometricModel> gm;
Teuchos::RCP<Amanzi::AmanziMesh::Mesh> mesh;
Teuchos::RCP<Amanzi::AmanziMesh::Mesh> surfmesh;
};
// Check the basic extraction geometry, topology.
TEST_FIXTURE(test_fixture, Extract_Surface_MSTK3_BASIC_EXTRACTION) {
extract(false);
// Number of cells (quadrilaterals) in surface mesh
int ncells_surf = surfmesh->num_entities(Amanzi::AmanziMesh::CELL,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(9,ncells_surf);
// Number of "faces" (edges) in surface mesh
int nfaces_surf = surfmesh->num_entities(Amanzi::AmanziMesh::FACE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(24,nfaces_surf);
// Number of nodes in surface mesh
int nnodes_surf = surfmesh->num_entities(Amanzi::AmanziMesh::NODE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(16,nnodes_surf);
// parent ids are the GIDs of the parent mesh's corresponding entities
int exp_parent_faces[9] = {79,83,91,87,94,101,97,104,107};
int *found = new int[ncells_surf];
for (int k = 0; k < ncells_surf; k++) {
Amanzi::AmanziMesh::Entity_ID parent = surfmesh->entity_get_parent(Amanzi::AmanziMesh::CELL,k);
found[k] = 0;
for (int kk = 0; kk < ncells_surf; kk++) {
if (exp_parent_faces[kk] == parent) {
Amanzi::AmanziGeometry::Point centroid1 = mesh->face_centroid(parent);
Amanzi::AmanziGeometry::Point centroid2 = surfmesh->cell_centroid(k);
CHECK_ARRAY_EQUAL(centroid1,centroid2,3);
found[k]++;
}
}
}
for (int k = 0; k < ncells_surf; k++)
CHECK_EQUAL(1,found[k]);
delete [] found;
}
TEST_FIXTURE(test_fixture, Extract_Surface_MSTK3_SIDE_FACES) {
extract(false);
// Test if the labeled set was inherited correctly and if we get the
// right entities for this set
//
bool is_valid = surfmesh->valid_set_name("Side Surface", Amanzi::AmanziMesh::FACE);
CHECK(is_valid);
Amanzi::AmanziMesh::Entity_ID_List setents;
// In this case, a face set in the parent becomes a face set in the surface
surfmesh->get_set_entities("Side Surface",Amanzi::AmanziMesh::FACE,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(3, setents.size());
}
TEST_FIXTURE(test_fixture, Extract_Surface_MSTK3_SIDE_FACES_NO_CELLS) {
extract(false);
// The side surface does not intersect with the top surface, so there are no
// cells. This is either valid, and get_set_entities() does not throw but
// returns an empty list, or is not valid.
bool is_valid = surfmesh->valid_set_name("Side Surface", Amanzi::AmanziMesh::CELL);
if (is_valid) {
Amanzi::AmanziMesh::Entity_ID_List setents;
surfmesh->get_set_entities("Side Surface",Amanzi::AmanziMesh::CELL,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(0, setents.size());
}
}
TEST_FIXTURE(test_fixture, Extract_Surface_MSTK3_TOP_FACES) {
extract(false);
// In this case, a face set in the parent becomes a cell set in the surface
bool is_valid = surfmesh->valid_set_name("Top Surface", Amanzi::AmanziMesh::CELL);
CHECK(is_valid);
Amanzi::AmanziMesh::Entity_ID_List setents;
surfmesh->get_set_entities("Top Surface",Amanzi::AmanziMesh::CELL,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(9, setents.size());
}
TEST_FIXTURE(test_fixture, Extract_Surface_MSTK3_TOP_FACES_NO_FACES) {
extract(false);
// In this case, a face set in the parent becomes a face set in the surface
//
// The top surface is only cells, so there are no faces. This is either
// valid, and get_set_entities() does not throw but returns an empty list, or
// is not valid.
bool is_valid = surfmesh->valid_set_name("Side Surface", Amanzi::AmanziMesh::FACE);
if (is_valid) {
Amanzi::AmanziMesh::Entity_ID_List setents;
surfmesh->get_set_entities("Top Surface",Amanzi::AmanziMesh::FACE,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(0, setents.size());
}
}
TEST_FIXTURE(test_fixture, Extract_Surface_MSTK3_TOP_CELLS) {
extract(false);
// In this case, a cell set in the parent becomes a cell set in the surface
bool is_valid = surfmesh->valid_set_name("Region 1", Amanzi::AmanziMesh::CELL);
CHECK(is_valid);
Amanzi::AmanziMesh::Entity_ID_List setents;
surfmesh->get_set_entities("Region 1",Amanzi::AmanziMesh::CELL,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(9, setents.size());
}
TEST_FIXTURE(test_fixture, Extract_Surface_MSTK3_BOTTOM_CELLS) {
extract(false);
// In this case, a cell set in the parent becomes a cell set in the surface,
// but there is no intersection. This is either valid, but doesn't throw and
// returns an empty set, or is not valid. Either is OK?
bool is_valid = surfmesh->valid_set_name("Region 2", Amanzi::AmanziMesh::CELL);
if (is_valid) {
Amanzi::AmanziMesh::Entity_ID_List setents;
surfmesh->get_set_entities("Region 2",Amanzi::AmanziMesh::CELL,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(0, setents.size());
}
}
// Check the basic extraction geometry, topology.
TEST_FIXTURE(test_fixture, Extract_Flatten_Surface_MSTK3_BASIC_EXTRACTION) {
extract(true);
// Number of cells (quadrilaterals) in surface mesh
int ncells_surf = surfmesh->num_entities(Amanzi::AmanziMesh::CELL,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(9,ncells_surf);
// Number of "faces" (edges) in surface mesh
int nfaces_surf = surfmesh->num_entities(Amanzi::AmanziMesh::FACE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(24,nfaces_surf);
// Number of nodes in surface mesh
int nnodes_surf = surfmesh->num_entities(Amanzi::AmanziMesh::NODE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(16,nnodes_surf);
// parent ids are the GIDs of the parent mesh's corresponding entities
int exp_parent_faces[9] = {79,83,91,87,94,101,97,104,107};
int *found = new int[ncells_surf];
for (int k = 0; k < ncells_surf; k++) {
Amanzi::AmanziMesh::Entity_ID parent = surfmesh->entity_get_parent(Amanzi::AmanziMesh::CELL,k);
found[k] = 0;
for (int kk = 0; kk < ncells_surf; kk++) {
if (exp_parent_faces[kk] == parent) {
Amanzi::AmanziGeometry::Point centroid1 = mesh->face_centroid(parent);
Amanzi::AmanziGeometry::Point centroid2 = surfmesh->cell_centroid(k);
CHECK_ARRAY_EQUAL(centroid1,centroid2,2);
found[k]++;
}
}
}
for (int k = 0; k < ncells_surf; k++)
CHECK_EQUAL(1,found[k]);
delete [] found;
}
TEST_FIXTURE(test_fixture, Extract_Flatten_Surface_MSTK3_SIDE_FACES) {
extract(true);
// Test if the labeled set was inherited correctly and if we get the
// right entities for this set
//
bool is_valid = surfmesh->valid_set_name("Side Surface", Amanzi::AmanziMesh::FACE);
CHECK(is_valid);
Amanzi::AmanziMesh::Entity_ID_List setents;
// In this case, a face set in the parent becomes a face set in the surface
surfmesh->get_set_entities("Side Surface",Amanzi::AmanziMesh::FACE,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(3, setents.size());
}
TEST_FIXTURE(test_fixture, Extract_Flatten_Surface_MSTK3_SIDE_FACES_NO_CELLS) {
extract(true);
// The side surface does not intersect with the top surface, so there are no
// cells. This is either valid, and get_set_entities() does not throw but
// returns an empty list, or is not valid.
bool is_valid = surfmesh->valid_set_name("Side Surface", Amanzi::AmanziMesh::CELL);
if (is_valid) {
Amanzi::AmanziMesh::Entity_ID_List setents;
surfmesh->get_set_entities("Side Surface",Amanzi::AmanziMesh::CELL,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(0, setents.size());
}
}
TEST_FIXTURE(test_fixture, Extract_Flatten_Surface_MSTK3_TOP_FACES) {
extract(true);
// In this case, a face set in the parent becomes a cell set in the surface
bool is_valid = surfmesh->valid_set_name("Top Surface", Amanzi::AmanziMesh::CELL);
CHECK(is_valid);
Amanzi::AmanziMesh::Entity_ID_List setents;
surfmesh->get_set_entities("Top Surface",Amanzi::AmanziMesh::CELL,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(9, setents.size());
}
TEST_FIXTURE(test_fixture, Extract_Flatten_Surface_MSTK3_TOP_FACES_NO_FACES) {
extract(true);
// In this case, a face set in the parent becomes a face set in the surface
//
// The top surface is only cells, so there are no faces. This is either
// valid, and get_set_entities() does not throw but returns an empty list, or
// is not valid.
bool is_valid = surfmesh->valid_set_name("Side Surface", Amanzi::AmanziMesh::FACE);
if (is_valid) {
Amanzi::AmanziMesh::Entity_ID_List setents;
surfmesh->get_set_entities("Top Surface",Amanzi::AmanziMesh::FACE,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(0, setents.size());
}
}
TEST_FIXTURE(test_fixture, Extract_Flatten_Surface_MSTK3_TOP_CELLS) {
extract(true);
// In this case, a cell set in the parent becomes a cell set in the surface
bool is_valid = surfmesh->valid_set_name("Region 1", Amanzi::AmanziMesh::CELL);
CHECK(is_valid);
Amanzi::AmanziMesh::Entity_ID_List setents;
surfmesh->get_set_entities("Region 1",Amanzi::AmanziMesh::CELL,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(9, setents.size());
}
TEST_FIXTURE(test_fixture, Extract_Flatten_Surface_MSTK3_BOTTOM_CELLS) {
extract(true);
// In this case, a cell set in the parent becomes a cell set in the surface,
// but there is no intersection. This is either valid, but doesn't throw and
// returns an empty set, or is not valid. Either is OK?
bool is_valid = surfmesh->valid_set_name("Region 2", Amanzi::AmanziMesh::CELL);
if (is_valid) {
Amanzi::AmanziMesh::Entity_ID_List setents;
surfmesh->get_set_entities("Region 2",Amanzi::AmanziMesh::CELL,
Amanzi::AmanziMesh::Parallel_type::OWNED,&setents);
CHECK_EQUAL(0, setents.size());
}
}
TEST_FIXTURE(test_fixture, Extract_Flatten_Surface_MSTK3_BAD_NAME) {
extract(false);
// In this case, a cell set in the parent becomes a cell set in the surface,
// but there is no intersection. This is either valid, but doesn't throw and
// returns an empty set, or is not valid. Either is OK?
bool is_valid = surfmesh->valid_set_name("Region Not Here", Amanzi::AmanziMesh::CELL);
CHECK(!is_valid);
is_valid = surfmesh->valid_set_name("Region Not Here", Amanzi::AmanziMesh::FACE);
CHECK(!is_valid);
}
}
| 40.99044 | 126 | 0.709768 | [
"mesh",
"geometry",
"vector",
"3d"
] |
e480581f9edcd03dab6c0f95845ce7f6d498d614 | 1,452 | cpp | C++ | Application/catchVector.cpp | StijnvanWijk98/Ipass | 39ec24ddbf3659b0fd46803f24b7b4c91f3439a7 | [
"BSL-1.0"
] | null | null | null | Application/catchVector.cpp | StijnvanWijk98/Ipass | 39ec24ddbf3659b0fd46803f24b7b4c91f3439a7 | [
"BSL-1.0"
] | null | null | null | Application/catchVector.cpp | StijnvanWijk98/Ipass | 39ec24ddbf3659b0fd46803f24b7b4c91f3439a7 | [
"BSL-1.0"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "particle.hpp"
TEST_CASE("constructor, basic") {
vector v{1.1, 2.2};
std::stringstream s;
s << v;
REQUIRE(s.str() == "(1.1,2.2)");
}
TEST_CASE("equality, equal") {
vector v{1.8, 5.2};
REQUIRE(v == vector{1.8, 5.2});
}
TEST_CASE("equality, unequal") {
vector v{2.2, 3.0};
REQUIRE(!(v == vector{1.8, 3.9}));
}
TEST_CASE("add with vector") {
vector v{4.5, 3.0};
vector x = v + vector{2.0, 2.5};
REQUIRE(v == vector{4.5, 3.0});
REQUIRE(x == vector{6.5, 5.5});
}
TEST_CASE("multiply by vector") {
vector v{2.5, 3.0};
vector x = v * vector{2.0, 3.5};
REQUIRE(v == vector{2.5, 3.0});
REQUIRE(x == vector{5.0, 10.5});
}
TEST_CASE("multiply by float") {
vector v{2.5, 3.0};
vector x = v * 2.5;
REQUIRE(v == vector{2.5, 3.0});
REQUIRE(x == vector{6.25, 7.5});
}
TEST_CASE("multiply by integer into vector") {
vector v{2.5, 3.0};
vector x = v * 2;
REQUIRE(v == vector{2.5, 3.0});
REQUIRE(x == vector{5.0, 6.0});
}
TEST_CASE("multiply float with vector") {
vector v{2.5, 3.0};
vector x = 2.5 * v;
REQUIRE(v == vector{2.5, 3.0});
REQUIRE(x == vector{6.25, 7.5});
}
TEST_CASE("Magnitude") {
vector v{3.0, 4.0};
float x = v.magnitude();
REQUIRE(v == vector{3.0, 4.0});
REQUIRE(x == 5.0);
}
TEST_CASE("Magnitude squared") {
vector v{2.5, 2.5};
float x = v.squaredMagnitude();
REQUIRE(v == vector{2.5, 2.5});
REQUIRE(x == 12.5);
} | 20.742857 | 46 | 0.573003 | [
"vector"
] |
6b01476128bc153c8b58d09dea386b22f6b561f4 | 734 | hpp | C++ | ios/Pods/boost-for-react-native/boost/geometry/multi/algorithms/remove_spikes.hpp | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 8,805 | 2015-11-03T00:52:29.000Z | 2022-03-29T22:30:03.000Z | ios/Pods/boost-for-react-native/boost/geometry/multi/algorithms/remove_spikes.hpp | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 14,694 | 2015-02-24T15:13:42.000Z | 2022-03-31T13:16:45.000Z | ios/Pods/boost-for-react-native/boost/geometry/multi/algorithms/remove_spikes.hpp | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 1,329 | 2015-11-03T20:25:51.000Z | 2022-03-31T18:10:38.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2013 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2013 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2013 Mateusz Loskot, London, UK.
// Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland.
// 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_MULTI_ALGORITHMS_REMOVE_SPIKES_HPP
#define BOOST_GEOMETRY_MULTI_ALGORITHMS_REMOVE_SPIKES_HPP
#include <boost/geometry/algorithms/remove_spikes.hpp>
#endif // BOOST_GEOMETRY_MULTI_ALGORITHMS_REMOVE_SPIKES_HPP
| 36.7 | 80 | 0.771117 | [
"geometry"
] |
6b020738b09eb385b96ac012962fb080d15312e9 | 12,947 | cpp | C++ | source/dawn/GenericModelDawn.cpp | gyagp/aquarium | 27c30da38df1a4df667c1696deaaa66d983ecf95 | [
"BSD-3-Clause"
] | null | null | null | source/dawn/GenericModelDawn.cpp | gyagp/aquarium | 27c30da38df1a4df667c1696deaaa66d983ecf95 | [
"BSD-3-Clause"
] | null | null | null | source/dawn/GenericModelDawn.cpp | gyagp/aquarium | 27c30da38df1a4df667c1696deaaa66d983ecf95 | [
"BSD-3-Clause"
] | null | null | null | //
// Copyright (c) 2019 The Aquarium Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "GenericModelDawn.h"
#include <vector>
#include "../Aquarium.h"
GenericModelDawn::GenericModelDawn(Context *context,
Aquarium *aquarium,
MODELGROUP type,
MODELNAME name,
bool blend)
: Model(type, name, blend), instance(0) {
mContextDawn = static_cast<ContextDawn *>(context);
mLightFactorUniforms.shininess = 50.0f;
mLightFactorUniforms.specularFactor = 1.0f;
}
GenericModelDawn::~GenericModelDawn() {
mPipeline = nullptr;
mGroupLayoutModel = nullptr;
mGroupLayoutPer = nullptr;
mPipelineLayout = nullptr;
mBindGroupModel = nullptr;
mBindGroupPer = nullptr;
mLightFactorBuffer = nullptr;
mWorldBuffer = nullptr;
}
void GenericModelDawn::init() {
mProgramDawn = static_cast<ProgramDawn *>(mProgram);
mDiffuseTexture = static_cast<TextureDawn *>(textureMap["diffuse"]);
mNormalTexture = static_cast<TextureDawn *>(textureMap["normalMap"]);
mReflectionTexture = static_cast<TextureDawn *>(textureMap["reflectionMap"]);
mSkyboxTexture = static_cast<TextureDawn *>(textureMap["skybox"]);
mPositionBuffer = static_cast<BufferDawn *>(bufferMap["position"]);
mNormalBuffer = static_cast<BufferDawn *>(bufferMap["normal"]);
mTexCoordBuffer = static_cast<BufferDawn *>(bufferMap["texCoord"]);
mTangentBuffer = static_cast<BufferDawn *>(bufferMap["tangent"]);
mBiNormalBuffer = static_cast<BufferDawn *>(bufferMap["binormal"]);
mIndicesBuffer = static_cast<BufferDawn *>(bufferMap["indices"]);
// Generic models use reflection, normal or diffuse shaders, of which
// groupLayouts are diiferent in texture binding. MODELGLOBEBASE use diffuse
// shader though it contains normal and reflection textures.
std::vector<wgpu::VertexAttributeDescriptor> vertexAttributeDescriptor;
if (mNormalTexture && mName != MODELNAME::MODELGLOBEBASE) {
vertexAttributeDescriptor.resize(5);
vertexAttributeDescriptor[0].format = wgpu::VertexFormat::Float3;
vertexAttributeDescriptor[0].offset = 0;
vertexAttributeDescriptor[0].shaderLocation = 0;
vertexAttributeDescriptor[1].format = wgpu::VertexFormat::Float3;
vertexAttributeDescriptor[1].offset = 0;
vertexAttributeDescriptor[1].shaderLocation = 1;
vertexAttributeDescriptor[2].format = wgpu::VertexFormat::Float2;
vertexAttributeDescriptor[2].offset = 0;
vertexAttributeDescriptor[2].shaderLocation = 2;
vertexAttributeDescriptor[3].format = wgpu::VertexFormat::Float3;
vertexAttributeDescriptor[3].offset = 0;
vertexAttributeDescriptor[3].shaderLocation = 3;
vertexAttributeDescriptor[4].format = wgpu::VertexFormat::Float3;
vertexAttributeDescriptor[4].offset = 0;
vertexAttributeDescriptor[4].shaderLocation = 4;
} else {
vertexAttributeDescriptor.resize(3);
vertexAttributeDescriptor[0].format = wgpu::VertexFormat::Float3;
vertexAttributeDescriptor[0].offset = 0;
vertexAttributeDescriptor[0].shaderLocation = 0;
vertexAttributeDescriptor[1].format = wgpu::VertexFormat::Float3;
vertexAttributeDescriptor[1].offset = 0;
vertexAttributeDescriptor[1].shaderLocation = 1;
vertexAttributeDescriptor[2].format = wgpu::VertexFormat::Float2;
vertexAttributeDescriptor[2].offset = 0;
vertexAttributeDescriptor[2].shaderLocation = 2;
}
// Generic models use reflection, normal or diffuse shaders, of which
// groupLayouts are diiferent in texture binding. MODELGLOBEBASE use diffuse
// shader though it contains normal and reflection textures.
std::vector<wgpu::VertexBufferLayoutDescriptor> vertexBufferLayoutDescriptor;
if (mNormalTexture && mName != MODELNAME::MODELGLOBEBASE) {
vertexBufferLayoutDescriptor.resize(5);
vertexBufferLayoutDescriptor[0].arrayStride =
mPositionBuffer->getDataSize();
vertexBufferLayoutDescriptor[0].stepMode = wgpu::InputStepMode::Vertex;
vertexBufferLayoutDescriptor[0].attributeCount = 1;
vertexBufferLayoutDescriptor[0].attributes = &vertexAttributeDescriptor[0];
vertexBufferLayoutDescriptor[1].arrayStride = mNormalBuffer->getDataSize();
vertexBufferLayoutDescriptor[1].stepMode = wgpu::InputStepMode::Vertex;
vertexBufferLayoutDescriptor[1].attributeCount = 1;
vertexBufferLayoutDescriptor[1].attributes = &vertexAttributeDescriptor[1];
vertexBufferLayoutDescriptor[2].arrayStride =
mTexCoordBuffer->getDataSize();
vertexBufferLayoutDescriptor[2].stepMode = wgpu::InputStepMode::Vertex;
vertexBufferLayoutDescriptor[2].attributeCount = 1;
vertexBufferLayoutDescriptor[2].attributes = &vertexAttributeDescriptor[2];
vertexBufferLayoutDescriptor[3].arrayStride = mTangentBuffer->getDataSize();
vertexBufferLayoutDescriptor[3].stepMode = wgpu::InputStepMode::Vertex;
vertexBufferLayoutDescriptor[3].attributeCount = 1;
vertexBufferLayoutDescriptor[3].attributes = &vertexAttributeDescriptor[3];
vertexBufferLayoutDescriptor[4].arrayStride =
mBiNormalBuffer->getDataSize();
vertexBufferLayoutDescriptor[4].stepMode = wgpu::InputStepMode::Vertex;
vertexBufferLayoutDescriptor[4].attributeCount = 1;
vertexBufferLayoutDescriptor[4].attributes = &vertexAttributeDescriptor[4];
} else {
vertexBufferLayoutDescriptor.resize(3);
vertexBufferLayoutDescriptor[0].arrayStride =
mPositionBuffer->getDataSize();
vertexBufferLayoutDescriptor[0].stepMode = wgpu::InputStepMode::Vertex;
vertexBufferLayoutDescriptor[0].attributeCount = 1;
vertexBufferLayoutDescriptor[0].attributes = &vertexAttributeDescriptor[0];
vertexBufferLayoutDescriptor[1].arrayStride = mNormalBuffer->getDataSize();
vertexBufferLayoutDescriptor[1].stepMode = wgpu::InputStepMode::Vertex;
vertexBufferLayoutDescriptor[1].attributeCount = 1;
vertexBufferLayoutDescriptor[1].attributes = &vertexAttributeDescriptor[1];
vertexBufferLayoutDescriptor[2].arrayStride =
mTexCoordBuffer->getDataSize();
vertexBufferLayoutDescriptor[2].stepMode = wgpu::InputStepMode::Vertex;
vertexBufferLayoutDescriptor[2].attributeCount = 1;
vertexBufferLayoutDescriptor[2].attributes = &vertexAttributeDescriptor[2];
}
mVertexStateDescriptor.vertexBufferCount =
static_cast<uint32_t>(vertexBufferLayoutDescriptor.size());
mVertexStateDescriptor.vertexBuffers = vertexBufferLayoutDescriptor.data();
mVertexStateDescriptor.indexFormat = wgpu::IndexFormat::Uint16;
if (mSkyboxTexture && mReflectionTexture &&
mName != MODELNAME::MODELGLOBEBASE) {
mGroupLayoutModel = mContextDawn->MakeBindGroupLayout({
{0, wgpu::ShaderStage::Fragment, wgpu::BindingType::UniformBuffer},
{1, wgpu::ShaderStage::Fragment, wgpu::BindingType::Sampler},
{2, wgpu::ShaderStage::Fragment, wgpu::BindingType::Sampler},
{3, wgpu::ShaderStage::Fragment, wgpu::BindingType::SampledTexture,
false, 0, false, wgpu::TextureViewDimension::e2D,
wgpu::TextureComponentType::Float},
{4, wgpu::ShaderStage::Fragment, wgpu::BindingType::SampledTexture,
false, 0, false, wgpu::TextureViewDimension::e2D,
wgpu::TextureComponentType::Float},
{5, wgpu::ShaderStage::Fragment, wgpu::BindingType::SampledTexture,
false, 0, false, wgpu::TextureViewDimension::e2D,
wgpu::TextureComponentType::Float},
{6, wgpu::ShaderStage::Fragment, wgpu::BindingType::SampledTexture,
false, 0, false, wgpu::TextureViewDimension::Cube,
wgpu::TextureComponentType::Float},
});
} else if (mNormalTexture && mName != MODELNAME::MODELGLOBEBASE) {
mGroupLayoutModel = mContextDawn->MakeBindGroupLayout({
{0, wgpu::ShaderStage::Fragment, wgpu::BindingType::UniformBuffer},
{1, wgpu::ShaderStage::Fragment, wgpu::BindingType::Sampler},
{2, wgpu::ShaderStage::Fragment, wgpu::BindingType::SampledTexture,
false, 0, false, wgpu::TextureViewDimension::e2D,
wgpu::TextureComponentType::Float},
{3, wgpu::ShaderStage::Fragment, wgpu::BindingType::SampledTexture,
false, 0, false, wgpu::TextureViewDimension::e2D,
wgpu::TextureComponentType::Float},
});
} else {
mGroupLayoutModel = mContextDawn->MakeBindGroupLayout({
{0, wgpu::ShaderStage::Fragment, wgpu::BindingType::UniformBuffer},
{1, wgpu::ShaderStage::Fragment, wgpu::BindingType::Sampler},
{2, wgpu::ShaderStage::Fragment, wgpu::BindingType::SampledTexture,
false, 0, false, wgpu::TextureViewDimension::e2D,
wgpu::TextureComponentType::Float},
});
}
mGroupLayoutPer = mContextDawn->MakeBindGroupLayout({
{0, wgpu::ShaderStage::Vertex, wgpu::BindingType::UniformBuffer},
});
mPipelineLayout = mContextDawn->MakeBasicPipelineLayout({
mContextDawn->groupLayoutGeneral,
mContextDawn->groupLayoutWorld,
mGroupLayoutModel,
mGroupLayoutPer,
});
mPipeline = mContextDawn->createRenderPipeline(
mPipelineLayout, mProgramDawn, mVertexStateDescriptor, mBlend);
mLightFactorBuffer = mContextDawn->createBufferFromData(
&mLightFactorUniforms, sizeof(mLightFactorUniforms),
sizeof(mLightFactorUniforms),
wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::Uniform);
mWorldBuffer = mContextDawn->createBufferFromData(
&mWorldUniformPer, sizeof(mWorldUniformPer), sizeof(mWorldUniformPer),
wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::Uniform);
// Generic models use reflection, normal or diffuse shaders, of which
// grouplayouts are diiferent in texture binding. MODELGLOBEBASE use diffuse
// shader though it contains normal and reflection textures.
if (mSkyboxTexture && mReflectionTexture &&
mName != MODELNAME::MODELGLOBEBASE) {
mBindGroupModel = mContextDawn->makeBindGroup(
mGroupLayoutModel,
{{0, mLightFactorBuffer, 0, sizeof(LightFactorUniforms), {}, {}},
{1, {}, 0, 0, mReflectionTexture->getSampler(), {}},
{2, {}, 0, 0, mSkyboxTexture->getSampler(), {}},
{3, {}, 0, 0, {}, mDiffuseTexture->getTextureView()},
{4, {}, 0, 0, {}, mNormalTexture->getTextureView()},
{5, {}, 0, 0, {}, mReflectionTexture->getTextureView()},
{6, {}, 0, 0, {}, mSkyboxTexture->getTextureView()}});
} else if (mNormalTexture && mName != MODELNAME::MODELGLOBEBASE) {
mBindGroupModel = mContextDawn->makeBindGroup(
mGroupLayoutModel,
{
{0, mLightFactorBuffer, 0, sizeof(LightFactorUniforms), {}, {}},
{1, {}, 0, 0, mDiffuseTexture->getSampler(), {}},
{2, {}, 0, 0, {}, mDiffuseTexture->getTextureView()},
{3, {}, 0, 0, {}, mNormalTexture->getTextureView()},
});
} else {
mBindGroupModel = mContextDawn->makeBindGroup(
mGroupLayoutModel,
{
{0, mLightFactorBuffer, 0, sizeof(LightFactorUniforms), {}, {}},
{1, {}, 0, 0, mDiffuseTexture->getSampler(), {}},
{2, {}, 0, 0, {}, mDiffuseTexture->getTextureView()},
});
}
mBindGroupPer = mContextDawn->makeBindGroup(
mGroupLayoutPer,
{
{0, mWorldBuffer, 0, sizeof(WorldUniformPer), {}, {}},
});
mContextDawn->setBufferData(mLightFactorBuffer, sizeof(LightFactorUniforms),
&mLightFactorUniforms,
sizeof(LightFactorUniforms));
}
void GenericModelDawn::prepareForDraw() {
mContextDawn->updateBufferData(mWorldBuffer, sizeof(WorldUniformPer),
&mWorldUniformPer, sizeof(WorldUniformPer));
}
void GenericModelDawn::draw() {
wgpu::RenderPassEncoder pass = mContextDawn->getRenderPass();
pass.SetPipeline(mPipeline);
pass.SetBindGroup(0, mContextDawn->bindGroupGeneral, 0, nullptr);
pass.SetBindGroup(1, mContextDawn->bindGroupWorld, 0, nullptr);
pass.SetBindGroup(2, mBindGroupModel, 0, nullptr);
pass.SetBindGroup(3, mBindGroupPer, 0, nullptr);
pass.SetVertexBuffer(0, mPositionBuffer->getBuffer());
pass.SetVertexBuffer(1, mNormalBuffer->getBuffer());
pass.SetVertexBuffer(2, mTexCoordBuffer->getBuffer());
// diffuseShader doesn't have to input tangent buffer or binormal buffer.
if (mTangentBuffer && mBiNormalBuffer && mName != MODELNAME::MODELGLOBEBASE) {
pass.SetVertexBuffer(3, mTangentBuffer->getBuffer());
pass.SetVertexBuffer(4, mBiNormalBuffer->getBuffer());
}
pass.SetIndexBuffer(mIndicesBuffer->getBuffer(), 0);
pass.DrawIndexed(mIndicesBuffer->getTotalComponents(), instance, 0, 0, 0);
instance = 0;
}
void GenericModelDawn::updatePerInstanceUniforms(
const WorldUniforms &worldUniforms) {
mWorldUniformPer.WorldUniforms[instance] = worldUniforms;
instance++;
}
| 47.251825 | 80 | 0.713215 | [
"vector",
"model"
] |
6b021acba891d945b41e86b86d3b2e5e0e6c230e | 7,343 | cc | C++ | selfdrive/ui/qt/offroad/moc_wifiManager.cc | leech2000/kona0813 | c3e73e220b86614b82959712668408a48c33ebd3 | [
"MIT"
] | 1 | 2022-03-23T13:52:40.000Z | 2022-03-23T13:52:40.000Z | selfdrive/ui/qt/offroad/moc_wifiManager.cc | leech2000/kona0813 | c3e73e220b86614b82959712668408a48c33ebd3 | [
"MIT"
] | null | null | null | selfdrive/ui/qt/offroad/moc_wifiManager.cc | leech2000/kona0813 | c3e73e220b86614b82959712668408a48c33ebd3 | [
"MIT"
] | 5 | 2022-03-24T16:18:47.000Z | 2022-03-30T02:18:49.000Z | /****************************************************************************
** Meta object code from reading C++ file 'wifiManager.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "wifiManager.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'wifiManager.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.12.8. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_WifiManager_t {
QByteArrayData data[22];
char stringdata0[276];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_WifiManager_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_WifiManager_t qt_meta_stringdata_WifiManager = {
{
QT_MOC_LITERAL(0, 0, 11), // "WifiManager"
QT_MOC_LITERAL(1, 12, 13), // "wrongPassword"
QT_MOC_LITERAL(2, 26, 0), // ""
QT_MOC_LITERAL(3, 27, 4), // "ssid"
QT_MOC_LITERAL(4, 32, 13), // "refreshSignal"
QT_MOC_LITERAL(5, 46, 11), // "stateChange"
QT_MOC_LITERAL(6, 58, 9), // "new_state"
QT_MOC_LITERAL(7, 68, 14), // "previous_state"
QT_MOC_LITERAL(8, 83, 13), // "change_reason"
QT_MOC_LITERAL(9, 97, 14), // "propertyChange"
QT_MOC_LITERAL(10, 112, 9), // "interface"
QT_MOC_LITERAL(11, 122, 5), // "props"
QT_MOC_LITERAL(12, 128, 17), // "invalidated_props"
QT_MOC_LITERAL(13, 146, 11), // "deviceAdded"
QT_MOC_LITERAL(14, 158, 15), // "QDBusObjectPath"
QT_MOC_LITERAL(15, 174, 4), // "path"
QT_MOC_LITERAL(16, 179, 17), // "connectionRemoved"
QT_MOC_LITERAL(17, 197, 13), // "newConnection"
QT_MOC_LITERAL(18, 211, 15), // "refreshFinished"
QT_MOC_LITERAL(19, 227, 24), // "QDBusPendingCallWatcher*"
QT_MOC_LITERAL(20, 252, 4), // "call"
QT_MOC_LITERAL(21, 257, 18) // "tetheringActivated"
},
"WifiManager\0wrongPassword\0\0ssid\0"
"refreshSignal\0stateChange\0new_state\0"
"previous_state\0change_reason\0"
"propertyChange\0interface\0props\0"
"invalidated_props\0deviceAdded\0"
"QDBusObjectPath\0path\0connectionRemoved\0"
"newConnection\0refreshFinished\0"
"QDBusPendingCallWatcher*\0call\0"
"tetheringActivated"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_WifiManager[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
9, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
2, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 59, 2, 0x06 /* Public */,
4, 0, 62, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
5, 3, 63, 2, 0x08 /* Private */,
9, 3, 70, 2, 0x08 /* Private */,
13, 1, 77, 2, 0x08 /* Private */,
16, 1, 80, 2, 0x08 /* Private */,
17, 1, 83, 2, 0x08 /* Private */,
18, 1, 86, 2, 0x08 /* Private */,
21, 1, 89, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, QMetaType::QString, 3,
QMetaType::Void,
// slots: parameters
QMetaType::Void, QMetaType::UInt, QMetaType::UInt, QMetaType::UInt, 6, 7, 8,
QMetaType::Void, QMetaType::QString, QMetaType::QVariantMap, QMetaType::QStringList, 10, 11, 12,
QMetaType::Void, 0x80000000 | 14, 15,
QMetaType::Void, 0x80000000 | 14, 15,
QMetaType::Void, 0x80000000 | 14, 15,
QMetaType::Void, 0x80000000 | 19, 20,
QMetaType::Void, 0x80000000 | 19, 20,
0 // eod
};
void WifiManager::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<WifiManager *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->wrongPassword((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 1: _t->refreshSignal(); break;
case 2: _t->stateChange((*reinterpret_cast< uint(*)>(_a[1])),(*reinterpret_cast< uint(*)>(_a[2])),(*reinterpret_cast< uint(*)>(_a[3]))); break;
case 3: _t->propertyChange((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QVariantMap(*)>(_a[2])),(*reinterpret_cast< const QStringList(*)>(_a[3]))); break;
case 4: _t->deviceAdded((*reinterpret_cast< const QDBusObjectPath(*)>(_a[1]))); break;
case 5: _t->connectionRemoved((*reinterpret_cast< const QDBusObjectPath(*)>(_a[1]))); break;
case 6: _t->newConnection((*reinterpret_cast< const QDBusObjectPath(*)>(_a[1]))); break;
case 7: _t->refreshFinished((*reinterpret_cast< QDBusPendingCallWatcher*(*)>(_a[1]))); break;
case 8: _t->tetheringActivated((*reinterpret_cast< QDBusPendingCallWatcher*(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (WifiManager::*)(const QString & );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&WifiManager::wrongPassword)) {
*result = 0;
return;
}
}
{
using _t = void (WifiManager::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&WifiManager::refreshSignal)) {
*result = 1;
return;
}
}
}
}
QT_INIT_METAOBJECT const QMetaObject WifiManager::staticMetaObject = { {
&QObject::staticMetaObject,
qt_meta_stringdata_WifiManager.data,
qt_meta_data_WifiManager,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *WifiManager::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *WifiManager::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_WifiManager.stringdata0))
return static_cast<void*>(this);
return QObject::qt_metacast(_clname);
}
int WifiManager::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 9)
qt_static_metacall(this, _c, _id, _a);
_id -= 9;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 9)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 9;
}
return _id;
}
// SIGNAL 0
void WifiManager::wrongPassword(const QString & _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void WifiManager::refreshSignal()
{
QMetaObject::activate(this, &staticMetaObject, 1, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 36.351485 | 189 | 0.618821 | [
"object"
] |
6b054fbdf4ccdc26dad83731ae8a175d85281dfc | 11,349 | cc | C++ | frontend/converters/chunking.cc | yomocchi/cloud-spanner-emulator | 0fc44c9571f5c4974a57db4fe3e0457196fc8540 | [
"Apache-2.0"
] | null | null | null | frontend/converters/chunking.cc | yomocchi/cloud-spanner-emulator | 0fc44c9571f5c4974a57db4fe3e0457196fc8540 | [
"Apache-2.0"
] | null | null | null | frontend/converters/chunking.cc | yomocchi/cloud-spanner-emulator | 0fc44c9571f5c4974a57db4fe3e0457196fc8540 | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "frontend/converters/chunking.h"
#include <vector>
#include "absl/memory/memory.h"
#include "absl/status/statusor.h"
#include "absl/strings/substitute.h"
#include "common/errors.h"
#include "zetasql/base/status_macros.h"
namespace google {
namespace spanner {
namespace emulator {
namespace frontend {
namespace {
// UTF-8 is at most 4 bytes. The follow chart explains the format of each
// UTF-8 character.
// Char. number range | UTF-8 octet sequence
// (hexadecimal) | (binary)
// --------------------+---------------------------------------------
// 0000 0000-0000 007F | 0xxxxxxx
// 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
// 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
// 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
//
// More detail in the spec: https://tools.ietf.org/html/rfc3629#page-4
const uint8_t kPartialUTF8Bytes = 1 << 7; // 0b10000000
const uint8_t kUTF8TwoBytes = 3 << 6; // 0b11000000
const uint8_t kUTF8ThreeBytes = 7 << 5; // 0b11100000
const uint8_t kUTF8FourBytes = 15 << 4; // 0b11110000
const int64_t kMaxUTF8CharSize = 4;
bool IsPartialUTF8(char input) {
return (static_cast<int>(input) & kPartialUTF8Bytes) != 0;
}
int64_t RemovePartialUTF8(absl::string_view string, int64_t available) {
for (int64_t pos = available - 1;
pos >= std::max<int64_t>(available - kMaxUTF8CharSize, 0); pos--) {
char partial = string[pos];
// Only remove partial UTF-8 character.
if ((partial & kUTF8FourBytes) == kUTF8FourBytes) {
if (pos != available - 4) available = pos;
break;
} else if ((partial & kUTF8ThreeBytes) == kUTF8ThreeBytes) {
if (pos != available - 3) available = pos;
break;
} else if ((partial & kUTF8TwoBytes) == kUTF8TwoBytes) {
if (pos != available - 2) available = pos;
break;
}
}
return available;
}
// Constructs a set of PartialResultSets. Data will be chunked as necessary to
// comply with the Cloud Spanner streaming chunk size limit. Only Strings and
// Lists need to be chunked (Structs are not a valid column type and will return
// an error if encountered).
class ResultSetBuilder {
public:
explicit ResultSetBuilder(
int64_t max_chunk_size,
std::vector<google::spanner::v1::PartialResultSet>* results)
: max_chunk_size_(max_chunk_size), results_(results) {
if (results_->empty()) {
results_->emplace_back();
}
current_chunk_size_ = results_->back().ByteSizeLong();
stack_.push_back(results_->back().mutable_values());
}
// Adds the incoming value to the set of PartialResultSets chunking as
// necessary.
absl::Status AddValue(const protobuf::Value& value) {
// If the current size exceeds the limit, create a new chunk.
if (HasExceededChunkLimit()) {
StartNewResultSet();
}
// Adds the value to the current result set. It will be chunked into pieces
// if the size of a result set would exceed max_chunk_size_. In that case,
// partial values will be added to the end of this result set and beginning
// of the next one. The partial results will be merged back together by the
// receiving client.
auto value_size = value.ByteSizeLong();
switch (value.kind_case()) {
case protobuf::Value::kListValue: {
// Check if list can fit into current chunk.
if (current_chunk_size_ + value_size <= max_chunk_size_) {
AddUnchunkedValue(value);
} else {
StartList();
for (const auto& list_value : value.list_value().values()) {
ZETASQL_RETURN_IF_ERROR(AddValue(list_value));
}
FinishList();
}
CheckListBoundary();
break;
}
case protobuf::Value::kStringValue: {
// Check if string can fit into current chunk.
if (current_chunk_size_ + value_size <= max_chunk_size_) {
AddUnchunkedValue(value);
} else {
AddString(value.string_value());
}
CheckStringBoundary();
break;
}
case protobuf::Value::kBoolValue:
case protobuf::Value::kNumberValue:
case protobuf::Value::kNullValue:
AddUnchunkedValue(value);
break;
default:
return error::Internal(absl::Substitute(
"Cannot convert value of type ($0) to a potentially "
"chunked PartialResultSet.",
value.GetTypeName()));
}
return absl::OkStatus();
}
private:
ResultSetBuilder(const ResultSetBuilder&) = delete;
ResultSetBuilder& operator=(const ResultSetBuilder&) = delete;
bool HasExceededChunkLimit() {
return current_chunk_size_ >= max_chunk_size_;
}
bool IsListOpen() { return stack_.size() > 1; }
// Adds a value as the next value without chunking. The value will be added to
// a list if there are any nested lists otherwise it will be added as the next
// value in results. Used for the fast path when it is known this will not
// need to be chunked.
void AddUnchunkedValue(const protobuf::Value& value) {
*stack_.back()->Add() = value;
current_chunk_size_ += value.ByteSizeLong();
}
// If a nested list ends at the boundary of the chunk, we need to make sure
// that an empty list is added at the beginning of the next chunk so they will
// be merged together. Otherwise it could end up being incorrectly merged with
// a disjoint list in the next chunk. We explicitly check for this to catch
// edge cases.
void CheckListBoundary() {
if (HasExceededChunkLimit() && IsListOpen()) {
StartNewResultSet();
// Add and empty list to merge with the last list from the previous
// chunk.
StartList();
FinishList();
}
}
// If a string nested inside a list ends at the boundary of the chunk, we
// need to make sure that an empty string is added at the beginning of the
// next chunk so they will be merged together. Otherwise it could end up being
// incorrectly merged with another string in the next chunk. We explicitly
// check for this to catch edge cases.
void CheckStringBoundary() {
if (HasExceededChunkLimit() && IsListOpen()) {
StartNewResultSet();
// The last string ended within the previous chunk, so we don't want to
// concatenate it with the next string. Add an empty string to prevent
// this.
AddUnchunkedString("");
}
}
// Adds a string as the next value. The value will be added to a list if there
// are any nested lists otherwise it will be added as the next value in
// results.
void AddString(absl::string_view str) {
if (str.empty()) {
// Handle empty string case.
AddUnchunkedString("");
return;
}
while (!str.empty()) {
int64_t available = std::max(max_chunk_size_ - current_chunk_size_,
static_cast<int64_t>(0));
if (str.size() > available) {
// Strings are UTF-8 encoded. Not all client libraries support a split
// UTF-8 character. Flush the entire and not partial UTF-8 character.
if (available > 0 && IsPartialUTF8(str[available - 1])) {
available = RemovePartialUTF8(str, available);
}
// Chunk the string into pieces.
AddUnchunkedString(str.substr(0, available));
results_->back().set_chunked_value(true);
StartNewResultSet();
str.remove_prefix(available);
} else {
// String can fit into remaing space of current chunk.
AddUnchunkedString(str);
break;
}
}
}
// Adds an unchunked string to the current result set or list.
void AddUnchunkedString(absl::string_view str) {
auto value = stack_.back()->Add();
value->mutable_string_value()->assign(str.data(), str.size());
current_chunk_size_ += value->ByteSizeLong();
}
// Adds a list as the next value. The list will be nested in another list if
// there are any lists currently in the stack otherwise it will be added as
// the next value in results.
void StartList() {
auto value = stack_.back()->Add();
stack_.push_back(value->mutable_list_value()->mutable_values());
current_chunk_size_ += value->ByteSizeLong();
}
// Removes a list from the stack.
void FinishList() { stack_.pop_back(); }
// Adds a new partial result set to results. If list(s) are currently being
// processed it will create corresponding list(s) in the new chunk. The
// current result set will have chunked_value set to true if a list was
// currently being processed or if a string is split up.
void StartNewResultSet() {
if (IsListOpen()) {
// Always mark as chunked if inside a list.
results_->back().set_chunked_value(true);
}
size_t stack_depth = stack_.size() - 1;
stack_.clear();
results_->emplace_back();
stack_.push_back(results_->back().mutable_values());
for (int i = 0; i < stack_depth; ++i) {
auto list = stack_.back()->Add()->mutable_list_value();
stack_.push_back(list->mutable_values());
}
// Reset the size of the current result set.
current_chunk_size_ = results_->back().ByteSizeLong();
}
// The size of the current chunk that is being appended to. This is an
// estimate of the current chunk size. This estimate should work fine in
// practice since the max chunk size is 1MB and the default message size limit
// is 4MB for gRPC. Since we do not explicitly track the metadata, our size
// estimate could be off by as much as a factor of 2. However, this shouldn't
// be a problem since it will be well below the gRPC limit.
int64_t current_chunk_size_;
// The maximum allowed size of a chunk.
int64_t max_chunk_size_;
// The list of PartialResultSets that store the resulting chunks.
std::vector<::google::spanner::v1::PartialResultSet>* results_;
// The list stack is used to track nested lists. When a result set is chunked
// all current lists need to be truncated and matching versions created in the
// next chunk.
std::vector<google::protobuf::RepeatedPtrField<protobuf::Value>*> stack_;
};
} // namespace
absl::StatusOr<std::vector<google::spanner::v1::PartialResultSet>>
ChunkResultSet(const google::spanner::v1::ResultSet& set,
int64_t max_chunk_size) {
std::vector<google::spanner::v1::PartialResultSet> results;
results.emplace_back();
*results.front().mutable_metadata() = set.metadata();
ResultSetBuilder builder(max_chunk_size, &results);
for (const auto& row : set.rows()) {
for (const auto& value : row.values()) {
ZETASQL_RETURN_IF_ERROR(builder.AddValue(value));
}
}
return results;
}
} // namespace frontend
} // namespace emulator
} // namespace spanner
} // namespace google
| 36.728155 | 80 | 0.670279 | [
"vector"
] |
6b0733857589682b3612b528e371aebe16edbcd9 | 2,253 | cpp | C++ | src/LumsTest/LumsTest.cpp | Nax/Lums | ca38b8f083fea17f96e2547acfa1dd7dfb7cbab3 | [
"MIT"
] | 1 | 2021-12-20T00:00:38.000Z | 2021-12-20T00:00:38.000Z | src/LumsTest/LumsTest.cpp | Nax/Lums | ca38b8f083fea17f96e2547acfa1dd7dfb7cbab3 | [
"MIT"
] | null | null | null | src/LumsTest/LumsTest.cpp | Nax/Lums | ca38b8f083fea17f96e2547acfa1dd7dfb7cbab3 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <LumsTest/LumsTest.h>
namespace
{
struct Label
{
const char* name;
const char* file;
int line;
};
struct Test
{
Label labelSuite;
Label labelTest;
std::function<void(void)> func;
bool errored;
};
struct Context
{
Label suiteLabel;
std::vector<Test> tests;
Test* current;
int errors;
};
Context& getContext(void)
{
static Context c{};
return c;
}
void runTest(Test& t)
{
auto& ctx = getContext();
ctx.current = &t;
t.func();
if (t.errored)
{
ctx.errors++;
}
else
{
std::printf(".");
}
}
}
lt::RegisterTestSuite::RegisterTestSuite(const char* name, const char* file, int line)
{
auto& ctx = getContext();
ctx.suiteLabel = { name, file, line };
}
lt::RegisterTest::RegisterTest(const char* name, const char* file, int line, std::function<void(void)> func)
{
auto& ctx = getContext();
Test t;
t.labelSuite = ctx.suiteLabel;
t.labelTest = { name, file, line };
t.func = func;
t.errored = false;
ctx.tests.push_back(t);
}
bool lt::assert_helper(const char* expr, const char* file, int line, bool value)
{
if (!value)
{
auto& ctx = getContext();
ctx.current->errored = true;
std::printf("x\n");
std::printf("%s (%s:%d)\n", ctx.current->labelSuite.name, ctx.current->labelSuite.file, ctx.current->labelSuite.line);
std::printf("%s (%s:%d)\n", ctx.current->labelTest.name, ctx.current->labelTest.file, ctx.current->labelTest.line);
std::printf("%s (%s:%d)\n", expr, file, line);
std::printf("\n");
return true;
}
return false;
}
int main(int argc, char** argv)
{
auto& ctx = getContext();
int total{};
for (auto& t : ctx.tests)
{
runTest(t);
total++;
}
std::printf("\n\n");
int errors = ctx.errors;
std::printf("Ran %d test%s, %d passed, %d error%s.\n", total, (total > 1) ? "s" : "", total - errors, errors, (errors > 1) ? "s" : "");
return errors ? 1 : 0;
}
| 20.481818 | 140 | 0.530404 | [
"vector"
] |
6b08478cc3207f02fa2c05ddb53de663eae1e171 | 11,457 | cpp | C++ | modules/src/components/cylindricaldetector.cpp | phernst/ctl | f2369cf3141ff6a696219f99b09fd60c0ea12eac | [
"MIT"
] | null | null | null | modules/src/components/cylindricaldetector.cpp | phernst/ctl | f2369cf3141ff6a696219f99b09fd60c0ea12eac | [
"MIT"
] | null | null | null | modules/src/components/cylindricaldetector.cpp | phernst/ctl | f2369cf3141ff6a696219f99b09fd60c0ea12eac | [
"MIT"
] | null | null | null | #include "cylindricaldetector.h"
#include <QSize>
#include <QSizeF>
#include <QtMath>
#include <iostream>
#include <limits>
namespace CTL {
DECLARE_SERIALIZABLE_TYPE(CylindricalDetector)
/*!
* Constructs an empty (invalid) CylindricalDetector object.
*
* To be used only in combination with deserialization by means of fromVariant().
*/
CylindricalDetector::CylindricalDetector(const QString &name)
: AbstractDetector(name)
{
}
/*!
* Constructs a CylindricalDetector object that is composed of \a nbDetectorModules (flat-panel)
* detector modules, each of which with \a nbPixelPerModule pixels with dimensions \a
* pixelDimensions. The arrangement of the individual modules is constructed based on the \a
* angulationPerModule and \a moduleSpacing parameters.
*/
CylindricalDetector::CylindricalDetector(const QSize& nbPixelPerModule,
const QSizeF& pixelDimensions,
uint nbDetectorModules,
double angulationPerModule,
double moduleSpacing,
const QString& name)
: AbstractDetector(nbPixelPerModule, pixelDimensions, name)
, _nbModules(nbDetectorModules)
, _angulationPerModule(angulationPerModule)
, _moduleSpacing(moduleSpacing)
{
//computeModuleLocations();
}
/*!
* Factory method to construct a CylindricalDetector from the parameters \a angulationPerModule and
* \a moduleSpacing. This method simply calls the constructor.
*
* \sa CylindricalDetector().
*/
CylindricalDetector CylindricalDetector::fromAngulationAndSpacing(const QSize& nbPixelPerModule,
const QSizeF& pixelDimensions,
uint nbDetectorModules,
double angulationPerModule,
double moduleSpacing,
const QString& name)
{
return CylindricalDetector(nbPixelPerModule, pixelDimensions, nbDetectorModules,
angulationPerModule, moduleSpacing, name);
}
/*!
* Factory method to construct a CylindricalDetector from the parameters \a radius and \a fanAngle
* instead of module spacing and angulation (as used in the constructor). Use this factory if you
* want to specify the detector system by its curvature radius and fan angle.
*
* Module angulation and spacing are computed using setAngulationFromFanAngle() and
* setSpacingFromRadius(), respectively.
*/
CylindricalDetector CylindricalDetector::fromRadiusAndFanAngle(const QSize& nbPixelPerModule,
const QSizeF& pixelDimensions,
uint nbDetectorModules,
double radius,
double fanAngle,
const QString& name)
{
CylindricalDetector ret;
ret.rename(name);
ret._nbModules = nbDetectorModules;
ret._nbPixelPerModule = nbPixelPerModule;
ret._pixelDimensions = pixelDimensions;
ret.setAngulationFromFanAngle(nbDetectorModules, fanAngle, radius);
ret.setSpacingFromRadius(radius);
//ret.computeModuleLocations();
return ret;
}
/*!
* Returns a formatted string with information about the object.
*
* In addition to the information from the base classes (GenericDetector and GenericComponent), the
* info string contains the following details:
* \li Fan angle
* \li Cone angle
* \li Row coverage
* \li Curvature radius
*/
QString CylindricalDetector::info() const
{
QString ret(AbstractDetector::info());
// clang-format off
ret += typeInfoString(typeid(this));
ret += "\tRow coverage: " + QString::number(rowCoverage()) + " mm\n"
"\tFan angle: " + QString::number(qRadiansToDegrees(fanAngle())) + " deg\n"
"\tCone angle: " + QString::number(qRadiansToDegrees(coneAngle())) + " deg\n"
"\tCurvature radius: " + QString::number(curvatureRadius()) + " mm\n";
ret += (this->type() == CylindricalDetector::Type) ? "}\n" : "";
// clang-format on
return ret;
}
/*!
* Returns the curvature radius of the given detector arrangement.
*
* This is computed as: \f$r=d/\sqrt{2(1-\cos\alpha)}\f$
* where \f$r\f$ denotes the curvature radius and \f$\alpha=\mathtt{\_angulationPerModule}\f$. The
* length \f$d\f$ is computed as follows:
* \f$d=\mathtt{\_moduleSpacing}+\mathtt{\_moduleWidth}\cdot\cos\left(\alpha/2\right)\f$.
*
* Returns std::numeric_limits<double>::max() if the module angulation is zero (flat panel),
*/
double CylindricalDetector::curvatureRadius() const
{
if(qFuzzyIsNull(_angulationPerModule))
return std::numeric_limits<double>::max(); // flat detector --> radius becomes infinite
const double modWidth = moduleWidth();
double d = _moduleSpacing + modWidth * std::cos(_angulationPerModule / 2.0);
return d / std::sqrt(2.0 * (1.0 - std::cos(_angulationPerModule)));
}
/*!
* Returns the default name for the component: "Cylindrical detector".
*/
QString CylindricalDetector::defaultName()
{
const QString defName(QStringLiteral("Cylindrical detector"));
static uint counter = 0;
return counter++ ? defName + " (" + QString::number(counter) + ")" : defName;
}
/*!
* This method computes the locations, i.e. their relative position and orientation w.r.t. the
* center of the full detector, of all detector modules based on the defining parameters `radius`
* (extracted using curvatureRadius()) and `_moduleAngulations` (set in advance using
* setEquidistantModuleAngulation()).
*/
QVector<AbstractDetector::ModuleLocation> CylindricalDetector::moduleLocations() const
{
QVector<ModuleLocation> loc;
loc.reserve(_nbModules);
const double radius = curvatureRadius(); // the radius of the cylinder
// starting point in the middle of the detector (in CT coordinates)
const Vector3x1 pt(0.0, 0.0, radius);
ModuleLocation tmp;
Matrix3x3 rotMat;
Vector3x1 rotPt;
const auto modAngul = moduleAngulations();
for(uint mod = 0; mod < _nbModules; ++mod)
{
rotMat = mat::rotationMatrix(modAngul.at(mod), Qt::YAxis);
rotPt = rotMat * pt; // rotate the starting point
rotPt.get<2>() -= radius; // translate the resulting vector to the detector position
tmp.position = rotPt;
tmp.rotation = rotMat.transposed(); // store the passive form
loc.append(tmp);
}
return loc;
}
/*!
* Computes and returns a vector \f$\vec{\varphi}\f$ with equidistributed angulation values.
*
* For a given number of \f$N\f$ modules (extracted using nbDetectorModules()) and an angulation
* \f$\alpha\f$ between adjacent modules
* (\a angulationPerModule), this is yields:
* \f$
* \vec{\varphi}=\begin{cases}
* \left(-(N-1)/2\cdot\alpha,-(N-2)/2\cdot\alpha,...,0,...,(N-2)/2\cdot\alpha,(N-1)/2\cdot\alpha
* \right) & N\,\textrm{odd}\\
* \left(-(N-1)/2\cdot\alpha,-(N-2)/2\cdot\alpha,...,-1/2\cdot\alpha,1/2\cdot\alpha,...,(N-2)/2
* \cdot\alpha,(N-1)/2\cdot\alpha\right) & N\,\textrm{even} \end{cases} \f$
*/
QVector<double> CylindricalDetector::moduleAngulations() const
{
const uint nbModules = _nbModules;
QVector<double> modAngul(nbModules);
for(uint module = 0; module < nbModules; ++module)
modAngul[module] = (double(module) - double(nbModules) * 0.5 + 0.5) * _angulationPerModule;
return modAngul;
}
// Use SerializationInterface::fromVariant() documentation.
void CylindricalDetector::fromVariant(const QVariant& variant)
{
AbstractDetector::fromVariant(variant);
QVariantMap varMap = variant.toMap();
_angulationPerModule = varMap.value("angulation per module").toDouble();
_moduleSpacing = varMap.value("module spacing").toDouble();
_nbModules = varMap.value("number of modules").toUInt();
}
// Use SerializationInterface::toVariant() documentation.
QVariant CylindricalDetector::toVariant() const
{
QVariantMap ret = AbstractDetector::toVariant().toMap();
ret.insert("angulation per module", _angulationPerModule);
ret.insert("module spacing", _moduleSpacing);
ret.insert("number of modules", _nbModules);
return ret;
}
/*!
* Returns the angulation of module \a module (in radians) with respect to the center of the
* detector.
*/
double CylindricalDetector::angulationOfModule(uint module) const
{
Q_ASSERT(module < nbDetectorModules());
return moduleAngulations().at(module);
}
/*!
* Returns the spacing between individual modules in this instance. Spacing refers to the
* edge-to-edge distance between adjacent modules in x-direction.
*/
double CylindricalDetector::moduleSpacing() const
{
return _moduleSpacing;
}
SystemComponent* CylindricalDetector::clone() const { return new CylindricalDetector(*this); }
/*!
* Returns the cone angle of the detector.
*
* The cone angle is computed under the assumption that a point source located at the distance of
* the curvature radius is used.
*/
double CylindricalDetector::coneAngle() const
{
return 2.0 * tan(0.5 * rowCoverage() / curvatureRadius());
}
/*!
* Returns the total fan angle covered by the detector.
*
* This contains the angle between all modules and the fan angle of one isolated module (two times
* half a module at the borders of the detector):
* \f$\mathtt{fanAngle}=\left(\mathtt{nbModule}-1\right)\cdot\alpha+2\cdot\arctan(\mathtt{moduleWidth}/
* (2\cdot\mathtt{radius})\f$
*/
double CylindricalDetector::fanAngle() const
{
return static_cast<double>(nbDetectorModules() - 1) * _angulationPerModule
+ 2.0 * atan(0.5 * moduleWidth() / curvatureRadius());
}
/*!
* Returns the width (in mm) of an individual module. Computes as number of pixels times width of a
* pixel.
*/
double CylindricalDetector::moduleWidth() const
{
return static_cast<double>(_nbPixelPerModule.width()) * _pixelDimensions.width();
}
/*!
* Returns the total coverage (in mm) by the rows of the detector. This is computed as number of
* rows times height of a module.
*/
double CylindricalDetector::rowCoverage() const
{
return static_cast<double>(_nbPixelPerModule.height()) * _pixelDimensions.height();
}
/*!
* Sets the module angulations based on the parameters \a nbModules, \a fanAngle, and \a radius.
*
* To do so, the required angulation per module \f$\alpha\f$ is computed as:
* \f$\alpha=\left(\mathtt{fanAngle}-2\cdot\arctan(\mathtt{moduleWidth}/(2\cdot\mathtt{radius})
* \right)/\left(\mathtt{nbModule}-1\right).\f$
*/
void CylindricalDetector::setAngulationFromFanAngle(uint nbModules, double fanAngle, double radius)
{
_angulationPerModule = (fanAngle - 2.0 * atan(0.5 * moduleWidth() / radius))
/ static_cast<double>(nbModules - 1);
}
/*!
* Sets the module spacing based on the \a radius.
*/
void CylindricalDetector::setSpacingFromRadius(double radius)
{
_moduleSpacing = radius * std::sqrt(2.0 * (1.0 - std::cos(_angulationPerModule)))
- moduleWidth() * std::cos(0.5 * _angulationPerModule);
}
} // namespace CTL
| 36.141956 | 103 | 0.663001 | [
"object",
"vector"
] |
6b119b5a3566086e91a2658b87d255c97fbe7084 | 5,585 | cc | C++ | libhwsec-foundation/tpm_error/handle_auth_failure.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | libhwsec-foundation/tpm_error/handle_auth_failure.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | libhwsec-foundation/tpm_error/handle_auth_failure.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 The Chromium OS 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 "libhwsec-foundation/tpm_error/handle_auth_failure.h"
#include <stddef.h>
#include <sys/wait.h>
#include <algorithm>
#include <string>
#include <vector>
#include <base/files/file_util.h>
#include <base/logging.h>
#include <base/strings/string_split.h>
#include <re2/re2.h>
#include "libhwsec-foundation/da_reset/da_resetter.h"
#include "libhwsec-foundation/tpm_error/auth_failure_analysis.h"
#include "libhwsec-foundation/tpm_error/tpm_error_data.h"
#include "libhwsec-foundation/tpm_error/tpm_error_uma_reporter.h"
namespace {
constexpr int64_t kLogMaxSize = 20'000;
constexpr int64_t kLogRemainingSize = 10'000;
char lastError[256] = {'\0'};
base::FilePath logFile;
base::FilePath permanentLogFile;
// Set the error in order to let consumer, e.g tcsd, fetch the error by
// FetchAuthFailureError().
void SetLastError(const std::string& msg) {
std::string error_msg = msg + ": " + strerror(errno);
strncpy(lastError, error_msg.c_str(), sizeof(lastError) - 1);
}
// Append |msg| to |log_path|, and limit the size of log to |kLogMaxSize|;
bool AppendMessage(const base::FilePath& log_path, const std::string& msg) {
if (!base::PathExists(log_path)) {
return base::WriteFile(log_path, msg);
}
if (!base::AppendToFile(log_path, msg)) {
return false;
}
int64_t file_size;
if (!base::GetFileSize(log_path, &file_size)) {
return false;
}
if (file_size >= kLogMaxSize) {
std::string contents;
if (!base::ReadFileToString(log_path, &contents)) {
return false;
}
// Truncate log size to |kLogRemainingSize|.
int64_t truncate_size = (int64_t)contents.size() - kLogRemainingSize;
contents.erase(0, truncate_size);
return base::WriteFile(log_path, contents);
}
return true;
}
// Handle any log message in this file, and send them to |logFile| and
// |permanentLogFile| which is set by InitializeAuthFailureLogging().
bool LogMessageHandler(int severity,
const char* file,
int line,
size_t message_start,
const std::string& str) {
// Skip if the message is not genenrated by this file.
if (strncmp(file, __FILE__, sizeof(__FILE__)) != 0) {
return false;
}
if (!AppendMessage(logFile, str) || !AppendMessage(permanentLogFile, str)) {
SetLastError("error logging");
}
return severity != logging::LOGGING_FATAL;
}
// This will log command to the file set by InitializeAuthFailureLogging().
void LogAuthFailureCommand(const struct TpmErrorData& data) {
LOG(WARNING) << "auth failure: command " << data.command << ", response "
<< data.response;
}
constexpr LazyRE2 auth_failure_command = {
R"(auth failure: command (\d+), response (\d+))"};
uint32_t GetCommandHash(const base::FilePath& log_path) {
std::string contents;
if (!base::ReadFileToString(log_path, &contents)) {
return 0;
}
auto lines = base::SplitString(contents, "\n", base::KEEP_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
// Parse TpmErrorData from auth failure log.
std::vector<struct TpmErrorData> data_set;
for (const std::string& line : lines) {
struct TpmErrorData data;
if (!RE2::PartialMatch(line, *auth_failure_command, &data.command,
&data.response)) {
continue;
}
data_set.push_back(data);
}
// Uniquify collcection of TpmErrorData.
std::sort(data_set.begin(), data_set.end());
auto it = std::unique(data_set.begin(), data_set.end());
data_set.resize(std::distance(data_set.begin(), it));
return GetHashFromTpmDataSet(data_set);
}
} // namespace
extern "C" int FetchAuthFailureError(char out[], size_t size) {
if (size <= 1)
return 0;
if (lastError[0] == '\0')
return 0;
strncpy(out, lastError, size - 1);
out[size - 1] = '\0';
lastError[0] = '\0';
return 1;
}
extern "C" void InitializeAuthFailureLogging(const char* log_path,
const char* permanent_log_path) {
CHECK(logging::GetLogMessageHandler() == nullptr)
<< "LogMessageHandler has already been set";
logFile = base::FilePath(log_path);
permanentLogFile = base::FilePath(permanent_log_path);
logging::SetLogMessageHandler(LogMessageHandler);
}
extern "C" int CheckAuthFailureHistory(const char* current_path,
const char* previous_path,
size_t* auth_failure_hash) {
base::FilePath current_log(current_path);
base::FilePath previous_log(previous_path);
if (!base::PathExists(current_log)) {
return 0;
}
int64_t size;
if (!base::GetFileSize(current_log, &size)) {
SetLastError("error checking file size");
return 0;
}
// If there is no failure log in |current_log|, nothing to do here.
if (size == 0) {
return 0;
}
if (!base::Move(current_log, previous_log)) {
SetLastError("error moving file");
return 0;
}
if (auth_failure_hash) {
*auth_failure_hash = GetCommandHash(previous_log);
}
return 1;
}
extern "C" int HandleAuthFailure(const struct TpmErrorData* data) {
if (!hwsec_foundation::DoesCauseDAIncrease(*data)) {
return true;
}
LogAuthFailureCommand(*data);
hwsec_foundation::TpmErrorUmaReporter reporter;
reporter.Report(*data);
hwsec_foundation::DAResetter resetter;
return resetter.ResetDictionaryAttackLock();
}
| 30.189189 | 78 | 0.674664 | [
"vector"
] |
6b1cbe92d9faef82e0dca1979e7c5cd74fd27f5d | 11,058 | cpp | C++ | source/NanairoCore/Material/Bxdf/ggx_dielectric_bsdf.cpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 30 | 2015-09-06T03:14:29.000Z | 2021-06-18T11:00:19.000Z | source/NanairoCore/Material/Bxdf/ggx_dielectric_bsdf.cpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 31 | 2016-01-14T14:50:34.000Z | 2018-06-25T13:21:48.000Z | source/NanairoCore/Material/Bxdf/ggx_dielectric_bsdf.cpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 6 | 2017-04-09T13:07:47.000Z | 2021-05-29T21:17:34.000Z | /*!
\file ggx_dielectric_bsdf.cpp
\author Sho Ikeda
Copyright (c) 2015-2018 Sho Ikeda
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
#include "ggx_dielectric_bsdf.hpp"
// Standard C++ library
#include <tuple>
// Zisc
#include "zisc/error.hpp"
#include "zisc/utility.hpp"
// Nanairo
#include "NanairoCore/nanairo_core_config.hpp"
#include "NanairoCore/Data/intersection_info.hpp"
#include "NanairoCore/Data/path_state.hpp"
#include "NanairoCore/Data/shape_point.hpp"
#include "NanairoCore/Geometry/transformation.hpp"
#include "NanairoCore/Geometry/vector.hpp"
#include "NanairoCore/Material/shader_model.hpp"
#include "NanairoCore/Material/SurfaceModel/Surface/microfacet_ggx.hpp"
#include "NanairoCore/Sampling/sampled_direction.hpp"
#include "NanairoCore/Sampling/sampled_spectra.hpp"
#include "NanairoCore/Sampling/Sampler/sampler.hpp"
namespace nanairo {
/*!
\details
No detailed.
*/
GgxDielectricBsdf::GgxDielectricBsdf(
const Float roughness_x,
const Float roughness_y,
const Float n) noexcept :
roughness_x_{roughness_x},
roughness_y_{roughness_y},
n_{n}
{
}
/*!
\details
No detailed.
*/
Float GgxDielectricBsdf::evalPdf(
const Vector3* vin,
const Vector3* vout,
const WavelengthSamples& /* wavelengths */,
const IntersectionInfo* info) const noexcept
{
ZISC_ASSERT(info != nullptr, "The info is null.");
const auto& point = info->shapePoint();
// Transform vectors
const auto vin_d = Transformation::toLocal(point.tangent(),
point.bitangent(),
point.normal(),
-(*vin));
ZISC_ASSERT(zisc::isInClosedBounds(vin_d[2], 0.0, 1.0),
"The vin isn't in the upper hemisphere.");
ZISC_ASSERT(isUnitVector(vin_d), "The vin isn't unit vector.");
const auto vout_d = Transformation::toLocal(point.tangent(),
point.bitangent(),
point.normal(),
*vout);
ZISC_ASSERT(isUnitVector(vout_d), "The vout isn't unit vector.");
// Check if the ray is reflected or refracted
const Float cos_no = vout_d[2];
const bool is_reflection = (0.0 < cos_no);
// Calculate the microfacet normal
const auto m_normal = (is_reflection)
? Microfacet::calcReflectionHalfVector(vin_d, vout_d)
: Microfacet::calcRefractionHalfVector(vin_d, vout_d, n_);
Float pdf = 0.0;
const Float cos_mi = zisc::dot(m_normal, vin_d);
const bool is_valid =
(0.0 < m_normal[2]) &&
(is_reflection || Fresnel::checkSnellsLaw(n_, cos_mi, zisc::dot(m_normal, vout_d)));
if (is_valid) {
// Calculate the fresnel term
const Float fresnel = Fresnel::evalFresnel(n_, cos_mi);
// Evaluate the pdf
pdf = (is_reflection)
? (fresnel *
MicrofacetGgx::evalReflectionPdf(roughness_x_, roughness_y_, vin_d, m_normal))
: ((1.0 - fresnel) *
MicrofacetGgx::evalRefractionPdf(roughness_x_, roughness_y_, vin_d, vout_d, m_normal, n_));
}
return pdf;
}
/*!
\details
No detailed.
*/
SampledSpectra GgxDielectricBsdf::evalRadiance(
const Vector3* vin,
const Vector3* vout,
const WavelengthSamples& wavelengths,
const IntersectionInfo* info) const noexcept
{
ZISC_ASSERT(info != nullptr, "The info is null.");
const auto& point = info->shapePoint();
// Transform vectors
const auto vin_d = Transformation::toLocal(point.tangent(),
point.bitangent(),
point.normal(),
-(*vin));
ZISC_ASSERT(zisc::isInClosedBounds(vin_d[2], 0.0, 1.0),
"The vin isn't in the upper hemisphere.");
ZISC_ASSERT(isUnitVector(vin_d), "The vin isn't unit vector.");
const auto vout_d = Transformation::toLocal(point.tangent(),
point.bitangent(),
point.normal(),
*vout);
ZISC_ASSERT(isUnitVector(vout_d), "The vout isn't unit vector.");
// Check if the ray is reflected or refracted
const Float cos_no = vout_d[2];
const bool is_reflection = (0.0 < cos_no);
// Calculate the microfacet normal
const auto m_normal = (is_reflection)
? Microfacet::calcReflectionHalfVector(vin_d, vout_d)
: Microfacet::calcRefractionHalfVector(vin_d, vout_d, n_);
SampledSpectra radiance{wavelengths};
const Float cos_mi = zisc::dot(m_normal, vin_d);
const bool is_valid =
(0.0 < m_normal[2]) &&
(is_reflection || Fresnel::checkSnellsLaw(n_, cos_mi, zisc::dot(m_normal, vout_d)));
if (is_valid) {
// Calculate the fresnel term
const Float fresnel = Fresnel::evalFresnel(n_, cos_mi);
// Evaluate the radiance
const Float f = (is_reflection)
? MicrofacetGgx::evalReflectance(roughness_x_, roughness_y_, vin_d, vout_d, m_normal, fresnel)
: MicrofacetGgx::evalTransmittance(roughness_x_, roughness_y_, vin_d, vout_d, m_normal, n_, fresnel);
radiance.setIntensity(wavelengths.primaryWavelengthIndex(), f);
}
return radiance;
}
/*!
\details
No detailed.
*/
std::tuple<SampledSpectra, Float> GgxDielectricBsdf::evalRadianceAndPdf(
const Vector3* vin,
const Vector3* vout,
const WavelengthSamples& wavelengths,
const IntersectionInfo* info) const noexcept
{
ZISC_ASSERT(info != nullptr, "The info is null.");
const auto& point = info->shapePoint();
// Transform vectors
const auto vin_d = Transformation::toLocal(point.tangent(),
point.bitangent(),
point.normal(),
-(*vin));
ZISC_ASSERT(zisc::isInClosedBounds(vin_d[2], 0.0, 1.0),
"The vin isn't in the upper hemisphere.");
ZISC_ASSERT(isUnitVector(vin_d), "The vin isn't unit vector.");
const auto vout_d = Transformation::toLocal(point.tangent(),
point.bitangent(),
point.normal(),
*vout);
ZISC_ASSERT(isUnitVector(vout_d), "The vout isn't unit vector.");
// Check if the ray is reflected or refracted
const Float cos_no = vout_d[2];
const bool is_reflection = 0.0 < cos_no;
// Calculate the microfacet normal
const auto m_normal = (is_reflection)
? Microfacet::calcReflectionHalfVector(vin_d, vout_d)
: Microfacet::calcRefractionHalfVector(vin_d, vout_d, n_);
SampledSpectra radiance{wavelengths};
Float pdf = 0.0;
const Float cos_mi = zisc::dot(m_normal, vin_d);
const Float cos_mo = zisc::dot(m_normal, vout_d);
const bool is_valid =
(0.0 < m_normal[2]) &&
(0.0 < cos_mi) &&
(is_reflection || Fresnel::checkSnellsLaw(n_, cos_mi, cos_mo));
if (is_valid) {
// Calculate the fresnel term
const Float fresnel = Fresnel::evalFresnel(n_, cos_mi);
// Evaluate the radiance
const Float f = (is_reflection)
? MicrofacetGgx::evalReflectance(roughness_x_, roughness_y_, vin_d, vout_d, m_normal, fresnel, &pdf)
: MicrofacetGgx::evalTransmittance(roughness_x_, roughness_y_, vin_d, vout_d, m_normal, n_, fresnel, &pdf);
radiance.setIntensity(wavelengths.primaryWavelengthIndex(), f);
// Evaluate the pdf
pdf = (is_reflection) ? fresnel * pdf : (1.0 - fresnel) * pdf;
}
return std::make_tuple(radiance, pdf);
}
/*!
*/
bool GgxDielectricBsdf::isReflective() const noexcept
{
return true;
}
/*!
*/
bool GgxDielectricBsdf::isTransmissive() const noexcept
{
return true;
}
/*!
*/
std::tuple<SampledDirection, SampledSpectra> GgxDielectricBsdf::sample(
const Vector3* vin,
const WavelengthSamples& wavelengths,
Sampler& sampler,
PathState& path_state,
const IntersectionInfo* info) const noexcept
{
ZISC_ASSERT(info != nullptr, "The info is null.");
const auto& point = info->shapePoint();
// Transform the incident vector
const auto vin_d = Transformation::toLocal(point.tangent(),
point.bitangent(),
point.normal(),
-(*vin));
ZISC_ASSERT(zisc::isInClosedBounds(vin_d[2], 0.0, 1.0),
"The vin isn't in the upper hemisphere.");
ZISC_ASSERT(isUnitVector(vin_d), "The vin isn't unit vector.");
// Sample a microfacet normal
const auto m_normal = MicrofacetGgx::sampleNormal(roughness_x_, roughness_y_,
vin_d, sampler, path_state);
// Evaluate the fresnel term
const Float cos_mi = zisc::dot(m_normal.direction(), vin_d);
const Float g2 = Fresnel::evalG2(n_, cos_mi);
const bool is_perfect_reflection = g2 <= 0.0;
const Float g = (!is_perfect_reflection) ? zisc::sqrt(g2) : 0.0;
const Float fresnel = (!is_perfect_reflection)
? Fresnel::evalFresnelFromG(cos_mi, g)
: 1.0; // Perfect reflection
// Determine a reflection or a refraction
path_state.setDimension(path_state.dimension() + 1);
const bool is_reflection = is_perfect_reflection ||
(sampler.draw1D(path_state) < fresnel);
auto vout = (is_reflection)
? Microfacet::calcReflectionDirection(vin_d, m_normal)
: Microfacet::calcRefractionDirection(vin_d, m_normal, n_, g);
SampledSpectra weight{wavelengths};
const Float cos_no = vout.direction()[2];
if ((is_reflection && (0.0 < cos_no)) || (!is_reflection && (cos_no < 0.0))) {
// Evaluate the weight
const Float w = MicrofacetGgx::evalWeight(roughness_x_,
roughness_y_,
vin_d,
vout.direction(),
m_normal.direction());
ZISC_ASSERT(0.0 <= w, "The weight is negative.");
weight.setIntensity(wavelengths.primaryWavelengthIndex(), w);
// Update the pdf of the outgoing direction
vout.setInversePdf((is_reflection)
? vout.inversePdf() / fresnel
: vout.inversePdf() / (1.0 - fresnel));
// Transformation the reflection direction
const auto vout_dir = Transformation::fromLocal(point.tangent(),
point.bitangent(),
point.normal(),
vout.direction());
ZISC_ASSERT(isUnitVector(vout_dir), "The vout isn't unit vector.");
vout.setDirection(vout_dir);
}
else {
vout.setPdf(0.0);
}
return std::make_tuple(vout, weight);
}
/*!
\details
No detailed.
*/
bool GgxDielectricBsdf::wavelengthIsSelected() const noexcept
{
return true;
}
} // namespace nanairo
| 35.902597 | 115 | 0.615663 | [
"geometry",
"vector",
"transform"
] |
6b22f19113b7c605bf15faf2c1926d95235a7e63 | 16,938 | hpp | C++ | pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Search.hpp | robfalck/pyoptsparse | c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d | [
"CNRI-Python"
] | 26 | 2020-08-25T16:16:21.000Z | 2022-03-10T08:23:57.000Z | pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Search.hpp | robfalck/pyoptsparse | c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d | [
"CNRI-Python"
] | 90 | 2020-08-24T23:02:47.000Z | 2022-03-29T13:48:15.000Z | pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Search.hpp | robfalck/pyoptsparse | c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d | [
"CNRI-Python"
] | 25 | 2020-08-24T19:28:24.000Z | 2022-01-27T21:17:37.000Z | /*-------------------------------------------------------------------------------------*/
/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.0.beta */
/* */
/* Copyright (C) 2001-2014 Mark Abramson - the Boeing Company, Seattle */
/* Charles Audet - Ecole Polytechnique, Montreal */
/* Gilles Couture - Ecole Polytechnique, Montreal */
/* John Dennis - Rice University, Houston */
/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */
/* Christophe Tribes - Ecole Polytechnique, Montreal */
/* */
/* funded in part by AFOSR and Exxon Mobil */
/* */
/* Author: Sebastien Le Digabel */
/* */
/* Contact information: */
/* Ecole Polytechnique de Montreal - GERAD */
/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */
/* e-mail: nomad@gerad.ca */
/* phone : 1-514-340-6053 #6928 */
/* fax : 1-514-340-5665 */
/* */
/* This program is free software: you can redistribute it and/or modify it under the */
/* terms of the GNU Lesser General Public License as published by the Free Software */
/* Foundation, either version 3 of the License, or (at your option) any later */
/* version. */
/* */
/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */
/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */
/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License along */
/* with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/* You can find information on the NOMAD software at www.gerad.ca/nomad */
/*-------------------------------------------------------------------------------------*/
/**
\file TGP_Model_Search.hpp
\brief TGP Model search (headers)
\author Sebastien Le Digabel
\date 2011-02-17
\see TGP_Model_Search.cpp
*/
#ifdef USE_TGP
#ifndef __TGP_MODEL_SEARCH__
#define __TGP_MODEL_SEARCH__
#include "LH_Search.hpp"
#include "TGP_Model_Evaluator.hpp"
namespace NOMAD {
/// Model search.
class TGP_Model_Search : public NOMAD::Search , private NOMAD::Uncopyable {
private:
NOMAD::TGP_Model * _model;
NOMAD::Model_Stats _one_search_stats; ///< Stats for one search.
NOMAD::Model_Stats _all_searches_stats; ///< Stats for all searches.
/// Delete a list of points.
/**
\param pts The points -- \b IN/OUT.
*/
static void clear_pts ( std::vector<NOMAD::Point *> & pts );
/// Delete a list of evaluation points.
/**
\param pts The points -- \b IN/OUT.
*/
static void clear_pts ( std::vector<NOMAD::Eval_Point *> & pts );
/// Model construction.
/**
\param cache Cache of true evaluations -- \b IN.
\param incumbent The incumbent -- \b IN.
\param delta_m Mesh size parameter -- \b IN.
\param out The NOMAD::Display object -- \b IN.
\param display_degree Display degree -- \b IN.
\param display_lim Max number of pts when sets are displayed -- \b IN.
\param stats Model search stats -- \b IN/OUT.
\param compute_Ds2x Flag to enable/disable Ds2x computation -- \b OUT.
\param XX The set of prediction points -- \b OUT.
\param stop Stop flag -- \b OUT.
\param stop_reason Stop reason -- \b OUT.
\param error_std Error string -- \b OUT.
\return A boolean equal to \c true if the model has been constructed.
*/
bool model_construction ( const NOMAD::Cache & cache ,
const NOMAD::Point & incumbent ,
const NOMAD::Point & delta_m ,
const NOMAD::Display & out ,
NOMAD::dd_type display_degree ,
int display_lim ,
NOMAD::Stats & stats ,
bool & compute_Ds2x ,
std::vector<NOMAD::Eval_Point *> & XX ,
bool & stop ,
NOMAD::stop_type & stop_reason ,
std::string & error_str );
/// Create a list of prediction points.
/**
\param cache Cache of true evaluations -- \b IN.
\param n Number of variables -- \b IN.
\param m Number of outputs -- \b IN.
\param incumbent The incumbent -- \b IN.
\param delta_m Mesh size parameter -- \b IN.
\param XX The set of prediction points -- \b OUT.
*/
void set_XX ( const NOMAD::Cache & cache ,
int n ,
int m ,
const NOMAD::Point & incumbent ,
const NOMAD::Point & delta_m ,
std::vector<NOMAD::Eval_Point *> & XX ) const;
/// Create the complete list of trial points (oracle + Ds2x + improv).
/**
\param oracle_pts Oracle points -- \b IN.
\param Ds2x_pts Ds2x points -- \b IN.
\param improv_pts Improv points -- \b IN.
\param incumbent The incumbent -- \b IN.
\param max_pts Max number of trial points -- \b IN.
\param out The NOMAD::Display object -- \b IN.
\param display_degree Display degree -- \b IN.
\param trial_pts The list of trial points -- \b OUT.
*/
void create_trial_pts
( const std::vector<NOMAD::Point *> & oracle_pts ,
const std::vector<NOMAD::Point *> & Ds2x_pts ,
const std::vector<NOMAD::Point *> & improv_pts ,
const NOMAD::Point & incumbent ,
int max_pts ,
const NOMAD::Display & out ,
NOMAD::dd_type display_degree ,
std::vector<NOMAD::Point *> & trial_pts ) const;
/// Create oracle points by optimizing the model.
/**
\param cache Cache of true evaluations -- \b IN.
\param incumbent The incumbent -- \b IN.
\param delta_m Mesh size parameter -- \b IN.
\param out The NOMAD::Display object -- \b IN.
\param display_degree Display degree -- \b IN.
\param display_lim Max number of pts when sets are displayed -- \b IN.
\param XX The set of prediction points -- \b IN.
\param oracle_pts Oracle candidates points -- \b OUT.
\param stop Stop flag -- \b OUT.
\param stop_reason Stop reason -- \b OUT.
\return A boolean equal to \c true oracle points are proposed.
*/
bool create_oracle_pts
( const NOMAD::Cache & cache ,
const NOMAD::Point & incumbent ,
const NOMAD::Point & delta_m ,
const NOMAD::Display & out ,
NOMAD::dd_type display_degree ,
int display_lim ,
const std::vector<NOMAD::Eval_Point *> & XX ,
std::vector<NOMAD::Point *> & oracle_pts ,
bool & stop ,
NOMAD::stop_type & stop_reason );
/// Model optimization.
/**
\param x0s The three starting points -- \b IN.
\param out The NOMAD::Display object -- \b IN.
\param display_degree Display degree -- \b IN.
\param xf Feasible solution \c xf -- \b OUT.
\param xi Infeasible solution \c xi -- \b OUT.
\param stop Stop flag -- \b OUT.
\param stop_reason Stop reason -- \b OUT.
*/
bool optimize_model ( const NOMAD::Eval_Point * x0s[3] ,
const NOMAD::Display & out ,
NOMAD::dd_type display_degree ,
NOMAD::Point *& xf ,
NOMAD::Point *& xi ,
bool & stop ,
NOMAD::stop_type & stop_reason );
/// Project and accept or reject an oracle trial point.
/**
\param cache Cache of true evaluations -- \b IN.
\param incumbent The incumbent -- \b IN.
\param delta_m Mesh size parameter -- \b IN.
\param out The NOMAD::Display object -- \b IN.
\param display_degree Display degree -- \b IN.
\param x The oracle point -- \b IN/OUT.
\return A boolean equal to \c true if the point is accepted.
*/
bool check_oracle_point
( const NOMAD::Cache & cache ,
const NOMAD::Point & incumbent ,
const NOMAD::Point & delta_m ,
const NOMAD::Display & out ,
NOMAD::dd_type display_degree ,
NOMAD::Point & x );
/// Insert a trial point in the evaluator control object.
/**
\param x The point coordinates -- \b IN.
\param signature Signature -- \b IN.
\param incumbent The incumbent -- \b IN.
\param display_degree Display degree -- \b IN.
\param ev_control The NOMAD::Evaluator_Control object -- \b IN/OUT.
*/
void register_point ( NOMAD::Point x ,
NOMAD::Signature & signature ,
const NOMAD::Point & incumbent ,
// C.Tribes august 26, 2014 --- not needed
// int mesh_index ,
NOMAD::dd_type display_degree ,
NOMAD::Evaluator_Control & ev_control ) const;
/// Create the list of improv points.
/**
These points (from the set \c XX) maximize
the expected improvement of the objective.
Priority is given to predicted feasible points.
\param XX The set of prediction points -- \b IN.
\param incumbent The incumbent -- \b IN.
\param max_pts Max number of points -- \b IN.
\param out The NOMAD::Display object -- \b IN.
\param display_degree Display degree -- \b IN.
\param display_lim Max number of pts when sets are displayed -- \b IN.
\param Ds2x_pts The list of improv points -- \b OUT.
*/
void create_improv_pts
( const std::vector<NOMAD::Eval_Point *> & XX ,
const NOMAD::Point & incumbent ,
int max_pts ,
const NOMAD::Display & out ,
NOMAD::dd_type display_degree ,
int display_lim ,
std::vector<NOMAD::Point *> & improv_pts ) const;
/// Create the list of Ds2x points.
/**
These points (from the set \c XX) maximize the expected reduction in
predictive variance for each output.
\param XX The set of prediction points -- \b IN.
\param out The NOMAD::Display object -- \b IN.
\param display_degree Display degree -- \b IN.
\param display_lim Max number of pts when sets are displayed -- \b IN.
\param Ds2x_pts The list of Ds2x points -- \b OUT.
*/
void create_Ds2x_pts
( const std::vector<NOMAD::Eval_Point *> & XX ,
const NOMAD::Display & out ,
NOMAD::dd_type display_degree ,
int display_lim ,
std::vector<NOMAD::Point *> & Ds2x_pts ) const;
/// Prediction at one point.
/**
\param x The point -- \b IN.
\param h Value of \c h -- \b OUT.
\param f Value of \c f -- \b OUT.
\return A boolean equal to \c true if the prediction was possible.
*/
bool predict ( const NOMAD::Point & x ,
NOMAD::Double & h ,
NOMAD::Double & f ) const;
/// Display the prediction error for the evaluated points.
/**
\param evaluated_pts List of evaluated points -- \b IN.
\param out The NOMAD::Display object -- \b IN.
*/
void display_eval_pred_errors
( const std::list<const NOMAD::Eval_Point *> & evaluated_pts ,
const NOMAD::Display & out );
/*----------------------------------------------------------------------*/
public:
/// Constructor.
/**
\param p Parameters -- \b IN.
*/
TGP_Model_Search ( NOMAD::Parameters & p )
: NOMAD::Search ( p , NOMAD::MODEL_SEARCH ) , _model ( NULL ) {}
/// Destructor.
virtual ~TGP_Model_Search ( void ) { reset(); }
/// Reset.
virtual void reset ( void );
/// The TGP model search.
/**
Based on quadratic regression/MFN interpolation models.
\param mads NOMAD::Mads object invoking this search -- \b IN/OUT.
\param nb_search_pts Number of generated search points -- \b OUT.
\param stop Stop flag -- \b IN/OUT.
\param stop_reason Stop reason -- \b OUT.
\param success Type of success -- \b OUT.
\param count_search Count or not the search -- \b OUT.
\param new_feas_inc New feasible incumbent -- \b IN/OUT.
\param new_infeas_inc New infeasible incumbent -- \b IN/OUT.
*/
virtual void search ( NOMAD::Mads & mads ,
int & nb_search_pts ,
bool & stop ,
NOMAD::stop_type & stop_reason ,
NOMAD::success_type & success ,
bool & count_search ,
const NOMAD::Eval_Point *& new_feas_inc ,
const NOMAD::Eval_Point *& new_infeas_inc );
/// Access to the model.
/**
\return The model.
*/
NOMAD::TGP_Model * get_model ( void ) const { return _model; }
//// Display stats.
/**
\param out The NOMAD::Display object -- \b IN.
*/
virtual void display ( const NOMAD::Display & out ) const
{
out << _all_searches_stats;
}
};
}
#endif
#endif
| 50.561194 | 96 | 0.442673 | [
"mesh",
"object",
"vector",
"model"
] |
6b2361b1a2acac4b00a51246359cda3fba620d15 | 2,590 | cpp | C++ | atcoder/arc078f.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | 1 | 2020-04-04T14:56:12.000Z | 2020-04-04T14:56:12.000Z | atcoder/arc078f.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | atcoder/arc078f.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int L = 15;
const int N = 1<<L;
int d[L][L];
//int ss[L][N];
int comp[N];
int dp[N][L];
int n,MSK;
//void sub_sum(int i){
// vector<int> pos(n, 0); // [j..0] : + - - - -
// int sum = 0;
// for (int j = 0; j < n; j++) {
// pos[j] = d[i][j] - sum;
// sum += d[i][j];
// }
// sum = 0;
// // since ...1000 by ...0111 add +---
// for (int msk = 1; msk < MSK; msk++) {
// sum += pos[__builtin_ctz(msk)];
// ss[i][msk] = sum;
// }
//}
void calc_comp(){
for (int msk = 0; msk < MSK; msk++) {
for (int i = 0; i < n; i++) {
if (!(msk&(1<<i))) continue;
for (int j = i+1; j < n; j++) {
if (!(msk&(1<<j))) continue;
comp[msk] += d[i][j];
}
}
}
}
void solve() {
int m;
cin >> n >> m;
MSK = 1<<n;
//memset(d, 0x3f, sizeof d);
for (int _ = 0; _ < m; _++) {
int x,y,c;
cin >> x >> y >> c;
x--;y--;
d[x][y] = d[y][x] = c;
}
for (int i = 0; i < n; i++) {
d[i][i] = 0;
}
//for (int i = 0; i < n; i++) {
// sub_sum(i);
//}
calc_comp();
memset(dp, 0x3f, sizeof dp);
dp[1][0] = 0;
for (int msk = 1; msk < MSK; msk++) {
// for [msk][j], remove (sub/j) - T
for (int sub = msk; sub; (sub-=1)&=msk) {
int T = msk^sub;
for (int j = 0; j < n; j++) {
if (sub & (1<<j)) {
// use ss, 5x slower
//int sum = 0;
//for (int i = 0; i < n; i++) {
// if (i!=j && (sub & (1<<i)))
// sum += ss[i][T];
//}
dp[msk][j] = min(dp[msk][j], dp[sub][j] - comp[sub^(1<<j)] - comp[T] +comp[msk^(1<<j)]);
}
}
}
// for [msk u i][i], remove (msk/j) - i
for (int i = 0; i < n; i++) {
if (msk & (1<<i)) continue;
for (int j = 0; j < n; j++) {
if ((msk & (1<<j)) && d[i][j]) {
dp[msk^(1<<i)][i] = min(dp[msk^(1<<i)][i], dp[msk][j] - comp[msk^(1<<j)] + comp[msk^(1<<j)^(1<<i)]);
}
}
}
}
//for (int msk = 0; msk < MSK; msk++) {
// for (int i = 0; i < n; i++) {
// cout << dp[msk][i] << ' ';
// }cout << "\n";
//}
cout << dp[MSK-1][n-1];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
cout << endl;
}
| 25.145631 | 120 | 0.335135 | [
"vector"
] |
6b263c26ed114a80769aa095ad3e9320fb9a3632 | 771 | cpp | C++ | main.cpp | mmbell/Airborne-Radar-QC | d361f14edf1a24c386df609af300dc230df5110e | [
"MIT"
] | 4 | 2018-08-19T01:26:16.000Z | 2021-02-02T18:33:46.000Z | main.cpp | DalavanCloud/Airborne-Radar-QC | d361f14edf1a24c386df609af300dc230df5110e | [
"MIT"
] | null | null | null | main.cpp | DalavanCloud/Airborne-Radar-QC | d361f14edf1a24c386df609af300dc230df5110e | [
"MIT"
] | 5 | 2015-08-06T17:33:11.000Z | 2022-01-27T03:05:53.000Z | /* AirborneRadarQC */
/* Copyright 2011 Michael Bell and Cory Wolff */
/* All rights reserved */
#include <iostream>
#include <QApplication>
#include "radarqc/ext/QCscript/Dorade.h"
#include "radarqc/ext/QCscript/AirborneRadarQC.h"
using namespace std;
int main (int argc, char *argv[]) {
// Get the arguments
if (argc < 3) {
// Eventually, no arguments would start an interactive GUI mode
//QApplication app(argc, argv);
cout << "Usage: eldoraqc /path/to/sweepfiles /path/to/output\n";
exit(1);
}
// The qc object will read from one directory and write to another
QString inpath = argv[1];
QString outpath = argv[2];
QString suffix = "QC";
AirborneRadarQC QC(inpath, outpath, suffix);
// Process the data
QC.processSweeps();
return 0;
}
| 22.028571 | 67 | 0.696498 | [
"object"
] |
6b3cf2124819111c7a500a24b15c88b3959ce00e | 26,468 | cc | C++ | dts/src/model/DescribeDtsJobsResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | dts/src/model/DescribeDtsJobsResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | dts/src/model/DescribeDtsJobsResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/dts/model/DescribeDtsJobsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Dts;
using namespace AlibabaCloud::Dts::Model;
DescribeDtsJobsResult::DescribeDtsJobsResult() :
ServiceResult()
{}
DescribeDtsJobsResult::DescribeDtsJobsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeDtsJobsResult::~DescribeDtsJobsResult()
{}
void DescribeDtsJobsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allDtsJobListNode = value["DtsJobList"]["DtsJobStatus"];
for (auto valueDtsJobListDtsJobStatus : allDtsJobListNode)
{
DtsJobStatus dtsJobListObject;
if(!valueDtsJobListDtsJobStatus["Status"].isNull())
dtsJobListObject.status = valueDtsJobListDtsJobStatus["Status"].asString();
if(!valueDtsJobListDtsJobStatus["DtsJobName"].isNull())
dtsJobListObject.dtsJobName = valueDtsJobListDtsJobStatus["DtsJobName"].asString();
if(!valueDtsJobListDtsJobStatus["Delay"].isNull())
dtsJobListObject.delay = std::stol(valueDtsJobListDtsJobStatus["Delay"].asString());
if(!valueDtsJobListDtsJobStatus["ErrorMessage"].isNull())
dtsJobListObject.errorMessage = valueDtsJobListDtsJobStatus["ErrorMessage"].asString();
if(!valueDtsJobListDtsJobStatus["ExpireTime"].isNull())
dtsJobListObject.expireTime = valueDtsJobListDtsJobStatus["ExpireTime"].asString();
if(!valueDtsJobListDtsJobStatus["DtsJobId"].isNull())
dtsJobListObject.dtsJobId = valueDtsJobListDtsJobStatus["DtsJobId"].asString();
if(!valueDtsJobListDtsJobStatus["CreateTime"].isNull())
dtsJobListObject.createTime = valueDtsJobListDtsJobStatus["CreateTime"].asString();
if(!valueDtsJobListDtsJobStatus["PayType"].isNull())
dtsJobListObject.payType = valueDtsJobListDtsJobStatus["PayType"].asString();
if(!valueDtsJobListDtsJobStatus["Reserved"].isNull())
dtsJobListObject.reserved = valueDtsJobListDtsJobStatus["Reserved"].asString();
if(!valueDtsJobListDtsJobStatus["ConsumptionClient"].isNull())
dtsJobListObject.consumptionClient = valueDtsJobListDtsJobStatus["ConsumptionClient"].asString();
if(!valueDtsJobListDtsJobStatus["DbObject"].isNull())
dtsJobListObject.dbObject = valueDtsJobListDtsJobStatus["DbObject"].asString();
if(!valueDtsJobListDtsJobStatus["DtsJobClass"].isNull())
dtsJobListObject.dtsJobClass = valueDtsJobListDtsJobStatus["DtsJobClass"].asString();
if(!valueDtsJobListDtsJobStatus["ConsumptionCheckpoint"].isNull())
dtsJobListObject.consumptionCheckpoint = valueDtsJobListDtsJobStatus["ConsumptionCheckpoint"].asString();
if(!valueDtsJobListDtsJobStatus["EndTimestamp"].isNull())
dtsJobListObject.endTimestamp = valueDtsJobListDtsJobStatus["EndTimestamp"].asString();
if(!valueDtsJobListDtsJobStatus["AppName"].isNull())
dtsJobListObject.appName = valueDtsJobListDtsJobStatus["AppName"].asString();
if(!valueDtsJobListDtsJobStatus["BeginTimestamp"].isNull())
dtsJobListObject.beginTimestamp = valueDtsJobListDtsJobStatus["BeginTimestamp"].asString();
if(!valueDtsJobListDtsJobStatus["DtsInstanceID"].isNull())
dtsJobListObject.dtsInstanceID = valueDtsJobListDtsJobStatus["DtsInstanceID"].asString();
if(!valueDtsJobListDtsJobStatus["DtsJobDirection"].isNull())
dtsJobListObject.dtsJobDirection = valueDtsJobListDtsJobStatus["DtsJobDirection"].asString();
if(!valueDtsJobListDtsJobStatus["Checkpoint"].isNull())
dtsJobListObject.checkpoint = valueDtsJobListDtsJobStatus["Checkpoint"].asString();
auto allTagListNode = valueDtsJobListDtsJobStatus["TagList"]["DtsTag"];
for (auto valueDtsJobListDtsJobStatusTagListDtsTag : allTagListNode)
{
DtsJobStatus::DtsTag tagListObject;
if(!valueDtsJobListDtsJobStatusTagListDtsTag["TagValue"].isNull())
tagListObject.tagValue = valueDtsJobListDtsJobStatusTagListDtsTag["TagValue"].asString();
if(!valueDtsJobListDtsJobStatusTagListDtsTag["TagKey"].isNull())
tagListObject.tagKey = valueDtsJobListDtsJobStatusTagListDtsTag["TagKey"].asString();
dtsJobListObject.tagList.push_back(tagListObject);
}
auto dataInitializationStatusNode = value["DataInitializationStatus"];
if(!dataInitializationStatusNode["Status"].isNull())
dtsJobListObject.dataInitializationStatus.status = dataInitializationStatusNode["Status"].asString();
if(!dataInitializationStatusNode["Percent"].isNull())
dtsJobListObject.dataInitializationStatus.percent = dataInitializationStatusNode["Percent"].asString();
if(!dataInitializationStatusNode["ErrorMessage"].isNull())
dtsJobListObject.dataInitializationStatus.errorMessage = dataInitializationStatusNode["ErrorMessage"].asString();
if(!dataInitializationStatusNode["Progress"].isNull())
dtsJobListObject.dataInitializationStatus.progress = dataInitializationStatusNode["Progress"].asString();
auto dataSynchronizationStatusNode = value["DataSynchronizationStatus"];
if(!dataSynchronizationStatusNode["Status"].isNull())
dtsJobListObject.dataSynchronizationStatus.status = dataSynchronizationStatusNode["Status"].asString();
if(!dataSynchronizationStatusNode["NeedUpgrade"].isNull())
dtsJobListObject.dataSynchronizationStatus.needUpgrade = dataSynchronizationStatusNode["NeedUpgrade"].asString() == "true";
if(!dataSynchronizationStatusNode["Percent"].isNull())
dtsJobListObject.dataSynchronizationStatus.percent = dataSynchronizationStatusNode["Percent"].asString();
if(!dataSynchronizationStatusNode["Progress"].isNull())
dtsJobListObject.dataSynchronizationStatus.progress = dataSynchronizationStatusNode["Progress"].asString();
if(!dataSynchronizationStatusNode["ErrorMessage"].isNull())
dtsJobListObject.dataSynchronizationStatus.errorMessage = dataSynchronizationStatusNode["ErrorMessage"].asString();
auto dataEtlStatusNode = value["DataEtlStatus"];
if(!dataEtlStatusNode["Status"].isNull())
dtsJobListObject.dataEtlStatus.status = dataEtlStatusNode["Status"].asString();
if(!dataEtlStatusNode["Percent"].isNull())
dtsJobListObject.dataEtlStatus.percent = dataEtlStatusNode["Percent"].asString();
if(!dataEtlStatusNode["ErrorMessage"].isNull())
dtsJobListObject.dataEtlStatus.errorMessage = dataEtlStatusNode["ErrorMessage"].asString();
if(!dataEtlStatusNode["Progress"].isNull())
dtsJobListObject.dataEtlStatus.progress = dataEtlStatusNode["Progress"].asString();
auto destinationEndpointNode = value["DestinationEndpoint"];
if(!destinationEndpointNode["SslSolutionEnum"].isNull())
dtsJobListObject.destinationEndpoint.sslSolutionEnum = destinationEndpointNode["SslSolutionEnum"].asString();
if(!destinationEndpointNode["OracleSID"].isNull())
dtsJobListObject.destinationEndpoint.oracleSID = destinationEndpointNode["OracleSID"].asString();
if(!destinationEndpointNode["Region"].isNull())
dtsJobListObject.destinationEndpoint.region = destinationEndpointNode["Region"].asString();
if(!destinationEndpointNode["DatabaseName"].isNull())
dtsJobListObject.destinationEndpoint.databaseName = destinationEndpointNode["DatabaseName"].asString();
if(!destinationEndpointNode["Ip"].isNull())
dtsJobListObject.destinationEndpoint.ip = destinationEndpointNode["Ip"].asString();
if(!destinationEndpointNode["InstanceID"].isNull())
dtsJobListObject.destinationEndpoint.instanceID = destinationEndpointNode["InstanceID"].asString();
if(!destinationEndpointNode["Port"].isNull())
dtsJobListObject.destinationEndpoint.port = destinationEndpointNode["Port"].asString();
if(!destinationEndpointNode["InstanceType"].isNull())
dtsJobListObject.destinationEndpoint.instanceType = destinationEndpointNode["InstanceType"].asString();
if(!destinationEndpointNode["UserName"].isNull())
dtsJobListObject.destinationEndpoint.userName = destinationEndpointNode["UserName"].asString();
if(!destinationEndpointNode["EngineName"].isNull())
dtsJobListObject.destinationEndpoint.engineName = destinationEndpointNode["EngineName"].asString();
auto migrationModeNode = value["MigrationMode"];
if(!migrationModeNode["DataInitialization"].isNull())
dtsJobListObject.migrationMode.dataInitialization = migrationModeNode["DataInitialization"].asString() == "true";
if(!migrationModeNode["DataSynchronization"].isNull())
dtsJobListObject.migrationMode.dataSynchronization = migrationModeNode["DataSynchronization"].asString() == "true";
if(!migrationModeNode["StructureInitialization"].isNull())
dtsJobListObject.migrationMode.structureInitialization = migrationModeNode["StructureInitialization"].asString() == "true";
auto performanceNode = value["Performance"];
if(!performanceNode["Rps"].isNull())
dtsJobListObject.performance.rps = performanceNode["Rps"].asString();
if(!performanceNode["Flow"].isNull())
dtsJobListObject.performance.flow = performanceNode["Flow"].asString();
auto precheckStatusNode = value["PrecheckStatus"];
if(!precheckStatusNode["Status"].isNull())
dtsJobListObject.precheckStatus.status = precheckStatusNode["Status"].asString();
if(!precheckStatusNode["Percent"].isNull())
dtsJobListObject.precheckStatus.percent = precheckStatusNode["Percent"].asString();
if(!precheckStatusNode["ErrorMessage"].isNull())
dtsJobListObject.precheckStatus.errorMessage = precheckStatusNode["ErrorMessage"].asString();
auto allDetailNode = precheckStatusNode["Detail"]["PrecheckDetail"];
for (auto precheckStatusNodeDetailPrecheckDetail : allDetailNode)
{
DtsJobStatus::PrecheckStatus::PrecheckDetail precheckDetailObject;
if(!precheckStatusNodeDetailPrecheckDetail["CheckResult"].isNull())
precheckDetailObject.checkResult = precheckStatusNodeDetailPrecheckDetail["CheckResult"].asString();
if(!precheckStatusNodeDetailPrecheckDetail["CheckItemDescription"].isNull())
precheckDetailObject.checkItemDescription = precheckStatusNodeDetailPrecheckDetail["CheckItemDescription"].asString();
if(!precheckStatusNodeDetailPrecheckDetail["CheckItem"].isNull())
precheckDetailObject.checkItem = precheckStatusNodeDetailPrecheckDetail["CheckItem"].asString();
if(!precheckStatusNodeDetailPrecheckDetail["RepairMethod"].isNull())
precheckDetailObject.repairMethod = precheckStatusNodeDetailPrecheckDetail["RepairMethod"].asString();
if(!precheckStatusNodeDetailPrecheckDetail["FailedReason"].isNull())
precheckDetailObject.failedReason = precheckStatusNodeDetailPrecheckDetail["FailedReason"].asString();
dtsJobListObject.precheckStatus.detail.push_back(precheckDetailObject);
}
auto reverseJobNode = value["ReverseJob"];
if(!reverseJobNode["Status"].isNull())
dtsJobListObject.reverseJob.status = reverseJobNode["Status"].asString();
if(!reverseJobNode["DtsJobName"].isNull())
dtsJobListObject.reverseJob.dtsJobName = reverseJobNode["DtsJobName"].asString();
if(!reverseJobNode["Delay"].isNull())
dtsJobListObject.reverseJob.delay = std::stol(reverseJobNode["Delay"].asString());
if(!reverseJobNode["ErrorMessage"].isNull())
dtsJobListObject.reverseJob.errorMessage = reverseJobNode["ErrorMessage"].asString();
if(!reverseJobNode["DtsJobId"].isNull())
dtsJobListObject.reverseJob.dtsJobId = reverseJobNode["DtsJobId"].asString();
if(!reverseJobNode["ExpireTime"].isNull())
dtsJobListObject.reverseJob.expireTime = reverseJobNode["ExpireTime"].asString();
if(!reverseJobNode["CreateTime"].isNull())
dtsJobListObject.reverseJob.createTime = reverseJobNode["CreateTime"].asString();
if(!reverseJobNode["PayType"].isNull())
dtsJobListObject.reverseJob.payType = reverseJobNode["PayType"].asString();
if(!reverseJobNode["Reserved"].isNull())
dtsJobListObject.reverseJob.reserved = reverseJobNode["Reserved"].asString();
if(!reverseJobNode["DbObject"].isNull())
dtsJobListObject.reverseJob.dbObject = reverseJobNode["DbObject"].asString();
if(!reverseJobNode["DtsJobClass"].isNull())
dtsJobListObject.reverseJob.dtsJobClass = reverseJobNode["DtsJobClass"].asString();
if(!reverseJobNode["DtsInstanceID"].isNull())
dtsJobListObject.reverseJob.dtsInstanceID = reverseJobNode["DtsInstanceID"].asString();
if(!reverseJobNode["DtsJobDirection"].isNull())
dtsJobListObject.reverseJob.dtsJobDirection = reverseJobNode["DtsJobDirection"].asString();
if(!reverseJobNode["Checkpoint"].isNull())
dtsJobListObject.reverseJob.checkpoint = reverseJobNode["Checkpoint"].asString();
auto dataInitializationStatus1Node = reverseJobNode["DataInitializationStatus"];
if(!dataInitializationStatus1Node["Status"].isNull())
dtsJobListObject.reverseJob.dataInitializationStatus1.status = dataInitializationStatus1Node["Status"].asString();
if(!dataInitializationStatus1Node["Percent"].isNull())
dtsJobListObject.reverseJob.dataInitializationStatus1.percent = dataInitializationStatus1Node["Percent"].asString();
if(!dataInitializationStatus1Node["ErrorMessage"].isNull())
dtsJobListObject.reverseJob.dataInitializationStatus1.errorMessage = dataInitializationStatus1Node["ErrorMessage"].asString();
if(!dataInitializationStatus1Node["Progress"].isNull())
dtsJobListObject.reverseJob.dataInitializationStatus1.progress = dataInitializationStatus1Node["Progress"].asString();
auto dataSynchronizationStatus2Node = reverseJobNode["DataSynchronizationStatus"];
if(!dataSynchronizationStatus2Node["Status"].isNull())
dtsJobListObject.reverseJob.dataSynchronizationStatus2.status = dataSynchronizationStatus2Node["Status"].asString();
if(!dataSynchronizationStatus2Node["NeedUpgrade"].isNull())
dtsJobListObject.reverseJob.dataSynchronizationStatus2.needUpgrade = dataSynchronizationStatus2Node["NeedUpgrade"].asString() == "true";
if(!dataSynchronizationStatus2Node["Percent"].isNull())
dtsJobListObject.reverseJob.dataSynchronizationStatus2.percent = dataSynchronizationStatus2Node["Percent"].asString();
if(!dataSynchronizationStatus2Node["Progress"].isNull())
dtsJobListObject.reverseJob.dataSynchronizationStatus2.progress = dataSynchronizationStatus2Node["Progress"].asString();
if(!dataSynchronizationStatus2Node["ErrorMessage"].isNull())
dtsJobListObject.reverseJob.dataSynchronizationStatus2.errorMessage = dataSynchronizationStatus2Node["ErrorMessage"].asString();
auto destinationEndpoint3Node = reverseJobNode["DestinationEndpoint"];
if(!destinationEndpoint3Node["SslSolutionEnum"].isNull())
dtsJobListObject.reverseJob.destinationEndpoint3.sslSolutionEnum = destinationEndpoint3Node["SslSolutionEnum"].asString();
if(!destinationEndpoint3Node["OracleSID"].isNull())
dtsJobListObject.reverseJob.destinationEndpoint3.oracleSID = destinationEndpoint3Node["OracleSID"].asString();
if(!destinationEndpoint3Node["Region"].isNull())
dtsJobListObject.reverseJob.destinationEndpoint3.region = destinationEndpoint3Node["Region"].asString();
if(!destinationEndpoint3Node["DatabaseName"].isNull())
dtsJobListObject.reverseJob.destinationEndpoint3.databaseName = destinationEndpoint3Node["DatabaseName"].asString();
if(!destinationEndpoint3Node["Ip"].isNull())
dtsJobListObject.reverseJob.destinationEndpoint3.ip = destinationEndpoint3Node["Ip"].asString();
if(!destinationEndpoint3Node["InstanceID"].isNull())
dtsJobListObject.reverseJob.destinationEndpoint3.instanceID = destinationEndpoint3Node["InstanceID"].asString();
if(!destinationEndpoint3Node["Port"].isNull())
dtsJobListObject.reverseJob.destinationEndpoint3.port = destinationEndpoint3Node["Port"].asString();
if(!destinationEndpoint3Node["InstanceType"].isNull())
dtsJobListObject.reverseJob.destinationEndpoint3.instanceType = destinationEndpoint3Node["InstanceType"].asString();
if(!destinationEndpoint3Node["UserName"].isNull())
dtsJobListObject.reverseJob.destinationEndpoint3.userName = destinationEndpoint3Node["UserName"].asString();
if(!destinationEndpoint3Node["EngineName"].isNull())
dtsJobListObject.reverseJob.destinationEndpoint3.engineName = destinationEndpoint3Node["EngineName"].asString();
auto migrationMode4Node = reverseJobNode["MigrationMode"];
if(!migrationMode4Node["DataInitialization"].isNull())
dtsJobListObject.reverseJob.migrationMode4.dataInitialization = migrationMode4Node["DataInitialization"].asString() == "true";
if(!migrationMode4Node["DataSynchronization"].isNull())
dtsJobListObject.reverseJob.migrationMode4.dataSynchronization = migrationMode4Node["DataSynchronization"].asString() == "true";
if(!migrationMode4Node["StructureInitialization"].isNull())
dtsJobListObject.reverseJob.migrationMode4.structureInitialization = migrationMode4Node["StructureInitialization"].asString() == "true";
auto performance5Node = reverseJobNode["Performance"];
if(!performance5Node["Rps"].isNull())
dtsJobListObject.reverseJob.performance5.rps = performance5Node["Rps"].asString();
if(!performance5Node["Flow"].isNull())
dtsJobListObject.reverseJob.performance5.flow = performance5Node["Flow"].asString();
auto precheckStatus6Node = reverseJobNode["PrecheckStatus"];
if(!precheckStatus6Node["Status"].isNull())
dtsJobListObject.reverseJob.precheckStatus6.status = precheckStatus6Node["Status"].asString();
if(!precheckStatus6Node["Percent"].isNull())
dtsJobListObject.reverseJob.precheckStatus6.percent = precheckStatus6Node["Percent"].asString();
if(!precheckStatus6Node["ErrorMessage"].isNull())
dtsJobListObject.reverseJob.precheckStatus6.errorMessage = precheckStatus6Node["ErrorMessage"].asString();
auto allDetail9Node = precheckStatus6Node["Detail"]["PrecheckDetail"];
for (auto precheckStatus6NodeDetailPrecheckDetail : allDetail9Node)
{
DtsJobStatus::ReverseJob::PrecheckStatus6::PrecheckDetail10 precheckDetail10Object;
if(!precheckStatus6NodeDetailPrecheckDetail["CheckResult"].isNull())
precheckDetail10Object.checkResult = precheckStatus6NodeDetailPrecheckDetail["CheckResult"].asString();
if(!precheckStatus6NodeDetailPrecheckDetail["CheckItemDescription"].isNull())
precheckDetail10Object.checkItemDescription = precheckStatus6NodeDetailPrecheckDetail["CheckItemDescription"].asString();
if(!precheckStatus6NodeDetailPrecheckDetail["CheckItem"].isNull())
precheckDetail10Object.checkItem = precheckStatus6NodeDetailPrecheckDetail["CheckItem"].asString();
if(!precheckStatus6NodeDetailPrecheckDetail["RepairMethod"].isNull())
precheckDetail10Object.repairMethod = precheckStatus6NodeDetailPrecheckDetail["RepairMethod"].asString();
if(!precheckStatus6NodeDetailPrecheckDetail["FailedReason"].isNull())
precheckDetail10Object.failedReason = precheckStatus6NodeDetailPrecheckDetail["FailedReason"].asString();
dtsJobListObject.reverseJob.precheckStatus6.detail9.push_back(precheckDetail10Object);
}
auto sourceEndpoint7Node = reverseJobNode["SourceEndpoint"];
if(!sourceEndpoint7Node["SslSolutionEnum"].isNull())
dtsJobListObject.reverseJob.sourceEndpoint7.sslSolutionEnum = sourceEndpoint7Node["SslSolutionEnum"].asString();
if(!sourceEndpoint7Node["OracleSID"].isNull())
dtsJobListObject.reverseJob.sourceEndpoint7.oracleSID = sourceEndpoint7Node["OracleSID"].asString();
if(!sourceEndpoint7Node["Region"].isNull())
dtsJobListObject.reverseJob.sourceEndpoint7.region = sourceEndpoint7Node["Region"].asString();
if(!sourceEndpoint7Node["DatabaseName"].isNull())
dtsJobListObject.reverseJob.sourceEndpoint7.databaseName = sourceEndpoint7Node["DatabaseName"].asString();
if(!sourceEndpoint7Node["Ip"].isNull())
dtsJobListObject.reverseJob.sourceEndpoint7.ip = sourceEndpoint7Node["Ip"].asString();
if(!sourceEndpoint7Node["InstanceID"].isNull())
dtsJobListObject.reverseJob.sourceEndpoint7.instanceID = sourceEndpoint7Node["InstanceID"].asString();
if(!sourceEndpoint7Node["Port"].isNull())
dtsJobListObject.reverseJob.sourceEndpoint7.port = sourceEndpoint7Node["Port"].asString();
if(!sourceEndpoint7Node["InstanceType"].isNull())
dtsJobListObject.reverseJob.sourceEndpoint7.instanceType = sourceEndpoint7Node["InstanceType"].asString();
if(!sourceEndpoint7Node["UserName"].isNull())
dtsJobListObject.reverseJob.sourceEndpoint7.userName = sourceEndpoint7Node["UserName"].asString();
if(!sourceEndpoint7Node["EngineName"].isNull())
dtsJobListObject.reverseJob.sourceEndpoint7.engineName = sourceEndpoint7Node["EngineName"].asString();
auto structureInitializationStatus8Node = reverseJobNode["StructureInitializationStatus"];
if(!structureInitializationStatus8Node["Status"].isNull())
dtsJobListObject.reverseJob.structureInitializationStatus8.status = structureInitializationStatus8Node["Status"].asString();
if(!structureInitializationStatus8Node["Percent"].isNull())
dtsJobListObject.reverseJob.structureInitializationStatus8.percent = structureInitializationStatus8Node["Percent"].asString();
if(!structureInitializationStatus8Node["ErrorMessage"].isNull())
dtsJobListObject.reverseJob.structureInitializationStatus8.errorMessage = structureInitializationStatus8Node["ErrorMessage"].asString();
if(!structureInitializationStatus8Node["Progress"].isNull())
dtsJobListObject.reverseJob.structureInitializationStatus8.progress = structureInitializationStatus8Node["Progress"].asString();
auto sourceEndpointNode = value["SourceEndpoint"];
if(!sourceEndpointNode["SslSolutionEnum"].isNull())
dtsJobListObject.sourceEndpoint.sslSolutionEnum = sourceEndpointNode["SslSolutionEnum"].asString();
if(!sourceEndpointNode["OracleSID"].isNull())
dtsJobListObject.sourceEndpoint.oracleSID = sourceEndpointNode["OracleSID"].asString();
if(!sourceEndpointNode["Region"].isNull())
dtsJobListObject.sourceEndpoint.region = sourceEndpointNode["Region"].asString();
if(!sourceEndpointNode["DatabaseName"].isNull())
dtsJobListObject.sourceEndpoint.databaseName = sourceEndpointNode["DatabaseName"].asString();
if(!sourceEndpointNode["Ip"].isNull())
dtsJobListObject.sourceEndpoint.ip = sourceEndpointNode["Ip"].asString();
if(!sourceEndpointNode["InstanceID"].isNull())
dtsJobListObject.sourceEndpoint.instanceID = sourceEndpointNode["InstanceID"].asString();
if(!sourceEndpointNode["Port"].isNull())
dtsJobListObject.sourceEndpoint.port = sourceEndpointNode["Port"].asString();
if(!sourceEndpointNode["InstanceType"].isNull())
dtsJobListObject.sourceEndpoint.instanceType = sourceEndpointNode["InstanceType"].asString();
if(!sourceEndpointNode["UserName"].isNull())
dtsJobListObject.sourceEndpoint.userName = sourceEndpointNode["UserName"].asString();
if(!sourceEndpointNode["EngineName"].isNull())
dtsJobListObject.sourceEndpoint.engineName = sourceEndpointNode["EngineName"].asString();
auto structureInitializationStatusNode = value["StructureInitializationStatus"];
if(!structureInitializationStatusNode["Status"].isNull())
dtsJobListObject.structureInitializationStatus.status = structureInitializationStatusNode["Status"].asString();
if(!structureInitializationStatusNode["Percent"].isNull())
dtsJobListObject.structureInitializationStatus.percent = structureInitializationStatusNode["Percent"].asString();
if(!structureInitializationStatusNode["ErrorMessage"].isNull())
dtsJobListObject.structureInitializationStatus.errorMessage = structureInitializationStatusNode["ErrorMessage"].asString();
if(!structureInitializationStatusNode["Progress"].isNull())
dtsJobListObject.structureInitializationStatus.progress = structureInitializationStatusNode["Progress"].asString();
auto retryStateNode = value["RetryState"];
if(!retryStateNode["RetryCount"].isNull())
dtsJobListObject.retryState.retryCount = std::stoi(retryStateNode["RetryCount"].asString());
if(!retryStateNode["MaxRetryTime"].isNull())
dtsJobListObject.retryState.maxRetryTime = std::stoi(retryStateNode["MaxRetryTime"].asString());
if(!retryStateNode["ErrMessage"].isNull())
dtsJobListObject.retryState.errMessage = retryStateNode["ErrMessage"].asString();
if(!retryStateNode["RetryTarget"].isNull())
dtsJobListObject.retryState.retryTarget = retryStateNode["RetryTarget"].asString();
if(!retryStateNode["RetryTime"].isNull())
dtsJobListObject.retryState.retryTime = std::stoi(retryStateNode["RetryTime"].asString());
dtsJobList_.push_back(dtsJobListObject);
}
if(!value["HttpStatusCode"].isNull())
httpStatusCode_ = std::stoi(value["HttpStatusCode"].asString());
if(!value["ErrCode"].isNull())
errCode_ = value["ErrCode"].asString();
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["PageRecordCount"].isNull())
pageRecordCount_ = std::stoi(value["PageRecordCount"].asString());
if(!value["TotalRecordCount"].isNull())
totalRecordCount_ = std::stoi(value["TotalRecordCount"].asString());
if(!value["ErrMessage"].isNull())
errMessage_ = value["ErrMessage"].asString();
if(!value["DynamicMessage"].isNull())
dynamicMessage_ = value["DynamicMessage"].asString();
if(!value["PageNumber"].isNull())
pageNumber_ = std::stoi(value["PageNumber"].asString());
if(!value["DynamicCode"].isNull())
dynamicCode_ = value["DynamicCode"].asString();
}
int DescribeDtsJobsResult::getTotalRecordCount()const
{
return totalRecordCount_;
}
std::vector<DescribeDtsJobsResult::DtsJobStatus> DescribeDtsJobsResult::getDtsJobList()const
{
return dtsJobList_;
}
int DescribeDtsJobsResult::getPageRecordCount()const
{
return pageRecordCount_;
}
int DescribeDtsJobsResult::getPageNumber()const
{
return pageNumber_;
}
int DescribeDtsJobsResult::getHttpStatusCode()const
{
return httpStatusCode_;
}
std::string DescribeDtsJobsResult::getDynamicCode()const
{
return dynamicCode_;
}
std::string DescribeDtsJobsResult::getDynamicMessage()const
{
return dynamicMessage_;
}
std::string DescribeDtsJobsResult::getErrMessage()const
{
return errMessage_;
}
bool DescribeDtsJobsResult::getSuccess()const
{
return success_;
}
std::string DescribeDtsJobsResult::getErrCode()const
{
return errCode_;
}
| 61.841121 | 139 | 0.798549 | [
"vector",
"model"
] |
6b4127000502303fac1998df3a0f79047cb61da2 | 21,562 | cpp | C++ | gensim/src/isa/ISADescriptionParser.cpp | Linestro/Gensim_Y | 031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8 | [
"MIT"
] | 10 | 2020-07-14T22:09:30.000Z | 2022-01-11T09:57:52.000Z | gensim/src/isa/ISADescriptionParser.cpp | Linestro/Gensim_Y | 031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8 | [
"MIT"
] | 6 | 2020-07-09T12:01:57.000Z | 2021-04-27T10:23:58.000Z | gensim/src/isa/ISADescriptionParser.cpp | Linestro/Gensim_Y | 031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8 | [
"MIT"
] | 10 | 2020-07-29T17:05:26.000Z | 2021-12-04T14:57:15.000Z | /* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */
#include "isa/ISADescriptionParser.h"
#include "isa/InstructionDescriptionParser.h"
#include "isa/AsmDescriptionParser.h"
#include "isa/AsmMapDescriptionParser.h"
#include <archcasm/archcasmParser.h>
#include <archcasm/archcasmLexer.h>
#include <archCBehaviour/archCBehaviourLexer.h>
#include <archCBehaviour/archCBehaviourParser.h>
#include "clean_defines.h"
#include "define.h"
#include <archc/archcParser.h>
#include "clean_defines.h"
#include <archc/archcLexer.h>
#include <cstring>
#include <fstream>
#include <antlr3.h>
#include <antlr-ver.h>
using namespace gensim;
using namespace gensim::isa;
ISADescriptionParser::ISADescriptionParser(DiagnosticContext &diag, uint8_t isa_size) : diag(diag), isa(new ISADescription(isa_size))
{
}
bool ISADescriptionParser::ParseFile(std::string filename)
{
if(parsed_files.count(filename)) {
diag.Error("Detected recursive inclusion of " + filename, filename);
return false;
}
parsed_files.insert(filename);
std::ifstream test (filename);
if(!test.good()) {
diag.Error("Could not open file " + filename, filename);
return false;
}
pANTLR3_UINT8 fname_str = (pANTLR3_UINT8)filename.c_str();
pANTLR3_INPUT_STREAM pts = antlr3AsciiFileStreamNew(fname_str);
parchcLexer lexer = archcLexerNew(pts);
pANTLR3_COMMON_TOKEN_STREAM tstream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lexer));
parchcParser parser = archcParserNew(tstream);
archcParser_arch_isa_return arch = parser->arch_isa(parser);
if (parser->pParser->rec->getNumberOfSyntaxErrors(parser->pParser->rec) > 0 || lexer->pLexer->rec->getNumberOfSyntaxErrors(lexer->pLexer->rec)) {
diag.Error("Syntax errors detected in ISA Description", filename);
return false;
}
pANTLR3_COMMON_TREE_NODE_STREAM nodes = antlr3CommonTreeNodeStreamNewTree(arch.tree, ANTLR3_SIZE_HINT);
bool valid = load_from_node(nodes->root, filename);
// FIXME: free these safely
nodes->free(nodes);
parser->free(parser);
tstream->free(tstream);
lexer->free(lexer);
pts->free(pts);
return valid;
}
ISADescription *ISADescriptionParser::Get()
{
return isa;
}
bool ISADescriptionParser::parse_struct(pANTLR3_BASE_TREE node)
{
bool success = true;
auto struct_name_node = (pANTLR3_BASE_TREE)node->getChild(node, 0);
StructDescription sd(std::string((char*)struct_name_node->getText(struct_name_node)->chars));
for(unsigned i = 1; i < node->getChildCount(node); i += 2) {
auto entry_name_node = (pANTLR3_BASE_TREE)node->getChild(node, i+1);
auto entry_type_node = (pANTLR3_BASE_TREE)node->getChild(node, i);
std::string entry_name = std::string((char*)entry_name_node->getText(entry_name_node)->chars);
std::string entry_type = std::string((char*)entry_type_node->getText(entry_type_node)->chars);
sd.AddMember(entry_name, entry_type);
}
isa->UserStructTypes.push_back(sd);
return success;
}
bool ISADescriptionParser::load_from_node(pANTLR3_BASE_TREE node, std::string filename)
{
bool success = true;
for (uint32_t i = 0; i < node->getChildCount(node); i++) {
pANTLR3_BASE_TREE child = (pANTLR3_BASE_TREE)node->getChild(node, i);
switch (child->getType(child)) {
case AC_FETCHSIZE: {
pANTLR3_BASE_TREE sizeNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
isa->SetFetchLength(atoi((char *)(sizeNode->getText(sizeNode)->chars)));
break;
}
case AC_INCLUDE: {
assert(child->getChildCount(child) == 1);
pANTLR3_BASE_TREE filenameNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string filename = std::string((char*)filenameNode->getText(filenameNode)->chars);
filename = filename.substr(1, filename.size()-2);
success &= ParseFile(filename);
break;
}
case AC_FORMAT: {
pANTLR3_BASE_TREE nameNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
pANTLR3_BASE_TREE formatNode = (pANTLR3_BASE_TREE)child->getChild(child, 1);
// trim quotes from format string
std::string format_str = (char *)formatNode->getText(formatNode)->chars;
format_str = format_str.substr(1, format_str.length() - 2);
std::string name_str = (char *)nameNode->getText(nameNode)->chars;
InstructionFormatDescriptionParser parser (diag, *isa);
InstructionFormatDescription *fmt;
if(!parser.Parse(name_str, format_str, fmt)) {
success = false;
break;
}
if(!fmt) {
success = false;
break;
}
for(int i = 2; i < child->getChildCount(child); ++i) {
pANTLR3_BASE_TREE attrNode = (pANTLR3_BASE_TREE)child->getChild(child, i);
fmt->AddAttribute(std::string((char*)attrNode->getText(attrNode)->chars));
if(!strcmp((char*)attrNode->getText(attrNode)->chars, "notpred")) {
fmt->SetCanBePredicated(false);
}
}
if(isa->HasFormat(fmt->GetName())) {
diag.Error("Instruction format " + name_str + " already defined", DiagNode(filename, formatNode));
success = false;
} else {
isa->AddFormat(fmt);
if ((fmt->GetLength() % isa->GetFetchLength()) != 0) {
diag.Error("Instruction format " + name_str + " does not conform to ISA instruction fetch length", DiagNode(filename, formatNode));
success = false;
continue;
}
}
break;
}
case AC_ASM_MAP: {
AsmMapDescription map = AsmMapDescriptionParser::Parse(child);
isa->AddMapping(map);
break;
}
case AC_INSTR: {
pANTLR3_BASE_TREE formatNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string formatName = (char *)(formatNode->getText(formatNode)->chars);
if (isa->Formats.find(formatName) == isa->Formats.end()) {
diag.Error("Instruction specified with unknown format", DiagNode(filename, formatNode));
success = false;
continue;
}
InstructionFormatDescription *format = (isa->Formats.at(formatName));
for (uint32_t j = 1; j < child->getChildCount(child); j++) {
pANTLR3_BASE_TREE instrNode = (pANTLR3_BASE_TREE)child->getChild(child, j);
std::string instrName = (char *)(instrNode->getText(instrNode)->chars);
isa::ISADescription::InstructionDescriptionMap::const_iterator ins = isa->Instructions.find(instrName);
if (ins != isa->Instructions.end()) {
diag.Error("Duplicate instruction specified: " + instrName, DiagNode(filename, formatNode));
success = false;
continue;
}
isa->AddInstruction(new InstructionDescription(instrName, *isa, format));
}
break;
}
case AC_FIELD: {
FieldDescriptionParser parser (diag);
if(parser.Parse(child)) {
isa->UserFields.push_back(*parser.Get());
}
break;
}
case ISA_CTOR: {
success &= load_isa_from_node(child, filename);
break;
}
case AC_BEHAVIOUR: {
for (int i = 0; i < child->getChildCount(child); ++i) {
pANTLR3_BASE_TREE behaviour_node = (pANTLR3_BASE_TREE)child->getChild(child, i);
std::string behaviour_name = (char *)behaviour_node->getText(behaviour_node)->chars;
if(isa->ExecuteActionDeclared(behaviour_name)) {
diag.Error("Behaviour action " + behaviour_name + " redefined", DiagNode(filename, behaviour_node));
success = false;
} else {
isa->DeclareExecuteAction(behaviour_name);
}
}
break;
}
case AC_ID: {
isa->ISAName = std::string((const char *)child->getText(child)->chars);
break;
}
case AC_PREDICATED: {
pANTLR3_BASE_TREE value = (pANTLR3_BASE_TREE)child->getChild(child, 0);
isa->SetDefaultPredicated(strcmp((const char *)value->getText(value)->chars, "yes") == 0);
break;
}
case AC_STRUCT: {
success &= parse_struct(child);
break;
}
default:
diag.Error("Internal error: Unknown node type on line " + std::to_string(child->getLine(child)));
success = false;
break;
}
}
return success;
}
bool ISADescriptionParser::load_isa_from_node(pANTLR3_BASE_TREE node, std::string filename)
{
using util::Util;
bool success = true;
for (uint32_t i = 0; i < node->getChildCount(node); i++) {
pANTLR3_BASE_TREE child = (pANTLR3_BASE_TREE)node->getChild(node, i);
switch (child->getType(child)) {
case AC_MODIFIERS: {
pANTLR3_BASE_TREE nameNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
// printf("Loading modifiers from file %s\n", nameNode->getText(nameNode)->chars);
std::string str = (char *)nameNode->getText(nameNode)->chars;
str = str.substr(1, str.length() - 2);
isa->SetProperty("Modifiers", str);
break;
}
case AC_BEHAVIOURS: {
pANTLR3_BASE_TREE nameNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
// if (Util::Verbose_Level) printf("Loading behaviours from file %s\n", nameNode->getText(nameNode)->chars);
std::string str = (char *)nameNode->getText(nameNode)->chars;
str = str.substr(1, str.length() - 2);
isa->BehaviourFiles.push_back(str);
break;
}
case AC_DECODES: {
pANTLR3_BASE_TREE nameNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
// if (Util::Verbose_Level) printf("Loading behaviours from file %s\n", nameNode->getText(nameNode)->chars);
std::string str = (char *)nameNode->getText(nameNode)->chars;
str = str.substr(1, str.length() - 2);
// if (Util::Verbose_Level) printf("Loading behaviours from file %s\n", str.c_str());
isa->DecodeFiles.push_back(str);
break;
}
case AC_EXECUTE: {
pANTLR3_BASE_TREE nameNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
// if (Util::Verbose_Level) printf("Loading behaviours from file %s\n", nameNode->getText(nameNode)->chars);
std::string str = (char *)nameNode->getText(nameNode)->chars;
str = str.substr(1, str.length() - 2);
isa->ExecuteFiles.push_back(str);
break;
}
case SET_DECODER: {
pANTLR3_BASE_TREE instrNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string instrName = (char *)instrNode->getText(instrNode)->chars;
// if (Util::Verbose_Level) printf("Loading decode info for instruction %s\n", instrNode->getText(instrNode)->chars);
if (isa->Instructions.find(instrName) == isa->Instructions.end()) {
diag.Error("Attempting to add decode constraints to unknown instruction", DiagNode(filename, instrNode));
success = false;
continue;
} else {
isa->instructions_.at(instrName)->bitStringsCalculated = false;
if(!InstructionDescriptionParser::load_constraints_from_node(child, isa->instructions_.at(instrName)->Decode_Constraints))
success = false;
}
break;
}
case SET_EOB: {
pANTLR3_BASE_TREE instrNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string instrName = (char *)instrNode->getText(instrNode)->chars;
// if (Util::Verbose_Level) printf("Loading decode info for instruction %s\n", instrNode->getText(instrNode)->chars);
if (isa->Instructions.find(instrName) == isa->Instructions.end()) {
diag.Error("Attempting to add end of block constraint to unknown instruction " + instrName, DiagNode(filename, instrNode));
success = false;
} else {
isa->instructions_.at(instrName)->bitStringsCalculated = false;
if(!InstructionDescriptionParser::load_constraints_from_node(child, isa->instructions_.at(instrName)->EOB_Contraints))
success = false;
}
break;
}
case SET_USES_PC: {
pANTLR3_BASE_TREE instrNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string instrName = (char *)instrNode->getText(instrNode)->chars;
// if (Util::Verbose_Level) printf("Loading decode info for instruction %s\n", instrNode->getText(instrNode)->chars);
if (isa->Instructions.find(instrName) == isa->Instructions.end()) {
diag.Error("Attempting to add Uses-PC constraint to unknown instruction", DiagNode(filename, instrNode));
success = false;
} else {
isa->instructions_.at(instrName)->bitStringsCalculated = false;
if(!InstructionDescriptionParser::load_constraints_from_node(child, isa->instructions_.at(instrName)->Uses_PC_Constraints))
success = false;
}
break;
}
case SET_JUMP_FIXED:
case SET_JUMP_FIXED_PREDICATED: {
pANTLR3_BASE_TREE instrNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string instrName = (char *)instrNode->getText(instrNode)->chars;
// if (Util::Verbose_Level) printf("Loading jump info for instruction %s\n", instrNode->getText(instrNode)->chars);
if (isa->Instructions.find(instrName) == isa->Instructions.end()) {
diag.Error("Attempting to add jump info to unknown instruction", DiagNode(filename, instrNode));
success = false;
} else {
pANTLR3_BASE_TREE fieldNode = (pANTLR3_BASE_TREE)child->getChild(child, 1);
InstructionDescription *instr = isa->instructions_.at(instrName);
instr->FixedJumpField = std::string((char *)fieldNode->getText(fieldNode)->chars);
if (child->getType(child) == SET_JUMP_FIXED) {
instr->FixedJump = true;
instr->FixedJumpPred = false;
} else {
instr->FixedJump = false;
instr->FixedJumpPred = true;
}
pANTLR3_BASE_TREE typeNode = (pANTLR3_BASE_TREE)child->getChild(child, 2);
if (typeNode->getType(typeNode) == RELATIVE)
instr->FixedJumpType = 1;
else
instr->FixedJumpType = 0;
if (child->getChildCount(child) > 3) {
pANTLR3_BASE_TREE offsetNode = (pANTLR3_BASE_TREE)child->getChild(child, 3);
instr->FixedJumpOffset = atoi((char *)(offsetNode->getText(offsetNode)->chars));
}
}
break;
}
case SET_JUMP_VARIABLE: {
pANTLR3_BASE_TREE instrNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string instrName = (char *)instrNode->getText(instrNode)->chars;
// if (Util::Verbose_Level) printf("Loading jump info for instruction %s\n", instrNode->getText(instrNode)->chars);
if (isa->Instructions.find(instrName) == isa->Instructions.end()) {
diag.Error("Attempting to add jump info to unknown instruction", DiagNode(filename, instrNode));
success = false;
} else {
InstructionDescription *instr = isa->instructions_.at(instrName);
instr->VariableJump = true;
}
break;
}
case SET_BLOCK_COND: {
pANTLR3_BASE_TREE instrNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string instrName = (char *)instrNode->getText(instrNode)->chars;
if (isa->Instructions.find(instrName) == isa->Instructions.end()) {
diag.Error("Attempting to add conditional block instruction info to unknown instruction", DiagNode(filename, instrNode));
success = false;
} else {
InstructionDescription *instr = isa->instructions_.at(instrName);
instr->blockCond = true;
}
break;
}
case SET_ASM: {
pANTLR3_BASE_TREE instrNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string instrName = (char *)instrNode->getText(instrNode)->chars;
// if (Util::Verbose_Level) printf("Loading disasm info for instruction %s\n", instrNode->getText(instrNode)->chars);
if (isa->Instructions.find(instrName) == isa->Instructions.end()) {
diag.Error("Attempting to add disasm info to unknown instruction", DiagNode(filename, instrNode));
success = false;
} else {
AsmDescriptionParser asm_parser (diag, filename);
if(!asm_parser.Parse(child, *isa)) break;
isa->instructions_[instrName]->Disasms.push_back(asm_parser.Get());
}
break;
}
case SET_BEHAVIOUR: {
pANTLR3_BASE_TREE instrNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
pANTLR3_BASE_TREE behaviourNode = (pANTLR3_BASE_TREE)child->getChild(child, 1);
std::string instrName = (char *)instrNode->getText(instrNode)->chars;
std::string behaviourName = (char *)behaviourNode->getText(behaviourNode)->chars;
if (isa->Instructions.find(instrName) == isa->Instructions.end()) {
diag.Error("Attempted to add behaviour to unknown instruction " + instrName, DiagNode(filename, child));
success = false;
} else {
if(!isa->ExecuteActionDeclared(behaviourName)) {
diag.Error("Attempted to add unknown behaviour " + behaviourName + " to instruction", DiagNode(filename, child));
success = false;
} else {
isa->SetBehaviour(instrName, behaviourName);
}
}
break;
}
case SET_HAS_LIMM: {
pANTLR3_BASE_TREE instrNode = (pANTLR3_BASE_TREE)child->getChild(child, 0);
pANTLR3_BASE_TREE limmLengthNode = (pANTLR3_BASE_TREE)child->getChild(child, 1);
std::string instrName = (char *)instrNode->getText(instrNode)->chars;
int limmLength = atoi((char *)limmLengthNode->getText(limmLengthNode)->chars);
if (isa->Instructions.find(instrName) == isa->Instructions.end()) {
// fprintf(stderr, "Attempting to set limm for unknown instruction %s (Line %u)\n", instrName.c_str(), instrNode->getLine(instrNode));
success = false;
}
if (success) {
InstructionDescription *inst = isa->instructions_[instrName];
inst->LimmCount = limmLength;
}
break;
}
}
}
isa->CleanupBehaviours();
// printf("Loading behaviours...\n");
success &= load_behaviours();
return success;
}
bool ISADescriptionParser::load_behaviour_file(std::string filename)
{
bool success = true;
std::ifstream _check_file(filename.c_str());
if (!_check_file) {
std::cerr << "Could not find behaviour file " << filename << std::endl;
return false;
}
if(loaded_files.count(filename)) return true;
loaded_files.insert(filename);
// printf("Parsing behaviour file %s\n", filename.c_str());
pANTLR3_UINT8 fname_str = (pANTLR3_UINT8)filename.c_str();
pANTLR3_INPUT_STREAM pts = antlr3AsciiFileStreamNew(fname_str);
parchCBehaviourLexer lexer = archCBehaviourLexerNew(pts);
pANTLR3_COMMON_TOKEN_STREAM tstream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lexer));
parchCBehaviourParser parser = archCBehaviourParserNew(tstream);
archCBehaviourParser_behaviour_file_return arch = parser->behaviour_file(parser);
pANTLR3_COMMON_TREE_NODE_STREAM nodes = antlr3CommonTreeNodeStreamNewTree(arch.tree, ANTLR3_SIZE_HINT);
pANTLR3_BASE_TREE behaviourTree = nodes->root;
for (uint32_t behaviourIndex = 0; behaviourIndex < behaviourTree->getChildCount(behaviourTree); behaviourIndex++) {
pANTLR3_BASE_TREE child = (pANTLR3_BASE_TREE)behaviourTree->getChild(behaviourTree, behaviourIndex);
switch (child->getType(child)) {
case BE_DECODE: {
pANTLR3_BASE_TREE nameChild = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string format = (char *)nameChild->getText(nameChild)->chars;
pANTLR3_BASE_TREE codeChild = (pANTLR3_BASE_TREE)child->getChild(child, 1);
std::string code = (char *)codeChild->getText(codeChild)->chars;
if (isa->Formats.find(format) != isa->Formats.end())
isa->formats_[format]->DecodeBehaviourCode = code;
else {
std::cerr << "Attempted to assign a behaviour string to a non-existant decode type " << format << "(Line " << child->getLine(child) << ")" << std::endl;
success = false;
}
break;
}
case BE_EXECUTE: {
pANTLR3_BASE_TREE nameChild = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string format = (char *)nameChild->getText(nameChild)->chars;
pANTLR3_BASE_TREE codeChild = (pANTLR3_BASE_TREE)child->getChild(child, 1);
std::string code = (char *)codeChild->getText(codeChild)->chars;
// if (ExecuteActions.find(format) != ExecuteActions.end())
if(!isa->ExecuteActionDeclared(format)) {
diag.Error("Adding behaviour to unknown execute action " + format, DiagNode(filename, nameChild));
success = false;
} else {
isa->AddExecuteAction(format, code);
}
// else
//{
// std::cerr << "Attempted to assign a behaviour string to an unknown behaviour " << format << std::endl;
// success = false;
//}
break;
}
case BE_BEHAVIOUR: {
pANTLR3_BASE_TREE nameChild = (pANTLR3_BASE_TREE)child->getChild(child, 0);
std::string name = (char *)nameChild->getText(nameChild)->chars;
pANTLR3_BASE_TREE codeChild = (pANTLR3_BASE_TREE)child->getChild(child, 1);
std::string code = (char *)codeChild->getText(codeChild)->chars;
isa->AddBehaviourAction(name, code);
break;
}
case BE_HELPER: {
pANTLR3_BASE_TREE prototypeChild = (pANTLR3_BASE_TREE)child->getChild(child, 0);
pANTLR3_BASE_TREE bodyChild = (pANTLR3_BASE_TREE)child->getChild(child, 1);
std::string prototype;
for (uint32_t i = 0; i < prototypeChild->getChildCount(prototypeChild); ++i) {
pANTLR3_BASE_TREE node = (pANTLR3_BASE_TREE)prototypeChild->getChild(prototypeChild, i);
prototype.append((char *)node->getText(node)->chars);
prototype.append(" ");
}
std::string body = (char *)bodyChild->getText(bodyChild)->chars;
if (util::Util::Verbose_Level) std::cout << "Loading helper function " << prototype << std::endl;
isa->AddHelperFn(prototype, body);
break;
}
}
}
// FIXME: free these safely
nodes->free(nodes);
parser->free(parser);
tstream->free(tstream);
lexer->free(lexer);
pts->free(pts);
return success;
}
bool ISADescriptionParser::load_behaviours()
{
bool success = true;
for (std::vector<std::string>::iterator ci = isa->BehaviourFiles.begin(); ci != isa->BehaviourFiles.end(); ++ci) success &= load_behaviour_file(*ci);
for (std::vector<std::string>::iterator ci = isa->DecodeFiles.begin(); ci != isa->DecodeFiles.end(); ++ci) success &= load_behaviour_file(*ci);
for (std::vector<std::string>::iterator ci = isa->ExecuteFiles.begin(); ci != isa->ExecuteFiles.end(); ++ci) success &= load_behaviour_file(*ci);
return success;
}
| 36.360877 | 157 | 0.699008 | [
"vector"
] |
6b4f5769e5b1e768a8f3909f95802caf2ee2dc8c | 17,644 | cpp | C++ | samples/cpp/tutorial_code/gapi/age_gender_emotion_recognition/age_gender_emotion_recognition.cpp | thisisgopalmandal/opencv | 4e2ef8c8f57644ccb8e762a37f70a61007c6be1c | [
"BSD-3-Clause"
] | 56,632 | 2016-07-04T16:36:08.000Z | 2022-03-31T18:38:14.000Z | samples/cpp/tutorial_code/gapi/age_gender_emotion_recognition/age_gender_emotion_recognition.cpp | thisisgopalmandal/opencv | 4e2ef8c8f57644ccb8e762a37f70a61007c6be1c | [
"BSD-3-Clause"
] | 13,593 | 2016-07-04T13:59:03.000Z | 2022-03-31T21:04:51.000Z | samples/cpp/tutorial_code/gapi/age_gender_emotion_recognition/age_gender_emotion_recognition.cpp | thisisgopalmandal/opencv | 4e2ef8c8f57644ccb8e762a37f70a61007c6be1c | [
"BSD-3-Clause"
] | 54,986 | 2016-07-04T14:24:38.000Z | 2022-03-31T22:51:18.000Z | #include "opencv2/opencv_modules.hpp"
#if defined(HAVE_OPENCV_GAPI)
#include <chrono>
#include <iomanip>
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/gapi.hpp"
#include "opencv2/gapi/core.hpp"
#include "opencv2/gapi/imgproc.hpp"
#include "opencv2/gapi/infer.hpp"
#include "opencv2/gapi/infer/ie.hpp"
#include "opencv2/gapi/cpu/gcpukernel.hpp"
#include "opencv2/gapi/streaming/cap.hpp"
namespace {
const std::string about =
"This is an OpenCV-based version of Security Barrier Camera example";
const std::string keys =
"{ h help | | print this help message }"
"{ input | | Path to an input video file }"
"{ fdm | | IE face detection model IR }"
"{ fdw | | IE face detection model weights }"
"{ fdd | | IE face detection device }"
"{ agem | | IE age/gender recognition model IR }"
"{ agew | | IE age/gender recognition model weights }"
"{ aged | | IE age/gender recognition model device }"
"{ emom | | IE emotions recognition model IR }"
"{ emow | | IE emotions recognition model weights }"
"{ emod | | IE emotions recognition model device }"
"{ pure | | When set, no output is displayed. Useful for benchmarking }"
"{ ser | | Run serially (no pipelining involved). Useful for benchmarking }";
struct Avg {
struct Elapsed {
explicit Elapsed(double ms) : ss(ms/1000.), mm(static_cast<int>(ss)/60) {}
const double ss;
const int mm;
};
using MS = std::chrono::duration<double, std::ratio<1, 1000>>;
using TS = std::chrono::time_point<std::chrono::high_resolution_clock>;
TS started;
void start() { started = now(); }
TS now() const { return std::chrono::high_resolution_clock::now(); }
double tick() const { return std::chrono::duration_cast<MS>(now() - started).count(); }
Elapsed elapsed() const { return Elapsed{tick()}; }
double fps(std::size_t n) const { return static_cast<double>(n) / (tick() / 1000.); }
};
std::ostream& operator<<(std::ostream &os, const Avg::Elapsed &e) {
os << e.mm << ':' << (e.ss - 60*e.mm);
return os;
}
} // namespace
namespace custom {
// Describe networks we use in our program.
// In G-API, topologies act like "operations". Here we define our
// topologies as operations which have inputs and outputs.
// Every network requires three parameters to define:
// 1) Network's TYPE name - this TYPE is then used as a template
// parameter to generic functions like cv::gapi::infer<>(),
// and is used to define network's configuration (per-backend).
// 2) Network's SIGNATURE - a std::function<>-like record which defines
// networks' input and output parameters (its API)
// 3) Network's IDENTIFIER - a string defining what the network is.
// Must be unique within the pipeline.
// Note: these definitions are neutral to _how_ the networks are
// executed. The _how_ is defined at graph compilation stage (via parameters),
// not on the graph construction stage.
//! [G_API_NET]
// Face detector: takes one Mat, returns another Mat
G_API_NET(Faces, <cv::GMat(cv::GMat)>, "face-detector");
// Age/Gender recognition - takes one Mat, returns two:
// one for Age and one for Gender. In G-API, multiple-return-value operations
// are defined using std::tuple<>.
using AGInfo = std::tuple<cv::GMat, cv::GMat>;
G_API_NET(AgeGender, <AGInfo(cv::GMat)>, "age-gender-recoginition");
// Emotion recognition - takes one Mat, returns another.
G_API_NET(Emotions, <cv::GMat(cv::GMat)>, "emotions-recognition");
//! [G_API_NET]
//! [Postproc]
// SSD Post-processing function - this is not a network but a kernel.
// The kernel body is declared separately, this is just an interface.
// This operation takes two Mats (detections and the source image),
// and returns a vector of ROI (filtered by a default threshold).
// Threshold (or a class to select) may become a parameter, but since
// this kernel is custom, it doesn't make a lot of sense.
G_API_OP(PostProc, <cv::GArray<cv::Rect>(cv::GMat, cv::GMat)>, "custom.fd_postproc") {
static cv::GArrayDesc outMeta(const cv::GMatDesc &, const cv::GMatDesc &) {
// This function is required for G-API engine to figure out
// what the output format is, given the input parameters.
// Since the output is an array (with a specific type),
// there's nothing to describe.
return cv::empty_array_desc();
}
};
// OpenCV-based implementation of the above kernel.
GAPI_OCV_KERNEL(OCVPostProc, PostProc) {
static void run(const cv::Mat &in_ssd_result,
const cv::Mat &in_frame,
std::vector<cv::Rect> &out_faces) {
const int MAX_PROPOSALS = 200;
const int OBJECT_SIZE = 7;
const cv::Size upscale = in_frame.size();
const cv::Rect surface({0,0}, upscale);
out_faces.clear();
const float *data = in_ssd_result.ptr<float>();
for (int i = 0; i < MAX_PROPOSALS; i++) {
const float image_id = data[i * OBJECT_SIZE + 0]; // batch id
const float confidence = data[i * OBJECT_SIZE + 2];
const float rc_left = data[i * OBJECT_SIZE + 3];
const float rc_top = data[i * OBJECT_SIZE + 4];
const float rc_right = data[i * OBJECT_SIZE + 5];
const float rc_bottom = data[i * OBJECT_SIZE + 6];
if (image_id < 0.f) { // indicates end of detections
break;
}
if (confidence < 0.5f) { // a hard-coded snapshot
continue;
}
// Convert floating-point coordinates to the absolute image
// frame coordinates; clip by the source image boundaries.
cv::Rect rc;
rc.x = static_cast<int>(rc_left * upscale.width);
rc.y = static_cast<int>(rc_top * upscale.height);
rc.width = static_cast<int>(rc_right * upscale.width) - rc.x;
rc.height = static_cast<int>(rc_bottom * upscale.height) - rc.y;
out_faces.push_back(rc & surface);
}
}
};
//! [Postproc]
} // namespace custom
namespace labels {
const std::string genders[] = {
"Female", "Male"
};
const std::string emotions[] = {
"neutral", "happy", "sad", "surprise", "anger"
};
namespace {
void DrawResults(cv::Mat &frame,
const std::vector<cv::Rect> &faces,
const std::vector<cv::Mat> &out_ages,
const std::vector<cv::Mat> &out_genders,
const std::vector<cv::Mat> &out_emotions) {
CV_Assert(faces.size() == out_ages.size());
CV_Assert(faces.size() == out_genders.size());
CV_Assert(faces.size() == out_emotions.size());
for (auto it = faces.begin(); it != faces.end(); ++it) {
const auto idx = std::distance(faces.begin(), it);
const auto &rc = *it;
const float *ages_data = out_ages[idx].ptr<float>();
const float *genders_data = out_genders[idx].ptr<float>();
const float *emotions_data = out_emotions[idx].ptr<float>();
const auto gen_id = std::max_element(genders_data, genders_data + 2) - genders_data;
const auto emo_id = std::max_element(emotions_data, emotions_data + 5) - emotions_data;
std::stringstream ss;
ss << static_cast<int>(ages_data[0]*100)
<< ' '
<< genders[gen_id]
<< ' '
<< emotions[emo_id];
const int ATTRIB_OFFSET = 15;
cv::rectangle(frame, rc, {0, 255, 0}, 4);
cv::putText(frame, ss.str(),
cv::Point(rc.x, rc.y - ATTRIB_OFFSET),
cv::FONT_HERSHEY_COMPLEX_SMALL,
1,
cv::Scalar(0, 0, 255));
}
}
void DrawFPS(cv::Mat &frame, std::size_t n, double fps) {
std::ostringstream out;
out << "FRAME " << n << ": "
<< std::fixed << std::setprecision(2) << fps
<< " FPS (AVG)";
cv::putText(frame, out.str(),
cv::Point(0, frame.rows),
cv::FONT_HERSHEY_SIMPLEX,
1,
cv::Scalar(0, 255, 0),
2);
}
} // anonymous namespace
} // namespace labels
int main(int argc, char *argv[])
{
cv::CommandLineParser cmd(argc, argv, keys);
cmd.about(about);
if (cmd.has("help")) {
cmd.printMessage();
return 0;
}
const std::string input = cmd.get<std::string>("input");
const bool no_show = cmd.get<bool>("pure");
const bool be_serial = cmd.get<bool>("ser");
// Express our processing pipeline. Lambda-based constructor
// is used to keep all temporary objects in a dedicated scope.
//! [GComputation]
cv::GComputation pp([]() {
// Declare an empty GMat - the beginning of the pipeline.
cv::GMat in;
// Run face detection on the input frame. Result is a single GMat,
// internally representing an 1x1x200x7 SSD output.
// This is a single-patch version of infer:
// - Inference is running on the whole input image;
// - Image is converted and resized to the network's expected format
// automatically.
cv::GMat detections = cv::gapi::infer<custom::Faces>(in);
// Parse SSD output to a list of ROI (rectangles) using
// a custom kernel. Note: parsing SSD may become a "standard" kernel.
cv::GArray<cv::Rect> faces = custom::PostProc::on(detections, in);
// Now run Age/Gender model on every detected face. This model has two
// outputs (for age and gender respectively).
// A special ROI-list-oriented form of infer<>() is used here:
// - First input argument is the list of rectangles to process,
// - Second one is the image where to take ROI from;
// - Crop/Resize/Layout conversion happens automatically for every image patch
// from the list
// - Inference results are also returned in form of list (GArray<>)
// - Since there're two outputs, infer<> return two arrays (via std::tuple).
cv::GArray<cv::GMat> ages;
cv::GArray<cv::GMat> genders;
std::tie(ages, genders) = cv::gapi::infer<custom::AgeGender>(faces, in);
// Recognize emotions on every face.
// ROI-list-oriented infer<>() is used here as well.
// Since custom::Emotions network produce a single output, only one
// GArray<> is returned here.
cv::GArray<cv::GMat> emotions = cv::gapi::infer<custom::Emotions>(faces, in);
// Return the decoded frame as a result as well.
// Input matrix can't be specified as output one, so use copy() here
// (this copy will be optimized out in the future).
cv::GMat frame = cv::gapi::copy(in);
// Now specify the computation's boundaries - our pipeline consumes
// one images and produces five outputs.
return cv::GComputation(cv::GIn(in),
cv::GOut(frame, faces, ages, genders, emotions));
});
//! [GComputation]
// Note: it might be very useful to have dimensions loaded at this point!
// After our computation is defined, specify how it should be executed.
// Execution is defined by inference backends and kernel backends we use to
// compile the pipeline (it is a different step).
// Declare IE parameters for FaceDetection network. Note here custom::Face
// is the type name we specified in GAPI_NETWORK() previously.
// cv::gapi::ie::Params<> is a generic configuration description which is
// specialized to every particular network we use.
//
// OpenCV DNN backend will have its own parmater structure with settings
// relevant to OpenCV DNN module. Same applies to other possible inference
// backends...
//! [Param_Cfg]
auto det_net = cv::gapi::ie::Params<custom::Faces> {
cmd.get<std::string>("fdm"), // read cmd args: path to topology IR
cmd.get<std::string>("fdw"), // read cmd args: path to weights
cmd.get<std::string>("fdd"), // read cmd args: device specifier
};
auto age_net = cv::gapi::ie::Params<custom::AgeGender> {
cmd.get<std::string>("agem"), // read cmd args: path to topology IR
cmd.get<std::string>("agew"), // read cmd args: path to weights
cmd.get<std::string>("aged"), // read cmd args: device specifier
}.cfgOutputLayers({ "age_conv3", "prob" });
auto emo_net = cv::gapi::ie::Params<custom::Emotions> {
cmd.get<std::string>("emom"), // read cmd args: path to topology IR
cmd.get<std::string>("emow"), // read cmd args: path to weights
cmd.get<std::string>("emod"), // read cmd args: device specifier
};
//! [Param_Cfg]
//! [Compile]
// Form a kernel package (with a single OpenCV-based implementation of our
// post-processing) and a network package (holding our three networks).
auto kernels = cv::gapi::kernels<custom::OCVPostProc>();
auto networks = cv::gapi::networks(det_net, age_net, emo_net);
// Compile our pipeline and pass our kernels & networks as
// parameters. This is the place where G-API learns which
// networks & kernels we're actually operating with (the graph
// description itself known nothing about that).
auto cc = pp.compileStreaming(cv::compile_args(kernels, networks));
//! [Compile]
Avg avg;
std::size_t frames = 0u; // Frame counter (not produced by the graph)
std::cout << "Reading " << input << std::endl;
// Duplicate huge portions of the code in if/else branches in the sake of
// better documentation snippets
if (!be_serial) {
//! [Source]
auto in_src = cv::gapi::wip::make_src<cv::gapi::wip::GCaptureSource>(input);
cc.setSource(cv::gin(in_src));
//! [Source]
avg.start();
//! [Run]
// After data source is specified, start the execution
cc.start();
// Declare data objects we will be receiving from the pipeline.
cv::Mat frame; // The captured frame itself
std::vector<cv::Rect> faces; // Array of detected faces
std::vector<cv::Mat> out_ages; // Array of inferred ages (one blob per face)
std::vector<cv::Mat> out_genders; // Array of inferred genders (one blob per face)
std::vector<cv::Mat> out_emotions; // Array of classified emotions (one blob per face)
// Implement different execution policies depending on the display option
// for the best performance.
while (cc.running()) {
auto out_vector = cv::gout(frame, faces, out_ages, out_genders, out_emotions);
if (no_show) {
// This is purely a video processing. No need to balance
// with UI rendering. Use a blocking pull() to obtain
// data. Break the loop if the stream is over.
if (!cc.pull(std::move(out_vector)))
break;
} else if (!cc.try_pull(std::move(out_vector))) {
// Use a non-blocking try_pull() to obtain data.
// If there's no data, let UI refresh (and handle keypress)
if (cv::waitKey(1) >= 0) break;
else continue;
}
// At this point we have data for sure (obtained in either
// blocking or non-blocking way).
frames++;
labels::DrawResults(frame, faces, out_ages, out_genders, out_emotions);
labels::DrawFPS(frame, frames, avg.fps(frames));
if (!no_show) cv::imshow("Out", frame);
}
//! [Run]
} else { // (serial flag)
//! [Run_Serial]
cv::VideoCapture cap(input);
cv::Mat in_frame, frame; // The captured frame itself
std::vector<cv::Rect> faces; // Array of detected faces
std::vector<cv::Mat> out_ages; // Array of inferred ages (one blob per face)
std::vector<cv::Mat> out_genders; // Array of inferred genders (one blob per face)
std::vector<cv::Mat> out_emotions; // Array of classified emotions (one blob per face)
while (cap.read(in_frame)) {
pp.apply(cv::gin(in_frame),
cv::gout(frame, faces, out_ages, out_genders, out_emotions),
cv::compile_args(kernels, networks));
labels::DrawResults(frame, faces, out_ages, out_genders, out_emotions);
frames++;
if (frames == 1u) {
// Start timer only after 1st frame processed -- compilation
// happens on-the-fly here
avg.start();
} else {
// Measurfe & draw FPS for all other frames
labels::DrawFPS(frame, frames, avg.fps(frames-1));
}
if (!no_show) {
cv::imshow("Out", frame);
if (cv::waitKey(1) >= 0) break;
}
}
//! [Run_Serial]
}
std::cout << "Processed " << frames << " frames in " << avg.elapsed()
<< " (" << avg.fps(frames) << " FPS)" << std::endl;
return 0;
}
#else
#include <iostream>
int main()
{
std::cerr << "This tutorial code requires G-API module "
"with Inference Engine backend to run"
<< std::endl;
return 1;
}
#endif // HAVE_OPECV_GAPI
| 42.92944 | 95 | 0.596577 | [
"vector",
"model"
] |
6b51f4f353bf7d200fa54e27e8a1b4d391137857 | 9,419 | cpp | C++ | src/Optimize/VariableSet.cpp | djstaros/qmcpack | 280f67e638bae280448b47fa618f05b848c530d2 | [
"NCSA"
] | null | null | null | src/Optimize/VariableSet.cpp | djstaros/qmcpack | 280f67e638bae280448b47fa618f05b848c530d2 | [
"NCSA"
] | null | null | null | src/Optimize/VariableSet.cpp | djstaros/qmcpack | 280f67e638bae280448b47fa618f05b848c530d2 | [
"NCSA"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
// Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign
// Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory
//
// File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
//////////////////////////////////////////////////////////////////////////////////////
#include "Optimize/VariableSet.h"
#include <map>
#include <stdexcept>
#include <iomanip>
#include <ios>
#include <algorithm>
using std::setw;
namespace optimize
{
// VariableSet::VariableSet(variable_map_type& input):num_active_vars(0)
// {
// Index.resize(input.size(),-1);
// NameAndValue.resize(input.size());
// copy(input.begin(),input.end(),NameAndValue.begin());
// for(int i=0; i<Index.size(); ++i) Index[i]=i;
//
// ParameterType.resize(0); Recompute.resize(0);
// for(int i=0; i<Index.size(); ++i) ParameterType.push_back(index_pair_type(NameAndValue[i].first,0));
// for(int i=0; i<Index.size(); ++i) Recompute.push_back(index_pair_type(NameAndValue[i].first,1));
// }
void VariableSet::clear()
{
num_active_vars = 0;
Index.clear();
NameAndValue.clear();
Recompute.clear();
ParameterType.clear();
}
/** insert name-value pairs of this object to output
* @param output parameters to be added
*/
// void VariableSet::insertTo(variable_map_type& output) const
// {
// for(int i=0; i<Index.size(); ++i)
// {
// if(Index[i]>-1)
// {
// output[NameAndValue[i].first]=NameAndValue[i].second;
// output[Recompute[i].first]=Recompute[i].second;
// output[ParameterType[i].first]=ParameterType[i].second;
// }
// }
// }
void VariableSet::insertFrom(const VariableSet& input)
{
for (int i = 0; i < input.size(); ++i)
{
iterator loc = find(input.name(i));
if (loc == NameAndValue.end())
{
Index.push_back(input.Index[i]);
NameAndValue.push_back(input.NameAndValue[i]);
ParameterType.push_back(input.ParameterType[i]);
Recompute.push_back(input.Recompute[i]);
}
else
(*loc).second = input.NameAndValue[i].second;
}
num_active_vars = input.num_active_vars;
}
void VariableSet::insertFromSum(const VariableSet& input_1, const VariableSet& input_2)
{
value_type sum_val;
std::string vname;
// Check that objects to be summed together have the same number of active
// variables.
if (input_1.num_active_vars != input_2.num_active_vars)
throw std::runtime_error("Inconsistent number of parameters in two provided "
"variable sets.");
for (int i = 0; i < input_1.size(); ++i)
{
// Check that each of the equivalent variables in both VariableSet objects
// have the same name - otherwise we certainly shouldn't be adding them.
if (input_1.NameAndValue[i].first != input_2.NameAndValue[i].first)
throw std::runtime_error("Inconsistent parameters exist in the two provided "
"variable sets.");
sum_val = input_1.NameAndValue[i].second + input_2.NameAndValue[i].second;
iterator loc = find(input_1.name(i));
if (loc == NameAndValue.end())
{
Index.push_back(input_1.Index[i]);
ParameterType.push_back(input_1.ParameterType[i]);
Recompute.push_back(input_1.Recompute[i]);
// We can reuse the above values, which aren't summed between the
// objects, but the parameter values themselves need to use the summed
// values.
vname = input_1.NameAndValue[i].first;
NameAndValue.push_back(pair_type(vname, sum_val));
}
else
(*loc).second = sum_val;
}
num_active_vars = input_1.num_active_vars;
}
void VariableSet::insertFromDiff(const VariableSet& input_1, const VariableSet& input_2)
{
value_type diff_val;
std::string vname;
// Check that objects to be subtracted have the same number of active
// variables.
if (input_1.num_active_vars != input_2.num_active_vars)
throw std::runtime_error("Inconsistent number of parameters in two provided "
"variable sets.");
for (int i = 0; i < input_1.size(); ++i)
{
// Check that each of the equivalent variables in both VariableSet objects
// have the same name - otherwise we certainly shouldn't be subtracting them.
if (input_1.NameAndValue[i].first != input_2.NameAndValue[i].first)
throw std::runtime_error("Inconsistent parameters exist in the two provided "
"variable sets.");
diff_val = input_1.NameAndValue[i].second - input_2.NameAndValue[i].second;
iterator loc = find(input_1.name(i));
if (loc == NameAndValue.end())
{
Index.push_back(input_1.Index[i]);
ParameterType.push_back(input_1.ParameterType[i]);
Recompute.push_back(input_1.Recompute[i]);
// We can reuse the above values, which aren't subtracted between the
// objects, but the parameter values themselves need to use the
// subtracted values.
vname = input_1.NameAndValue[i].first;
NameAndValue.push_back(pair_type(vname, diff_val));
}
else
(*loc).second = diff_val;
}
num_active_vars = input_1.num_active_vars;
}
void VariableSet::activate(const variable_map_type& selected)
{
//activate the variables
variable_map_type::const_iterator it(selected.begin()), it_end(selected.end());
while (it != it_end)
{
iterator loc = find((*it++).first);
if (loc != NameAndValue.end())
{
int i = loc - NameAndValue.begin();
if (Index[i] < 0)
Index[i] = num_active_vars++;
}
}
}
void VariableSet::disable(const variable_map_type& selected)
{
variable_map_type::const_iterator it(selected.begin()), it_end(selected.end());
while (it != it_end)
{
int loc = find((*it++).first) - NameAndValue.begin();
if (loc < NameAndValue.size())
Index[loc] = -1;
}
}
void VariableSet::removeInactive()
{
std::vector<int> valid(Index);
std::vector<pair_type> acopy(NameAndValue);
std::vector<index_pair_type> bcopy(Recompute), ccopy(ParameterType);
num_active_vars = 0;
Index.clear();
NameAndValue.clear();
Recompute.clear();
ParameterType.clear();
for (int i = 0; i < valid.size(); ++i)
{
if (valid[i] > -1)
{
Index.push_back(num_active_vars++);
NameAndValue.push_back(acopy[i]);
Recompute.push_back(bcopy[i]);
ParameterType.push_back(ccopy[i]);
}
}
}
void VariableSet::resetIndex()
{
num_active_vars = 0;
for (int i = 0; i < Index.size(); ++i)
{
Index[i] = (Index[i] < 0) ? -1 : num_active_vars++;
}
}
void VariableSet::getIndex(const VariableSet& selected)
{
for (int i = 0; i < NameAndValue.size(); ++i)
{
Index[i] = selected.getIndex(NameAndValue[i].first);
if (Index[i] >= 0)
num_active_vars++;
}
}
void VariableSet::setDefaults(bool optimize_all)
{
for (int i = 0; i < Index.size(); ++i)
Index[i] = optimize_all ? i : -1;
}
void VariableSet::print(std::ostream& os, int leftPadSpaces, bool printHeader)
{
std::string pad_str = std::string(leftPadSpaces, ' ');
int max_name_len = 0;
max_name_len =
std::max_element(NameAndValue.begin(), NameAndValue.end(),
[](const pair_type& e1, const pair_type& e2) { return e1.first.length() < e2.first.length(); })
->first.length();
int max_value_len = 28; // 6 for the precision and 7 for minus sign, leading value, period, and exponent.
int max_type_len = 1;
int max_recompute_len = 1;
int max_use_len = 3;
int max_index_len = 1;
if (printHeader)
{
max_name_len = std::max(max_name_len, 4); // size of "Name" header
max_type_len = 4;
max_recompute_len = 9;
max_index_len = 5;
os << pad_str << setw(max_name_len) << "Name"
<< " " << setw(max_value_len) << "Value"
<< " " << setw(max_type_len) << "Type"
<< " " << setw(max_recompute_len) << "Recompute"
<< " " << setw(max_use_len) << "Use"
<< " " << setw(max_index_len) << "Index" << std::endl;
os << pad_str << std::setfill('-') << setw(max_name_len) << ""
<< " " << setw(max_value_len) << ""
<< " " << setw(max_type_len) << ""
<< " " << setw(max_recompute_len) << ""
<< " " << setw(max_use_len) << ""
<< " " << setw(max_index_len) << "" << std::endl;
os << std::setfill(' ');
}
for (int i = 0; i < NameAndValue.size(); ++i)
{
os << pad_str << setw(max_name_len) << NameAndValue[i].first << " " << std::setprecision(6) << std::scientific
<< setw(max_value_len) << NameAndValue[i].second << " " << setw(max_type_len) << ParameterType[i].second << " "
<< setw(max_recompute_len) << Recompute[i].second << " ";
os << std::defaultfloat;
if (Index[i] < 0)
os << setw(max_use_len) << "OFF" << std::endl;
else
os << setw(max_use_len) << "ON"
<< " " << setw(max_index_len) << Index[i] << std::endl;
}
}
} // namespace optimize
| 32.704861 | 118 | 0.621934 | [
"object",
"vector"
] |
6b5564807114691832873a4c2a3b526ea4bf7ad3 | 22,115 | cpp | C++ | dashboard.cpp | vain3219/463_project | 7c661c8bf98c6da6d889e2813bc97eed343e071e | [
"Info-ZIP"
] | 1 | 2021-04-08T23:54:31.000Z | 2021-04-08T23:54:31.000Z | dashboard.cpp | vain3219/463_project | 7c661c8bf98c6da6d889e2813bc97eed343e071e | [
"Info-ZIP"
] | null | null | null | dashboard.cpp | vain3219/463_project | 7c661c8bf98c6da6d889e2813bc97eed343e071e | [
"Info-ZIP"
] | null | null | null | #include "dashboard.h"
#include "ui_dashboard.h"
#include "loginauth.h"
DashBoard::DashBoard(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::DashBoard)
{
// Nothing before this line
ui->setupUi(this);
// Change the window title
this->setWindowTitle("User Dashboard");
// Hide database fail text
ui->DatabaseLoadError->hide();
// QPalette is used to change the color of the text in FailedAuth label to RED
QPalette palette = ui->DatabaseLoadError->palette();
palette.setColor(ui->DatabaseLoadError->backgroundRole(), Qt::red);
palette.setColor(ui->DatabaseLoadError->foregroundRole(), Qt::red);
ui->DatabaseLoadError->setPalette(palette);
//
// Set initial GUI enviornment
ui->stackedWidgetRDB->setCurrentIndex(1);
setBlankPage();
//
databaseInit();
updateTable("select * from Customer;");
ui->DataTable->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->DataTable, SIGNAL(customContextMenuRequested(QPoint)), SLOT(customMenuRequested(QPoint)));
}
DashBoard::~DashBoard()
{
delete ui;
}
bool DashBoard::databaseInit()
{
// Establish connection with SQLite Database
//db = new DbManager("AntaresRDB.db");
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("AntaresRDB.db");
//db.setDatabaseName("C://Users//Grant//Desktop//orig//AntaresRDB.db");
if (!db.open())
{
qDebug() << "Error: connection with database fail";
return false;
} else {
qDebug() << "Database: connection ok";
}
// Attempt to populate the DataTable
// If the DataTable can't be populated, display error text
if( !db.isOpen() )
{
ui->DataTable->hide();
ui->DatabaseLoadError->show();
}
if( db.isValid()) {
qDebug() << "Database is valid.";
}
return true;
}
void DashBoard::on_LogoutButton_clicked()
{
// Create new login form object, show the new window, and close the dashboard window
LoginAuth *LoginLoader = new LoginAuth;
LoginLoader->show();
db.close();
this->close();
}
void DashBoard::on_SearchButton_clicked()
// Capability 7
{
guestEdit = true;
resEdit = false;
hkEdit = false;
// Set the stacked widget to display the additional search GUI
ui->stackedWidgetSR->setCurrentWidget(ui->SearchPage);
}
void DashBoard::on_DailyButton_clicked()
{
guestEdit = true;
resEdit = false;
hkEdit = false;
// Hide unecessary GUI elements
setBlankPage();
updateTable("select * from Customer;");
}
void DashBoard::on_GuestsButton_clicked()
{
guestEdit = true;
resEdit = false;
hkEdit = false;
// Hide unecessary GUI elements
setBlankPage();
updateTable("SELECT * FROM Customer");
}
void DashBoard::on_HousekeepingButton_clicked()
{
guestEdit = false;
resEdit = false;
hkEdit = true;
// Hide unecessary GUI elements
setBlankPage();
updateTable("SELECT * FROM Housekeeping");
}
void DashBoard::on_InfoButton_clicked()
{
guestEdit = false;
resEdit = false;
hkEdit = false;
// Hide unecessary GUI elements
setBlankPage();
updateTable("SELECT * FROM Customer");
}
void DashBoard::on_ReservationButton_clicked()
{
guestEdit = false;
resEdit = true;
hkEdit = false;
// Hide unecessary GUI elements
setBlankPage();
// Set the stacked widget to display the additional reservation GUI
ui->stackedWidgetSR->setCurrentWidget(ui->ReservationPage);
updateTable("SELECT * FROM Reservations");
}
void DashBoard::on_RoomsButton_clicked()
{
guestEdit = false;
resEdit = false;
hkEdit = false;
// Hide unecessary GUI elements
setBlankPage();
// Set the stacked widget to display the room buttons
setRoomStatusButtons();
ui->stackedWidgetRDB->setCurrentIndex(0);
}
void DashBoard::on_WeeklyButton_clicked()
{
guestEdit = false;
resEdit = false;
hkEdit = false;
// Hide unecessary GUI elements
setBlankPage();
updateTable("SELECT * FROM Customer");
}
void DashBoard::on_SubmitButon_clicked()
{
QString inputStr = ui->SearchField->text(), statement;
QVector<QStringRef> args = inputStr.splitRef(" ");
QSqlQuery* qry = new QSqlQuery(db);
int cusID = 0;
qDebug() << QString::number(args.count()) + " arguements given.";
switch(args.count())
{
case 0:
ui->SearchField->placeholderText() = "Please enter a first and/or last name";
break;
case 1:
statement = "SELECT CusID FROM Customer WHERE (FName = '" + args.at(0) + "' OR LName = '" + args.at(0) + "' )";
qDebug() << args.at(0);
break;
case 2:
statement = "SELECT CusID FROM Customer WHERE (FName = '" + args.at(0) + "' OR LName = '" + args.at(1) + "' )";
qDebug() << args.at(0);
qDebug() << args.at(1);
break;
}
if( qry->prepare(statement) && args.count() > 0 )
{
qry->exec();
qry->first();
qDebug() << "Customer found.";
cusID = qry->value(0).toInt();
// add "Reservations.roomNum" to the query
updateTable("SELECT Customer.FName, Customer.LName, Customer.Phone, Customer.Address, Reservations.CheckIn, Reservations.Checkout "
"FROM Reservations INNER JOIN Customer ON Reservations.CusID = Customer.CusID WHERE Reservations.CusID = " + QString::number(cusID));
} else {
QSqlError error = qry->lastError();
qDebug() << "Failed to prepare query.";
qDebug() << "Database says: " + error.databaseText();
}
}
void DashBoard::on_SearchField_returnPressed()
{
on_SubmitButon_clicked();
}
void DashBoard::on_SearchField_editingFinished()
{
on_SubmitButon_clicked();
}
void DashBoard::on_MakeResButton_clicked()
{
guestEdit = false;
resEdit = false;
hkEdit = false;
// Create new form object and display the window
Reservations* loadMe = new Reservations;
// Disable window resizing
loadMe->setFixedSize(loadMe->size());
loadMe->setModal(1);
loadMe->show();
}
void DashBoard::setBlankPage() {
// Sets the stacked widget to display the blankPage when additional GUI
// elements are unecessary
if(ui->stackedWidgetSR->currentIndex() != 0)
{
ui->stackedWidgetSR->setCurrentWidget(ui->BlankPage);
}
if(ui->stackedWidgetRDB->currentIndex() == 0)
{
ui->stackedWidgetRDB->setCurrentIndex(1);
}
}
void DashBoard::setRoomButton(int roomNumber, QPushButton* button)
// void DashBoard::setRoomButton(int roomNumber, QPushButton* button, roomStatus status)
/*
* We can use a database query to retrieve the value for the room status and append it to the strin as
* I have commented out below. This would allow dynamic button text and color.
*/
{
QString* buttonText = new QString("Room " + QString::number(roomNumber) + " - #STATUS HERE#");// + getStringStatus(Query));
button->setText(*buttonText);
// Random coloring for testing
int statusTemp = rand() % 4 + 0;
//
setColor(roomStatus(statusTemp), button);
}
QString DashBoard::getStatusString(roomStatus status)
{
switch(status)
{
case AVAILABLE:
return "Available";
break;
case OCCUPIED:
return "Occupied";
break;
case DIRTY:
return "Dirty";
break;
case MAINTENANCE:
return "Maintenance Needed";
break;
default:
return "Contact Tech Support";
break;
}
}
void DashBoard::setColor(roomStatus status, QPushButton* button) {
switch(status)
{
case AVAILABLE:
// Set Green
button->setStyleSheet("font: bold;background-color : green;");
break;
case OCCUPIED:
// Set Red
button->setStyleSheet("font: bold;background-color : red");
break;
case DIRTY:
// Set Yellow
button->setStyleSheet("font: bold;background-color : yellow;");
break;
case MAINTENANCE:
// Set Orange
button->setStyleSheet("font: bold;background-color : orange;");
break;
default:
// No Change -- defualt Grey
break;
}
}
void DashBoard::setRoomStatusButtons()
{
srand (time(NULL));
setRoomButton(10, ui->RoomButton_10);
setRoomButton(11, ui->RoomButton_11);
setRoomButton(12, ui->RoomButton_12);
setRoomButton(13, ui->RoomButton_13);
setRoomButton(14, ui->RoomButton_14);
setRoomButton(15, ui->RoomButton_15);
setRoomButton(16, ui->RoomButton_16);
setRoomButton(17, ui->RoomButton_17);
setRoomButton(18, ui->RoomButton_18);
setRoomButton(19, ui->RoomButton_19);
setRoomButton(20, ui->RoomButton_20);
setRoomButton(21, ui->RoomButton_21);
setRoomButton(22, ui->RoomButton_22);
setRoomButton(23, ui->RoomButton_23);
setRoomButton(24, ui->RoomButton_24);
}
void DashBoard::setRoomDetails(int roomNumber, QPushButton* button)
{
QString details =
"<body><style>#boxes {content: "";display: table;clear: both;}"
"div {float: left;height: 470px;width: 23%;padding: 0 10px;}</style>"
"<main id=\"boxes\">"
""
"<div><h1>Room " + QString::number(roomNumber)+ " - #ROOM STATUS HERE# </h1>\n"
"<p>This is information relevent to the rooms status.</p>"
"<p>All of this text will be presented on the screen.</p></div>"
"<p>That's right; look no further! More text!</p>"
"<p>We can have more text here also! Yay html!</p>"
"</div></main></body>";
/*
* Some SQL Query logic here and create a more detialed report
*/
ui->textEdit->setText(details);
}
void DashBoard::updateTable(QString rawString)
{
QSqlQueryModel* model = new QSqlQueryModel;
QSqlQuery* qry = new QSqlQuery(db);
if( qry->prepare(rawString) )
{
qry->exec();
model->setQuery(*qry);
ui->DataTable->setModel(model);
qDebug() << model->rowCount() << " rows returned.";
} else {
QSqlError error = qry->lastError();
qDebug() << "Failed to prepare query.";
qDebug() << "Database says: " + error.databaseText();
}
}
// Room status buttons for Capabillity one
void DashBoard::on_RoomButton_10_clicked()
{
roomNum = 10;
roomPtr = ui->RoomButton_10;
//setRoomDetails(10, ui->RoomButton_10);
}
void DashBoard::on_RoomButton_11_clicked()
{
roomNum = 11;
roomPtr = ui->RoomButton_11;
//setRoomDetails(11, ui->RoomButton_11);
}
void DashBoard::on_RoomButton_12_clicked()
{
setRoomDetails(12, ui->RoomButton_12);
}
void DashBoard::on_RoomButton_13_clicked()
{
setRoomDetails(13, ui->RoomButton_13);
}
void DashBoard::on_RoomButton_14_clicked()
{
setRoomDetails(14, ui->RoomButton_14);
}
void DashBoard::on_RoomButton_15_clicked()
{
setRoomDetails(15, ui->RoomButton_15);
}
void DashBoard::on_RoomButton_16_clicked()
{
setRoomDetails(16, ui->RoomButton_16);
}
void DashBoard::on_RoomButton_17_clicked()
{
setRoomDetails(17, ui->RoomButton_17);
}
void DashBoard::on_RoomButton_18_clicked()
{
setRoomDetails(18, ui->RoomButton_18);
}
void DashBoard::on_RoomButton_19_clicked()
{
setRoomDetails(19, ui->RoomButton_19);
}
void DashBoard::on_RoomButton_20_clicked()
{
setRoomDetails(20, ui->RoomButton_20);
}
void DashBoard::on_RoomButton_21_clicked()
{
setRoomDetails(21, ui->RoomButton_21);
}
void DashBoard::on_RoomButton_22_clicked()
{
setRoomDetails(22, ui->RoomButton_22);
}
void DashBoard::on_RoomButton_23_clicked()
{
setRoomDetails(23, ui->RoomButton_23);
}
void DashBoard::on_RoomButton_24_clicked()
{
setRoomDetails(24, ui->RoomButton_24);
}
void DashBoard::on_DataTable_doubleClicked(const QModelIndex &index)
{
if(guestEdit)
{
qDebug() << ui->DataTable->model()->data(ui->DataTable->model()->index(index.row(),0)).toInt();
GuestInfo* loadMeBaby = new GuestInfo(&db, ui->DataTable->model()->data(ui->DataTable->model()->index(index.row(),0)).toInt());
loadMeBaby->setModal(1);
// Disable window resizing
loadMeBaby->setFixedSize(loadMeBaby->size());
loadMeBaby->show();
}
else
{
qDebug() << "Guest editting is not permitted at the momment.";
}
}
void DashBoard::on_DataTable_customContextMenuRequested(const QPoint &pos)
{
qDebug() << "Right clicked. Displaying context menu.";
if( resEdit )
{
qDebug() << "Reservation editting menu.";
QModelIndex index= ui->DataTable->indexAt(pos);
QMenu *menu=new QMenu(this);
QAction* del= new QAction("Delete Reservation", this);
menu->addAction(del);
del->setStatusTip("Deleted the currently selected row.");
menu->popup(ui->DataTable->viewport()->mapToGlobal(pos));
ResID = ui->DataTable->model()->data(ui->DataTable->model()->index(index.row(),0)).toInt();
connect(del, &QAction::triggered, this, &DashBoard::deleteReservation);
}
else if( hkEdit )
{
qDebug() << "Housekeeping editting menu.";
QModelIndex index= ui->DataTable->indexAt(pos);
QMenu *menu=new QMenu(this);
QAction* Bathroom= new QAction("Bathroom", this);
QAction* Towels= new QAction("Towels", this);
QAction* Vacuum= new QAction("Vacuum", this);
QAction* Dusting= new QAction("Dusting", this);
QAction* Electronics= new QAction("Electronics", this);
menu->addAction(Bathroom);
Bathroom->setStatusTip("Bathroom cleaning requested");
Bathroom->setCheckable(true);
menu->addAction(Towels);
Towels->setStatusTip("Towels requested");
Towels->setCheckable(true);
menu->addAction(Vacuum);
Vacuum->setStatusTip("Vacuuming requested");
Vacuum->setCheckable(true);
menu->addAction(Dusting);
Dusting->setStatusTip("Dusting requested");
Dusting->setCheckable(true);
menu->addAction(Electronics);
Electronics->setStatusTip("Electronics help requested");
Electronics->setCheckable(true);
menu->popup(ui->DataTable->viewport()->mapToGlobal(pos));
roomID = ui->DataTable->model()->data(ui->DataTable->model()->index(index.row(),0)).toInt();
connect(Bathroom, &QAction::toggled, this, &DashBoard::bathEdit);
connect(Towels, &QAction::toggled, this, &DashBoard::towelEdit);
connect(Vacuum, &QAction::toggled, this, &DashBoard::vacuumEdit);
connect(Dusting, &QAction::toggled, this, &DashBoard::dustEdit);
connect(Electronics, &QAction::toggled, this, &DashBoard::elecEdit);
// GRANT
// SQL query here to check if the selected room(defined by variable roomID) is currently available
//if()
{
qDebug() << "Present 'Make room unavaible' option";
QAction* makeUn= new QAction("Make room unavaible", this);
menu->addSection("Availability");
menu->addAction(makeUn);
makeUn->setStatusTip("Make the selected room unavaible");
makeUn->setCheckable(true);
connect(Electronics, &QAction::toggled, this, &DashBoard::elecEdit);
}
//else
{
qDebug() << "The selected room is already unavailable";
}
}
else
{
qDebug() << "Context menu unavailable.";
}
}
void DashBoard::deleteReservation()
{
qDebug() << "Delete selected.";
Alert* alert = new Alert("Are you sure you want to delete this reservation?\nThis action can't be undone.");
alert->setModal(1);
// Disable window resizing
alert->setFixedSize(alert->size());
alert->exec();
if(alert->isAccepted()) {
QSqlQuery* qry = new QSqlQuery(db);
if( qry->prepare("DELETE FROM Reservations WHERE ResID = " + QString::number(ResID)) )
{
qry->exec();
} else {
QSqlError error = qry->lastError();
qDebug() << "Failed to prepare query.";
qDebug() << "Database says: " + error.databaseText();
}
qDebug() << "Reservation " + QString::number(ResID) + " has been deleted";
} else {
qDebug() << "No changes were made.";
}
alert->close();
delete alert;
updateTable("Select * FROM Reservations");
}
void DashBoard::bathEdit()
{
//edit here
QSqlQuery* qry = new QSqlQuery(db);
int set = 0;
if(qry->prepare("SELECT Bathroom FROM Housekeeping WHERE RoomID = " + QString::number(roomID)) )
{
qry->exec();
qry->first();
set = qry->value(0).toInt();
if(set == 0) {
qry->prepare("UPDATE Housekeeping SET Bathroom = " + QString::number(1) + " WHERE RoomID = " + QString::number(roomID));
qDebug() << "Room " + QString::number(roomID) + " requires bathroom cleaning";
}
else {
qry->prepare("UPDATE Housekeeping SET Bathroom = " + QString::number(0) + " WHERE RoomID = " + QString::number(roomID));
qDebug() << "Room " + QString::number(roomID) + " does not require bathroom cleaning";
}
qry->exec();
updateTable("SELECT * FROM Housekeeping");
}
else
{
QSqlError error = qry->lastError();
qDebug() << "Failed to prepare query.";
qDebug() << "Database says: " + error.databaseText();
}
}
void DashBoard::towelEdit()
{
//edit here
QSqlQuery* qry = new QSqlQuery(db);
int set = 0;
if(qry->prepare("SELECT Towels FROM Housekeeping WHERE RoomID = " + QString::number(roomID)) )
{
qry->exec();
qry->first();
set = qry->value(0).toInt();
if(set == 0) {
qry->prepare("UPDATE Housekeeping SET Towels = " + QString::number(1) + " WHERE RoomID = " + QString::number(roomID));
qDebug() << "Room " + QString::number(roomID) + " requires towels";
}
else {
qry->prepare("UPDATE Housekeeping SET Towels = " + QString::number(0) + " WHERE RoomID = " + QString::number(roomID));
qDebug() << "Room " + QString::number(roomID) + " does not require towels";
}
qry->exec();
updateTable("SELECT * FROM Housekeeping");
}
else
{
QSqlError error = qry->lastError();
qDebug() << "Failed to prepare query.";
qDebug() << "Database says: " + error.databaseText();
}
}
void DashBoard::vacuumEdit()
{
QSqlQuery* qry = new QSqlQuery(db);
int set = 0;
if(qry->prepare("SELECT Vacuum FROM Housekeeping WHERE RoomID = " + QString::number(roomID)) )
{
qry->exec();
qry->first();
set = qry->value(0).toInt();
if(set == 0) {
qry->prepare("UPDATE Housekeeping SET Vacuum = " + QString::number(1) + " WHERE RoomID = " + QString::number(roomID));
qDebug() << "Room " + QString::number(roomID) + " requires vacuuming";
}
else {
qry->prepare("UPDATE Housekeeping SET Vacuum = " + QString::number(0) + " WHERE RoomID = " + QString::number(roomID));
qDebug() << "Room " + QString::number(roomID) + " does not require vacuuming";
}
qry->exec();
updateTable("SELECT * FROM Housekeeping");
}
else
{
QSqlError error = qry->lastError();
qDebug() << "Failed to prepare query.";
qDebug() << "Database says: " + error.databaseText();
}
}
void DashBoard::dustEdit()
{
QSqlQuery* qry = new QSqlQuery(db);
int set = 0;
if(qry->prepare("SELECT Dusting FROM Housekeeping WHERE RoomID = " + QString::number(roomID)) )
{
qry->exec();
qry->first();
set = qry->value(0).toInt();
if(set == 0) {
qry->prepare("UPDATE Housekeeping SET Dusting = " + QString::number(1) + " WHERE RoomID = " + QString::number(roomID));
qDebug() << "Room " + QString::number(roomID) + " requires dusting";
}
else {
qry->prepare("UPDATE Housekeeping SET Dusting = " + QString::number(0) + " WHERE RoomID = " + QString::number(roomID));
qDebug() << "Room " + QString::number(roomID) + " does not require dusting";
}
qry->exec();
updateTable("SELECT * FROM Housekeeping");
}
else
{
QSqlError error = qry->lastError();
qDebug() << "Failed to prepare query.";
qDebug() << "Database says: " + error.databaseText();
}
}
void DashBoard::elecEdit()
{
QSqlQuery* qry = new QSqlQuery(db);
int set = 0;
if(qry->prepare("SELECT Electronics FROM Housekeeping WHERE RoomID = " + QString::number(roomID)) )
{
qry->exec();
qry->first();
set = qry->value(0).toInt();
if(set == 0) {
qry->prepare("UPDATE Housekeeping SET Electronics = " + QString::number(1) + " WHERE RoomID = " + QString::number(roomID));
qDebug() << "Room " + QString::number(roomID) + " requires electronic maintenance";
}
else {
qry->prepare("UPDATE Housekeeping SET Electronics = " + QString::number(0) + " WHERE RoomID = " + QString::number(roomID));
qDebug() << "Room " + QString::number(roomID) + " does not require electronic maintenance";
}
qry->exec();
updateTable("SELECT * FROM Housekeeping");
}
else
{
QSqlError error = qry->lastError();
qDebug() << "Failed to prepare query.";
qDebug() << "Database says: " + error.databaseText();
}
}
void DashBoard::makeRoomUnavailable()
{
QSqlQuery* qry = new QSqlQuery(db);
if(qry->prepare(""))
{
qry->exec();
qry->first();
// GRANT
// SQL query to make the room unavaiable here
qry->exec();
updateTable("SELECT * FROM Housekeeping");
}
else
{
QSqlError error = qry->lastError();
qDebug() << "Failed to prepare query.";
qDebug() << "Database says: " + error.databaseText();
}
}
| 29.060447 | 145 | 0.612254 | [
"object",
"model"
] |
6b5b90b65cdfae4bf0608f7f55ed25818aafc99b | 2,686 | cpp | C++ | codeforces/D - Professor GukiZ and Two Arrays/Wrong answer on test 1 (2).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/D - Professor GukiZ and Two Arrays/Wrong answer on test 1 (2).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/D - Professor GukiZ and Two Arrays/Wrong answer on test 1 (2).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Oct/06/2020 13:51
* solution_verdict: Wrong answer on test 1 language: GNU C++14
* run_time: 31 ms memory_used: 7800 KB
* problem: https://codeforces.com/contest/620/problem/D
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#include<queue>
#include<sstream>
#include<unordered_map>
#include<unordered_set>
#include<chrono>
#include<stack>
#include<deque>
#include<random>
#define long long long
using namespace std;
const int N=1e6,mod=1e9+7;
int a[N+2],b[N+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n;cin>>n;long s1=0,s2=0;
for(int i=1;i<=n;i++)cin>>a[i],s1+=a[i];
int m;cin>>m;
for(int i=1;i<=m;i++)cin>>b[i],s2+=b[i];
long ans=abs(s1-s2),k=0,on,tw,th,fr;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
long s3=s1-a[i]+b[j];
long s4=s2-b[j]+a[i];
if(abs(s3-s4)<ans)ans=abs(s3-s4),k=1,on=i,tw=j;
}
}
vector<int>v;map<int,pair<int,int> >mp;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
int x=a[i]+a[j];
v.push_back(x);mp[x]={i,j};
}
}
sort(v.begin(),v.end());v.erase(unique(v.begin(),v.end()),v.end());
for(int i=1;i<=m;i++)
{
for(int j=i+1;j<=m;j++)
{
int id=lower_bound(v.begin(),v.end(),(s1-s2)/2+(b[i]+b[j]))-v.begin();
long s3,s4;
if(id<v.size())
{
s3=s1-v[id]+b[i]+b[j];
s4=s2-(b[i]+b[j])+v[id];
if(abs(s3-s4)<ans)
{
pair<int,int>p=mp[v[id]];
ans=abs(s3-s4),k=2,on=i,tw=p.first,th=j,fr=p.second;
}
}
id++;
if(id<v.size())
{
s3=s1-v[id]+b[i]+b[j];
s4=s2-(b[i]+b[j])+v[id];
if(abs(s3-s4)<ans)
{
pair<int,int>p=mp[v[id]];
ans=abs(s3-s4),k=2,on=i,tw=p.first,th=j,fr=p.second;
}
}
id-=2;
if(id>=0)
{
s3=s1-v[id]+b[i]+b[j];
s4=s2-(b[i]+b[j])+v[id];
if(abs(s3-s4)<ans)
{
pair<int,int>p=mp[v[id]];
ans=abs(s3-s4),k=2,on=i,tw=p.first,th=j,fr=p.second;
}
}
}
}
cout<<ans<<endl;
cout<<k<<endl;
if(k>=1)cout<<on<<" "<<tw<<endl;
if(k==2)cout<<th<<" "<<fr<<endl;
return 0;
} | 26.594059 | 111 | 0.445644 | [
"vector"
] |
6b6e8b508f3173356214ea638d804d30c78cfeff | 12,885 | cpp | C++ | isis/src/base/objs/OverlapNormalization/OverlapNormalization.cpp | kdl222/ISIS3 | aab0e63088046690e6c031881825596c1c2cc380 | [
"CC0-1.0"
] | 134 | 2018-01-18T00:16:24.000Z | 2022-03-24T03:53:33.000Z | isis/src/base/objs/OverlapNormalization/OverlapNormalization.cpp | kdl222/ISIS3 | aab0e63088046690e6c031881825596c1c2cc380 | [
"CC0-1.0"
] | 3,825 | 2017-12-11T21:27:34.000Z | 2022-03-31T21:45:20.000Z | isis/src/base/objs/OverlapNormalization/OverlapNormalization.cpp | jlaura/isis3 | 2c40e08caed09968ea01d5a767a676172ad20080 | [
"CC0-1.0"
] | 164 | 2017-11-30T21:15:44.000Z | 2022-03-23T10:22:29.000Z | /** This is free and unencumbered software released into the public domain.
The authors of ISIS do not claim copyright on the contents of this file.
For more details about the LICENSE terms and the AUTHORS, you will
find files of those names at the top level of this repository. **/
/* SPDX-License-Identifier: CC0-1.0 */
#include "OverlapNormalization.h"
#include <iomanip>
#include "BasisFunction.h"
#include "IException.h"
#include "LeastSquares.h"
#include "Statistics.h"
using namespace std;
namespace Isis {
/**
* Constructs an OverlapNormalization object. Compares and
* stores the vector, and initializes the basis and least
* squares functions. This object will also take ownership of the pointers
* in the vector parameter.
*
* @param statsList The list of Statistics objects corresponding
* to specific data sets (e.g., cubes)
*/
OverlapNormalization::OverlapNormalization(std::vector<Statistics *> statsList) {
m_gainFunction = NULL;
m_gainLsq = NULL;
m_offsetFunction = NULL;
m_offsetLsq = NULL;
m_statsList = statsList;
m_gainFunction = new BasisFunction("BasisFunction",
statsList.size(), statsList.size());
m_gainLsq = new LeastSquares(*m_gainFunction);
m_offsetFunction = new BasisFunction("BasisFunction",
statsList.size(), statsList.size());
m_offsetLsq = new LeastSquares(*m_offsetFunction);
m_gains.resize(statsList.size());
m_offsets.resize(statsList.size());
for (unsigned int i = 0; i < statsList.size(); i++) {
m_gains[i] = 1.0;
m_offsets[i] = 0.0;
}
m_solved = false;
}
/**
* Destroys the OverlapNormalization object, frees up
* pointers
*/
OverlapNormalization::~OverlapNormalization() {
if (m_gainFunction != NULL) delete m_gainFunction;
if (m_offsetFunction != NULL) delete m_offsetFunction;
if (m_gainLsq != NULL) delete m_gainLsq;
if (m_offsetLsq != NULL) delete m_offsetLsq;
for (unsigned int i = 0; i < m_statsList.size(); i++) delete m_statsList[i];
};
/**
* Attempts to add the given overlap data to a collection of
* valid overlaps, and returns the success or failure of that
* attempt.
*
* @param area1 The statistics for the overlap area of the first
* overlapping data set
* @param index1 The index in the list of Statistics of the
* first data set
* @param area2 The statistics for the overlap area of the
* second data set
* @param index2 The index in the list of Statistics of the
* second overlapping data set
* @param weight Relative significance of this overlap. Default
* value = 1.0
*
* @return AddStatus An enumeration representing either a
* successful add, or the reason for failure
*
* @throws Isis::iException::Programmer - Identifying index 1
* must exist in the statsList
* @throws Isis::iException::Programmer - Identifying index 2
* must exist in the statsList
* @throws Isis::iException::Programmer - Weights must be all
* positive real numbers
*/
OverlapNormalization::AddStatus OverlapNormalization::AddOverlap(
const Statistics &area1, const unsigned index1,
const Statistics &area2, const unsigned index2,
double weight) {
if (index1 >= m_statsList.size()) {
string msg = "The index 1 is outside the bounds of the list.";
throw IException(IException::Programmer, msg, _FILEINFO_);
}
if (index2 >= m_statsList.size()) {
string msg = "The index 2 is outside the bounds of the list.";
throw IException(IException::Programmer, msg, _FILEINFO_);
}
// If there is no overlapping area, then the overlap is invalid
if (area1.ValidPixels() == 0 || area2.ValidPixels() == 0) {
return NoOverlap;
}
// The weight must be a positive real number
if (weight <= 0.0) {
string msg = "All weights must be positive real numbers.";
throw IException(IException::Programmer, msg, _FILEINFO_);
}
OverlapNormalization::Overlap o;
o.area1 = area1;
o.area2 = area2;
o.index1 = index1;
o.index2 = index2;
double avg1 = area1.Average();
double avg2 = area2.Average();
// Averages must not be 0 to avoid messing up least squares
if (avg1 == 0 || avg2 == 0) return NoContrast;
m_overlapList.push_back(o);
m_deltas.push_back(avg2 - avg1);
m_weights.push_back(weight);
m_solved = false;
return Success;
}
/**
* Attempts to solve the least squares equation for all data sets.
*
* @param type The enumeration clarifying whether the offset, gain, or both
* should be solved here
* @param method The enumeration clarifying the LeastSquares::SolveMethod to
* be used.
*
* @return bool Is the least squares equation now solved
*
* @throws Isis::iException::User - Number of overlaps and
* holds must be greater than the number of data
* sets
*/
void OverlapNormalization::Solve(SolutionType type,
LeastSquares::SolveMethod method) {
// Make sure that there is at least one overlap
if (m_overlapList.size() == 0) {
string msg = "None of the input images overlap";
throw IException(IException::User, msg, _FILEINFO_);
}
// Make sure the number of valid overlaps + hold images is greater than the
// number of input images (otherwise the least squares equation will be
// unsolvable due to having more unknowns than knowns)
if (m_overlapList.size() + m_idHoldList.size() < m_statsList.size()) {
string msg = "Unable to normalize overlaps. The number of overlaps and "
"holds must be greater than the number of input images";
throw IException(IException::User, msg, _FILEINFO_);
}
if ( method == LeastSquares::SPARSE ) {
m_offsetLsq = NULL;
m_gainLsq = NULL;
delete m_offsetLsq;
delete m_gainLsq;
int sparseMatrixRows = m_overlapList.size() + m_idHoldList.size();
int sparseMatrixCols = m_offsetFunction->Coefficients();
m_offsetLsq = new LeastSquares(*m_offsetFunction, true, sparseMatrixRows, sparseMatrixCols, true);
sparseMatrixCols = m_gainFunction->Coefficients();
m_gainLsq = new LeastSquares(*m_gainFunction, true, sparseMatrixRows, sparseMatrixCols, true);
const std::vector<double> alphaWeight(sparseMatrixCols, 1/1000.0);
m_offsetLsq->SetParameterWeights( alphaWeight );
m_gainLsq->SetParameterWeights( alphaWeight );
}
// Calculate offsets
if (type != Gains && type != GainsWithoutNormalization) {
// Add knowns to least squares for each overlap
for (int overlap = 0; overlap < (int)m_overlapList.size(); overlap++) {
Overlap curOverlap = m_overlapList[overlap];
int id1 = curOverlap.index1;
int id2 = curOverlap.index2;
vector<double> input;
input.resize(m_statsList.size());
for (int i = 0; i < (int)input.size(); i++) input[i] = 0.0;
input[id1] = 1.0;
input[id2] = -1.0;
m_offsetLsq->AddKnown(input, m_deltas[overlap], m_weights[overlap]);
}
// Add a known to the least squares for each hold image
for (int h = 0; h < (int)m_idHoldList.size(); h++) {
int hold = m_idHoldList[h];
vector<double> input;
input.resize(m_statsList.size());
for (int i = 0; i < (int)input.size(); i++) input[i] = 0.0;
input[hold] = 1.0;
m_offsetLsq->AddKnown(input, 0.0, 1e30);
}
// Solve the least squares and get the offset coefficients to apply to the
// images
m_offsets.resize(m_statsList.size());
m_offsetLsq->Solve(method);
for (int i = 0; i < m_offsetFunction->Coefficients(); i++) {
m_offsets[i] = m_offsetFunction->Coefficient(i);
}
}
// Calculate Gains
if (type != Offsets) {
// Add knowns to least squares for each overlap
for (int overlap = 0; overlap < (int)m_overlapList.size(); overlap++) {
Overlap curOverlap = m_overlapList[overlap];
int id1 = curOverlap.index1;
int id2 = curOverlap.index2;
vector<double> input;
input.resize(m_statsList.size());
for (int i = 0; i < (int)input.size(); i++) input[i] = 0.0;
input[id1] = 1.0;
input[id2] = -1.0;
double tanp;
if (type != GainsWithoutNormalization) {
if (curOverlap.area1.StandardDeviation() == 0.0) {
tanp = 0.0; // Set gain to 1.0
}
else {
tanp = curOverlap.area2.StandardDeviation()
/ curOverlap.area1.StandardDeviation();
}
}
else {
if (curOverlap.area1.Average() == 0.0) {
tanp = 0.0;
}
else {
tanp = curOverlap.area2.Average() / curOverlap.area1.Average();
}
}
if (tanp > 0.0) {
m_gainLsq->AddKnown(input, log(tanp), m_weights[overlap]);
}
else {
m_gainLsq->AddKnown(input, 0.0, 1e10); // Set gain to 1.0
}
}
// Add a known to the least squares for each hold image
for (int h = 0; h < (int)m_idHoldList.size(); h++) {
int hold = m_idHoldList[h];
vector<double> input;
input.resize(m_statsList.size());
for (int i = 0; i < (int)input.size(); i++) input[i] = 0.0;
input[hold] = 1.0;
m_gainLsq->AddKnown(input, 0.0, 1e10);
}
// Solve the least squares and get the gain coefficients to apply to the
// images
m_gains.resize(m_statsList.size());
m_gainLsq->Solve(method);
for (int i = 0; i < m_gainFunction->Coefficients(); i++) {
m_gains[i] = exp(m_gainFunction->Coefficient(i));
}
}
m_solved = true;
}
/**
* Returns the calculated average DN value for the given
* data set
*
* @param index The index in the Statistics list corresponding
* to the data set desired
*
* @return double The average for the data
*
* @throws Isis::iException::Programmer - Identifying index must
* exist in the statsList
*/
double OverlapNormalization::Average(const unsigned index) const {
if (index >= m_statsList.size()) {
string msg = "The index was out of bounds for the list of statistics.";
throw IException(IException::Programmer, msg, _FILEINFO_);
}
return m_statsList[index]->Average();
}
/**
* Returns the calculated gain (multiplier) for the given
* data set
*
* @param index The index in the Statistics list corresponding
* to the data set desired
*
* @return double The gain for the data
*
* @throws Isis::iException::Programmer - Identifying index must
* exist in the statsList
*/
double OverlapNormalization::Gain(const unsigned index) const {
if (index >= m_statsList.size()) {
string msg = "The index was out of bounds for the list of statistics.";
throw IException(IException::Programmer, msg, _FILEINFO_);
}
return m_gains[index];
}
/**
* Returns the calculated offset (base) for the given
* data set
*
* @param index The index in the Statistics list corresponding
* to the data set desired
*
* @return double The offset for the data
*
* @throws Isis::iException::Programmer - Identifying index must
* exist in the statsList
*/
double OverlapNormalization::Offset(const unsigned index) const {
if (index >= m_statsList.size()) {
string msg = "The index was out of bounds for the list of statistics.";
throw IException(IException::Programmer, msg, _FILEINFO_);
}
return m_offsets[index];
}
/**
* Returns a new DN from an old using the calculated gains and
* offsets of the data set the pixel belongs to
*
* @param dn The value of the pixel prior to equalization
*
* @param index The index in the Statistics list corresponding
* to the data set for the pixel
*
* @return double The newly calculated DN value
*
* @throws Isis::iException::Programmer - Least Squares equation
* must be solved before returning the gain
*/
double OverlapNormalization::Evaluate(double dn, unsigned index) const {
if (!m_solved) {
string msg = "The least squares equation has not been successfully ";
msg += "solved yet.";
throw IException(IException::Programmer, msg, _FILEINFO_);
}
if (Isis::IsSpecial(dn)) return dn;
return (dn - Average(index)) * Gain(index) + Average(index) + Offset(index);
}
}
| 34.918699 | 104 | 0.627784 | [
"object",
"vector"
] |
6b6fd568da9f5380a846de6770229617cbff6adf | 3,684 | cpp | C++ | Tools/KFModTool/models/filelistmodel.cpp | IvanDSM/KingsFieldRE | b22549a7e93e3c0e77433d7bea8bbde6a5b9f6a3 | [
"MIT"
] | 16 | 2020-07-09T15:38:41.000Z | 2022-03-03T19:05:24.000Z | Tools/KFModTool/models/filelistmodel.cpp | IvanDSM/KingsFieldRE | b22549a7e93e3c0e77433d7bea8bbde6a5b9f6a3 | [
"MIT"
] | 7 | 2020-07-03T22:38:24.000Z | 2022-01-09T18:25:22.000Z | Tools/KFModTool/models/filelistmodel.cpp | IvanDSM/KingsFieldRE | b22549a7e93e3c0e77433d7bea8bbde6a5b9f6a3 | [
"MIT"
] | 2 | 2021-08-23T08:25:44.000Z | 2022-01-09T16:05:46.000Z | #include "filelistmodel.h"
#include "core/icons.h"
#include "core/prettynames.h"
#include <QAbstractItemView>
#include <QIcon>
QVariant FileListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
Q_UNUSED(section)
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) return QStringLiteral("Files");
return {};
}
QModelIndex FileListModel::index(int row, int column, const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent)) return {};
if (!parent.isValid()) return createIndex(row, column, &core.files[row]);
return createIndex(row,
column,
&reinterpret_cast<KFMTFile*>(parent.internalPointer())->subFiles[row]);
}
QModelIndex FileListModel::parent(const QModelIndex &index) const
{
if (!index.isValid()) return {};
auto* indexFile = reinterpret_cast<KFMTFile*>(index.internalPointer());
size_t fileNo = 0;
for (auto& f : core.files)
{
// If the file is not a subfile of anything, there is no parent
if (f.filePath == indexFile->filePath) return {};
// But if it is a subfile, we return the proper parent.
if (indexFile->filePath.startsWith(f.filePath)) return createIndex(fileNo, 0, &f);
fileNo++;
}
return {};
}
int FileListModel::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid()) return core.files.size();
//return core.files[parent.row()].subFiles.size();
return reinterpret_cast<KFMTFile*>(parent.internalPointer())->subFiles.size();
}
int FileListModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return 1;
}
QVariant FileListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) return {};
if (role == Qt::DisplayRole)
{
const auto& filePath = reinterpret_cast<KFMTFile*>(index.internalPointer())->filePath;
switch (core.curGame)
{
case KFMTCore::VersionedGame::KF2Jv1_0: [[fallthrough]];
case KFMTCore::VersionedGame::KF2Jv1_7: [[fallthrough]];
case KFMTCore::VersionedGame::KF2Jv1_8A: [[fallthrough]];
case KFMTCore::VersionedGame::KF2Jv1_8B: [[fallthrough]];
case KFMTCore::VersionedGame::KF2U: return PrettyNames::kf2(filePath);
default: return filePath;
}
}
if (role == Qt::DecorationRole)
{
switch (reinterpret_cast<KFMTFile*>(index.internalPointer())->dataType)
{
case KFMTFile::DataType::Container: return Icons::container;
case KFMTFile::DataType::GameDB: return Icons::gameDb;
case KFMTFile::DataType::GameEXE: return Icons::gameExe;
case KFMTFile::DataType::MapTilemap: [[fallthrough]];
case KFMTFile::DataType::MapDB: [[fallthrough]];
case KFMTFile::DataType::MapScript: return Icons::map;
case KFMTFile::DataType::Model: return Icons::model;
case KFMTFile::DataType::TextureDB: return Icons::textureDb;
default: return Icons::unknown;
}
}
return {};
}
void FileListModel::update()
{
emit layoutChanged();
}
void FileListModel::contextMenu(const QPoint& pos)
{
// We reset this in case stuff goes wrong.
contextMenuFile = nullptr;
auto* view = dynamic_cast<QAbstractItemView*>(QObject::parent());
auto index = view->indexAt(pos);
if (!index.isValid()) return;
contextMenuFile = reinterpret_cast<KFMTFile*>(index.internalPointer());
if (contextMenuFile->dataType != KFMTFile::DataType::Container) return;
containerContextMenu->exec(view->viewport()->mapToGlobal(pos));
}
| 31.487179 | 97 | 0.653366 | [
"model"
] |
6b753858b9c4cedc90e742ae71d81a8183130196 | 4,899 | cpp | C++ | mobilican_demos/pick_and_place/src/pan_tilt_object_tracking.cpp | robotican/mobilican_robots | faf97fa1dbb05db8068eaede65b572e1e0ba2273 | [
"BSD-2-Clause"
] | 1 | 2020-05-01T19:39:51.000Z | 2020-05-01T19:39:51.000Z | mobilican_demos/pick_and_place/src/pan_tilt_object_tracking.cpp | robotican/mobilican_robots | faf97fa1dbb05db8068eaede65b572e1e0ba2273 | [
"BSD-2-Clause"
] | 1 | 2019-01-21T11:00:54.000Z | 2019-01-28T08:21:30.000Z | mobilican_demos/pick_and_place/src/pan_tilt_object_tracking.cpp | robotican/mobilican_robots | faf97fa1dbb05db8068eaede65b572e1e0ba2273 | [
"BSD-2-Clause"
] | 2 | 2019-01-22T12:13:19.000Z | 2019-01-30T10:07:21.000Z | /*******************************************************************************
* Copyright (c) 2018, RoboTICan, LTD.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of RoboTICan 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.
*******************************************************************************/
/* Author: Elchay Rauper*/
#include <ros/ros.h>
#include <std_msgs/Float64MultiArray.h>
#include <tf/transform_listener.h>
#include <actionlib/client/simple_action_client.h>
#include <mobilican_msgs/PointHeadAction.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <std_srvs/SetBool.h>
// Our Action interface type, provided as a typedef for convenience
typedef actionlib::SimpleActionClient<mobilican_msgs::PointHeadAction> PointHeadClient;
void callback(const geometry_msgs::PoseStamped::ConstPtr& pose);
PointHeadClient* point_head_client;
int main(int argc, char **argv) {
ros::init(argc, argv, "pan_tilt_object_trackking");
ros::NodeHandle n;
ros::NodeHandle pn("~");
std::string object_name;
pn.param<std::string>("object_name", object_name, "can");
moveit::planning_interface::PlanningSceneInterface planning_scene_interface;
//Initialize the client for the Action interface to the head controller
point_head_client = new PointHeadClient("/pan_tilt_trajectory_controller/point_head_action", true);
//wait for head controller action server to come up
while(!point_head_client->waitForServer(ros::Duration(5.0))){
ROS_INFO("Waiting for the point_head_action server to come up");
}
ROS_INFO("Ready to track!");
ros::Rate r(10);
ros::ServiceClient uc_client = n.serviceClient<std_srvs::SetBool>("update_collision_objects");
ROS_INFO("Waiting for update_collision service...");
uc_client.waitForExistence();
std_srvs::SetBool srv;
srv.request.data=true;
uc_client.call(srv);
while (ros::ok()) {
std::vector<std::string> ids;
ids.push_back(object_name);
std::map<std::string, moveit_msgs::CollisionObject> poses=planning_scene_interface.getObjects(ids);
std::map<std::string, moveit_msgs::CollisionObject>::iterator it;
it = poses.find(object_name);
if (it != poses.end()) {
moveit_msgs::CollisionObject obj=it->second;
//the goal message we will be sending
mobilican_msgs::PointHeadGoal goal;
//the target point, expressed in the requested frame
geometry_msgs::PointStamped point;
point.header.frame_id = obj.header.frame_id;
point.header.stamp=obj.header.stamp;
point.point = obj.primitive_poses[0].position;
goal.target = point;
//we are pointing the high-def camera frame
//(pointing_axis defaults to X-axis)
goal.pointing_frame = "kinect2_depth_frame";
goal.pointing_axis.x = 1;
goal.pointing_axis.y = 0;
goal.pointing_axis.z = 0;
//take at least 0.5 seconds to get there
goal.min_duration = ros::Duration(0.5);
//and go no faster than 0.2 rad/s
goal.max_velocity = 0.3;
//send the goal
point_head_client->sendGoal(goal);
//wait for it to get there (abort after 2 secs to prevent getting stuck)
point_head_client->waitForResult(goal.min_duration );
}
ros::spinOnce();
r.sleep();
}
return 0;
}
| 37.976744 | 107 | 0.681772 | [
"vector"
] |
6b76f533a5c4d5e4a8a0819fbc187a0eae725dfc | 2,883 | cpp | C++ | PiSw/src/System/lowlib.cpp | Simulators/PiBusRaider | ec091f3c74ea25c3287d26d990ff5d1b90e97e92 | [
"MIT"
] | 7 | 2021-01-23T04:37:18.000Z | 2022-01-08T04:44:00.000Z | PiSw/src/System/lowlib.cpp | Simulators/PiBusRaider | ec091f3c74ea25c3287d26d990ff5d1b90e97e92 | [
"MIT"
] | 3 | 2021-04-01T11:28:31.000Z | 2021-05-10T09:56:05.000Z | PiSw/src/System/lowlib.cpp | robdobsn/BusRaider | 691e7882a06408208ca2abece5e7c4bcb4b4fa45 | [
"MIT"
] | null | null | null |
// Bus Raider
// Low-level library
// Rob Dobson 2019
#include "lowlib.h"
#include "CInterrupts.h"
#include <limits.h>
#include "memorymap.h"
#include "nmalloc.h"
#ifdef __cplusplus
extern "C" {
#endif
uint32_t micros()
{
static const uint32_t volatile* pTimerLower32Bits = (uint32_t*)ARM_SYSTIMER_CLO;
return *pTimerLower32Bits;
}
uint32_t millis()
{
static const uint32_t volatile* pTimerLower32Bits = (uint32_t*)ARM_SYSTIMER_CLO;
return (*pTimerLower32Bits) / 1000;
}
void microsDelay(uint32_t us)
{
uint32_t timeNow = micros();
while (!isTimeout(micros(), timeNow, us)) {
// Do nothing
}
}
int isTimeout(unsigned long curTime, unsigned long lastTime, unsigned long maxDuration)
{
if (curTime >= lastTime) {
return curTime > lastTime + maxDuration;
}
return ((ULONG_MAX - lastTime) + curTime) > maxDuration;
}
uint32_t timeToTimeout(unsigned long curTime, unsigned long lastTime, unsigned long maxDuration)
{
if (curTime >= lastTime)
{
if (curTime > lastTime + maxDuration)
{
return 0;
}
return maxDuration - (curTime - lastTime);
}
if (ULONG_MAX - (lastTime - curTime) > maxDuration)
{
return 0;
}
return maxDuration - (ULONG_MAX - (lastTime - curTime));
}
// Startup code
extern "C" void entry_point()
{
// Start and end points of the constructor list,
// defined by the linker script.
extern void (*__init_start)();
extern void (*__init_end)();
// Call each function in the list.
// We have to take the address of the symbols, as __init_start *is*
// the first function pointer, not the address of it.
for (void (**p)() = &__init_start; p < &__init_end; ++p) {
(*p)();
}
// Heap init
nmalloc_set_memory_area((unsigned char*)(MEM_HEAP_START), MEM_HEAP_SIZE);
// Interrupts
CInterrupts::setup();
// Main function
extern int main (void);
main();
}
// CXX
// extern void __aeabi_unwind_cpp_pr0(void);
// extern void __cxa_end_cleanup(void);
// Error handler for pure virtual functions
// extern void __cxa_pure_virtual();
void __cxa_pure_virtual()
{
}
// // Stubbed out exception routine to avoid unwind errors in ARM code
// // https://stackoverflow.com/questions/14028076/memory-utilization-for-unwind-support-on-arm-architecture
// void __aeabi_unwind_cpp_pr0(void)
// {
// }
// // Stubbed out - probably should restore registers but might only be necessary on unwinding after exceptions
// // which are not used
// void __cxa_end_cleanup(void)
// {
// }
extern "C" int __aeabi_atexit(
void *object,
void (*destructor)(void *),
void *dso_handle)
{
static_cast<void>(object);
static_cast<void>(destructor);
static_cast<void>(dso_handle);
return 0;
}
void* __dso_handle = nullptr;
#ifdef __cplusplus
}
#endif
| 22.523438 | 111 | 0.664239 | [
"object"
] |
6b7f26f0940a1cf21cdc96b2bea135ff919aa6aa | 12,869 | cc | C++ | mindspore/lite/tools/converter/adapter/dpico/src/data_preprocessor.cc | httpsgithu/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | 1 | 2022-02-23T09:13:43.000Z | 2022-02-23T09:13:43.000Z | mindspore/lite/tools/converter/adapter/dpico/src/data_preprocessor.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/converter/adapter/dpico/src/data_preprocessor.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/data_preprocessor.h"
#include <unordered_set>
#include <vector>
#include <map>
#include <utility>
#include <string>
#include "common/anf_util.h"
#include "common/file_util.h"
#include "common/op_enum.h"
#include "common/data_transpose_utils.h"
#include "common/string_util.h"
#include "src/mapper_config_parser.h"
#include "opencv2/opencv.hpp"
using mindspore::lite::RET_ERROR;
using mindspore::lite::RET_OK;
namespace mindspore {
namespace dpico {
namespace {
const std::unordered_set<std::string> kRgbInputFormats = {"BGR_PLANAR", "RGB_PLANAR", "RGB_PACKAGE", "BGR_PACKAGE"};
const std::unordered_set<std::string> kGrayInputFormats = {"RAW_RGGB", "RAW_GRBG", "RAW_GBRG", "RAW_BGGR"};
std::vector<std::string> GetImageRealPaths(const std::string &file_path) {
std::vector<std::string> img_paths;
std::ifstream ifs;
if (ReadFileToIfstream(file_path, &ifs) != RET_OK) {
MS_LOG(ERROR) << "read file to ifstream failed.";
return {};
}
size_t num_of_line = 0;
std::string raw_line;
while (getline(ifs, raw_line)) {
if (num_of_line > kMaxLineCount) {
MS_LOG(WARNING) << "the line count is exceeds the maximum range 9999.";
return img_paths;
}
num_of_line++;
if (EraseBlankSpace(&raw_line) != RET_OK) {
MS_LOG(ERROR) << "erase blank space failed. " << raw_line;
return {};
}
if (raw_line.empty() || raw_line.at(0) == '#') {
continue;
}
auto img_path = RealPath(raw_line.c_str());
if (img_path.empty()) {
MS_LOG(ERROR) << "cur image get realpath failed. " << raw_line;
return {};
} else {
img_paths.push_back(img_path);
}
}
return img_paths;
}
int Normalize(cv::Mat *image, const std::map<int, double> &mean, const std::map<int, double> &var) {
if (image == nullptr) {
MS_LOG(ERROR) << "input image is nullptr.";
return RET_ERROR;
}
std::vector<double> mean_vec;
std::vector<double> var_vec;
size_t img_channel_size = image->channels();
if (mean.empty()) {
mean_vec = std::vector<double>(img_channel_size, 0.0);
} else {
if (mean.size() != img_channel_size) {
MS_LOG(ERROR) << "input mean_chn size " << mean.size() << " is not equal to image channels " << img_channel_size;
return RET_ERROR;
}
(void)std::transform(mean.begin(), mean.end(), std::back_inserter(mean_vec),
[](const std::pair<int, double> &pair) { return pair.second; });
}
if (var.empty()) {
var_vec = std::vector<double>(img_channel_size, 0.0);
} else {
if (var.size() != img_channel_size) {
MS_LOG(ERROR) << "input var_reci_chn size " << var.size() << " is not equal to image channels "
<< img_channel_size;
return RET_ERROR;
}
(void)std::transform(var.begin(), var.end(), std::back_inserter(var_vec),
[](const std::pair<int, double> &pair) { return pair.second; });
}
std::vector<cv::Mat> channels(img_channel_size);
cv::split(*image, channels);
for (size_t i = 0; i < channels.size(); i++) {
channels[i].convertTo(channels[i], CV_32FC1, var_vec.at(i), (0.0 - mean_vec.at(i)) * var_vec.at(i));
}
cv::merge(channels, *image);
return RET_OK;
}
} // namespace
DataPreprocessor *DataPreprocessor::GetInstance() {
static DataPreprocessor instance;
return &instance;
}
int DataPreprocessor::ModifyDynamicInputShape(std::vector<int64_t> *input_shape) {
std::vector<size_t> indexes;
for (size_t i = 0; i < input_shape->size(); i++) {
if (input_shape->at(i) < 0) {
indexes.push_back(i);
}
}
if (!indexes.empty()) {
if (indexes.size() == 1 && indexes.at(0) == 0) {
input_shape->at(0) = 1;
} else {
MS_LOG(ERROR) << "dynamic graph input is unsupported by dpico.";
return RET_NO_CHANGE;
}
}
return RET_OK;
}
int DataPreprocessor::GetOutputBinDir(const std::string &op_name, std::string *output_bin_dir) {
auto folder_name = ReplaceSpecifiedChar(op_name, '/', '_');
*output_bin_dir = preprocessed_data_dir_ + folder_name + "/";
if (CreateDir(output_bin_dir) != RET_OK) {
MS_LOG(ERROR) << "Create directory failed. " << *output_bin_dir;
return RET_ERROR;
}
size_t count = 0;
while (AccessFile(*output_bin_dir + "/" + std::to_string(count), F_OK) == 0) {
MS_LOG(DEBUG) << "current file_path has existed, file_path cnt plus 1."; // such as: /xxx/0 ==> /xxx/1
count++;
if (count > kMaximumNumOfFolders) {
MS_LOG(ERROR) << "the number of file folders exceeds the upper limit " << kMaximumNumOfFolders;
return RET_ERROR;
}
}
*output_bin_dir += std::to_string(count);
return RET_OK;
}
int DataPreprocessor::WriteCvMatToBin(const cv::Mat &image, const std::string &op_name) {
std::string generated_bin_dir;
if (GetOutputBinDir(op_name, &generated_bin_dir) != RET_OK) {
MS_LOG(ERROR) << "get output bin dir failed.";
return RET_ERROR;
}
if (Mkdir(generated_bin_dir) != RET_OK) {
MS_LOG(ERROR) << "mkdir failed. " << generated_bin_dir;
return RET_ERROR;
}
std::string output_bin_path = generated_bin_dir + "/input.bin";
std::ofstream ofs;
ofs.open(output_bin_path, std::ios::binary);
if (!ofs.good() || !ofs.is_open()) {
MS_LOG(ERROR) << "open output bin file failed. " << output_bin_path;
return RET_ERROR;
}
for (int i = 0; i < image.rows; i++) {
ofs.write(reinterpret_cast<const char *>(image.ptr(i)), image.cols * image.elemSize());
}
ofs.close();
return RET_OK;
}
int DataPreprocessor::GenerateInputBinFromTxt(const std::string &raw_data_path, const std::string &op_name,
const std::vector<int64_t> &op_shape, TypeId type_id) {
if (op_shape.empty()) {
MS_LOG(ERROR) << "op shape shouldn't be empty.";
return RET_ERROR;
}
std::ifstream ifs;
if (ReadFileToIfstream(raw_data_path, &ifs) != RET_OK) {
MS_LOG(ERROR) << "read file to ifstream failed.";
return RET_ERROR;
}
std::string raw_line;
batch_size_ = 0;
while (getline(ifs, raw_line)) {
if (batch_size_ > kMaxLineCount) {
MS_LOG(WARNING) << "the line count is exceeds the maximum range 9999.";
return RET_ERROR;
}
batch_size_++;
auto preprocessed_line = ReplaceSpecifiedChar(raw_line, ',', ' '); // uniformly separated by spaces
if (EraseHeadTailSpace(&preprocessed_line) != RET_OK) {
MS_LOG(ERROR) << "erase head & tail blank space failed. " << preprocessed_line;
return RET_ERROR;
}
if (preprocessed_line.empty() || preprocessed_line.at(0) == '#') {
continue;
}
int status;
switch (type_id) {
case kNumberTypeFloat:
case kNumberTypeFloat32:
status = GenerateInputBin<float>(preprocessed_line, op_shape, op_name);
break;
case kNumberTypeInt8:
status = GenerateInputBin<int8_t, int16_t>(preprocessed_line, op_shape, op_name);
break;
case kNumberTypeUInt8:
status = GenerateInputBin<uint8_t, uint16_t>(preprocessed_line, op_shape, op_name);
break;
case kNumberTypeInt16:
status = GenerateInputBin<int16_t>(preprocessed_line, op_shape, op_name);
break;
case kNumberTypeUInt16:
status = GenerateInputBin<uint16_t>(preprocessed_line, op_shape, op_name);
break;
case kNumberTypeInt:
case kNumberTypeInt32:
status = GenerateInputBin<int32_t>(preprocessed_line, op_shape, op_name);
break;
case kNumberTypeInt64:
status = GenerateInputBin<int64_t>(preprocessed_line, op_shape, op_name);
break;
case kNumberTypeUInt64:
status = GenerateInputBin<uint64_t>(preprocessed_line, op_shape, op_name);
break;
default:
MS_LOG(ERROR) << "unsupported data type " << dpico::TypeIdToString(type_id);
status = RET_ERROR;
}
if (status != RET_OK) {
MS_LOG(ERROR) << "generate input bin files failed.";
return RET_ERROR;
}
}
return RET_OK;
}
int DataPreprocessor::GenerateInputBinFromImages(const std::string &raw_data_path, const std::string &op_name,
const std::vector<int64_t> &op_shape,
const struct AippModule &aipp_module) {
auto img_paths = GetImageRealPaths(raw_data_path);
if (img_paths.empty()) {
MS_LOG(ERROR) << "[image_list] corresponding file is invalid. " << raw_data_path;
return RET_ERROR;
}
batch_size_ = img_paths.size();
if (op_shape.size() != kDims4) {
MS_LOG(ERROR) << "op shape should be 4 when input is image.";
return RET_ERROR;
}
for (const auto &img_path : img_paths) { // preprocess input image
cv::Mat image;
if (kRgbInputFormats.find(aipp_module.input_format) != kRgbInputFormats.end()) {
image = cv::imread(img_path, cv::IMREAD_COLOR);
} else if (kGrayInputFormats.find(aipp_module.input_format) != kGrayInputFormats.end()) {
image = cv::imread(img_path, cv::IMREAD_GRAYSCALE);
}
if (image.empty() || image.data == nullptr) {
MS_LOG(ERROR) << "missing file, improper permissions, unsupported or invalid format.";
return RET_ERROR;
}
if (aipp_module.model_format == "RGB") {
cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
}
if (image.cols != op_shape[kAxis3] || image.rows != op_shape[kAxis2]) {
MS_LOG(INFO) << "input image shape don't match op shape, and it will be resized.";
cv::resize(image, image, cv::Size(op_shape[kAxis3], op_shape[kAxis2]));
}
if (Normalize(&image, aipp_module.mean_map, aipp_module.val_map) != RET_OK) {
MS_LOG(ERROR) << "image normalize process failed.";
return RET_ERROR;
}
if (WriteCvMatToBin(image, op_name) != RET_OK) {
MS_LOG(ERROR) << "write image to bin file failed." << op_name;
return RET_ERROR;
}
}
return RET_OK;
}
int DataPreprocessor::Run(const api::AnfNodePtrList &inputs) {
if (inputs.empty()) {
MS_LOG(ERROR) << "graph inputs shouldn't be empty.";
return RET_ERROR;
}
auto image_lists = MapperConfigParser::GetInstance()->GetImageLists();
auto aipp_modules = MapperConfigParser::GetInstance()->GetAippModules();
for (const auto &input : inputs) {
auto op_name = input->fullname_with_scope();
if (image_lists.find(op_name) == image_lists.end()) {
MS_LOG(ERROR) << "current op don't exist in image_lists. " << op_name;
return RET_ERROR;
}
auto param_node = input->cast<api::ParameterPtr>();
if (param_node == nullptr) {
MS_LOG(ERROR) << "graph input node should be parameter ptr. " << input->fullname_with_scope();
return RET_ERROR;
}
auto abstract_base = param_node->abstract();
if (abstract_base == nullptr) {
MS_LOG(ERROR) << "Abstract of parameter is nullptr, " << param_node->name();
return lite::RET_PARAM_INVALID;
}
ShapeVector op_shape;
if (FetchShapeFromAbstract(abstract_base, &op_shape) != RET_OK) {
MS_LOG(ERROR) << "get shape vector from graph input failed. " << op_name;
return RET_ERROR;
}
if (op_shape.empty()) {
MS_LOG(ERROR) << "shape is empty." << op_name;
return RET_ERROR;
}
if (ModifyDynamicInputShape(&op_shape) != RET_OK) {
MS_LOG(ERROR) << "modify dynamic input shape failed. " << op_name;
return RET_ERROR;
}
TypeId op_type;
if (FetchTypeIdFromAbstract(abstract_base, &op_type) != RET_OK) {
MS_LOG(ERROR) << "get type id from graph input failed. " << op_name;
return RET_ERROR;
}
auto raw_data_path = image_lists.at(op_name);
preprocessed_data_dir_ = MapperConfigParser::GetInstance()->GetOutputPath() + "preprocessed_data/";
if (aipp_modules.find(op_name) == aipp_modules.end()) {
if (GenerateInputBinFromTxt(raw_data_path, op_name, op_shape, op_type) != RET_OK) {
MS_LOG(ERROR) << "generate input bin from txt failed.";
return RET_ERROR;
}
} else {
if (GenerateInputBinFromImages(raw_data_path, op_name, op_shape, aipp_modules.at(op_name)) != RET_OK) {
MS_LOG(ERROR) << "generate input bin from images failed.";
return RET_ERROR;
}
}
}
return RET_OK;
}
} // namespace dpico
} // namespace mindspore
| 36.768571 | 119 | 0.652654 | [
"shape",
"vector",
"transform"
] |
6b81ebfea13d8be56eecfdc08019806e35651ec2 | 11,762 | cpp | C++ | packages/monte_carlo/event/estimator/test/tstStandardEstimatorFactory_Root.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/monte_carlo/event/estimator/test/tstStandardEstimatorFactory_Root.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/monte_carlo/event/estimator/test/tstStandardEstimatorFactory_Root.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file tstStandardEstimatorFactory_Root.cpp
//! \author Alex Robinson
//! \brief Standard estimator factory specialization for Root unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
#include <memory>
#include <unordered_map>
// Trilinos Includes
#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_ParameterList.hpp>
#include <Teuchos_XMLParameterListCoreHelpers.hpp>
#include <Teuchos_VerboseObject.hpp>
// FRENSIE Includes
#include "MonteCarlo_StandardEstimatorFactory_Root.hpp"
#include "MonteCarlo_ResponseFunctionFactory.hpp"
#include "MonteCarlo_EventHandler.hpp"
#include "MonteCarlo_EstimatorHDF5FileHandler.hpp"
#include "Geometry_Root.hpp"
#include "Geometry_RootInstanceFactory.hpp"
#include "Geometry_ModuleInterface_Root.hpp"
#include "Utility_OneDDistributionEntryConverterDB.hpp"
//---------------------------------------------------------------------------//
// Testing Variables
//---------------------------------------------------------------------------//
Teuchos::RCP<Teuchos::ParameterList> observer_reps;
boost::unordered_map<unsigned,std::shared_ptr<MonteCarlo::ResponseFunction> >
response_function_id_map;
std::shared_ptr<MonteCarlo::EventHandler> event_handler;
std::shared_ptr<MonteCarlo::EstimatorFactory> estimator_factory;
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that the factory can be constructed
TEUCHOS_UNIT_TEST( StandardEstimatorFactory_Root, constructor )
{
std::shared_ptr<MonteCarlo::SimulationGeneralProperties> properties(
new MonteCarlo::SimulationGeneralProperties );
TEST_NOTHROW( estimator_factory =
MonteCarlo::getEstimatorFactoryInstance<Geometry::Root>(
event_handler,
response_function_id_map,
properties ) );
}
//---------------------------------------------------------------------------//
// Check if the parameter list describes an estimator
TEUCHOS_UNIT_TEST( StandardEstimatorFactory_Root, isEstimatorRep )
{
Teuchos::ParameterList dummy_rep;
TEST_ASSERT( !estimator_factory->isEstimatorRep( dummy_rep ) );
TEST_ASSERT( estimator_factory->isEstimatorRep(
observer_reps->get<Teuchos::ParameterList>(
"Cell Track Length Flux Estimator 2" ) ) );
TEST_ASSERT( estimator_factory->isEstimatorRep(
observer_reps->get<Teuchos::ParameterList>(
"Cell Collision Flux Estimator 2" ) ) );
TEST_ASSERT( estimator_factory->isEstimatorRep(
observer_reps->get<Teuchos::ParameterList>(
"Pulse Height Estimator 2" ) ) );
TEST_ASSERT( estimator_factory->isEstimatorRep(
observer_reps->get<Teuchos::ParameterList>(
"Surface Flux Estimator 2" ) ) );
TEST_ASSERT( estimator_factory->isEstimatorRep(
observer_reps->get<Teuchos::ParameterList>(
"Surface Current Estimator 2" ) ) );
}
//---------------------------------------------------------------------------//
// Check if estimators can be created and registered with the event handler
TEUCHOS_UNIT_TEST( StandardEstimatorFactory_Root, createAndRegisterEstimator )
{
Teuchos::ParameterList::ConstIterator observer_rep_it =
observer_reps->begin();
while( observer_rep_it != observer_reps->end() )
{
const Teuchos::ParameterList& observer_rep =
Teuchos::any_cast<Teuchos::ParameterList>(
observer_rep_it->second.getAny() );
estimator_factory->createAndRegisterEstimator( observer_rep );
++observer_rep_it;
}
// Check that all of the estimators got created
TEST_EQUALITY_CONST( event_handler->getNumberOfObservers(), 8 );
std::string estimator_file_name( "estimator_factory_root.h5" );
{
std::shared_ptr<Utility::HDF5FileHandler>
hdf5_file( new Utility::HDF5FileHandler );
hdf5_file->openHDF5FileAndOverwrite( estimator_file_name );
event_handler->exportObserverData( hdf5_file,
1,
1,
0.0,
1.0,
false );
}
// Initialize the hdf5 file
std::shared_ptr<Utility::HDF5FileHandler>
hdf5_file( new Utility::HDF5FileHandler );
hdf5_file->openHDF5FileAndReadOnly( estimator_file_name );
// Create an estimator hdf5 file handler
MonteCarlo::EstimatorHDF5FileHandler hdf5_file_handler( hdf5_file );
// Check that the correct estimators exist
TEST_ASSERT( hdf5_file_handler.doesEstimatorExist( 12 ) );
TEST_ASSERT( hdf5_file_handler.doesEstimatorExist( 13 ) );
TEST_ASSERT( hdf5_file_handler.doesEstimatorExist( 14 ) );
// Check that estimator 12 has the correct properties
TEST_ASSERT( hdf5_file_handler.isCellEstimator( 12 ) );
double multiplier;
hdf5_file_handler.getEstimatorMultiplier( 12, multiplier );
TEST_EQUALITY_CONST( multiplier, 2.0 );
Teuchos::Array<unsigned> response_function_ordering;
hdf5_file_handler.getEstimatorResponseFunctionOrdering(
12, response_function_ordering );
TEST_EQUALITY_CONST( response_function_ordering.size(), 1 );
TEST_EQUALITY_CONST( response_function_ordering[0], 0 );
Teuchos::Array<MonteCarlo::PhaseSpaceDimension> dimension_ordering;
hdf5_file_handler.getEstimatorDimensionOrdering( 12, dimension_ordering );
TEST_EQUALITY_CONST( dimension_ordering.size(), 1 );
TEST_EQUALITY_CONST( dimension_ordering[0],
MonteCarlo::SOURCE_ENERGY_DIMENSION );
Teuchos::Array<double> energy_bins;
hdf5_file_handler.getEstimatorBinBoundaries<MonteCarlo::SOURCE_ENERGY_DIMENSION>(
12, energy_bins );
TEST_EQUALITY_CONST( energy_bins.size(), 14 );
TEST_EQUALITY_CONST( energy_bins.front(), 1e-3 );
TEST_EQUALITY_CONST( energy_bins.back(), 20.0 );
std::unordered_map<Geometry::ModuleTraits::EntityId,double>
cell_id_vols;
hdf5_file_handler.getEstimatorEntities( 12, cell_id_vols );
TEST_EQUALITY_CONST( cell_id_vols.size(), 1 );
TEST_ASSERT( cell_id_vols.count( 1 ) );
// Check that estimator 13 has the correct properties
TEST_ASSERT( hdf5_file_handler.isCellEstimator( 13 ) );
hdf5_file_handler.getEstimatorMultiplier( 13, multiplier );
TEST_EQUALITY_CONST( multiplier, 2.0 );
hdf5_file_handler.getEstimatorResponseFunctionOrdering(
13, response_function_ordering );
TEST_EQUALITY_CONST( response_function_ordering.size(), 1 );
TEST_EQUALITY_CONST( response_function_ordering[0], 0 );
dimension_ordering.clear();
hdf5_file_handler.getEstimatorDimensionOrdering( 13, dimension_ordering );
Teuchos::Array<double> time_bins;
hdf5_file_handler.getEstimatorBinBoundaries<MonteCarlo::SOURCE_TIME_DIMENSION>(
13, time_bins );
TEST_EQUALITY_CONST( time_bins.size(), 5 );
TEST_EQUALITY_CONST( time_bins.front(), 0.0 );
TEST_EQUALITY_CONST( time_bins.back(), 1.0 );
cell_id_vols.clear();
hdf5_file_handler.getEstimatorEntities( 13, cell_id_vols );
TEST_EQUALITY_CONST( cell_id_vols.size(), 1 );
TEST_ASSERT( cell_id_vols.count( 1 ) );
// Check that estimator 14 has the correct properties
TEST_ASSERT( hdf5_file_handler.isCellEstimator( 14 ) );
hdf5_file_handler.getEstimatorMultiplier( 14, multiplier );
TEST_EQUALITY_CONST( multiplier, 1.0 );
response_function_ordering.clear();
hdf5_file_handler.getEstimatorResponseFunctionOrdering(
14, response_function_ordering );
TEST_EQUALITY_CONST( response_function_ordering.size(), 1 );
TEST_EQUALITY_CONST( response_function_ordering.front(), 4294967295 );
dimension_ordering.clear();
hdf5_file_handler.getEstimatorDimensionOrdering( 14, dimension_ordering );
TEST_EQUALITY_CONST( dimension_ordering.size(), 0 );
cell_id_vols.clear();
hdf5_file_handler.getEstimatorEntities( 14, cell_id_vols );
TEST_EQUALITY_CONST( cell_id_vols.size(), 1 );
TEST_ASSERT( cell_id_vols.count( 1 ) );
}
//---------------------------------------------------------------------------//
// Check that cached estimators can be created and registered
TEUCHOS_UNIT_TEST( StandardEstimatorFactory_Root,
createAndRegisterCachedEstimators )
{
TEST_NOTHROW( estimator_factory->createAndRegisterCachedEstimators() );
// Check that all of the estimators got created
TEST_EQUALITY_CONST( event_handler->getNumberOfObservers(), 8 );
}
//---------------------------------------------------------------------------//
// Custom main function
//---------------------------------------------------------------------------//
int main( int argc, char** argv )
{
std::string test_geom_xml_file_name;
std::string test_resp_func_xml_file_name;
std::string test_observer_xml_file_name;
Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP();
clp.setOption( "test_geom_xml_file",
&test_geom_xml_file_name,
"Test xml geometry file name" );
clp.setOption( "test_resp_func_xml_file",
&test_resp_func_xml_file_name,
"Test response function xml file name" );
clp.setOption( "test_observer_xml_file",
&test_observer_xml_file_name,
"Test estimator xml file name" );
const Teuchos::RCP<Teuchos::FancyOStream> out =
Teuchos::VerboseObjectBase::getDefaultOStream();
Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return =
clp.parse(argc,argv);
if ( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) {
*out << "\nEnd Result: TEST FAILED" << std::endl;
return parse_return;
}
// Initialize Root
Teuchos::RCP<Teuchos::ParameterList> geom_rep =
Teuchos::getParametersFromXmlFile( test_geom_xml_file_name );
Geometry::RootInstanceFactory::initializeRoot( *geom_rep );
// Load the observer parameter lists
observer_reps =
Teuchos::getParametersFromXmlFile( test_observer_xml_file_name );
// Load the response functions
{
Teuchos::RCP<Teuchos::ParameterList> response_reps =
Teuchos::getParametersFromXmlFile( test_resp_func_xml_file_name );
MonteCarlo::ResponseFunctionFactory::createResponseFunctions(
*response_reps,
response_function_id_map );
}
// Initialize the event handler
event_handler.reset( new MonteCarlo::EventHandler );
// Run the unit tests
Teuchos::GlobalMPISession mpiSession( &argc, &argv );
const bool success = Teuchos::UnitTestRepository::runUnitTests(*out);
if (success)
*out << "\nEnd Result: TEST PASSED" << std::endl;
else
*out << "\nEnd Result: TEST FAILED" << std::endl;
clp.printFinalTimerSummary(out.ptr());
return (success ? 0 : 1);
}
//---------------------------------------------------------------------------//
// end tstStandardEstimatorFactory_Root.cpp
//---------------------------------------------------------------------------//
| 36.75625 | 83 | 0.627104 | [
"geometry"
] |
6b838abf1476487d176787fb9a4557c895488c28 | 5,261 | cpp | C++ | src/contrib/mlir/core/ngraph_dialect/dialect.cpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/contrib/mlir/core/ngraph_dialect/dialect.cpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/contrib/mlir/core/ngraph_dialect/dialect.cpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
// NOTE: This file follows nGraph format style and MLIR naming convention since
// it does
// not expose public API to the rest of nGraph codebase and heavily depends on
// MLIR API.
#include "dialect.hpp"
#include <llvm/ADT/TypeSwitch.h>
#include <mlir/IR/DialectImplementation.h>
#include <mlir/Parser.h>
#include "ngraph/check.hpp"
#include "ops.hpp"
#include "type.hpp"
using namespace mlir;
NGraphOpsDialect::NGraphOpsDialect(mlir::MLIRContext* ctx)
: mlir::Dialect(getDialectNamespace(), ctx, mlir::TypeID::get<NGraphOpsDialect>())
{
addTypes<NGTensorType>();
addTypes<NGBoolType>();
addOperations<
#define GET_OP_LIST
#include "ops.cpp.inc"
>();
}
mlir::Type NGraphOpsDialect::parseType(mlir::DialectAsmParser& parser) const
{
MLIRContext* context = getContext();
// Process nGraph tensor type.
// failure is true
if (!parser.parseOptionalKeyword("tensor"))
{
llvm::SMLoc typeLoc = parser.getCurrentLocation();
if (parser.parseLess())
{
parser.emitError(typeLoc, "expected '<' and '>' enclosing the tensor shape");
return Type();
}
// Parse shape dimensions.
SmallVector<int64_t, 4> shape;
parser.parseDimensionList(shape);
// Parse the current element type.
Type eltType;
parser.parseType(eltType);
if (!eltType)
{
typeLoc = parser.getCurrentLocation();
parser.emitError(typeLoc, "Invalid tensor element type");
}
parser.parseGreater();
return NGTensorType::get(context, eltType, shape);
}
else
{
// parse nGraph scalar type
return parseEltType(parser);
}
}
mlir::Type NGraphOpsDialect::parseEltType(mlir::DialectAsmParser& parser) const
{
// Process nGraph integer element types.
MLIRContext* context = getContext();
bool isSigned = false;
llvm::SMLoc loc = parser.getCurrentLocation();
StringRef tyData = parser.getFullSymbolSpec();
StringRef origTypeStr = tyData;
if (tyData.startswith("i") || tyData.startswith("u"))
{
isSigned = tyData.consume_front("i");
tyData.consume_front("u");
unsigned width = 0;
// NOTE: `consumeInteger` returns false if an integer was parsed
// successfully.
if (tyData.consumeInteger(/*Radix=*/10, width) || width == 0 || !tyData.empty())
{
parser.emitError(loc, "Unexpected nGraph integer type: " + origTypeStr);
}
auto signedness = isSigned ? NGIntegerType::SignednessSemantics::Signed
: NGIntegerType::SignednessSemantics::Unsigned;
if (!(width == 8 || width == 16 || width == 32 || width == 64))
{
parser.emitError(loc,
"Unexpected width = " + std::to_string(width) +
" for nGraph integer type: " + origTypeStr);
}
return NGIntegerType::get(width, signedness, context);
}
// nGraph reuses standard dialect floating point element types.
NGRAPH_CHECK(!tyData.startswith("f"),
"Floating point types should be processed by standard parser");
// NOTE: We may hit this error if the nGraph type is not yet supported in
// parser.
parser.emitError(loc, "Unknown nGraph type: " + origTypeStr);
return Type();
}
void NGraphOpsDialect::printType(mlir::Type type, mlir::DialectAsmPrinter& printer) const
{
TypeSwitch<Type>(type)
.Case<NGTensorType>([&](Type) {
printer << "tensor<";
auto tensorTy = type.cast<NGTensorType>();
for (auto dim : tensorTy.getShape())
{
printer << dim << 'x';
}
printer << tensorTy.getElementType() << '>';
})
.Case<NGIntegerType>([&](Type) {
auto intTy = type.cast<NGIntegerType>();
auto signedness = intTy.getSignedness();
if (signedness == NGIntegerType::SignednessSemantics::Signed)
{
printer << "i";
}
else if (signedness == NGIntegerType::SignednessSemantics::Unsigned)
{
printer << "u";
}
// TODO: What about Signless?
printer << intTy.getWidth();
})
.Case<NGBoolType>([&](Type) { printer << "bool"; })
.Default([](Type) { NGRAPH_UNREACHABLE("Incorrect type to print?"); });
}
| 33.509554 | 89 | 0.592283 | [
"shape"
] |
6b85134fda0e2b1e1050bcf49fded8760f999a56 | 1,335 | hpp | C++ | location/src/GenomeLocation.hpp | lucyhancock3533/CRISPR-search | 4ed4544589ae941af787d09880817b77a413a3b1 | [
"Unlicense"
] | null | null | null | location/src/GenomeLocation.hpp | lucyhancock3533/CRISPR-search | 4ed4544589ae941af787d09880817b77a413a3b1 | [
"Unlicense"
] | null | null | null | location/src/GenomeLocation.hpp | lucyhancock3533/CRISPR-search | 4ed4544589ae941af787d09880817b77a413a3b1 | [
"Unlicense"
] | null | null | null | #ifndef CRISPR_SEARCH_LOCATION_GENOMELOCATION_HPP
#define CRISPR_SEARCH_LOCATION_GENOMELOCATION_HPP
#include "cslocation.hpp"
#include "LocationDb.hpp"
namespace crisprsearch::location {
/**
* Genome location class, to prepare and run CRISPRCasFinder
*/
class GenomeLocation {
private:
Genome* genome;
string genomePath;
LocationDb* dbConnection;
/**
* Process genome function. Launches CCF and calls genome results parser.
*/
void processGenome();
public:
/**
* Build a GenomeLocation class to prepare and run CRISPRCasFinder
* @param path Full UNIX path to the genome to search
* @param db LocationDb object pointer, pointer to created and opened database object
* @param name Name of genome being searched
* @param info Info link of genome
* @param source Source of genome to be searched
*/
explicit GenomeLocation(string path, LocationDb* db, string name, string info, string source);
/**
* GenomeLocation destructor, cleans up any pointers used.
*/
~GenomeLocation();
/**
* Load a genome into processing directory and call processGenome to search for crispr.
*/
void loadGenome();
};
}
#endif | 32.560976 | 102 | 0.641948 | [
"object"
] |
6b8907055649ad880bbb6e5a8b89fb1a604a8842 | 21,201 | cpp | C++ | lite/io.cpp | philomath213/nlp-engine | 9c9d694b985a6a266004c32f8866098666a640ca | [
"MIT"
] | null | null | null | lite/io.cpp | philomath213/nlp-engine | 9c9d694b985a6a266004c32f8866098666a640ca | [
"MIT"
] | null | null | null | lite/io.cpp | philomath213/nlp-engine | 9c9d694b985a6a266004c32f8866098666a640ca | [
"MIT"
] | null | null | null | /*******************************************************************************
Copyright (c) 2001-2010 by Text Analysis International, Inc.
All rights reserved.
********************************************************************************
*
* NAME: IO.CPP
* FILE: lite\io.cpp
* CR: 10/06/98 AM.
* SUBJ: I/O functions.
*
*******************************************************************************/
#include "StdAfx.h"
#include "machine.h" // 03/09/00 AM.
#include "u_out.h" // 01/19/06 AM.
#include "prim/libprim.h" // 01/18/06 AM.
#include "prim/str.h" // 01/18/06 AM.
#include "lite/global.h"
#include "inline.h" // 05/19/99 AM.
#include "std.h"
#include "chars.h"
#include "io.h"
/********************************************
*
* FN: COPY_FILE
* CR: 10/06/98 AM.
* SUBJ: Copy input file to output file.
* NOTE: Presumably doesn't matter if file is unicode or not.
* A char is a char in any case.
*
********************************************/
void copy_file(const _TCHAR *iname, const _TCHAR *oname)
{
//ifstream inFile(iname, ios::in | ios::nocreate);
_t_ifstream inFile(CTCHAR2CA(iname), ios::in); // Upgrade. // 01/24/01 AM.
if (!inFile)
{
_t_strstream gerrStr;
gerrStr << _T("Could not open input file '") << iname << _T("'.") << ends;
errOut(&gerrStr,false);
return; // 06/15/99 AM.
}
_t_ofstream outFile(CTCHAR2CA(oname), ios::out);
if (!outFile)
{
_t_strstream gerrStr;
gerrStr << _T("Could not open output file '") << oname << _T("'.") << ends;
errOut(&gerrStr,false);
return; // 06/15/99 AM.
}
// Echo input file to output.
// << and >> ignore whitespace!
_TCHAR ch;
// Changing handling of EOF. // 12/16/01 AM.
//while ((ch = inFile.get()) != EOF) // 12/16/01 AM.
// outFile.put(ch); // 12/16/01 AM.
for (;;) // 12/18/01 AM.
{
ch = inFile.get(); // 12/18/01 AM.
if (inFile.eof()) // 12/18/01 AM.
break; // 12/18/01 AM.
outFile.put(ch); // 12/18/01 AM.
}
}
/********************************************
*
* FN: FILE_EXISTS
* CR: 12/14/98 AM.
* SUBJ: Check if file exists.
********************************************/
bool file_exists(const _TCHAR *iname)
{
//ifstream inFile(iname, ios::in | ios::nocreate);
_t_ifstream inFile(CTCHAR2CA(iname), ios::in);
return (inFile ? true : false);
}
/********************************************
*
* FN: FILE_TO_BUFFER
* CR: 10/08/98 AM.
* SUBJ: Copy input file to a buffer.
* NOTE: Presumably doesn't matter if file is unicode or not.
* A char is a char in any case.
* 05/28/00 AM. Length of good chars may not be equivalent to file
* size obtained from system, so keep a count here and return it.
* ASS: Assume buffer is large enough. Assume buffer was allocated
* using length of the file.
*
********************************************/
void file_to_buffer(const _TCHAR *iname, _TCHAR *buf,
/*UP*/ long &len // 05/28/00 AM.
)
{
//ifstream inFile(iname, ios::in | ios::nocreate);
_t_ifstream inFile(CTCHAR2CA(iname), ios::in); // Update. // 01/24/01 AM.
if (!inFile)
{
_t_strstream gerrStr;
gerrStr << _T("Could not open input file '") << iname << _T("'.") << ends;
errOut(&gerrStr,false);
//exit(1); // 06/15/99 AM.
return; // 06/15/99 AM.
}
//char ch; // 12/16/01 AM.
_TCHAR *ptr=buf; // 05/28/00 AM.
// Better EOF handling etc. // 12/16/01 AM.
//while ((ch = inFile.get()) != EOF) // 12/16/01 AM.
// *buf++ = ch; // 12/16/01 AM.
//*buf = '\0'; // Terminate buffer. // 12/16/01 AM.
--buf; // For efficiency. // 12/16/01 AM.
while (!inFile.eof()) // 12/16/01 AM.
*++buf = inFile.get(); // 12/16/01 AM.
*buf = '\0'; // Terminate buffer (AND OVERWRITE EOF CHAR) // 12/16/01 AM.
len = (unsigned long)buf - (unsigned long)ptr + 1; // 05/28/00 AM.
}
/********************************************
* FN: FIX_FILE_NAME
* CR: 10/23/98 AM.
* SUBJ: Add the file name extension if absent.
* WARN: MODIFIES GIVEN FILE NAME BUFFER.
* IF ANY EXTENSION PRESENT, DOES NOT MODIFY FILE NAME.
* ASS: BUFFER MUST BE BIG ENOUGH FOR ADDED EXTENSION, IF MISSING.
* Note: May want a string handling class to do some of the ops here.
********************************************/
bool fix_file_name(
_TCHAR *file, // Buffer big enough to hold extension.
_TCHAR *suff // File name extension needed.
)
{
if (empty(file))
{
_t_strstream gerrStr;
gerrStr << _T("[fix_file_name: Given no file name.]") << ends;
errOut(&gerrStr,false);
return false;
}
if (empty(suff))
{
_t_strstream gerrStr;
gerrStr << _T("[fix_file_name: Given no file name extension.]") << ends;
errOut(&gerrStr,false);
return false;
}
_TCHAR *ptr;
// 12/03/98 AM. Go backward, finding backslash or period, whichever comes
// first.
ptr = file;
while (*ptr++)
; // Go to forward to end of buffer.
ptr--; // Back to end of string.
while (--ptr != file) // Go backward now.
{
if (*ptr == '.') // Found extension.
{
// Not modifying extension, since one is present.
// Here's a check for some abnormal filenames, though.
if (ptr == file || !*++ptr)
{
_t_strstream gerrStr;
gerrStr << _T("[Bad file name='") << file << _T("'.]") << ends;
errOut(&gerrStr,false);
return false;
}
return true; // 12/03/98 AM.
}
#ifndef LINUX
if (*ptr == '\\') // Found backslash. Stop looking for period.
#else
if (*ptr == DIR_CH) // Found slash.
#endif
break;
}
// Add extension to file name.
_tcscat(file, _T("."));
_tcscat(file, suff);
return true;
}
/********************************************
* FN: PRETTY_CHAR
* CR: 10/09/98 AM.
* SUBJ: Get printable form for a character.
* NOTE: User had better copy string immediately.
********************************************/
_TCHAR *pretty_char(_TCHAR x)
{
static _TCHAR twofer[2] = { '\0', '\0' };
switch (x)
{
case '\a': return _T("\\a");
case '\b': return _T("\\b");
case '\n': return _T("\\n");
case '\r': return _T("\\r");
case '\f': return _T("\\f");
case '\t': return _T("\\t");
case '\v': return _T("\\v");
case '\\': return _T("\\\\"); // 11/24/98 AM.
case '\0': return _T("\\0"); // 11/18/98 AM.
case ' ': return _T("\\_"); // 03/24/99 AM.
default: twofer[0] = x; return twofer;
}
}
/********************************************
* FN: PRETTY_STR
* CR: 11/24/98 AM.
* SUBJ: Get printable form for a string.
* NOTE: User had better copy string immediately.
* RET: User-supplied buffer for cleaned up string.
********************************************/
_TCHAR *pretty_str(
_TCHAR *str, // String to be prettified.
_TCHAR *buf, // Buffer for placing prettified string.
long size // Buffer size.
)
{
*buf = '\0';
_TCHAR *end;
end = &(buf[0]);
for (; *str; ++str) // Traverse string.
{
if (!strcat_e(end, pretty_char(*str), size))
return buf;
}
return buf;
}
/********************************************
* FN: READ_FILE
* CR: 10/13/98 AM.
* SUBJ: Read contents of a file into a buffer.
* ALLOC: Creates buffer that must be freed.
********************************************/
void read_file(
_TCHAR *fname, // The filename
/*UP*/
long &len, // Length of file.
_TCHAR* &buf // Buffer to create.
)
{
// Get file length.
len = file_size(fname);
buf = 0;
if (len <= 0)
return;
++len; // Add one for null termination. // 05/28/00 AM.
// Allocate a buffer to hold all the chars of file.
buf = Chars::create(len); // 11/19/98 AM.
// Don't include null terminator in count. // 05/28/00 AM.
file_to_buffer(fname, buf, // Suck in the file.
/*UP*/ len); // Use count from examining chars of file. // 05/28/00 AM.
}
/********************************************
* FN: NEXT_TOKEN
* CR: 10/13/98 AM.
* SUBJ: Find next token on current line in buffer.
* NOTE: Assumes whitespace, newlines and end of buffer are only delimiters.
* buf is at lookahead char. eol tells if end of current line seen.
* buf returned null only at end of buffer.
* Should also skip # signs!
* A SPECIALIZED FUNCTION.
* WARN: MODIFIES GIVEN BUFFER. Places NULLS for token delimiters.
********************************************/
_TCHAR *next_token(
/*DU*/
_TCHAR* &buf,
bool &eol,
_TCHAR *comment // Buffer for storing comment. // 01/13/99 AM.
)
{
_TCHAR *first; // First char of next token.
if (!buf || !*buf)
{
eol = true;
return buf;
}
// Skip whitespace.
bool found = false; // 09/02/99 AM.
while (_istspace((_TUCHAR)*buf) && *buf != '\n')
++buf;
if (*buf == '\n') // At end of current line.
{
eol = true;
++buf;
return 0;
}
else if (*buf == '#') // Comment
{
found = false; // Haven't found nonwhite yet. // 09/02/99 AM.
while (*++buf && *buf != '\n' // Find end of line.
&& *buf != '\r') // 02/12/99 AM.
{
// 09/02/99 AM. SKIP LEADING WHITESPACE IN COMMENT!
if (found)
*comment++ = *buf; // 01/15/99 AM.
else if (!_istspace((_TUCHAR)*buf)) // IGNORE LEADING WHITE. // 09/02/99 AM.
{
*comment++ = *buf;
found = true; // Found first nonwhite. // 09/02/99 AM.
}
}
*comment = '\0'; // 01/15/99 AM.
eol = true;
if (!*buf)
return 0;
++buf; // One past newline.
return (_TCHAR *) NULL;
}
first = buf++; // Found first char of next token.
while (*buf && !_istspace((_TUCHAR)*buf)) // Find next whitespace.
++buf; // OPT. // 11/29/00 AM.
if (!*buf) // End of buffer.
{
eol = true;
return first;
}
if (*buf == '\n')
eol = true;
*buf = '\0'; // MODIFY BUFFER TO TERMINATE TOKEN.
++buf;
return first;
}
/********************************************
* FN: EQ_STR_RANGE
* CR: 10/26/98 AM.
* SUBJ: See if string matches character range.
* NOTE: Defining "range" as a char substring with a start and end offset.
* start and end are inclusive.
********************************************/
bool eq_str_range(_TCHAR *str, _TCHAR *buf, long start, long end)
{
if (empty(str) && empty(buf)) // Both empty.
return true;
if (empty(str) || empty(buf)) // Exactly one is empty.
return false;
if (start < 0 || end < 0 || end < start)
{
_t_strstream gerrStr;
gerrStr << _T("[eq_str_range: Bad start, end=")
<< start << _T(",") << end << _T(".]") << ends;
errOut(&gerrStr,false);
return false;
}
_TCHAR *ptr;
_TCHAR *eptr;
ptr = &(buf[start]);
eptr = &(buf[end]);
if (!*eptr)
{
_t_strstream gerrStr;
gerrStr << _T("[eq_str_range: Endpoint shouldn't be null.]") << ends;
errOut(&gerrStr,false);
return false;
}
while (*str && (*str == *ptr) && (ptr != eptr))
{
++str;
++ptr;
}
if (*str && (*str == *ptr) && (ptr == eptr)) // Exhausted range.
return *++str ? false : true; // If str exhausted, then equal.
return false;
}
/********************************************
* FN: MAKE_STR
* CR: 10/28/98 AM.
* SUBJ: Create a new string.
* ALLOC: Creates a new char array.
* NOTE: Doesn't create array for empty string.
********************************************/
_TCHAR *make_str(_TCHAR *str)
{
if (empty(str))
return 0;
_TCHAR *tmp;
//tmp = new char[strlen(str) + 1];
tmp = Chars::create(_tcsclen(str) + 1);
_tcscpy(tmp, str);
return tmp;
}
/******** VARIANT ***********/
_TCHAR *make_str(
_TCHAR *str, // Substring to copy.
long len // Length of substring.
)
{
if (empty(str) || len <= 0)
return 0;
_TCHAR *tmp;
//tmp = new char[len + 1];
tmp = Chars::create(len + 1);
_tcsnccpy(tmp, str, len);
tmp[len] = '\0';
return tmp;
}
/********************************************
* FN: STRCAT_E
* CR: 11/20/98 AM.
* SUBJ: Catenate strings.
* NOTE: Useful for multiple catenation.
* Handling the count with termination char is tricky.
* More straightforward would require the user to call this with
* buffer size - 1.
* RET: DU ptr - points to end of the newly catenated string.
* DU count < 0 then not using this. Else it tracks space left
* in catenation buffer (pointed into by ptr).
********************************************/
bool strcat_e(
/*DU*/ _TCHAR* &ptr,
/*DN*/ _TCHAR *str,
/*DU*/ long &count
)
{
if (empty(str))
return true; // Nothing to do.
if (count == 0 || count == 1)
{
// Note: count == 1 means that the terminator has filled buffer.
_t_strstream gerrStr;
gerrStr << _T("[strcat_e: String overflow.]") << ends;
errOut(&gerrStr,false);
return false;
}
if (count > 0)
{
while (*ptr++ = *str++)
{
if (--count == 0)
break;
}
if (*(ptr-1)) // Didn't complete copying.
{
_t_strstream gerrStr;
gerrStr << _T("[strcat_e: String overflow(2).]") << ends;
errOut(&gerrStr,false);
*(ptr-1) = '\0'; // Truncate the string in buffer.
return false;
}
// DON'T COUNT THE TERMINATION CHAR.
--ptr; // Back up to termination char.
}
else // Not checking on buffer size.
{
while (*ptr++ = *str++)
;
--ptr; // Back up to termination char.
}
return true;
}
/********************************************
* FN: STRNCAT_E
* CR: 11/20/98 AM.
* SUBJ: Catenate strings.
* NOTE: Useful for multiple catenation.
* RET: DU ptr - points to end of the newly catenated string.
* DU count < 0 then not using this. Else it tracks space left
* in catenation buffer (pointed into by ptr).
********************************************/
bool strncat_e(
/*DU*/ _TCHAR* &ptr, // Pointer to terminal char in buffer.
/*DN*/ _TCHAR *str, // String to add.
/*DN*/ long len, // String length.
/*DU*/ long &count // Space left in buffer.
)
{
if (empty(str) || (len <= 0))
return true; // Nothing to do.
if (count == 0 || count == 1)
{
// Note: count == 1 means that the terminator has filled buffer.
_t_strstream gerrStr;
gerrStr << _T("[strncat_e: String overflow.]") << ends;
errOut(&gerrStr,false);
return false;
}
if (count > 0) // Tracking space left in buffer.
{
if (len >= count)
{
// Note: len >= count, because one space needed for terminator.
_t_strstream gerrStr;
gerrStr << _T("[strncat_e: String overflow(1).]") << ends;
errOut(&gerrStr,false);
// Could recover by filling buffer to the max.
// len = count - 1;
// count = 0;
return false;
}
// DON'T COUNT THE TERMINATION CHAR!
count -= len;
}
while (len--)
*ptr++ = *str++;
*ptr = '\0'; // Terminate the buffer.
return true;
}
/********************************************
*
* FN: DIRECTOUTPUT
* CR: 12/01/98 AM.
* SUBJ: Direct standard output to a file.
* NOTE: Just rebinding the standard output stream.
* DOES NOT WORK.
* STAT: I can redirect cout to output to a file, but I can't get it
* back to standard output again!
*
********************************************/
#ifdef JUNKYY_
_t_filebuf *directOutput(_TCHAR *fname)
{
if (empty(fname))
{
_t_strstream gerrStr;
gerrStr << _T("[directOutput: Given null file name.]") << ends;
errOut(&gerrStr,false);
return 0;
}
#ifndef LINUX
int fh;
fh = open_outfile(fname);
_t_filebuf *fb;
fb = new _t_filebuf(fh);
//filebuf fb(fh); // Filebuf object attached to "test.dat"
_t_cout = fb; // fb associated with cout
_t_cerr = fb; // ELSE CERR MESSAGES BOMB.
_t_cout << _T("testing"); // Message goes to "test.dat" instead of stdout
_t_cout << endl;
_t_cout << endl;
close_outfile(fh);
#endif
return 0;
}
#endif
/********************************************
* FN: FILE_NAME
* CR: 12/24/99 AM.
* SUBJ: Given a file, get its name without path.
* WARN: MODIFIES GIVEN FILE NAME BUFFER.
* (Not really, but some related fns do.)
********************************************/
bool file_name(
_TCHAR *file, // Buffer with full file string.
/*UP*/
_TCHAR* &fname // Pointer to the name in buffer.
)
{
fname = 0;
if (!file || !*file)
return false;
_TCHAR *ptr;
ptr = file;
while (*ptr++)
; // Go to forward to end of buffer.
ptr--; // Back to end of string.
// Go backward, finding backslash if any.
while (--ptr != file)
{
if (*ptr == '\\') // Found backslash.
break;
}
fname = ++ptr; // Points to filename, if any, now.
return true;
}
/********************************************
* FN: FILE_PATH
* CR: 12/24/99 AM.
* SUBJ: Given a file, get its path without name.
* RET: Path without final backslash.
* WARN: MODIFIES GIVEN FILE NAME BUFFER.
********************************************/
bool file_path(
_TCHAR *file, // Buffer with full file string.
/*UP*/
_TCHAR* &fpath // Pointer to the path in buffer.
)
{
fpath = 0;
if (!file || !*file)
return false;
_TCHAR *ptr;
ptr = file;
while (*ptr++)
; // Go to forward to end of buffer.
ptr--; // Back to end of string.
// Go backward, finding backslash if any.
while (--ptr != file)
{
if (*ptr == '\\') // Found backslash.
{
*ptr = '\0'; // Terminate path.
fpath = file; // Return pointer to path.
return true;
}
}
// Even if first char is backslash, return null path.
return true;
}
/********************************************
* FN: FILE_HEAD
* CR: 12/24/99 AM.
* SUBJ: Given a file, get its filename head.
* RET: File name without extension.
* WARN: MODIFIES GIVEN FILE NAME BUFFER.
********************************************/
bool file_head(
_TCHAR *file, // Buffer with full file string.
/*UP*/
_TCHAR* &fhead // Pointer to the file head in buffer.
)
{
fhead = 0;
if (!file || !*file)
return false;
_TCHAR *ptr;
ptr = file;
while (*ptr++)
; // Go to forward to end of buffer.
ptr--; // Back to end of string.
// Go backward, finding period if any.
while (--ptr != file)
{
if (*ptr == '.') // Found period.
break;
if (*ptr == '\\') // Found backslash first.
break;
}
if (*ptr == '\\') // Found backslash first.
{
fhead = ++ptr; // No extension in file string.
return true;
}
if (ptr == file) // At beginning of file string.
{
if (*ptr == '.') // One period that starts file string.
return false; // Return empty file head.
// Found no period or backslash, so file is head with no extension.
fhead = file;
return true;
}
// Must be at a period, not at beginning of file.
if (*ptr != '.' || ptr == file)
{
_t_strstream gerrStr;
gerrStr << _T("[file_head: Error.]") << ends;
errOut(&gerrStr,false);
return false;
}
*ptr = '\0'; // Terminate file head. MODIFIES BUFFER.
// Look for backslash of beginning of file.
while (--ptr != file)
{
if (*ptr == '\\') // Found backslash.
{
fhead = ++ptr;
return true; // Got file head.
}
}
// Got to beginning of file without finding a backslash.
fhead = file;
return true;
}
/********************************************
* FN: FILE_TAIL
* CR: 12/24/99 AM.
* SUBJ: Given a file, get its filename extension.
* RET: Filename extension.
********************************************/
bool file_tail(
_TCHAR *file, // Buffer with full file string.
/*UP*/
_TCHAR* &ftail // Pointer to tail in buffer.
)
{
ftail = 0;
if (!file || !*file)
return false;
_TCHAR *ptr;
ptr = file;
while (*ptr++)
; // Go to forward to end of buffer.
ptr--; // Back to end of string.
// Go backward, finding period if any.
while (--ptr != file)
{
if (*ptr == '.') // Found the last period.
{
ftail = ++ptr;
return true;
}
if (*ptr == '\\') // Found backslash first.
{
// No file tail (ie, extension).
return false;
}
}
// No period or backslash in file.
return false;
}
/********************************************
* FN: C_CHAR
* CR: 05/10/00 AM.
* SUBJ: Get printable form for a character.
* NOTE: User had better copy string immediately.
* Like pretty_char, but \_ is not a good C/C++ char.
* 01/18/06 AM. Get rid of static buffer while I'm at it.
********************************************/
_TCHAR *c_char(
_TCHAR x,
_TCHAR *buf // 01/18/06 AM.
)
{
//static _TCHAR twofer[2] = { '\0', '\0' }; // 01/18/06 AM.
switch (x)
{
case '\a': return _T("\\a");
case '\b': return _T("\\b");
case '\n': return _T("\\n");
case '\r': return _T("\\r");
case '\f': return _T("\\f");
case '\t': return _T("\\t");
case '\v': return _T("\\v");
case '\\': return _T("\\\\");
case '\0': return _T("\\0");
case '"': return _T("\\\""); // 06/05/00 AM.
default:
{
// twofer[0] = x; return twofer; // 01/18/06 AM.
#ifndef UNICODE
buf[0] = x; // 01/18/06 AM.
buf[1] = '\0'; // 01/18/06 AM.
#else
// if ((long) x < 128) // 01/18/06 AM.
if ((long) x < 255) // 01/18/06 AM.
{
buf[0] = x;
buf[1] = '\0';
}
else
{
buf[0] = '\\';
buf[1] = 'x';
num_to_hex((long)x,/*DU*/&(buf[2]));// 01/18/06 AM.
}
#endif
return buf; // 01/18/06 AM.
}
}
}
/********************************************
* FN: C_STR
* CR: 05/10/00 AM.
* SUBJ: Get printable form for a string.
* NOTE: User had better copy string immediately.
* RET: User-supplied buffer for cleaned up string.
********************************************/
_TCHAR *c_str(
_TCHAR *str, // String to be prettified.
_TCHAR *buf, // Buffer for placing prettified string.
long size // Buffer size.
)
{
*buf = '\0';
_TCHAR *end;
end = &(buf[0]);
_TCHAR chbuf[32]; // 01/18/06 AM.
for (; *str; ++str) // Traverse string.
{
if (!strcat_e(end, c_char(*str,chbuf), size))
return buf;
}
return buf;
}
/******************************************************************************/
| 23.688268 | 80 | 0.54271 | [
"object"
] |
6b8dd19a9c60076b30e9c7f96dbb547595dacd25 | 6,350 | cpp | C++ | src/skybox/skybox.cpp | redfeatherplusplus/sandbox-graphics | 1075966820806d8b3e5d3d31f4563c2b4718d805 | [
"MIT"
] | null | null | null | src/skybox/skybox.cpp | redfeatherplusplus/sandbox-graphics | 1075966820806d8b3e5d3d31f4563c2b4718d805 | [
"MIT"
] | null | null | null | src/skybox/skybox.cpp | redfeatherplusplus/sandbox-graphics | 1075966820806d8b3e5d3d31f4563c2b4718d805 | [
"MIT"
] | null | null | null | #include "sandbox.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
const float skybox_vertices[24][6] =
{
// V_x V_y V_z N_x N_y N_z
// Front
{ -1.0, -1.0, 1.0, 0.0, 0.0, 1.0 },
{ 1.0, -1.0, 1.0, 0.0, 0.0, 1.0 },
{ -1.0, 1.0, 1.0, 0.0, 0.0, 1.0 },
{ 1.0, 1.0, 1.0, 0.0, 0.0, 1.0 },
// Back
{ 1.0, -1.0, -1.0, 0.0, 0.0, -1.0 },
{ -1.0, -1.0, -1.0, 0.0, 0.0, -1.0 },
{ 1.0, 1.0, -1.0, 0.0, 0.0, -1.0 },
{ -1.0, 1.0, -1.0, 0.0, 0.0, -1.0 },
// Right
{ 1.0, -1.0, 1.0, 1.0, 0.0, 0.0 },
{ 1.0, -1.0, -1.0, 1.0, 0.0, 0.0 },
{ 1.0, 1.0, 1.0, 1.0, 0.0, 0.0 },
{ 1.0, 1.0, -1.0, 1.0, 0.0, 0.0 },
// Left
{ -1.0, -1.0, -1.0, -1.0, 0.0, 0.0 },
{ -1.0, -1.0, 1.0, -1.0, 0.0, 0.0 },
{ -1.0, 1.0, -1.0, -1.0, 0.0, 0.0 },
{ -1.0, 1.0, 1.0, -1.0, 0.0, 0.0 },
// Bottom
{ -1.0, -1.0, -1.0, 0.0, -1.0, 0.0 },
{ 1.0, -1.0, -1.0, 0.0, -1.0, 0.0 },
{ -1.0, -1.0, 1.0, 0.0, -1.0, 0.0 },
{ 1.0, -1.0, 1.0, 0.0, -1.0, 0.0 },
// Top
{ -1.0, 1.0, 1.0, 0.0, 1.0, 0.0 },
{ 1.0, 1.0, 1.0, 0.0, 1.0, 0.0 },
{ -1.0, 1.0, -1.0, 0.0, 1.0, 0.0 },
{ 1.0, 1.0, -1.0, 0.0, 1.0, 0.0 }
} ;
const GLushort skybox_indices[] =
{
0, 1, 2, 3,
0xFFFF,
4, 5, 6, 7,
0xFFFF,
8, 9, 10, 11,
0xFFFF,
12, 13, 14, 15,
0xFFFF,
16, 17, 18, 19,
0xFFFF,
20, 21, 22, 23
} ;
class skybox : public sandbox
{
GLuint vao ;
GLuint vbo ;
GLuint ebo ;
const char *front = "@CURR_PATH@/textures/negz.jpg" ;
const char *back = "@CURR_PATH@/textures/posz.jpg" ;
const char *top = "@CURR_PATH@/textures/negy.jpg" ;
const char *bottom = "@CURR_PATH@/textures/posy.jpg" ;
const char *left = "@CURR_PATH@/textures/negx.jpg" ;
const char *right = "@CURR_PATH@/textures/posx.jpg" ;
void init()
{
// Set up shaders
const GLchar *vs_fname = "@CURR_PATH@/shaders/skybox-vert.glsl" ;
const GLchar *fs_fname = "@CURR_PATH@/shaders/skybox-frag.glsl" ;
std::list<std::pair<const char *, GLuint>> shaders ;
shaders.push_back( std::make_pair( vs_fname, GL_VERTEX_SHADER ) ) ;
shaders.push_back( std::make_pair( fs_fname, GL_FRAGMENT_SHADER ) ) ;
program = loadShaders( shaders ) ;
// Set up element array buffer
glGenBuffers( 1, &ebo ) ;
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ebo ) ;
glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( skybox_indices ), skybox_indices, GL_STATIC_DRAW ) ;
// Set up vertex data
glGenVertexArrays( 1, &vao ) ;
glBindVertexArray( vao ) ;
glGenBuffers( 1, &vbo ) ;
glBindBuffer( GL_ARRAY_BUFFER, vbo ) ;
glBufferData( GL_ARRAY_BUFFER, sizeof( skybox_vertices ), skybox_vertices, GL_STATIC_DRAW ) ;
glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof( float ) * 6, NULL ) ;
glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, sizeof( float ) * 6, (void*) (3 * sizeof( float ) ) ) ;
glEnableVertexAttribArray( 0 ) ;
glEnableVertexAttribArray( 1 ) ;
create_skybox_texture() ;
view_matrix = glm::lookAt( glm::vec3( 0.0, 0.0, 0.0 ),
glm::vec3( 0.0, 0.0, 0.0 ),
glm::vec3( 0.0, 1.0, 0.0 ) ) ;
projection_matrix = glm::perspective( 45.0f, (GLfloat) width / height, 0.1f, 100.0f ) ;
}
GLuint create_skybox_texture()
{
GLuint tex ;
glActiveTexture(GL_TEXTURE0) ;
glGenTextures(1, &tex) ;
load_side(tex, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, front ) ;
load_side(tex, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, back ) ;
load_side(tex, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, top ) ;
load_side(tex, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, bottom) ;
load_side(tex, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, left ) ;
load_side(tex, GL_TEXTURE_CUBE_MAP_POSITIVE_X, right ) ;
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR) ;
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR) ;
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE) ;
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) ;
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) ;
return tex ;
}
void load_side(GLuint tex, GLenum target, const char* fname)
{
int x, y, n ;
unsigned char *image_data = stbi_load(fname, &x, &y, &n, 4) ;
if( !image_data )
{
throw std::runtime_error(std::string("Could not open texture file ") + std::string(fname));
}
glTexImage2D( target,
0,
GL_RGBA,
x, y,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
image_data) ;
free(image_data) ;
}
void render( double time )
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) ;
// Set up matrices
const glm::mat4 model_matrix = glm::mat4(1.0) ;
const glm::mat4 mvp_matrix = projection_matrix * skybox_matrix * model_matrix ;
// Set shader state
glUseProgram( program ) ;
GLint model_loc = glGetUniformLocation( program, "model_matrix" ) ;
glUniformMatrix4fv( model_loc, 1, GL_FALSE, glm::value_ptr( model_matrix ) ) ;
GLint mvp_loc = glGetUniformLocation( program, "mvp_matrix" ) ;
glUniformMatrix4fv( mvp_loc, 1, GL_FALSE, glm::value_ptr( mvp_matrix ) ) ;
glBindVertexArray( vao ) ;
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ebo ) ;
glDisable( GL_CULL_FACE ) ;
glDisable( GL_DEPTH_TEST ) ;
glDepthMask( GL_TRUE ) ;
glEnable( GL_PRIMITIVE_RESTART ) ;
glPrimitiveRestartIndex( 0xFFFF ) ;
glDrawElements( GL_TRIANGLE_STRIP, 29, GL_UNSIGNED_SHORT, NULL ) ;
}
void shutdown()
{
glDeleteBuffers( 1, &vbo ) ;
glDeleteBuffers( 1, &ebo ) ;
glDeleteVertexArrays( 1, &vao ) ;
glDeleteProgram( program ) ;
}
} ;
MAIN( skybox, "Skybox" )
| 32.731959 | 112 | 0.542677 | [
"render"
] |
6b8e5b57f4030708d8651ba8fa33e1769ceda318 | 3,683 | cpp | C++ | leetcode/794. Valid Tic-Tac-Toe State.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | 1 | 2018-09-13T12:16:42.000Z | 2018-09-13T12:16:42.000Z | leetcode/794. Valid Tic-Tac-Toe State.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | null | null | null | leetcode/794. Valid Tic-Tac-Toe State.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | null | null | null | class Solution {
public:
bool validTicTacToe(vector<string>& board) {
int xCount = 0, oCount = 0;
int counter = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(board[i][j] == 'X')
{
xCount++;
++counter;
}
else if(board[i][j] == 'O')
{
oCount++;
++counter;
}
}
}
if(counter == 0)
{
return true;
}
vector<string> &str = board;
//xcount checking
if(xCount < oCount || xCount > oCount+1)
{
return false;
}
//check for tic tac toe pattern
int pattern = 0;
int isX = 0, isO = 0;
for(int i = 0; i < 3; i++)
{
bool isT = true;
int ctr = 0;
if(str[i][0] == ' ')
{
++ctr;
}
for(int j = 1; j < 3; j++)
{
if(str[i][j] == ' ')
{
++ctr;
}
if(str[i][j] != str[i][j-1])
{
isT = false;
break;
}
}
if(ctr == 3)
{
continue;
}
if(isT)
{
if(str[i][0] == 'X')
{
isX++;
}
else
{
isO++;
}
++pattern;
}
}
for(int i = 0; i < 3; i++)
{
bool isT = true;
int ctr = 0;
if(str[0][i] == ' ')
{
++ctr;
}
for(int j = 1; j < 3; j++)
{
if(str[j][i] == ' ')
{
++ctr;
}
if(str[j][i] != str[j-1][i])
{
isT = false;
break;
}
}
if(ctr == 3)
{
continue;
}
if(isT)
{
if(str[0][i] == 'X')
{
isX++;
}
else
{
isO++;
}
++pattern;
}
}
//diagonal 1
if(str[1][1] == str[0][0] && str[2][2] == str[1][1] && (str[1][1] == 'O' || str[1][1] == 'X'))
{
++pattern;
if(str[1][1] == 'X')
{
isX++;
}
else
{
isO++;
}
}
if(str[1][1] == str[0][2] && str[2][0] == str[1][1] && (str[1][1] == 'O' || str[1][1] == 'X'))
{
++pattern;
if(str[1][1] == 'X')
{
isX++;
}
else
{
isO++;
}
}
if(pattern > 1)
{
return false;
}
if(pattern == 1)
{
if(isX == 1)
{
if(xCount > oCount)
{
return true;
}
return false;
}
else
{
if(oCount == xCount)
{
return true;
}
return false;
}
}
return true;
}
}; | 22.875776 | 102 | 0.217214 | [
"vector"
] |
6b8e9d2c217df148bf68f37e269f0d7151b74f78 | 581 | cpp | C++ | atcoder/nikkei/second/b.cpp | Lambda1/atcoder | a4a57ddc21cc29b8b795173630e1d07db4abb559 | [
"MIT"
] | null | null | null | atcoder/nikkei/second/b.cpp | Lambda1/atcoder | a4a57ddc21cc29b8b795173630e1d07db4abb559 | [
"MIT"
] | null | null | null | atcoder/nikkei/second/b.cpp | Lambda1/atcoder | a4a57ddc21cc29b8b795173630e1d07db4abb559 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <queue>
using lint = long long int;
using Graph = std::vector<std::vector<lint>>;
template<class T>
struct edge
{
T dist;
lint to;
edge(){}
edge(const T &a_dist,const lint &a_to) : dist(a_dist), to(a_to) {}
~edge(){}
};
int main(int argc,char *argv[])
{
lint n;
std::cin >> n;
std::vector<lint> d(n);
for(lint i = 0;i < n;i++) std::cin >> d[i];
std::sort(d.begin(),d.end());
for(int i = 0;i < n;i++) std::cout << d[i] << std::endl;
return 0;
}
| 16.6 | 67 | 0.604131 | [
"vector"
] |
6b9b184047bda04522bcceb2d155d2c1e8f8063b | 5,151 | hpp | C++ | src/gravity/obcgravity.hpp | aviator24/athena-public-version | bb82d77a67374e8cf17977f21121d4682dd8806c | [
"BSD-3-Clause"
] | null | null | null | src/gravity/obcgravity.hpp | aviator24/athena-public-version | bb82d77a67374e8cf17977f21121d4682dd8806c | [
"BSD-3-Clause"
] | null | null | null | src/gravity/obcgravity.hpp | aviator24/athena-public-version | bb82d77a67374e8cf17977f21121d4682dd8806c | [
"BSD-3-Clause"
] | null | null | null | #ifndef GRAVITY_OBCGRAVITY_HPP_
#define GRAVITY_OBCGRAVITY_HPP_
//========================================================================================
// Athena++ astrophysical MHD code
// Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors
// Licensed under the 3-clause BSD License, see LICENSE file for details
//========================================================================================
//! \file athena_fft.hpp
// \brief defines FFT class which implements parallel FFT using MPI/OpenMP
// C headers
// C++ headers
#include <iostream>
// Athena++ classes headers
#include "../athena.hpp"
#include "../athena_arrays.hpp"
#include "../globals.hpp"
#include "../mesh/mesh.hpp"
#include "../mesh/meshblock_tree.hpp"
#include "../task_list/fft_grav_task_list.hpp"
#include "gravity.hpp"
#ifdef FFT
#include <fftw3.h>
#ifdef MPI_PARALLEL
#include <mpi.h>
#include "../fft/plimpton/fft_2d.h"
#include "../fft/plimpton/fft_3d.h"
#include "../fft/plimpton/pack_2d.h"
#include "../fft/plimpton/pack_3d.h"
#include "../fft/plimpton/remap_2d.h"
#include "../fft/plimpton/remap_3d.h"
#endif // MPI_PARALLEL
#endif // FFT
class Mesh;
class MeshBlock;
class ParameterInput;
class OBCGravityCar;
class OBCGravityCyl;
class OBCGravityDriver;
enum CylBoundaryFace {TOP=0, BOT=1, INN=2, OUT=3};
enum CylDecompNames {XB=0, X1P=1, X2P=2, X3P=3, X2P0=4, E1P=5, E2P=6, E3P=7,
E2P0=8, Gii=9, Gik=10, Gki=11, Gkk=12, EB=13, Gii2P=14,
Gik2P=15, Gki2P=16, Gkk2P=17, Gii2P0=18, Gik2P0=19,
Gki2P0=20, Gkk2P0=21, Gii_BLOCK=22, Gik_BLOCK=23,
Gki_BLOCK=24, Gkk_BLOCK=25};
enum CylBndryDcmp {BLOCK=0, FFT_LONG=1, FFT_SHORT=2, PSI=3, SIGv=4, SIGr=5};
enum CarBoundaryFace {STH=0, NTH=1, WST=2, EST=3, CBOT=4, CTOP=5};
enum CarDecompNames {CXB=0, CX1P=1, CX2P=2, CX3P=3, PB=4, P1P=5, P2P=6, P3P=7,
CEB=8, CE1P=9, CE2P=10, CE3P=11};
enum CarBndryDcmp {CBLOCK=0, FFT_FIRST=1, FFT_SECOND=2};
enum James {C=0, S=1};
typedef struct DomainDecomp {
int is,ie,js,je,ks,ke,nx1,nx2,nx3,block_size;
} DomainDecomp;
//! \class OBCGravityDriver
// \brief OBC driver
class OBCGravityDriver {
public:
OBCGravityDriver(Mesh *pm, ParameterInput *pin);
~OBCGravityDriver();
OBCGravityCar *pmy_og_car;
OBCGravityCyl *pmy_og_cyl;
void Solve(int stage);
protected:
Mesh *pmy_mesh_;
private:
FFTGravitySolverTaskList *gtlist_;
};
//! \class OBCGravityCar
// \brief
class OBCGravityCar : public Gravity {
public:
OBCGravityCar(OBCGravityDriver *pcd, MeshBlock *pmb, ParameterInput *pin);
~OBCGravityCar();
void BndFFTForward(int first_nslow, int first_nfast, int second_nslow,
int second_nfast,int B);
void BndFFTBackward(int first_nslow, int first_nfast, int second_nslow,
int second_nfast, int B);
void FillDscGrf();
void FillCntGrf();
void LoadSource(const AthenaArray<Real> &src);
void SolveZeroBC();
void CalcBndCharge();
void CalcBndPot();
void RetrieveResult(AthenaArray<Real> &dst);
protected:
int Nx1,Nx2,Nx3,nx1,nx2,nx3;
int x1rank,x2rank,x3rank,x1comm_size,x2comm_size,x3comm_size;
int np1,np2,np3;
int ngh_, ngh_grf_;
DomainDecomp dcmps[12];
DomainDecomp bndry_dcmps[6][3];
OBCGravityDriver *pmy_driver_;
Real *sigma[6], *sigma_mid[6][2], *sigma_fft[6][2][2], *sigfft[2][2][2], *grf;
Real *in_, *out_, *buf_, *in2_;
AthenaArray<Real> lambda1_, lambda2_, lambda3_, lambda11_, lambda22_, lambda33_;
Real dx1_, dx2_, dx3_;
fftw_plan fft_plan_r2r_[15];
fftw_plan fft_2d_plan[6][14];
struct remap_plan_2d *BndryRmpPlan[6][3][3];
struct remap_plan_3d *RmpPlan[12][12];
MPI_Comm bndcomm[6],x1comm,x2comm,x3comm;
};
//! \class OBCGravityCyl
// \brief
class OBCGravityCyl : public Gravity {
public:
OBCGravityCyl(OBCGravityDriver *pcd, MeshBlock *pmb, ParameterInput *pin);
~OBCGravityCyl();
void FillDscGrf();
void FillCntGrf();
void CalcGrf(int gip, int gkp);
void LoadSource(const AthenaArray<Real> &src);
void SolveZeroBC();
void CalcBndCharge();
void CalcBndPot();
void RetrieveResult(AthenaArray<Real> &dst);
protected:
int Nx1,Nx2,Nx3,nx1,nx2,nx3,lNx1,lNx3,hNx2,hnx2;
int x1rank, x3rank, x1comm_size, x3comm_size;
int np1,np2,np3;
DomainDecomp dcmps[26];
DomainDecomp bndry_dcmps[4][6];
OBCGravityDriver *pmy_driver_;
Real *psi[4], *psi2[4], *sigma[4];
fftw_complex *sigma_fft[4], *psi_fft[4], *sigma_fft_v[4], *sigma_fft_r[4];
fftw_complex *in_, *in2_, *out_, *out2_, *buf_;
fftw_complex *grf[4][4];
AthenaArray<Real> a_,b_,c_,x_,r_,lambda2_,lambda3_;
AthenaArray<Real> aa_,bb_,cc_,xx_,rr_,lambda22_,lambda33_;
AthenaArray<Real> x1f_, dx1f_, x1v_, dx1v_;
AthenaArray<Real> x1f2_, dx1f2_, x1v2_, dx1v2_;
Real rat, dx2_, dx3_;
fftw_plan fft_x2_forward_[18];
fftw_plan fft_x2_backward_[2];
fftw_plan fft_x3_r2r_[8];
fftw_plan fft_2d_plan[4][2];
struct remap_plan_2d *BndryRmpPlan[4][6][6];
struct remap_plan_3d *RmpPlan[26][26];
MPI_Comm bndcomm[4],x1comm,x3comm;
private:
int ng_, noffset1_, noffset2_, ngh_grf_, pfold_;
};
#endif // GRAVITY_OBCGRAVITY_HPP_
| 29.267045 | 90 | 0.683168 | [
"mesh"
] |
6b9b1c6f6403939be34839a659dbb1d18e6b194f | 2,299 | cpp | C++ | MMOCoreORB/src/server/zone/objects/tangible/wearables/WearableContainerObjectImplementation.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/src/server/zone/objects/tangible/wearables/WearableContainerObjectImplementation.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/src/server/zone/objects/tangible/wearables/WearableContainerObjectImplementation.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | /*
* WearableContainerObjectImplementation.cpp
*
* Created on: Oct 27, 2012
* Author: loshult
*/
#include "server/zone/objects/tangible/wearables/WearableContainerObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/managers/skill/SkillModManager.h"
#include "server/zone/packets/scene/AttributeListMessage.h"
void WearableContainerObjectImplementation::initializeTransientMembers() {
ContainerImplementation::initializeTransientMembers();
setLoggingName("WearableContainerObject");
}
void WearableContainerObjectImplementation::fillAttributeList(AttributeListMessage* alm,
CreatureObject* object) {
TangibleObjectImplementation::fillAttributeList(alm, object);
for(int i = 0; i < wearableSkillMods.size(); ++i) {
String key = wearableSkillMods.elementAt(i).getKey();
String statname = "cat_skill_mod_bonus.@stat_n:" + key;
int value = wearableSkillMods.get(key);
if (value > 0)
alm->insertAttribute(statname, value);
}
}
void WearableContainerObjectImplementation::applySkillModsTo(CreatureObject* creature) const {
if (creature == nullptr) {
return;
}
for (int i = 0; i < wearableSkillMods.size(); ++i) {
String name = wearableSkillMods.elementAt(i).getKey();
int value = wearableSkillMods.get(name);
if (!SkillModManager::instance()->isWearableModDisabled(name))
{
creature->addSkillMod(SkillModManager::WEARABLE, name, value, true);
creature->updateTerrainNegotiation();
}
}
SkillModManager::instance()->verifyWearableSkillMods(creature);
}
void WearableContainerObjectImplementation::removeSkillModsFrom(CreatureObject* creature) {
if (creature == nullptr) {
return;
}
for (int i = 0; i < wearableSkillMods.size(); ++i) {
String name = wearableSkillMods.elementAt(i).getKey();
int value = wearableSkillMods.get(name);
if (!SkillModManager::instance()->isWearableModDisabled(name))
{
creature->removeSkillMod(SkillModManager::WEARABLE, name, value, true);
creature->updateTerrainNegotiation();
}
}
SkillModManager::instance()->verifyWearableSkillMods(creature);
}
bool WearableContainerObjectImplementation::isEquipped() {
ManagedReference<SceneObject*> parent = getParent().get();
if (parent != nullptr && parent->isPlayerCreature())
return true;
return false;
}
| 29.857143 | 94 | 0.754676 | [
"object"
] |
6b9f814bb5ca76b5e49a0182c587f7c9f01d3ea7 | 10,290 | cpp | C++ | source/MaterialXTest/MaterialXGenMdl/GenMdl.cpp | ZapAndersson/MaterialX | 886ddc617ab9dda957ab3858a3e884ba60b166b7 | [
"Apache-2.0"
] | 38 | 2022-02-28T21:36:43.000Z | 2022-03-29T18:11:08.000Z | source/MaterialXTest/MaterialXGenMdl/GenMdl.cpp | ZapAndersson/MaterialX | 886ddc617ab9dda957ab3858a3e884ba60b166b7 | [
"Apache-2.0"
] | 37 | 2022-02-28T23:13:33.000Z | 2022-03-31T23:50:43.000Z | source/MaterialXTest/MaterialXGenMdl/GenMdl.cpp | kwokcb/MaterialX | 483c616e10e6d9a23763ae33cd10f7bcb08cf2e9 | [
"Apache-2.0"
] | 4 | 2022-03-03T20:24:13.000Z | 2022-03-25T09:53:52.000Z | //
// TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd.
// All rights reserved. See LICENSE.txt for license.
//
#include <MaterialXTest/Catch/catch.hpp>
#include <MaterialXTest/MaterialXGenMdl/GenMdl.h>
#include <MaterialXCore/Document.h>
#include <MaterialXFormat/File.h>
#include <MaterialXGenMdl/MdlShaderGenerator.h>
#include <MaterialXGenMdl/MdlSyntax.h>
#include <MaterialXGenShader/DefaultColorManagementSystem.h>
#include <MaterialXGenShader/GenContext.h>
#include <MaterialXGenShader/Util.h>
namespace mx = MaterialX;
TEST_CASE("GenShader: MDL Syntax", "[genmdl]")
{
mx::SyntaxPtr syntax = mx::MdlSyntax::create();
REQUIRE(syntax->getTypeName(mx::Type::FLOAT) == "float");
REQUIRE(syntax->getTypeName(mx::Type::COLOR3) == "color");
REQUIRE(syntax->getTypeName(mx::Type::VECTOR3) == "float3");
REQUIRE(syntax->getTypeName(mx::Type::FLOATARRAY) == "float");
REQUIRE(syntax->getTypeName(mx::Type::INTEGERARRAY) == "int");
REQUIRE(mx::Type::FLOATARRAY->isArray());
REQUIRE(mx::Type::INTEGERARRAY->isArray());
REQUIRE(syntax->getTypeName(mx::Type::BSDF) == "material");
REQUIRE(syntax->getOutputTypeName(mx::Type::BSDF) == "material");
// Set fixed precision with one digit
mx::ScopedFloatFormatting format(mx::Value::FloatFormatFixed, 1);
std::string value;
value = syntax->getDefaultValue(mx::Type::FLOAT);
REQUIRE(value == "0.0");
value = syntax->getDefaultValue(mx::Type::COLOR3);
REQUIRE(value == "color(0.0)");
value = syntax->getDefaultValue(mx::Type::COLOR3, true);
REQUIRE(value == "color(0.0)");
value = syntax->getDefaultValue(mx::Type::COLOR4);
REQUIRE(value == "mk_color4(0.0)");
value = syntax->getDefaultValue(mx::Type::COLOR4, true);
REQUIRE(value == "mk_color4(0.0)");
value = syntax->getDefaultValue(mx::Type::FLOATARRAY, true);
REQUIRE(value.empty());
value = syntax->getDefaultValue(mx::Type::INTEGERARRAY, true);
REQUIRE(value.empty());
mx::ValuePtr floatValue = mx::Value::createValue<float>(42.0f);
value = syntax->getValue(mx::Type::FLOAT, *floatValue);
REQUIRE(value == "42.0");
value = syntax->getValue(mx::Type::FLOAT, *floatValue, true);
REQUIRE(value == "42.0");
mx::ValuePtr color3Value = mx::Value::createValue<mx::Color3>(mx::Color3(1.0f, 2.0f, 3.0f));
value = syntax->getValue(mx::Type::COLOR3, *color3Value);
REQUIRE(value == "color(1.0, 2.0, 3.0)");
value = syntax->getValue(mx::Type::COLOR3, *color3Value, true);
REQUIRE(value == "color(1.0, 2.0, 3.0)");
mx::ValuePtr color4Value = mx::Value::createValue<mx::Color4>(mx::Color4(1.0f, 2.0f, 3.0f, 4.0f));
value = syntax->getValue(mx::Type::COLOR4, *color4Value);
REQUIRE(value == "mk_color4(1.0, 2.0, 3.0, 4.0)");
value = syntax->getValue(mx::Type::COLOR4, *color4Value, true);
REQUIRE(value == "mk_color4(1.0, 2.0, 3.0, 4.0)");
std::vector<float> floatArray = { 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f };
mx::ValuePtr floatArrayValue = mx::Value::createValue<std::vector<float>>(floatArray);
value = syntax->getValue(mx::Type::FLOATARRAY, *floatArrayValue);
REQUIRE(value == "float[](0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7)");
std::vector<int> intArray = { 1, 2, 3, 4, 5, 6, 7 };
mx::ValuePtr intArrayValue = mx::Value::createValue<std::vector<int>>(intArray);
value = syntax->getValue(mx::Type::INTEGERARRAY, *intArrayValue);
REQUIRE(value == "int[](1, 2, 3, 4, 5, 6, 7)");
}
TEST_CASE("GenShader: MDL Implementation Check", "[genmdl]")
{
mx::GenContext context(mx::MdlShaderGenerator::create());
mx::StringSet generatorSkipNodeTypes;
generatorSkipNodeTypes.insert("light");
mx::StringSet generatorSkipNodeDefs;
GenShaderUtil::checkImplementations(context, generatorSkipNodeTypes, generatorSkipNodeDefs, 55);
}
void MdlShaderGeneratorTester::compileSource(const std::vector<mx::FilePath>& sourceCodePaths)
{
if (sourceCodePaths.empty() || sourceCodePaths[0].isEmpty())
return;
mx::FilePath moduleToTestPath = sourceCodePaths[0].getParentPath();
mx::FilePath module = sourceCodePaths[0];
std::string moduleToTest = module[module.size()-1];
moduleToTest = moduleToTest.substr(0, moduleToTest.size() - sourceCodePaths[0].getExtension().length() - 1);
mx::StringVec extraModulePaths = mx::splitString(MATERIALX_MDL_MODULE_PATHS, ",");
std::string renderExec(MATERIALX_MDL_RENDER_EXECUTABLE);
bool testMDLC = renderExec.empty();
if (testMDLC)
{
std::string mdlcExec(MATERIALX_MDLC_EXECUTABLE);
if (mdlcExec.empty())
{
return;
}
std::string mdlcCommand = mdlcExec;
for (const std::string& extraPath : extraModulePaths)
{
mdlcCommand += " -p\"" + extraPath + "\"";
}
// Note: These paths are based on
mx::FilePath currentPath = mx::FilePath::getCurrentPath();
mx::FilePath coreModulePath = currentPath / std::string(MATERIALX_INSTALL_MDL_MODULE_PATH) / "mdl";
mx::FilePath coreModulePath2 = coreModulePath / mx::FilePath("materialx");
mdlcCommand += " -p \"" + currentPath.asString() + "\"";
mdlcCommand += " -p \"" + coreModulePath.asString() + "\"";
mdlcCommand += " -p \"" + coreModulePath2.asString() + "\"";
mdlcCommand += " -p \"" + moduleToTestPath.asString() + "\"";
mdlcCommand += " -p \"" + moduleToTestPath.getParentPath().asString() + "\"";
mdlcCommand += " -p \"" + _libSearchPath.asString() + "\"";
mdlcCommand += " -W \"181=off\" -W \"183=off\" -W \"225=off\"";
mdlcCommand += " " + moduleToTest;
mx::FilePath errorFile = moduleToTestPath / (moduleToTest + ".mdl_compile_errors.txt");
mdlcCommand += " > " + errorFile.asString() + " 2>&1";
int returnValue = std::system(mdlcCommand.c_str());
std::ifstream errorStream(errorFile);
mx::StringVec result;
std::string line;
bool writeErrorCode = false;
while (std::getline(errorStream, line))
{
if (!writeErrorCode)
{
_logFile << mdlcCommand << std::endl;
_logFile << "\tReturn code: " << std::to_string(returnValue) << std::endl;
writeErrorCode = true;
}
_logFile << "\tError: " << line << std::endl;
}
CHECK(returnValue == 0);
}
else
{
std::string renderCommand = renderExec;
for (const std::string& extraPath : extraModulePaths)
{
renderCommand += " --mdl_path\"" + extraPath + "\"";
}
// Note: These paths are based on
mx::FilePath currentPath = mx::FilePath::getCurrentPath();
mx::FilePath coreModulePath = currentPath / std::string(MATERIALX_INSTALL_MDL_MODULE_PATH) / "mdl";
mx::FilePath coreModulePath2 = coreModulePath / mx::FilePath("materialx");
renderCommand += " --mdl_path \"" + currentPath.asString() + "\"";
renderCommand += " --mdl_path \"" + coreModulePath.asString() + "\"";
renderCommand += " --mdl_path \"" + coreModulePath2.asString() + "\"";
renderCommand += " --mdl_path \"" + moduleToTestPath.asString() + "\"";
renderCommand += " --mdl_path \"" + moduleToTestPath.getParentPath().asString() + "\"";
renderCommand += " --mdl_path \"" + _libSearchPath.asString() + "\"";
// This must be a render args option. Rest are consistent between dxr and cuda example renderers.
std::string renderArgs(MATERIALX_MDL_RENDER_ARGUMENTS);
if (renderArgs.empty())
{
// Assume df_cuda is being used and set reasonable arguments automatically
renderCommand += " --nogl --res 512 512 -p 2.0 0 0.5 -f 70 --spi 1 --spp 16";
}
else
{
renderCommand += " " + renderArgs;
}
renderCommand += " --noaux";
std::string iblFile = (currentPath / "resources/lights/san_giuseppe_bridge.hdr").asString();
renderCommand += " --hdr \"" + iblFile + "\"";
renderCommand += " ::" + moduleToTest + "::*";
std::string extension("_mdl.png");
#if defined(MATERIALX_BUILD_OIIO)
extension = "_mdl.exr";
#endif
mx::FilePath outputImageName = moduleToTestPath / (moduleToTest + extension);
renderCommand += " -o " + outputImageName.asString();
mx::FilePath logFile = moduleToTestPath / (moduleToTest + ".mdl_render_errors.txt");
renderCommand += " > " + logFile.asString() + " 2>&1";
int returnValue = std::system(renderCommand.c_str());
std::ifstream logStream(logFile);
mx::StringVec result;
std::string line;
bool writeLogCode = false;
while (std::getline(logStream, line))
{
if (!writeLogCode)
{
_logFile << renderCommand << std::endl;
_logFile << "\tReturn code: " << std::to_string(returnValue) << std::endl;
writeLogCode = true;
}
_logFile << "\tLog: " << line << std::endl;
}
CHECK(returnValue == 0);
}
}
TEST_CASE("GenShader: MDL Shader Generation", "[genmdl]")
{
mx::FilePathVec testRootPaths;
testRootPaths.push_back("resources/Materials/TestSuite");
testRootPaths.push_back("resources/Materials/Examples");
const mx::FilePath libSearchPath = mx::FilePath::getCurrentPath();
mx::FileSearchPath srcSearchPath(libSearchPath.asString());
srcSearchPath.append(libSearchPath / mx::FilePath("libraries/stdlib/genmdl"));
const mx::FilePath logPath("genmdl_mdl_generate_test.txt");
// Write shaders and try to compile only if mdlc exe specified.
std::string mdlcExec(MATERIALX_MDLC_EXECUTABLE);
bool writeShadersToDisk = !mdlcExec.empty();
MdlShaderGeneratorTester tester(mx::MdlShaderGenerator::create(), testRootPaths, libSearchPath, srcSearchPath, logPath, writeShadersToDisk);
tester.addSkipLibraryFiles();
mx::GenOptions genOptions;
genOptions.targetColorSpaceOverride = "lin_rec709";
mx::FilePath optionsFilePath("resources/Materials/TestSuite/_options.mtlx");
tester.validate(genOptions, optionsFilePath);
}
| 41.829268 | 144 | 0.631876 | [
"render",
"vector"
] |
6ba275f66d2c87cd8a7fe7803027ff6a334100b2 | 17,070 | cpp | C++ | Example/Source/Examples/Private/Renderer/Scene/VrController.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | 187 | 2015-11-02T21:27:57.000Z | 2022-02-17T21:39:17.000Z | Example/Source/Examples/Private/Renderer/Scene/VrController.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | null | null | null | Example/Source/Examples/Private/Renderer/Scene/VrController.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | 20 | 2015-11-04T19:17:01.000Z | 2021-11-18T11:23:25.000Z | /*********************************************************\
* Copyright (c) 2012-2021 The Unrimp 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 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "Examples/Private/Renderer/Scene/VrController.h"
#include <Renderer/Public/IRenderer.h>
#include <Renderer/Public/Core/Math/Math.h>
#include <Renderer/Public/Core/Math/Transform.h>
#include <Renderer/Public/Resource/Scene/SceneNode.h>
#include <Renderer/Public/Resource/Scene/SceneResource.h>
#include <Renderer/Public/Resource/Scene/Item/Mesh/MeshSceneItem.h>
#include <Renderer/Public/Resource/Scene/Item/Light/LightSceneItem.h>
#include <Renderer/Public/Resource/Scene/Item/Camera/CameraSceneItem.h>
#include <Renderer/Public/Resource/MaterialBlueprint/MaterialBlueprintResourceManager.h>
#include <Renderer/Public/Resource/MaterialBlueprint/Listener/MaterialBlueprintResourceListener.h>
#include <Renderer/Public/Vr/OpenVR/VrManagerOpenVR.h>
#include <Renderer/Public/Vr/OpenVR/IVrManagerOpenVRListener.h>
#ifdef RENDERER_IMGUI
#include <imgui/imgui.h>
#endif
// Disable warnings in external headers, we can't fix them
PRAGMA_WARNING_PUSH
PRAGMA_WARNING_DISABLE_MSVC(4464) // warning C4464: relative include path contains '..'
PRAGMA_WARNING_DISABLE_MSVC(4324) // warning C4324: '<x>': structure was padded due to alignment specifier
#include <glm/gtx/intersect.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <glm/gtc/type_ptr.hpp>
PRAGMA_WARNING_POP
//[-------------------------------------------------------]
//[ Anonymous detail namespace ]
//[-------------------------------------------------------]
namespace
{
namespace detail
{
//[-------------------------------------------------------]
//[ Global definitions ]
//[-------------------------------------------------------]
#define DEFINE_CONSTANT(name) static constexpr uint32_t name = STRING_ID(#name);
// Pass
DEFINE_CONSTANT(IMGUI_OBJECT_SPACE_TO_CLIP_SPACE_MATRIX)
#undef DEFINE_CONSTANT
static constexpr uint32_t FIRST_CONTROLLER_INDEX = 0;
static constexpr uint32_t SECOND_CONTROLLER_INDEX = 1;
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* Virtual reality manager OpenVR listener
*
* @todo
* - TODO(co) Support the dynamic adding and removal of VR controllers (index updates)
*/
class VrManagerOpenVRListener : public Renderer::IVrManagerOpenVRListener
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
VrManagerOpenVRListener() :
mVrManagerOpenVR(nullptr),
mVrController(nullptr),
mNumberOfVrControllers(0)
{
for (uint32_t i = 0; i < vr::k_unMaxTrackedDeviceCount; ++i)
{
mVrControllerTrackedDeviceIndices[i] = Renderer::getInvalid<vr::TrackedDeviceIndex_t>();
}
}
inline virtual ~VrManagerOpenVRListener() override
{
// Nothing here
}
inline void setVrManagerOpenVR(const Renderer::VrManagerOpenVR& vrManagerOpenVR, VrController& vrController)
{
mVrManagerOpenVR = &vrManagerOpenVR;
mVrController = &vrController;
}
[[nodiscard]] inline uint32_t getNumberOfVrControllers() const
{
return mNumberOfVrControllers;
}
[[nodiscard]] inline vr::TrackedDeviceIndex_t getVrControllerTrackedDeviceIndices(uint32_t vrControllerIndex) const
{
ASSERT(vrControllerIndex < vr::k_unMaxTrackedDeviceCount, "Invalid VR controller index")
return mVrControllerTrackedDeviceIndices[vrControllerIndex];
}
//[-------------------------------------------------------]
//[ Private virtual Renderer::IVrManagerOpenVRListener methods ]
//[-------------------------------------------------------]
private:
virtual void onVrEvent(const vr::VREvent_t& vrVrEvent) override
{
switch (vrVrEvent.eventType)
{
// Handle quiting the application from Steam
case vr::VREvent_DriverRequestedQuit:
case vr::VREvent_Quit:
// TODO(co)
NOP;
break;
case vr::VREvent_ButtonPress:
{
// The first VR controller is used for teleporting
// -> A green light indicates the position one will end up
// -> When pressing the trigger button one teleports to this position
if (mNumberOfVrControllers > 0 && mVrControllerTrackedDeviceIndices[FIRST_CONTROLLER_INDEX] == vrVrEvent.trackedDeviceIndex && vrVrEvent.data.controller.button == vr::k_EButton_SteamVR_Trigger && mVrController->getTeleportIndicationLightSceneItemSafe().isVisible())
{
mVrController->getCameraSceneItem().getParentSceneNodeSafe().setPosition(mVrController->getTeleportIndicationLightSceneItemSafe().getParentSceneNodeSafe().getGlobalTransform().position);
}
break;
}
}
}
virtual void onSceneNodeCreated(vr::TrackedDeviceIndex_t trackedDeviceIndex, Renderer::SceneResource& sceneResource, Renderer::SceneNode& sceneNode) override
{
if (mVrManagerOpenVR->getVrSystem()->GetTrackedDeviceClass(trackedDeviceIndex) == vr::TrackedDeviceClass_Controller)
{
// Attach a light to controllers, this way they can be seen easier and it's possible to illuminate the scene by using the hands
Renderer::LightSceneItem* lightSceneItem = sceneResource.createSceneItem<Renderer::LightSceneItem>(sceneNode);
if (0 == mNumberOfVrControllers && nullptr != lightSceneItem)
{
// Spot light for the first VR controller
lightSceneItem->setLightTypeAndRadius(Renderer::LightSceneItem::LightType::SPOT, 5.0f);
lightSceneItem->setColor(glm::vec3(10.0f, 10.0f, 10.0f));
lightSceneItem->setInnerOuterAngle(glm::radians(20.0f), glm::radians(30.0f));
lightSceneItem->setNearClipDistance(0.05f);
}
// Remember the VR controller tracked device index
mVrControllerTrackedDeviceIndices[mNumberOfVrControllers] = trackedDeviceIndex;
++mNumberOfVrControllers;
}
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit VrManagerOpenVRListener(const VrManagerOpenVRListener&) = delete;
VrManagerOpenVRListener& operator=(const VrManagerOpenVRListener&) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
const Renderer::VrManagerOpenVR* mVrManagerOpenVR;
VrController* mVrController;
uint32_t mNumberOfVrControllers;
vr::TrackedDeviceIndex_t mVrControllerTrackedDeviceIndices[vr::k_unMaxTrackedDeviceCount];
};
class MaterialBlueprintResourceListener : public Renderer::MaterialBlueprintResourceListener
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
inline MaterialBlueprintResourceListener() :
mVrManagerOpenVR(nullptr),
mVrManagerOpenVRListener(nullptr),
mVrController(nullptr)
{
// Nothing here
}
inline virtual ~MaterialBlueprintResourceListener() override
{
// Nothing here
}
inline void setVrManagerOpenVR(const Renderer::VrManagerOpenVR& vrManagerOpenVR, const VrManagerOpenVRListener& vrManagerOpenVRListener, VrController& vrController)
{
mVrManagerOpenVR = &vrManagerOpenVR;
mVrManagerOpenVRListener = &vrManagerOpenVRListener;
mVrController = &vrController;
}
//[-------------------------------------------------------]
//[ Private virtual Renderer::IMaterialBlueprintResourceListener methods ]
//[-------------------------------------------------------]
private:
[[nodiscard]] virtual bool fillPassValue(uint32_t referenceValue, uint8_t* buffer, uint32_t numberOfBytes) override
{
// The GUI is placed over the second VR controller
#ifdef RENDERER_IMGUI
if (::detail::IMGUI_OBJECT_SPACE_TO_CLIP_SPACE_MATRIX == referenceValue && mVrManagerOpenVRListener->getNumberOfVrControllers() > SECOND_CONTROLLER_INDEX)
{
ASSERT(sizeof(float) * 4 * 4 == numberOfBytes, "Invalid number of bytes")
const ImGuiIO& imGuiIo = ImGui::GetIO();
const glm::quat rotationOffset = glm::eulerAngleYXZ(0.0f, glm::degrees(180.0f), 0.0f);
const glm::mat4 guiScaleMatrix = glm::scale(Renderer::Math::MAT4_IDENTITY, glm::vec3(1.0f / imGuiIo.DisplaySize.x, 1.0f / imGuiIo.DisplaySize.y, 1.0f));
const glm::mat4& devicePoseMatrix = mVrManagerOpenVR->getDevicePoseMatrix(mVrManagerOpenVRListener->getVrControllerTrackedDeviceIndices(SECOND_CONTROLLER_INDEX));
// TODO(co) 64 bit support
const glm::mat4& cameraPositionMatrix = glm::translate(Renderer::Math::MAT4_IDENTITY, glm::vec3(-mVrController->getCameraSceneItem().getParentSceneNodeSafe().getGlobalTransform().position));
const glm::mat4 objectSpaceToClipSpaceMatrix = getPassData().cameraRelativeWorldSpaceToClipSpaceMatrixReversedZ[0] * cameraPositionMatrix * devicePoseMatrix * glm::mat4_cast(rotationOffset) * guiScaleMatrix;
memcpy(buffer, glm::value_ptr(objectSpaceToClipSpaceMatrix), numberOfBytes);
// Value filled
return true;
}
else
#endif
{
// Call the base implementation
return Renderer::MaterialBlueprintResourceListener::fillPassValue(referenceValue, buffer, numberOfBytes);
}
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit MaterialBlueprintResourceListener(const MaterialBlueprintResourceListener&) = delete;
MaterialBlueprintResourceListener& operator=(const MaterialBlueprintResourceListener&) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
const Renderer::VrManagerOpenVR* mVrManagerOpenVR;
const VrManagerOpenVRListener* mVrManagerOpenVRListener;
VrController* mVrController;
};
//[-------------------------------------------------------]
//[ Global variables ]
//[-------------------------------------------------------]
static VrManagerOpenVRListener defaultVrManagerOpenVRListener;
static MaterialBlueprintResourceListener materialBlueprintResourceListener;
//[-------------------------------------------------------]
//[ Anonymous detail namespace ]
//[-------------------------------------------------------]
} // detail
}
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
VrController::VrController(Renderer::CameraSceneItem& cameraSceneItem) :
IController(cameraSceneItem),
mRenderer(cameraSceneItem.getSceneResource().getRenderer()),
mTeleportIndicationLightSceneItem(nullptr)
{
// Register our listeners
if (mRenderer.getVrManager().getVrManagerTypeId() == Renderer::VrManagerOpenVR::TYPE_ID)
{
Renderer::VrManagerOpenVR& vrManagerOpenVR = static_cast<Renderer::VrManagerOpenVR&>(mRenderer.getVrManager());
::detail::defaultVrManagerOpenVRListener.setVrManagerOpenVR(vrManagerOpenVR, *this);
vrManagerOpenVR.setVrManagerOpenVRListener(&::detail::defaultVrManagerOpenVRListener);
::detail::materialBlueprintResourceListener.setVrManagerOpenVR(vrManagerOpenVR, ::detail::defaultVrManagerOpenVRListener, *this);
mRenderer.getMaterialBlueprintResourceManager().setMaterialBlueprintResourceListener(&::detail::materialBlueprintResourceListener);
}
{ // Create the teleport indication light scene item
Renderer::SceneResource& sceneResource = cameraSceneItem.getSceneResource();
Renderer::SceneNode* sceneNode = sceneResource.createSceneNode(Renderer::Transform::IDENTITY);
RHI_ASSERT(mRenderer.getContext(), nullptr != sceneNode, "Invalid scene node")
mTeleportIndicationLightSceneItem = sceneResource.createSceneItem<Renderer::LightSceneItem>(*sceneNode);
RHI_ASSERT(mRenderer.getContext(), nullptr != mTeleportIndicationLightSceneItem, "Invalid teleport indication light scene item")
mTeleportIndicationLightSceneItem->setColor(glm::vec3(0.0f, 1.0f, 0.0f));
mTeleportIndicationLightSceneItem->setVisible(false);
}
}
VrController::~VrController()
{
// TODO(co) Destroy the teleport indication light scene item? (not really worth the effort here)
// Unregister our listeners
if (mRenderer.getVrManager().getVrManagerTypeId() == Renderer::VrManagerOpenVR::TYPE_ID)
{
static_cast<Renderer::VrManagerOpenVR&>(mRenderer.getVrManager()).setVrManagerOpenVRListener(nullptr);
mRenderer.getMaterialBlueprintResourceManager().setMaterialBlueprintResourceListener(nullptr);
}
}
const Renderer::LightSceneItem& VrController::getTeleportIndicationLightSceneItemSafe() const
{
RHI_ASSERT(mRenderer.getContext(), nullptr != mTeleportIndicationLightSceneItem, "Invalid teleport indication light scene item")
return *mTeleportIndicationLightSceneItem;
}
//[-------------------------------------------------------]
//[ Public virtual IController methods ]
//[-------------------------------------------------------]
void VrController::onUpdate(float, bool)
{
// The first VR controller is used for teleporting
// -> A green light indicates the position one will end up
// -> When pressing the trigger button one teleports to this position
if (mRenderer.getVrManager().getVrManagerTypeId() == Renderer::VrManagerOpenVR::TYPE_ID && ::detail::defaultVrManagerOpenVRListener.getNumberOfVrControllers() >= 1 && nullptr != mTeleportIndicationLightSceneItem)
{
const Renderer::VrManagerOpenVR& vrManagerOpenVR = static_cast<Renderer::VrManagerOpenVR&>(mRenderer.getVrManager());
const bool hasFocus = vrManagerOpenVR.getVrSystem()->IsInputAvailable();
bool teleportIndicationLightSceneItemVisible = hasFocus;
// Do only show the teleport indication light scene item visible if the input focus is captured by our process
if (hasFocus)
{
// Get VR controller transform data
const glm::mat4& devicePoseMatrix = vrManagerOpenVR.getDevicePoseMatrix(::detail::defaultVrManagerOpenVRListener.getVrControllerTrackedDeviceIndices(::detail::FIRST_CONTROLLER_INDEX));
glm::vec3 scale;
glm::quat rotation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(devicePoseMatrix, scale, rotation, translation, skew, perspective);
// Construct ray
const glm::dvec3 rayOrigin = glm::dvec3(translation) + getCameraSceneItem().getParentSceneNodeSafe().getGlobalTransform().position;
const glm::dvec3 rayDirection = rotation * Renderer::Math::VEC3_FORWARD;
// Simple ray-plane intersection
static constexpr double MAXIMUM_TELEPORT_DISTANCE = 10.0;
double distance = 0.0;
if (glm::intersectRayPlane(rayOrigin, rayDirection, Renderer::Math::DVEC3_ZERO, Renderer::Math::DVEC3_UP, distance) && !std::isnan(distance) && distance <= MAXIMUM_TELEPORT_DISTANCE)
{
mTeleportIndicationLightSceneItem->getParentSceneNode()->setPosition(rayOrigin + rayDirection * distance);
}
else
{
teleportIndicationLightSceneItemVisible = false;
}
}
// Set teleport indication light scene item visibility
mTeleportIndicationLightSceneItem->setVisible(teleportIndicationLightSceneItemVisible);
}
}
| 44.222798 | 271 | 0.649971 | [
"mesh",
"transform"
] |
6ba3650d5a4850f449fded217ae3a8e8b624fcd1 | 4,667 | cpp | C++ | src/likelihood_ratio.cpp | tgstoecker/CAFE5 | bfc745ef7cf3ca8b11cfe984b4aadf4a90795868 | [
"ECL-2.0"
] | 33 | 2020-11-23T02:15:17.000Z | 2022-03-17T17:12:57.000Z | src/likelihood_ratio.cpp | tgstoecker/CAFE5 | bfc745ef7cf3ca8b11cfe984b4aadf4a90795868 | [
"ECL-2.0"
] | 33 | 2020-11-11T18:58:38.000Z | 2022-03-28T14:04:13.000Z | src/likelihood_ratio.cpp | tgstoecker/CAFE5 | bfc745ef7cf3ca8b11cfe984b4aadf4a90795868 | [
"ECL-2.0"
] | 11 | 2021-03-11T21:15:28.000Z | 2022-03-24T20:44:37.000Z | #include "core.h"
#include "matrix_cache.h"
#include "user_data.h"
#include "chisquare.h"
#include "optimizer_scorer.h"
#include "root_equilibrium_distribution.h"
#include <memory>
#include <cmath>
#include <algorithm>
namespace LikelihoodRatioTest
{
using namespace std;
clade * update_branchlength(const clade * p_tree, double bl_augment, int t)
{
return new clade(*p_tree, nullptr, [&](const clade& c) {
return c.get_branch_length() + (c.get_branch_length() + bl_augment * t); });
}
double get_likelihood_for_diff_lambdas(const gene_family & gf, const clade * p_tree, const clade * p_lambda_tree,
int lambda_index,
std::vector<lambda*> & lambda_cache,
optimizer *opt,
int max_root_family_size,
int max_family_size)
{
const double bl_augment = 0.5;
unique_ptr<clade> adjusted_tree(update_branchlength(p_tree, bl_augment, lambda_index));
if (lambda_cache[lambda_index] == nullptr)
{
auto result = opt->optimize(optimizer_parameters());
if (p_lambda_tree)
lambda_cache[lambda_index] = new multiple_lambda(map<string, int>(), result.values);
else
lambda_cache[lambda_index] = new single_lambda(result.values[0]);
}
matrix_cache m(max_family_size + 1);
m.precalculate_matrices(get_lambda_values(lambda_cache[lambda_index]), adjusted_tree->get_branch_lengths());
auto probs = inference_prune(gf, m, lambda_cache[lambda_index], nullptr, adjusted_tree.get(), 1.0, max_root_family_size, max_family_size);
return *max_element(probs.begin(), probs.end());
}
void compute_for_diff_lambdas_i(const user_data & data,
std::vector<int> & lambda_index,
std::vector<double> & pvalues,
std::vector<lambda*> & lambda_cache,
optimizer* p_opt
)
{
auto references = build_reference_list(data.gene_families);
matrix_cache cache(max(data.max_root_family_size, data.max_family_size) + 1);
for (size_t i = 0; i < data.gene_families.size(); i += 1)
{
auto& pitem = data.gene_families[i];
if (references[i] != i) continue;
cache.precalculate_matrices(get_lambda_values(data.p_lambda), data.p_tree->get_branch_lengths());
auto values = inference_prune(pitem, cache, data.p_lambda, data.p_error_model, data.p_tree, 1.0, data.max_root_family_size, data.max_family_size);
double maxlh1 = *max_element(values.begin(), values.end());
double prev = -1;
double next = get_likelihood_for_diff_lambdas(pitem, data.p_tree, data.p_lambda_tree, 0, lambda_cache, p_opt, data.max_root_family_size, data.max_family_size);
int j = 1;
for (; prev < next; j++)
{
prev = next;
next = get_likelihood_for_diff_lambdas(pitem, data.p_tree, data.p_lambda_tree, j, lambda_cache, p_opt, data.max_root_family_size, data.max_family_size);
}
pvalues[i] = (prev == maxlh1) ? 1 : 2 * (log(prev) - log(maxlh1));
lambda_index[i] = j - 2;
}
}
void likelihood_ratio_report(std::ostream & ost, const std::vector<gene_family> & families,
const clade * pcafe,
const std::vector<double> & pvalues,
const std::vector<int> & plambda,
const std::vector<lambda*> & lambda_cache)
{
for (size_t i = 0; i < families.size(); ++i)
{
ost << families[i].id() << "\t";
pcafe->write_newick(ost, [](const clade* c) { return c->get_taxon_name(); });
auto l = lambda_cache[plambda[i]];
cout << "(" << plambda[i] << ", " << *l << ")\t" << pvalues[i] << "\t" << (pvalues[1] == 1 ? 1 : 1 - chi2cdf(pvalues[i], 1)) << endl;
}
}
void lhr_for_diff_lambdas(const user_data & data, model *p_model)
{
std::vector<lambda*> lambda_cache(100);
cout << "Running Likelihood Ratio Test 2....\n";
std::vector<double> pvalues(data.gene_families.size());
std::vector<int> lambdas(data.gene_families.size());
auto lengths = data.p_tree->get_branch_lengths();
auto longest_branch = *max_element(lengths.begin(), lengths.end());
auto scorer = new lambda_optimizer(data.p_lambda, p_model, &data.prior, longest_branch);
optimizer opt(scorer);
opt.quiet = true;
compute_for_diff_lambdas_i(data, lambdas, pvalues, lambda_cache, &opt);
likelihood_ratio_report(cout, data.gene_families, data.p_tree, pvalues, lambdas, lambda_cache);
}
} | 41.669643 | 171 | 0.628027 | [
"vector",
"model"
] |
6ba781ec3c57d6d3ca8c96aab22b4d9a0446772e | 7,372 | cpp | C++ | Child/Code/tLithologyManager/childLithTestDriver.cpp | dvalters/child | 9874278f5308ab6c5f0cb93ed879bca9761d24b9 | [
"MIT"
] | 9 | 2015-02-23T15:47:20.000Z | 2020-05-19T23:42:05.000Z | Child/Code/tLithologyManager/childLithTestDriver.cpp | dvalters/child | 9874278f5308ab6c5f0cb93ed879bca9761d24b9 | [
"MIT"
] | 3 | 2020-04-21T06:12:53.000Z | 2020-08-20T16:56:17.000Z | Child/Code/tLithologyManager/childLithTestDriver.cpp | dvalters/child | 9874278f5308ab6c5f0cb93ed879bca9761d24b9 | [
"MIT"
] | 12 | 2015-02-18T18:34:57.000Z | 2020-07-12T04:04:36.000Z | /**************************************************************************/
/**
** childDriver.cpp: This provides a test and example of the CHILD
** interface.
**
** The variation "childTestDriver" is used to test new additions,
** especially to the childInterface.
**
** Apr 2010
**
** For information regarding this program, please contact Greg Tucker at:
**
** Cooperative Institute for Research in Environmental Sciences (CIRES)
** and Department of Geological Sciences
** University of Colorado
** 2200 Colorado Avenue, Campus Box 399
** Boulder, CO 80309-0399
**
*/
/**************************************************************************/
#include "../ChildInterface/childInterface.h"
#include "tLithologyManager.h"
int main( int argc, char **argv )
{
childInterface myChildInterface;
tLithologyManager my_lith_mgr;
tOption option( argc, argv );
tInputFile infile( option.inputFile );
myChildInterface.Initialize( argc, argv );
std::cout << "CHILD has finished initializing. Now for some tests.\n\n";
std::cout << "Testing GetNodeCount(): this run has "
<< myChildInterface.GetNodeCount() << " nodes.\n";
std::cout << "Testing GetNodeCoords() and GetValueSet() with 'elevation' and 'discharge':\n";
std::cout << "The coordinates and properties of these nodes are:\n"
<< "(note that the two z columns should be the same)\n"
<< "x\ty\tz\tz\tQ\tQs\n";
int nn = myChildInterface.GetNodeCount();
std::vector<double> coords = myChildInterface.GetNodeCoords();
std::vector<double> elevs = myChildInterface.GetValueSet( "elevation" );
std::vector<double> q = myChildInterface.GetValueSet( "discharge" );
std::vector<double> qs = myChildInterface.GetValueSet( "sedflux" );
for( long i=0; i<nn; i++ )
{
std::cout << coords[3*i] << "\t"
<< coords[3*i+1] << "\t" << coords[3*i+2];
std::cout << "\t" << elevs[i]
<< "\t" << q[i]
<< "\t" << qs[i] << std::endl;
}
std::cout << "Testing GetTriangleCount(): this run has "
<< myChildInterface.GetTriangleCount() << " triangles.\n";
std::cout << "Testing GetTriangleVertexIDs(): the vertex IDs of these triangles are:\n"
<< "Tri ID\tp0\tp1\tp2\n";
int nt = myChildInterface.GetTriangleCount();
std::vector<long> vertices = myChildInterface.GetTriangleVertexIDs();
for( long i=0; i<nt; i++ )
{
std::cout << i << "\t";
std::cout << vertices[3*i] << "\t";
std::cout << vertices[3*i+1] << "\t"
<< vertices[3*i+2] << std::endl;
}
// Now some tests on the lithology manager:
// First, initialize it.
my_lith_mgr.InitializeFromInputFile( infile, myChildInterface.GetMeshPointer() );
// Now, see if we can re-set the rock erodibility at each node
std::vector<double> erody( coords.size() );
for( long i=0; i<nn; i++ )
if( coords[3*i] > 4000.0 && coords[3*i] < 6000.0 )
erody[i] = 500.0;
else
erody[i] = 1.0e-6;
my_lith_mgr.SetRockErodibilityValuesAtAllDepths( erody );
// Test the point in polygon routine
std::vector<double> polyx( 4 );
std::vector<double> polyy( 4 );
polyx[0] = 2.0;
polyx[1] = 4.0;
polyx[2] = 4.0;
polyx[3] = 2.0;
polyy[0] = 2.0;
polyy[1] = 2.0;
polyy[2] = 4.0;
polyy[3] = 4.0;
std::cout << "This should be false: " << my_lith_mgr.PointInPolygon( polyx, polyy, 1.0, 3.0 ) << std::endl;
std::cout << "This should be false: " << my_lith_mgr.PointInPolygon( polyx, polyy, 3.0, 5.0 ) << std::endl;
std::cout << "This should be false: " << my_lith_mgr.PointInPolygon( polyx, polyy, 5.0, 3.0 ) << std::endl;
std::cout << "This should be false: " << my_lith_mgr.PointInPolygon( polyx, polyy, 3.0, 1.0 ) << std::endl;
std::cout << "This should be true: " << my_lith_mgr.PointInPolygon( polyx, polyy, 3.0, 3.0 ) << std::endl;
// Now back to the main attraction ... running the model!
myChildInterface.Run( 0 );
std::cout << "CHILD run has finished. Now re-run the tests.\n\n";
std::cout << "Testing GetNodeCount(): this run has "
<< myChildInterface.GetNodeCount() << " nodes.\n";
std::cout << "Testing GetNodeCoords() and GetValueSet() with 'elevation' and 'discharge':\n";
std::cout << "The coordinates and properties of these nodes are:\n"
<< "(note that the two z columns should be the same)\n"
<< "x\ty\tz\tz\tQ\tQs\n";
nn = myChildInterface.GetNodeCount();
coords = myChildInterface.GetNodeCoords();
elevs = myChildInterface.GetValueSet( "elevation" );
q = myChildInterface.GetValueSet( "discharge" );
qs = myChildInterface.GetValueSet( "sedflux" );
for( long i=0; i<nn; i++ )
{
std::cout << coords[3*i] << "\t"
<< coords[3*i+1] << "\t" << coords[3*i+2];
std::cout << "\t" << elevs[i]
<< "\t" << q[i] << "\t" << qs[i] << std::endl;
}
std::cout << "Testing GetTriangleCount(): this run has "
<< myChildInterface.GetTriangleCount() << " triangles.\n";
std::cout << "Testing GetTriangleVertexIDs(): the vertex IDs of these triangles are:\n"
<< "Tri ID\tp0\tp1\tp2\n";
nt = myChildInterface.GetTriangleCount();
vertices = myChildInterface.GetTriangleVertexIDs();
for( long i=0; i<nt; i++ )
{
std::cout << i << "\t";
std::cout << vertices[3*i] << "\t";
std::cout << vertices[3*i+1] << "\t"
<< vertices[3*i+2] << std::endl;
}
std::cout << "\nTest of AdjustElevations() and AdjustInteriorElevations:\n\n";
std::vector<double> dz( nn, 1.0 );
myChildInterface.AdjustInteriorElevations( dz );
std::vector<double> new_elevs = myChildInterface.GetValueSet( "elevation" );
std::cout << "The interior nodes should now be 1m higher, but not the boundary nodes:\n";
std::cout << "ID\tOld z\tNew z:\n";
for( long i=0; i<nt; i++ )
{
std::cout << i << "\t";
std::cout << elevs[i] << "\t" << new_elevs[i] << std::endl;
}
myChildInterface.AdjustElevations( dz );
new_elevs = myChildInterface.GetValueSet( "elevation" );
std::cout << "Now all nodes should be another 1m higher:\n";
std::cout << "ID\tOriginal z\tNew z:\n";
for( long i=0; i<nt; i++ )
{
std::cout << i << "\t";
std::cout << elevs[i] << "\t" << new_elevs[i] << std::endl;
}
// Now we'll test ExternalErodeAndDepositToElevation
elevs = new_elevs;
std::vector<double> desired_elevs( nn, 2.5 );
myChildInterface.ExternalErodeAndDepositToElevation( desired_elevs );
new_elevs = myChildInterface.GetValueSet( "elevation" );
std::cout << "Now all interior nodes should be 2.5m elevation\n";
std::cout << "ID\tPrevious z\tNew z:\n";
for( long i=0; i<nt; i++ )
{
std::cout << i << "\t";
std::cout << elevs[i] << "\t" << new_elevs[i] << std::endl;
}
desired_elevs = elevs;
myChildInterface.ExternalErodeAndDepositToElevation( elevs );
new_elevs = myChildInterface.GetValueSet( "elevation" );
std::cout << "Now they should be back to their previous values\n";
std::cout << "ID\tPrevious z\tNew z:\n";
for( long i=0; i<nt; i++ )
{
std::cout << i << "\t";
std::cout << new_elevs[i] << std::endl;
}
// Note that calling CleanUp() isn't strictly necessary, as the destructor will automatically clean it
// up when myChildInterface is deleted ... but it's nice to be able to do this at will (and free up
// memory)
myChildInterface.CleanUp();
return 0;
}
| 37.612245 | 109 | 0.612588 | [
"vector",
"model"
] |
6ba80d379ae5d9b60db037c8df01320456197666 | 725 | cpp | C++ | 08/05_filter_by_index/main.cpp | MATF-Functional-Programming/FP-4I-2019-2020 | bb78c55a6d88190e9d90dbd4adcef4d25e3c2492 | [
"MIT"
] | 1 | 2021-08-29T13:09:39.000Z | 2021-08-29T13:09:39.000Z | 08/05_filter_by_index/main.cpp | MATF-Functional-Programming/FP-4I-2019-2020 | bb78c55a6d88190e9d90dbd4adcef4d25e3c2492 | [
"MIT"
] | null | null | null | 08/05_filter_by_index/main.cpp | MATF-Functional-Programming/FP-4I-2019-2020 | bb78c55a6d88190e9d90dbd4adcef4d25e3c2492 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <functional>
#include <range/v3/view.hpp>
using namespace ranges::v3;
using namespace std::placeholders;
bool index_filter(size_t index) {
return index % 3 != 0;
}
int main(int argc, char *argv[])
{
std::vector<int> xs = { -1, -3, -5, 1, 3, 5};
// Zipujemo xs sa listom svih prirodnih brojeva,
// filtriramo po indeksu, posle toga zaboravljamo indeks.
auto results =
view::zip(xs, view::ints(1))
| view::filter([] (auto value) { return index_filter(value.second); })
| view::transform([] (auto value) { return value.first; });
for (auto value: results) {
std::cout << value << std::endl;
}
return 0;
}
| 24.166667 | 81 | 0.611034 | [
"vector",
"transform"
] |
6bac3e1912e7233eb3b45e0e53c34c31aff5af20 | 2,236 | cpp | C++ | DivideAndConquer/CountOfSmallerNumbersAfterSelf/CountOfSmallerNumbersAfterSelf.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | 2 | 2015-08-28T03:52:05.000Z | 2015-09-03T09:54:40.000Z | DivideAndConquer/CountOfSmallerNumbersAfterSelf/CountOfSmallerNumbersAfterSelf.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | null | null | null | DivideAndConquer/CountOfSmallerNumbersAfterSelf/CountOfSmallerNumbersAfterSelf.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | null | null | null | // Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/
// Author : Yijing Bai
// Date : 2016-03-25
/**********************************************************************************
*
* You are given an integer array nums and you have to return a new counts array.
* The counts array has the property where counts[i] is
* the number of smaller elements to the right of nums[i].
*
* Example:
*
* Given nums = [5, 2, 6, 1]
*
* To the right of 5 there are 2 smaller elements (2 and 1).
* To the right of 2 there is only 1 smaller element (1).
* To the right of 6 there is 1 smaller element (1).
* To the right of 1 there is 0 smaller element.
*
* Return the array [2, 1, 1, 0].
*
**********************************************************************************/
class Solution {
private:
void merge_count_smaller(vector<int>& indices, int first, int last,
vector<int>& results, vector<int>& nums) {
int count = last - first;
if (count > 1) {
int step = count / 2;
int mid = first + step;
merge_count_smaller(indices, first, mid, results, nums);
merge_count_smaller(indices, mid, last, results, nums);
vector<int> tmp;
tmp.reserve(count);
int idx1 = first;
int idx2 = mid;
int semicount = 0;
while ((idx1 < mid) || (idx2 < last)) {
if ((idx2 == last) || ((idx1 < mid) && (nums[indices[idx1]] <= nums[indices[idx2]]))) {
tmp.push_back(indices[idx1]);
results[indices[idx1]] += semicount;
++idx1;
} else {
tmp.push_back(indices[idx2]);
++semicount;
++idx2;
}
}
move(tmp.begin(), tmp.end(), indices.begin() + first);
}
}
public:
vector<int> countSmaller(vector<int>& nums) {
int n = nums.size();
vector<int> results(n, 0);
vector<int> indices(n, 0);
iota(indices.begin(), indices.end(), 0);
merge_count_smaller(indices, 0, n, results, nums);
return results;
}
};
| 33.878788 | 103 | 0.489714 | [
"vector"
] |
6bc6a29a2963a6ef39fdd0b43a9d8f91bea676bb | 19,434 | cpp | C++ | lib/_studio/mfx_lib/fei/h264_enc/mfx_h264_enc.cpp | 3xLOGICKevinHan/MediaSDK | 92b6ee70f5ea45d08527f81cb93105f9ee71d84e | [
"MIT"
] | null | null | null | lib/_studio/mfx_lib/fei/h264_enc/mfx_h264_enc.cpp | 3xLOGICKevinHan/MediaSDK | 92b6ee70f5ea45d08527f81cb93105f9ee71d84e | [
"MIT"
] | null | null | null | lib/_studio/mfx_lib/fei/h264_enc/mfx_h264_enc.cpp | 3xLOGICKevinHan/MediaSDK | 92b6ee70f5ea45d08527f81cb93105f9ee71d84e | [
"MIT"
] | null | null | null | // Copyright (c) 2017 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice 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 "mfx_common.h"
#if defined(MFX_ENABLE_H264_VIDEO_ENCODE_HW) && defined(MFX_ENABLE_H264_VIDEO_FEI_ENC)
#include "mfx_h264_enc.h"
#if defined(_DEBUG)
#define mdprintf fprintf
#else
#define mdprintf(...)
#endif
using namespace MfxHwH264Encode;
using namespace MfxH264FEIcommon;
namespace MfxEncENC
{
static bool IsVideoParamExtBufferIdSupported(mfxU32 id)
{
return
id == MFX_EXTBUFF_FEI_PPS ||
id == MFX_EXTBUFF_FEI_SPS ||
id == MFX_EXTBUFF_CODING_OPTION ||
id == MFX_EXTBUFF_CODING_OPTION2 ||
id == MFX_EXTBUFF_CODING_OPTION3 ||
id == MFX_EXTBUFF_FEI_PARAM;
}
static mfxStatus CheckExtBufferId(mfxVideoParam const & par)
{
for (mfxU32 i = 0; i < par.NumExtParam; ++i)
{
MFX_CHECK(par.ExtParam[i], MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(MfxEncENC::IsVideoParamExtBufferIdSupported(par.ExtParam[i]->BufferId), MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(!MfxHwH264Encode::GetExtBuffer(
par.ExtParam + i + 1,
par.NumExtParam - i - 1,
par.ExtParam[i]->BufferId), MFX_ERR_INVALID_VIDEO_PARAM);
}
return MFX_ERR_NONE;
}
} // namespace MfxEncENC
bool bEnc_ENC(mfxVideoParam *par)
{
MFX_CHECK(par, false);
mfxExtFeiParam *pControl = NULL;
for (mfxU16 i = 0; i < par->NumExtParam; ++i)
{
if (par->ExtParam[i] != 0 && par->ExtParam[i]->BufferId == MFX_EXTBUFF_FEI_PARAM)
{
pControl = reinterpret_cast<mfxExtFeiParam *>(par->ExtParam[i]);
break;
}
}
return pControl ? (pControl->Func == MFX_FEI_FUNCTION_ENC) : false;
}
static mfxStatus AsyncRoutine(void * state, void * param, mfxU32, mfxU32)
{
MFX_CHECK_NULL_PTR1(state);
VideoENC_ENC & impl = *(VideoENC_ENC *)state;
return impl.RunFrameVmeENC(NULL, NULL);
}
mfxStatus VideoENC_ENC::RunFrameVmeENC(mfxENCInput *in, mfxENCOutput *out)
{
mdprintf(stderr, "VideoENC_ENC::RunFrameVmeENC\n");
MFX_AUTO_LTRACE(MFX_TRACE_LEVEL_HOTSPOTS, "VideoENC_ENC::RunFrameVmeENC");
mfxStatus sts = MFX_ERR_NONE;
DdiTask & task = m_incoming.front();
mfxU32 f_start = 0, fieldCount = task.m_fieldPicFlag;
if (MFX_CODINGOPTION_ON == m_singleFieldProcessingMode)
{
fieldCount = f_start = m_firstFieldDone; // 0 or 1
}
for (mfxU32 f = f_start; f <= fieldCount; ++f)
{
sts = m_ddi->Execute(task.m_handleRaw.first, task, task.m_fid[f], m_sei);
MFX_CHECK(sts == MFX_ERR_NONE, Error(sts));
}
if (MFX_CODINGOPTION_ON == m_singleFieldProcessingMode)
{
m_firstFieldDone = 1 - m_firstFieldDone;
}
if (0 == m_firstFieldDone)
{
m_prevTask = task;
}
return sts;
}
static mfxStatus AsyncQuery(void * state, void * param, mfxU32 /*threadNumber*/, mfxU32 /*callNumber*/)
{
MFX_CHECK_NULL_PTR2(state, param);
VideoENC_ENC & impl = *(VideoENC_ENC *)state;
DdiTask & task = *(DdiTask *)param;
return impl.QueryStatus(task);
}
mfxStatus VideoENC_ENC::QueryStatus(DdiTask& task)
{
mdprintf(stderr, "VideoENC_ENC::QueryStatus\n");
mfxStatus sts = MFX_ERR_NONE;
mfxU32 f_start = 0, fieldCount = task.m_fieldPicFlag;
if (MFX_CODINGOPTION_ON == m_singleFieldProcessingMode)
{
f_start = fieldCount = 1 - m_firstFieldDone;
}
for (mfxU32 f = f_start; f <= fieldCount; f++)
{
sts = m_ddi->QueryStatus(task, task.m_fid[f]);
MFX_CHECK(sts != MFX_WRN_DEVICE_BUSY, MFX_TASK_BUSY);
MFX_CHECK(sts == MFX_ERR_NONE, Error(sts));
}
mfxENCInput *input = reinterpret_cast<mfxENCInput *>(task.m_userData[0]);
mfxENCOutput *output = reinterpret_cast<mfxENCOutput *>(task.m_userData[1]);
m_core->DecreaseReference(&input->InSurface->Data);
m_core->DecreaseReference(&output->OutSurface->Data);
UMC::AutomaticUMCMutex guard(m_listMutex);
//move that task to free tasks from m_incoming
//m_incoming
std::list<DdiTask>::iterator it = std::find(m_incoming.begin(), m_incoming.end(), task);
MFX_CHECK(it != m_incoming.end(), MFX_ERR_NOT_FOUND);
m_free.splice(m_free.end(), m_incoming, it);
ReleaseResource(m_rec, task.m_midRec);
return MFX_ERR_NONE;
}
mfxStatus VideoENC_ENC::QueryIOSurf(VideoCORE* , mfxVideoParam *par, mfxFrameAllocRequest *request)
{
MFX_CHECK_NULL_PTR2(par,request);
mfxU32 inPattern = par->IOPattern & MFX_IOPATTERN_IN_MASK;
MFX_CHECK(
inPattern == MFX_IOPATTERN_IN_SYSTEM_MEMORY ||
inPattern == MFX_IOPATTERN_IN_VIDEO_MEMORY ||
inPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY,
MFX_ERR_INVALID_VIDEO_PARAM);
if (inPattern == MFX_IOPATTERN_IN_SYSTEM_MEMORY)
{
request->Type =
MFX_MEMTYPE_EXTERNAL_FRAME |
MFX_MEMTYPE_FROM_ENCODE |
MFX_MEMTYPE_SYSTEM_MEMORY;
}
else // MFX_IOPATTERN_IN_VIDEO_MEMORY || MFX_IOPATTERN_IN_OPAQUE_MEMORY
{
request->Type = MFX_MEMTYPE_FROM_ENCODE | MFX_MEMTYPE_DXVA2_DECODER_TARGET;
request->Type |= (inPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY)
? MFX_MEMTYPE_OPAQUE_FRAME
: MFX_MEMTYPE_EXTERNAL_FRAME;
}
/* 2*par->mfx.GopRefDist */
request->NumFrameMin = 2*par->mfx.GopRefDist + par->AsyncDepth;
request->NumFrameSuggested = request->NumFrameMin;
request->Info = par->mfx.FrameInfo;
return MFX_ERR_NONE;
}
VideoENC_ENC::VideoENC_ENC(VideoCORE *core, mfxStatus * sts)
: m_bInit(false)
, m_core(core)
, m_caps()
, m_prevTask()
, m_inputFrameType()
, m_currentPlatform(MFX_HW_UNKNOWN)
, m_currentVaType(MFX_HW_NO)
, m_singleFieldProcessingMode(0)
, m_firstFieldDone(0)
{
*sts = MFX_ERR_NONE;
}
VideoENC_ENC::~VideoENC_ENC()
{
Close();
}
mfxStatus VideoENC_ENC::Init(mfxVideoParam *par)
{
MFX_AUTO_LTRACE(MFX_TRACE_LEVEL_HOTSPOTS, "VideoENC_ENC::Init");
MFX_CHECK_NULL_PTR1(par);
mfxStatus sts = MfxEncENC::CheckExtBufferId(*par);
MFX_CHECK_STS(sts);
m_video = *par;
//add ext buffers from par to m_video
MfxVideoParam tmp(*par);
sts = ReadSpsPpsHeaders(tmp);
MFX_CHECK_STS(sts);
sts = CheckWidthAndHeight(tmp);
MFX_CHECK_STS(sts);
sts = CopySpsPpsToVideoParam(tmp);
MFX_CHECK(sts >= MFX_ERR_NONE, sts);
m_ddi.reset(new VAAPIFEIENCEncoder);
sts = m_ddi->CreateAuxilliaryDevice(
m_core,
DXVA2_Intel_Encode_AVC,
GetFrameWidth(m_video),
GetFrameHeight(m_video));
MFX_CHECK(sts == MFX_ERR_NONE, MFX_WRN_PARTIAL_ACCELERATION);
sts = m_ddi->QueryEncodeCaps(m_caps);
MFX_CHECK(sts == MFX_ERR_NONE, MFX_WRN_PARTIAL_ACCELERATION);
m_currentPlatform = m_core->GetHWType();
m_currentVaType = m_core->GetVAType();
mfxStatus spsppsSts = CopySpsPpsToVideoParam(m_video);
mfxStatus checkStatus = CheckVideoParam(m_video, m_caps, m_core->IsExternalFrameAllocator(), m_currentPlatform, m_currentVaType);
MFX_CHECK(checkStatus != MFX_WRN_PARTIAL_ACCELERATION, MFX_WRN_PARTIAL_ACCELERATION);
MFX_CHECK(checkStatus >= MFX_ERR_NONE, checkStatus);
if (checkStatus == MFX_ERR_NONE)
checkStatus = spsppsSts;
const mfxExtFeiParam* params = GetExtBuffer(m_video);
if (MFX_CODINGOPTION_ON == params->SingleFieldProcessing)
m_singleFieldProcessingMode = MFX_CODINGOPTION_ON;
//raw surfaces should be created before accel service
mfxFrameAllocRequest request = { };
request.Info = m_video.mfx.FrameInfo;
/* ENC does not generate real reconstruct surface,
* and this surface should be unchanged
* BUT (!)
* (1): this surface should be from reconstruct surface pool which was passed to
* component when vaCreateContext was called
* (2): And it should be same surface which will be used for PAK reconstructed in next call
* (3): And main rule: ENC (N number call) and PAK (N number call) should have same exactly
* same reference /reconstruct list !
* */
request.Type = MFX_MEMTYPE_FROM_ENC | MFX_MEMTYPE_DXVA2_DECODER_TARGET | MFX_MEMTYPE_INTERNAL_FRAME;
request.NumFrameMin = m_video.mfx.GopRefDist * 2 + (m_video.AsyncDepth-1) + 1 + m_video.mfx.NumRefFrame + 1;
request.NumFrameSuggested = request.NumFrameMin;
request.AllocId = par->AllocId;
//sts = m_core->AllocFrames(&request, &m_rec);
sts = m_rec.Alloc(m_core, request, false, true);
MFX_CHECK_STS(sts);
sts = m_ddi->Register(m_rec, D3DDDIFMT_NV12);
MFX_CHECK_STS(sts);
m_recFrameOrder.resize(m_rec.NumFrameActual, 0xffffffff);
sts = CheckInitExtBuffers(m_video, *par);
MFX_CHECK_STS(sts);
sts = m_ddi->CreateAccelerationService(m_video);
MFX_CHECK(sts == MFX_ERR_NONE, MFX_WRN_PARTIAL_ACCELERATION);
m_inputFrameType =
(m_video.IOPattern == MFX_IOPATTERN_IN_SYSTEM_MEMORY || m_video.IOPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY)
? MFX_IOPATTERN_IN_SYSTEM_MEMORY
: MFX_IOPATTERN_IN_VIDEO_MEMORY;
m_free.resize(m_video.AsyncDepth);
m_incoming.clear();
m_bInit = true;
return checkStatus;
}
mfxStatus VideoENC_ENC::Reset(mfxVideoParam *par)
{
Close();
return Init(par);
}
mfxStatus VideoENC_ENC::GetVideoParam(mfxVideoParam *par)
{
MFX_CHECK_NULL_PTR1(par);
// For buffers which are field-based
std::map<mfxU32, mfxU32> buffers_offsets;
for (mfxU32 i = 0; i < par->NumExtParam; ++i)
{
if (buffers_offsets.find(par->ExtParam[i]->BufferId) == buffers_offsets.end())
buffers_offsets[par->ExtParam[i]->BufferId] = 0;
else
buffers_offsets[par->ExtParam[i]->BufferId]++;
if (mfxExtBuffer * buf = MfxHwH264Encode::GetExtBuffer(m_video.ExtParam, m_video.NumExtParam, par->ExtParam[i]->BufferId, buffers_offsets[par->ExtParam[i]->BufferId]))
{
MFX_INTERNAL_CPY(par->ExtParam[i], buf, par->ExtParam[i]->BufferSz);
}
else
{
return MFX_ERR_UNSUPPORTED;
}
}
mfxExtBuffer ** ExtParam = par->ExtParam;
mfxU16 NumExtParam = par->NumExtParam;
MFX_INTERNAL_CPY(par, &(static_cast<mfxVideoParam &>(m_video)), sizeof(mfxVideoParam));
par->ExtParam = ExtParam;
par->NumExtParam = NumExtParam;
return MFX_ERR_NONE;
}
mfxStatus VideoENC_ENC::RunFrameVmeENCCheck(
mfxENCInput *input,
mfxENCOutput *output,
MFX_ENTRY_POINT pEntryPoints[],
mfxU32 &numEntryPoints)
{
mdprintf(stderr, "VideoENC_ENC::RunFrameVmeENCCheck\n");
// Check that all appropriate parameters passed
MFX_CHECK(m_bInit, MFX_ERR_UNDEFINED_BEHAVIOR);
MFX_CHECK_NULL_PTR2(input, output);
MFX_CHECK_NULL_PTR2(input->InSurface, output->OutSurface);
mfxStatus sts = CheckRuntimeExtBuffers(input, output, m_video);
MFX_CHECK_STS(sts);
// For frame type detection
PairU8 frame_type = PairU8(mfxU8(MFX_FRAMETYPE_UNKNOWN), mfxU8(MFX_FRAMETYPE_UNKNOWN));
mfxU32 fieldMaxCount = (m_video.mfx.FrameInfo.PicStruct & MFX_PICSTRUCT_PROGRESSIVE) ? 1 : 2;
for (mfxU32 field = 0; field < fieldMaxCount; ++field)
{
// Additionally check ENC specific requirements for extension buffers
mfxExtFeiEncMV * mvout = GetExtBufferFEI(output, field);
mfxExtFeiPakMBCtrl * mbcodeout = GetExtBufferFEI(output, field);
// Driver need both buffer to generate bitstream. If they both are not provided, driver will create them on his side
MFX_CHECK(!!mvout == !!mbcodeout, MFX_ERR_INVALID_VIDEO_PARAM);
// Check FrameCtrl settings
mfxExtFeiEncFrameCtrl * frameCtrl = GetExtBufferFEI(input, field);
MFX_CHECK(frameCtrl, MFX_ERR_UNDEFINED_BEHAVIOR);
MFX_CHECK(frameCtrl->SearchWindow != 0, MFX_ERR_INCOMPATIBLE_VIDEO_PARAM);
mfxExtCodingOption const * extOpt = GetExtBuffer(m_video);
if (((m_video.mfx.CodecProfile & MFX_PROFILE_AVC_BASELINE) == MFX_PROFILE_AVC_BASELINE || m_video.mfx.CodecProfile == MFX_PROFILE_AVC_MAIN
|| extOpt->IntraPredBlockSize == MFX_BLOCKSIZE_MIN_16X16) && !(frameCtrl->IntraPartMask & 0x02))
{
// For Main and Baseline profiles 8x8 transform is prohibited
return MFX_ERR_INCOMPATIBLE_VIDEO_PARAM;
}
// Frame type detection
mfxExtFeiPPS* extFeiPPSinRuntime = GetExtBufferFEI(input, field);
mfxU8 type = extFeiPPSinRuntime->PictureType;
// MFX_FRAMETYPE_xI / P / B disallowed here
MFX_CHECK(!(type & 0xff00), MFX_ERR_UNDEFINED_BEHAVIOR);
switch (type & 0xf)
{
case MFX_FRAMETYPE_UNKNOWN:
case MFX_FRAMETYPE_I:
case MFX_FRAMETYPE_P:
case MFX_FRAMETYPE_B:
break;
default:
return MFX_ERR_UNDEFINED_BEHAVIOR;
break;
}
frame_type[field] = type;
}
if (!frame_type[1]){ frame_type[1] = frame_type[0] & ~MFX_FRAMETYPE_IDR; }
UMC::AutomaticUMCMutex guard(m_listMutex);
m_free.front().m_yuv = input->InSurface;
//m_free.front().m_ctrl = 0;
m_free.front().m_type = frame_type;
m_free.front().m_extFrameTag = input->InSurface->Data.FrameOrder;
m_free.front().m_frameOrder = input->InSurface->Data.FrameOrder;
m_free.front().m_timeStamp = input->InSurface->Data.TimeStamp;
m_free.front().m_userData.resize(2);
m_free.front().m_userData[0] = input;
m_free.front().m_userData[1] = output;
m_incoming.splice(m_incoming.end(), m_free, m_free.begin());
DdiTask& task = m_incoming.front();
task.m_picStruct = GetPicStruct(m_video, task);
task.m_fieldPicFlag = task.m_picStruct[ENC] != MFX_PICSTRUCT_PROGRESSIVE;
task.m_fid[0] = task.m_picStruct[ENC] == MFX_PICSTRUCT_FIELD_BFF;
task.m_fid[1] = task.m_fieldPicFlag - task.m_fid[0];
if (task.m_picStruct[ENC] == MFX_PICSTRUCT_FIELD_BFF)
{
std::swap(task.m_type.top, task.m_type.bot);
}
m_core->IncreaseReference(&input->InSurface->Data);
m_core->IncreaseReference(&output->OutSurface->Data);
// Configure current task
//if (m_firstFieldDone == 0)
{
sts = GetNativeHandleToRawSurface(*m_core, m_video, task, task.m_handleRaw);
MFX_CHECK(sts == MFX_ERR_NONE, Error(sts));
mfxHDL handle_src, handle_rec;
sts = m_core->GetExternalFrameHDL(output->OutSurface->Data.MemId, &handle_src);
MFX_CHECK(sts == MFX_ERR_NONE, MFX_ERR_INVALID_HANDLE);
mfxMemId midRec;
mfxU32 *src_surf_id = (mfxU32 *)handle_src, *rec_surf_id, i;
for (i = 0; i < m_rec.NumFrameActual; ++i)
{
midRec = AcquireResource(m_rec, i);
sts = m_core->GetFrameHDL(m_rec.mids[i], &handle_rec);
MFX_CHECK(MFX_ERR_NONE == sts, MFX_ERR_INVALID_HANDLE);
rec_surf_id = (mfxU32 *)handle_rec;
if ((*src_surf_id) == (*rec_surf_id))
{
task.m_idxRecon = i;
task.m_midRec = midRec;
break;
}
else
{
ReleaseResource(m_rec, midRec);
}
}
MFX_CHECK(task.m_idxRecon != NO_INDEX && task.m_midRec != MID_INVALID && i != m_rec.NumFrameActual, MFX_ERR_UNDEFINED_BEHAVIOR);
ConfigureTaskFEI(task, m_prevTask, m_video, input, input, m_frameOrder_frameNum);
//!!! HACK !!!
m_recFrameOrder[task.m_idxRecon] = task.m_frameOrder;
TEMPORAL_HACK_WITH_DPB(task.m_dpb[0], m_rec.mids, m_recFrameOrder);
TEMPORAL_HACK_WITH_DPB(task.m_dpb[1], m_rec.mids, m_recFrameOrder);
TEMPORAL_HACK_WITH_DPB(task.m_dpbPostEncoding, m_rec.mids, m_recFrameOrder);
}
pEntryPoints[0].pState = this;
pEntryPoints[0].pParam = &m_incoming.front();
pEntryPoints[0].pCompleteProc = 0;
pEntryPoints[0].pGetSubTaskProc = 0;
pEntryPoints[0].pCompleteSubTaskProc = 0;
pEntryPoints[0].requiredNumThreads = 1;
pEntryPoints[0].pRoutineName = "AsyncRoutine";
pEntryPoints[0].pRoutine = AsyncRoutine;
pEntryPoints[1] = pEntryPoints[0];
pEntryPoints[1].pRoutineName = "Async Query";
pEntryPoints[1].pRoutine = AsyncQuery;
pEntryPoints[1].pParam = &m_incoming.front();
numEntryPoints = 2;
return MFX_ERR_NONE;
}
static mfxStatus CopyRawSurfaceToVideoMemory(VideoCORE & core,
MfxVideoParam const & video,
mfxFrameSurface1 * src_sys,
mfxMemId dst_d3d,
mfxHDL& handle)
{
MFX_CHECK_NULL_PTR1(src_sys);
mfxExtOpaqueSurfaceAlloc const * extOpaq = GetExtBuffer(video);
MFX_CHECK(extOpaq, MFX_ERR_NOT_FOUND);
mfxFrameData d3dSurf = {0};
if (video.IOPattern == MFX_IOPATTERN_IN_SYSTEM_MEMORY ||
(video.IOPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY && (extOpaq->In.Type & MFX_MEMTYPE_SYSTEM_MEMORY)))
{
mfxFrameData sysSurf = src_sys->Data;
d3dSurf.MemId = dst_d3d;
FrameLocker lock2(&core, sysSurf, true);
MFX_CHECK_NULL_PTR1(sysSurf.Y)
{
MFX_AUTO_LTRACE(MFX_TRACE_LEVEL_HOTSPOTS, "Copy input (sys->d3d)");
MFX_CHECK_STS(CopyFrameDataBothFields(&core, d3dSurf, sysSurf, video.mfx.FrameInfo));
}
MFX_CHECK_STS(lock2.Unlock());
}
else
{
d3dSurf.MemId = src_sys->Data.MemId;
}
if (video.IOPattern != MFX_IOPATTERN_IN_OPAQUE_MEMORY)
MFX_CHECK_STS(core.GetExternalFrameHDL(d3dSurf.MemId, &handle))
else
MFX_CHECK_STS(core.GetFrameHDL(d3dSurf.MemId, &handle));
return MFX_ERR_NONE;
}
mfxStatus VideoENC_ENC::Close(void)
{
MFX_CHECK(m_bInit, MFX_ERR_NONE);
m_bInit = false;
m_ddi->Destroy();
m_core->FreeFrames(&m_rec);
//m_core->FreeFrames(&m_opaqHren);
return MFX_ERR_NONE;
}
#endif // if defined(MFX_VA) && defined(MFX_ENABLE_H264_VIDEO_ENCODE_HW) && defined(MFX_ENABLE_H264_VIDEO_FEI_ENC)
| 33.277397 | 175 | 0.666821 | [
"transform"
] |
6bc6f152f0db788c06157500be706d3373d9e0c1 | 41,384 | cxx | C++ | panda/src/egg/eggGroup.cxx | cflavio/panda3d | 147bac69a76817097ffc65bd01de3709ca7c6fb0 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | panda/src/egg/eggGroup.cxx | cflavio/panda3d | 147bac69a76817097ffc65bd01de3709ca7c6fb0 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | panda/src/egg/eggGroup.cxx | cflavio/panda3d | 147bac69a76817097ffc65bd01de3709ca7c6fb0 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file eggGroup.cxx
* @author drose
* @date 1999-01-16
*/
#include "eggGroup.h"
#include "eggMiscFuncs.h"
#include "eggVertexPool.h"
#include "eggBin.h"
#include "lexerDefs.h"
#include "indent.h"
#include "string_utils.h"
#include "lmatrix.h"
#include "dcast.h"
using std::ostream;
using std::string;
TypeHandle EggGroup::_type_handle;
/**
*
*/
EggGroup::
EggGroup(const string &name) : EggGroupNode(name) {
_flags = 0;
_flags2 = 0;
_fps = 0.0;
_blend_mode = BM_unspecified;
_blend_operand_a = BO_unspecified;
_blend_operand_b = BO_unspecified;
_blend_color = LColor::zero();
_u_speed = 0;
_v_speed = 0;
_w_speed = 0;
_r_speed = 0;
}
/**
*
*/
EggGroup::
EggGroup(const EggGroup ©) {
(*this) = copy;
}
/**
*
*/
EggGroup &EggGroup::
operator = (const EggGroup ©) {
EggTransform::operator = (copy);
_flags = copy._flags;
_flags2 = copy._flags2;
_collide_mask = copy._collide_mask;
_from_collide_mask = copy._from_collide_mask;
_into_collide_mask = copy._into_collide_mask;
_billboard_center = copy._billboard_center;
_object_types = copy._object_types;
_collision_name = copy._collision_name;
_fps = copy._fps;
_lod = copy._lod;
_blend_mode = copy._blend_mode;
_blend_operand_a = copy._blend_operand_a;
_blend_operand_b = copy._blend_operand_b;
_blend_color = copy._blend_color;
_tag_data = copy._tag_data;
_u_speed = copy._u_speed;
_v_speed = copy._v_speed;
_w_speed = copy._w_speed;
_r_speed = copy._r_speed;
_default_pose = copy._default_pose;
unref_all_vertices();
_vref = copy._vref;
// We must walk through the vertex ref list, and flag each vertex as now
// reffed by this group.
VertexRef::iterator vri;
for (vri = _vref.begin(); vri != _vref.end(); ++vri) {
EggVertex *vert = (*vri).first;
bool inserted = vert->_gref.insert(this).second;
// Did the group not exist previously in the vertex's gref list? If it
// was there already, we must be out of sync between vertices and groups.
nassertr(inserted, *this);
}
// These must be down here, because the EggNode assignment operator will
// force an update_under(). Therefore, we can't call it until all the
// attributes that affect adjust_under() are in place.
EggGroupNode::operator = (copy);
EggRenderMode::operator = (copy);
return *this;
}
/**
*
*/
EggGroup::
~EggGroup() {
unref_all_vertices();
}
/**
*
*/
void EggGroup::
set_group_type(GroupType type) {
if (type != get_group_type()) {
#ifndef NDEBUG
if (type != GT_instance) {
// Only valid to change to a non-instance type if we have no group refs.
nassertv(_group_refs.empty());
}
#endif
// Make sure the user didn't give us any stray bits.
nassertv((type & ~F_group_type)==0);
_flags = (_flags & ~F_group_type) | type;
// Now we might have changed the type to or from an instance node, so we
// have to recompute the under_flags.
update_under(0);
}
}
/**
* Returns true if the indicated object type has been added to the group, or
* false otherwise.
*/
bool EggGroup::
has_object_type(const string &object_type) const {
vector_string::const_iterator oi;
for (oi = _object_types.begin(); oi != _object_types.end(); ++oi) {
if (cmp_nocase_uh((*oi), object_type) == 0) {
return true;
}
}
return false;
}
/**
* Removes the first instance of the indicated object type from the group if
* it is present. Returns true if the object type was found and removed,
* false otherwise.
*/
bool EggGroup::
remove_object_type(const string &object_type) {
vector_string::iterator oi;
for (oi = _object_types.begin(); oi != _object_types.end(); ++oi) {
if (cmp_nocase_uh((*oi), object_type) == 0) {
_object_types.erase(oi);
return true;
}
}
return false;
}
/**
* Writes the group and all of its children to the indicated output stream in
* Egg format.
*/
void EggGroup::
write(ostream &out, int indent_level) const {
test_under_integrity();
switch (get_group_type()) {
case GT_group:
write_header(out, indent_level, "<Group>");
break;
case GT_instance:
write_header(out, indent_level, "<Instance>");
break;
case GT_joint:
write_header(out, indent_level, "<Joint>");
break;
default:
// invalid group type
nassert_raise("invalid EggGroup type");
return;
}
if (is_of_type(EggBin::get_class_type())) {
indent(out, indent_level + 2)
<< "// Bin " << DCAST(EggBin, this)->get_bin_number() << "\n";
}
if (has_lod()) {
get_lod().write(out, indent_level + 2);
}
write_billboard_flags(out, indent_level + 2);
write_collide_flags(out, indent_level + 2);
write_model_flags(out, indent_level + 2);
write_switch_flags(out, indent_level + 2);
if (has_transform()) {
EggTransform::write(out, indent_level + 2, "<Transform>");
}
if (get_group_type() == GT_joint && _default_pose.has_transform()) {
_default_pose.write(out, indent_level + 2, "<DefaultPose>");
}
if (get_scroll_u() != 0) {
indent(out, indent_level + 2)
<< "<Scalar> scroll_u { " << get_scroll_u() << " }\n";
}
if (get_scroll_v() != 0) {
indent(out, indent_level + 2)
<< "<Scalar> scroll_v { " << get_scroll_v() << " }\n";
}
if (get_scroll_w() != 0) {
indent(out, indent_level + 2)
<< "<Scalar> scroll_w { " << get_scroll_w() << " }\n";
}
if (get_scroll_r() != 0) {
indent(out, indent_level + 2)
<< "<Scalar> scroll_r { " << get_scroll_r() << " }\n";
}
write_object_types(out, indent_level + 2);
write_decal_flags(out, indent_level + 2);
write_tags(out, indent_level + 2);
write_render_mode(out, indent_level + 2);
if (get_portal_flag()) {
indent(out, indent_level + 2) << "<Scalar> portal { 1 }\n";
}
if (get_occluder_flag()) {
indent(out, indent_level + 2) << "<Scalar> occluder { 1 }\n";
}
if (get_polylight_flag()) {
indent(out, indent_level + 2) << "<Scalar> polylight { 1 }\n";
}
if (has_indexed_flag()) {
indent(out, indent_level + 2)
<< "<Scalar> indexed { " << get_indexed_flag() << " }\n";
}
if (get_blend_mode() != BM_unspecified) {
indent(out, indent_level + 2)
<< "<Scalar> blend { " << get_blend_mode() << " }\n";
}
if (get_blend_operand_a() != BO_unspecified) {
indent(out, indent_level + 2)
<< "<Scalar> blendop-a { " << get_blend_operand_a() << " }\n";
}
if (get_blend_operand_b() != BO_unspecified) {
indent(out, indent_level + 2)
<< "<Scalar> blendop-b { " << get_blend_operand_b() << " }\n";
}
if (has_blend_color()) {
const LColor &c = get_blend_color();
indent(out, indent_level + 2)
<< "<Scalar> blendr { " << c[0] << " }\n";
indent(out, indent_level + 2)
<< "<Scalar> blendg { " << c[1] << " }\n";
indent(out, indent_level + 2)
<< "<Scalar> blendb { " << c[2] << " }\n";
indent(out, indent_level + 2)
<< "<Scalar> blenda { " << c[3] << " }\n";
}
GroupRefs::const_iterator gri;
for (gri = _group_refs.begin(); gri != _group_refs.end(); ++gri) {
EggGroup *group_ref = (*gri);
indent(out, indent_level + 2)
<< "<Ref> { " << group_ref->get_name() << " }\n";
}
// We have to write the children nodes before we write the vertex
// references, since we might be referencing a vertex that's defined in one
// of those children nodes!
EggGroupNode::write(out, indent_level + 2);
write_vertex_ref(out, indent_level + 2);
indent(out, indent_level) << "}\n";
}
/**
* Writes just the <Billboard> entry and related fields to the indicated
* ostream.
*/
void EggGroup::
write_billboard_flags(ostream &out, int indent_level) const {
if (get_billboard_type() != BT_none) {
indent(out, indent_level)
<< "<Billboard> { " << get_billboard_type() << " }\n";
}
if (has_billboard_center()) {
indent(out, indent_level)
<< "<BillboardCenter> { " << get_billboard_center() << " }\n";
}
}
/**
* Writes just the <Collide> entry and related fields to the indicated
* ostream.
*/
void EggGroup::
write_collide_flags(ostream &out, int indent_level) const {
if (get_cs_type() != CST_none) {
indent(out, indent_level) << "<Collide> ";
if (has_collision_name()) {
enquote_string(out, get_collision_name()) << " ";
}
out << "{ " << get_cs_type();
if (get_collide_flags() != CF_none) {
out << " " << get_collide_flags();
}
out << " }\n";
}
if (has_collide_mask()) {
indent(out, indent_level)
<< "<Scalar> collide-mask { 0x";
get_collide_mask().output_hex(out, 0);
out << " }\n";
}
if (has_from_collide_mask()) {
indent(out, indent_level)
<< "<Scalar> from-collide-mask { 0x";
get_from_collide_mask().output_hex(out, 0);
out << " }\n";
}
if (has_into_collide_mask()) {
indent(out, indent_level)
<< "<Scalar> into-collide-mask { 0x";
get_into_collide_mask().output_hex(out, 0);
out << " }\n";
}
}
/**
* Writes the <Model> flag and related flags to the indicated ostream.
*/
void EggGroup::
write_model_flags(ostream &out, int indent_level) const {
if (get_dcs_type() != DC_unspecified) {
indent(out, indent_level)
<< "<DCS> { " << get_dcs_type() << " }\n";
}
if (get_dart_type() != DT_none) {
indent(out, indent_level)
<< "<Dart> { " << get_dart_type() << " }\n";
}
if (get_model_flag()) {
indent(out, indent_level) << "<Model> { 1 }\n";
}
if (get_texlist_flag()) {
indent(out, indent_level) << "<TexList> { 1 }\n";
}
if (get_direct_flag()) {
indent(out, indent_level) << "<Scalar> direct { 1 }\n";
}
}
/**
* Writes the <Switch> flag and related flags to the indicated ostream.
*/
void EggGroup::
write_switch_flags(ostream &out, int indent_level) const {
if (get_switch_flag()) {
indent(out, indent_level) << "<Switch> { 1 }\n";
if (get_switch_fps() != 0.0) {
indent(out, indent_level)
<< "<Scalar> fps { " << get_switch_fps() << " }\n";
}
}
}
/**
* Writes just the <ObjectTypes> entries, if any, to the indicated ostream.
*/
void EggGroup::
write_object_types(ostream &out, int indent_level) const {
vector_string::const_iterator oi;
for (oi = _object_types.begin(); oi != _object_types.end(); ++oi) {
indent(out, indent_level)
<< "<ObjectType> { ";
enquote_string(out, (*oi)) << " }\n";
}
}
/**
* Writes the flags related to decaling, if any.
*/
void EggGroup::
write_decal_flags(ostream &out, int indent_level) const {
if (get_decal_flag()) {
indent(out, indent_level) << "<Scalar> decal { 1 }\n";
}
}
/**
* Writes just the <Tag> entries, if any, to the indicated ostream.
*/
void EggGroup::
write_tags(ostream &out, int indent_level) const {
TagData::const_iterator ti;
for (ti = _tag_data.begin(); ti != _tag_data.end(); ++ti) {
const string &key = (*ti).first;
const string &value = (*ti).second;
indent(out, indent_level) << "<Tag> ";
enquote_string(out, key) << " {\n";
enquote_string(out, value, indent_level + 2) << "\n";
indent(out, indent_level) << "}\n";
}
}
/**
* Writes the flags inherited from EggRenderMode and similar flags that
* control obscure render effects.
*/
void EggGroup::
write_render_mode(ostream &out, int indent_level) const {
EggRenderMode::write(out, indent_level);
if (get_nofog_flag()) {
indent(out, indent_level) << "<Scalar> no-fog { 1 }\n";
}
}
/**
* Returns true if this particular node represents a <Joint> entry or not.
* This is a handy thing to know since Joints are sorted to the end of their
* sibling list when writing an egg file. See EggGroupNode::write().
*/
bool EggGroup::
is_joint() const {
return (get_group_type() == GT_joint);
}
/**
* Walks back up the hierarchy, looking for an EggGroup or EggPrimitive or
* some such object at this level or above this group that has an alpha_mode
* other than AM_unspecified. Returns a valid EggRenderMode pointer if one is
* found, or NULL otherwise.
*/
EggRenderMode *EggGroup::
determine_alpha_mode() {
if (get_alpha_mode() != AM_unspecified) {
return this;
}
return EggGroupNode::determine_alpha_mode();
}
/**
* Walks back up the hierarchy, looking for an EggGroup or EggPrimitive or
* some such object at this level or above this group that has a
* depth_write_mode other than DWM_unspecified. Returns a valid EggRenderMode
* pointer if one is found, or NULL otherwise.
*/
EggRenderMode *EggGroup::
determine_depth_write_mode() {
if (get_depth_write_mode() != DWM_unspecified) {
return this;
}
return EggGroupNode::determine_depth_write_mode();
}
/**
* Walks back up the hierarchy, looking for an EggGroup or EggPrimitive or
* some such object at this level or above this group that has a
* depth_test_mode other than DTM_unspecified. Returns a valid EggRenderMode
* pointer if one is found, or NULL otherwise.
*/
EggRenderMode *EggGroup::
determine_depth_test_mode() {
if (get_depth_test_mode() != DTM_unspecified) {
return this;
}
return EggGroupNode::determine_depth_test_mode();
}
/**
* Walks back up the hierarchy, looking for an EggGroup or EggPrimitive or
* some such object at this level or above this group that has a
* visibility_mode other than VM_unspecified. Returns a valid EggRenderMode
* pointer if one is found, or NULL otherwise.
*/
EggRenderMode *EggGroup::
determine_visibility_mode() {
if (get_visibility_mode() != VM_unspecified) {
return this;
}
return EggGroupNode::determine_visibility_mode();
}
/**
* Walks back up the hierarchy, looking for an EggGroup or EggPrimitive or
* some such object at this level or above this group that has a depth_offset
* specified. Returns a valid EggRenderMode pointer if one is found, or NULL
* otherwise.
*/
EggRenderMode *EggGroup::
determine_depth_offset() {
if (has_depth_offset()) {
return this;
}
return EggGroupNode::determine_depth_offset();
}
/**
* Walks back up the hierarchy, looking for an EggGroup or EggPrimitive or
* some such object at this level or above this group that has a draw_order
* specified. Returns a valid EggRenderMode pointer if one is found, or NULL
* otherwise.
*/
EggRenderMode *EggGroup::
determine_draw_order() {
if (has_draw_order()) {
return this;
}
return EggGroupNode::determine_draw_order();
}
/**
* Walks back up the hierarchy, looking for an EggGroup or EggPrimitive or
* some such object at this level or above this group that has a bin
* specified. Returns a valid EggRenderMode pointer if one is found, or NULL
* otherwise.
*/
EggRenderMode *EggGroup::
determine_bin() {
if (has_bin()) {
return this;
}
return EggGroupNode::determine_bin();
}
/**
* Walks back up the hierarchy, looking for an EggGroup at this level or above
* that has the "indexed" scalar set. Returns the value of the indexed scalar
* if it is found, or false if it is not.
*
* In other words, returns true if the "indexed" flag is in effect for the
* indicated node, false otherwise.
*/
bool EggGroup::
determine_indexed() {
if (has_indexed_flag()) {
return get_indexed_flag();
}
return EggGroupNode::determine_indexed();
}
/**
* Walks back up the hierarchy, looking for an EggGroup at this level or above
* that has the "decal" flag set. Returns the value of the decal flag if it
* is found, or false if it is not.
*
* In other words, returns true if the "decal" flag is in effect for the
* indicated node, false otherwise.
*/
bool EggGroup::
determine_decal() {
if (get_decal_flag()) {
return true;
}
return EggGroupNode::determine_decal();
}
/**
* Adds the vertex to the set of those referenced by the group, at the
* indicated membership level. If the vertex is already being referenced,
* increases the membership amount by the indicated amount.
*/
void EggGroup::
ref_vertex(EggVertex *vert, double membership) {
VertexRef::iterator vri = _vref.find(vert);
if (vri != _vref.end()) {
// The vertex was already being reffed; increment its membership amount.
(*vri).second += membership;
// If that takes us down to zero, go ahead and unref the vertex.
if ((*vri).second == 0.0) {
unref_vertex(vert);
}
} else {
// The vertex was not already reffed; ref it.
if (membership != 0.0) {
_vref[vert] = membership;
bool inserted = vert->_gref.insert(this).second;
// Did the group not exist previously in the vertex's gref list? If it
// was there already, we must be out of sync between vertices and
// groups.
nassertv(inserted);
}
}
}
/**
* Removes the vertex from the set of those referenced by the group. Does
* nothing if the vertex is not already reffed.
*/
void EggGroup::
unref_vertex(EggVertex *vert) {
VertexRef::iterator vri = _vref.find(vert);
if (vri != _vref.end()) {
_vref.erase(vri);
int count = vert->_gref.erase(this);
// Did the group exist in the vertex's gref list? If it didn't, we must
// be out of sync between vertices and groups.
nassertv(count == 1);
}
}
/**
* Removes all vertices from the reference list.
*/
void EggGroup::
unref_all_vertices() {
// We must walk through the vertex ref list, and flag each vertex as
// unreffed in its own structure.
VertexRef::iterator vri;
for (vri = _vref.begin(); vri != _vref.end(); ++vri) {
EggVertex *vert = (*vri).first;
int count = vert->_gref.erase(this);
// Did the group exist in the vertex's gref list? If it didn't, we must
// be out of sync between vertices and groups.
nassertv(count == 1);
}
_vref.clear();
}
/**
* Returns the amount of membership of the indicated vertex in this group. If
* the vertex is not reffed by the group, returns 0.
*/
double EggGroup::
get_vertex_membership(const EggVertex *vert) const {
VertexRef::const_iterator vri = _vref.find((EggVertex *)vert);
if (vri != _vref.end()) {
return (*vri).second;
} else {
return 0.0;
}
}
/**
* Explicitly sets the net membership of the indicated vertex in this group to
* the given value.
*/
void EggGroup::
set_vertex_membership(EggVertex *vert, double membership) {
if (membership == 0.0) {
unref_vertex(vert);
return;
}
VertexRef::iterator vri = _vref.find(vert);
if (vri != _vref.end()) {
// The vertex was already being reffed; just change its membership amount.
(*vri).second = membership;
} else {
// The vertex was not already reffed; ref it.
_vref[vert] = membership;
bool inserted = vert->_gref.insert(this).second;
// Did the group not exist previously in the vertex's gref list? If it
// was there already, we must be out of sync between vertices and groups.
nassertv(inserted);
}
}
/**
* Moves all of the vertex references from the indicated other group into this
* one. If a given vertex was previously shared by both groups, the relative
* memberships will be summed.
*/
void EggGroup::
steal_vrefs(EggGroup *other) {
nassertv(other != this);
VertexRef::const_iterator vri;
for (vri = other->vref_begin(); vri != other->vref_end(); ++vri) {
EggVertex *vert = (*vri).first;
double membership = (*vri).second;
ref_vertex(vert, membership);
}
other->unref_all_vertices();
}
#ifdef _DEBUG
/**
* Verifies that each vertex in the group exists and that it knows it is
* referenced by the group.
*/
void EggGroup::
test_vref_integrity() const {
test_ref_count_integrity();
VertexRef::const_iterator vri;
for (vri = vref_begin(); vri != vref_end(); ++vri) {
const EggVertex *vert = (*vri).first;
vert->test_ref_count_integrity();
nassertv(vert->has_gref(this));
}
}
#endif // _DEBUG
/**
* Adds a new <Ref> entry to the group. This declares an internal reference
* to another node, and is used to implement scene-graph instancing; it is
* only valid if the group_type is GT_instance.
*/
void EggGroup::
add_group_ref(EggGroup *group) {
nassertv(get_group_type() == GT_instance);
_group_refs.push_back(group);
}
/**
* Returns the number of <Ref> entries within this group. See
* add_group_ref().
*/
int EggGroup::
get_num_group_refs() const {
return _group_refs.size();
}
/**
* Returns the nth <Ref> entry within this group. See add_group_ref().
*/
EggGroup *EggGroup::
get_group_ref(int n) const {
nassertr(n >= 0 && n < (int)_group_refs.size(), nullptr);
return _group_refs[n];
}
/**
* Removes the nth <Ref> entry within this group. See add_group_ref().
*/
void EggGroup::
remove_group_ref(int n) {
nassertv(n >= 0 && n < (int)_group_refs.size());
_group_refs.erase(_group_refs.begin() + n);
}
/**
* Removes all of the <Ref> entries within this group. See add_group_ref().
*/
void EggGroup::
clear_group_refs() {
_group_refs.clear();
}
/**
* Returns the GroupType value associated with the given string
* representation, or GT_invalid if the string does not match any known
* GroupType value.
*/
EggGroup::GroupType EggGroup::
string_group_type(const string &strval) {
if (cmp_nocase_uh(strval, "group") == 0) {
return GT_group;
} else if (cmp_nocase_uh(strval, "instance") == 0) {
return GT_instance;
} else if (cmp_nocase_uh(strval, "joint") == 0) {
return GT_joint;
} else {
return GT_invalid;
}
}
/**
* Returns the DartType value associated with the given string representation,
* or DT_none if the string does not match any known DartType value.
*/
EggGroup::DartType EggGroup::
string_dart_type(const string &strval) {
if (cmp_nocase_uh(strval, "sync") == 0) {
return DT_sync;
} else if (cmp_nocase_uh(strval, "nosync") == 0) {
return DT_nosync;
} else if (cmp_nocase_uh(strval, "default") == 0) {
return DT_default;
} else if (cmp_nocase_uh(strval, "structured") == 0) {
return DT_structured;
} else {
return DT_none;
}
}
/**
* Returns the DCSType value associated with the given string representation,
* or DC_unspecified if the string does not match any known DCSType value.
*/
EggGroup::DCSType EggGroup::
string_dcs_type(const string &strval) {
if (cmp_nocase_uh(strval, "none") == 0) {
return DC_none;
} else if (cmp_nocase_uh(strval, "local") == 0) {
return DC_local;
} else if (cmp_nocase_uh(strval, "net") == 0) {
return DC_net;
} else if (cmp_nocase_uh(strval, "no_touch") == 0) {
return DC_no_touch;
} else if (cmp_nocase_uh(strval, "default") == 0) {
return DC_default;
} else {
return DC_unspecified;
}
}
/**
* Returns the BillboardType value associated with the given string
* representation, or BT_none if the string does not match any known
* BillboardType value.
*/
EggGroup::BillboardType EggGroup::
string_billboard_type(const string &strval) {
if (cmp_nocase_uh(strval, "axis") == 0) {
return BT_axis;
} else if (cmp_nocase_uh(strval, "point_eye") == 0) {
return BT_point_camera_relative;
} else if (cmp_nocase_uh(strval, "point_world") == 0) {
return BT_point_world_relative;
} else if (cmp_nocase_uh(strval, "point") == 0) {
return BT_point_world_relative;
} else {
return BT_none;
}
}
/**
* Returns the CollisionSolidType value associated with the given string
* representation, or CST_none if the string does not match any known
* CollisionSolidType value.
*/
EggGroup::CollisionSolidType EggGroup::
string_cs_type(const string &strval) {
if (cmp_nocase_uh(strval, "plane") == 0) {
return CST_plane;
} else if (cmp_nocase_uh(strval, "polygon") == 0) {
return CST_polygon;
} else if (cmp_nocase_uh(strval, "polyset") == 0) {
return CST_polyset;
} else if (cmp_nocase_uh(strval, "sphere") == 0) {
return CST_sphere;
} else if (cmp_nocase_uh(strval, "box") == 0) {
return CST_box;
} else if (cmp_nocase_uh(strval, "inv-sphere") == 0 ||
cmp_nocase_uh(strval, "invsphere") == 0) {
return CST_inv_sphere;
} else if (cmp_nocase_uh(strval, "tube") == 0) {
return CST_tube;
} else if (cmp_nocase_uh(strval, "floor-mesh") == 0 ||
cmp_nocase_uh(strval, "floormesh") == 0) {
return CST_floor_mesh;
} else {
return CST_none;
}
}
/**
* Returns the CollideFlags value associated with the given string
* representation, or CF_none if the string does not match any known
* CollideFlags value. This only recognizes a single keyword; it does not
* attempt to parse a string of keywords.
*/
EggGroup::CollideFlags EggGroup::
string_collide_flags(const string &strval) {
if (cmp_nocase_uh(strval, "intangible") == 0) {
return CF_intangible;
} else if (cmp_nocase_uh(strval, "event") == 0) {
return CF_event;
} else if (cmp_nocase_uh(strval, "descend") == 0) {
return CF_descend;
} else if (cmp_nocase_uh(strval, "keep") == 0) {
return CF_keep;
} else if (cmp_nocase_uh(strval, "solid") == 0) {
return CF_solid;
} else if (cmp_nocase_uh(strval, "center") == 0) {
return CF_center;
} else if (cmp_nocase_uh(strval, "turnstile") == 0) {
return CF_turnstile;
} else if (cmp_nocase_uh(strval, "level") == 0) {
return CF_level;
} else {
return CF_none;
}
}
/**
* Returns the BlendMode value associated with the given string
* representation, or BM_none if the string does not match any known
* BlendMode.
*/
EggGroup::BlendMode EggGroup::
string_blend_mode(const string &strval) {
if (cmp_nocase_uh(strval, "none") == 0) {
return BM_none;
} else if (cmp_nocase_uh(strval, "add") == 0) {
return BM_add;
} else if (cmp_nocase_uh(strval, "subtract") == 0) {
return BM_subtract;
} else if (cmp_nocase_uh(strval, "inv_subtract") == 0) {
return BM_inv_subtract;
} else if (cmp_nocase_uh(strval, "min") == 0) {
return BM_min;
} else if (cmp_nocase_uh(strval, "max") == 0) {
return BM_max;
} else {
return BM_unspecified;
}
}
/**
* Returns the BlendOperand value associated with the given string
* representation, or BO_none if the string does not match any known
* BlendOperand.
*/
EggGroup::BlendOperand EggGroup::
string_blend_operand(const string &strval) {
if (cmp_nocase_uh(strval, "zero") == 0) {
return BO_zero;
} else if (cmp_nocase_uh(strval, "one") == 0) {
return BO_one;
} else if (cmp_nocase_uh(strval, "incoming_color") == 0) {
return BO_incoming_color;
} else if (cmp_nocase_uh(strval, "one_minus_incoming_color") == 0) {
return BO_one_minus_incoming_color;
} else if (cmp_nocase_uh(strval, "fbuffer_color") == 0) {
return BO_fbuffer_color;
} else if (cmp_nocase_uh(strval, "one_minus_fbuffer_color") == 0) {
return BO_one_minus_fbuffer_color;
} else if (cmp_nocase_uh(strval, "incoming_alpha") == 0) {
return BO_incoming_alpha;
} else if (cmp_nocase_uh(strval, "one_minus_incoming_alpha") == 0) {
return BO_one_minus_incoming_alpha;
} else if (cmp_nocase_uh(strval, "fbuffer_alpha") == 0) {
return BO_fbuffer_alpha;
} else if (cmp_nocase_uh(strval, "one_minus_fbuffer_alpha") == 0) {
return BO_one_minus_fbuffer_alpha;
} else if (cmp_nocase_uh(strval, "constant_color") == 0) {
return BO_constant_color;
} else if (cmp_nocase_uh(strval, "one_minus_constant_color") == 0) {
return BO_one_minus_constant_color;
} else if (cmp_nocase_uh(strval, "constant_alpha") == 0) {
return BO_constant_alpha;
} else if (cmp_nocase_uh(strval, "one_minus_constant_alpha") == 0) {
return BO_one_minus_constant_alpha;
} else if (cmp_nocase_uh(strval, "incoming_color_saturate") == 0) {
return BO_incoming_color_saturate;
} else if (cmp_nocase_uh(strval, "color_scale") == 0) {
return BO_color_scale;
} else if (cmp_nocase_uh(strval, "one_minus_color_scale") == 0) {
return BO_one_minus_color_scale;
} else if (cmp_nocase_uh(strval, "alpha_scale") == 0) {
return BO_alpha_scale;
} else if (cmp_nocase_uh(strval, "one_minus_alpha_scale") == 0) {
return BO_one_minus_alpha_scale;
} else {
return BO_unspecified;
}
}
/**
* Returns this object cross-cast to an EggTransform pointer, if it inherits
* from EggTransform, or NULL if it does not.
*/
EggTransform *EggGroup::
as_transform() {
return this;
}
/**
* Writes out the vertex ref component of the group body only. This may
* consist of a number of <VertexRef> entries, each with its own membership
* value.
*/
void EggGroup::
write_vertex_ref(ostream &out, int indent_level) const {
// We want to put the vertices together into groups first by vertex pool,
// then by membership value. Each of these groups becomes a separate
// VertexRef entry. Within each group, we'll sort the vertices by index
// number.
typedef pset<int> Indices;
typedef pmap<double, Indices> Memberships;
typedef pmap<EggVertexPool *, Memberships> Pools;
Pools _entries;
bool all_membership_one = true;
VertexRef::const_iterator vri;
for (vri = _vref.begin(); vri != _vref.end(); ++vri) {
EggVertex *vert = (*vri).first;
double membership = (*vri).second;
if (membership != 1.0) {
all_membership_one = false;
}
_entries[vert->get_pool()][membership].insert(vert->get_index());
}
// Now that we've reordered them, we can simply traverse the entries and
// write them out.
Pools::const_iterator pi;
for (pi = _entries.begin(); pi != _entries.end(); ++pi) {
EggVertexPool *pool = (*pi).first;
const Memberships &memberships = (*pi).second;
Memberships::const_iterator mi;
for (mi = memberships.begin(); mi != memberships.end(); ++mi) {
double membership = (*mi).first;
const Indices &indices = (*mi).second;
indent(out, indent_level)
<< "<VertexRef> {\n";
write_long_list(out, indent_level+2, indices.begin(), indices.end(),
"", "", 72);
// If all vrefs in this group have membership of 1, don't bother to
// write out the membership scalar.
if (!all_membership_one) {
indent(out, indent_level + 2)
<< "<Scalar> membership { " << membership << " }\n";
}
if (pool == nullptr) {
indent(out, indent_level + 2)
<< "// Invalid NULL vertex pool.\n";
} else {
indent(out, indent_level + 2)
<< "<Ref> { " << pool->get_name() << " }\n";
}
indent(out, indent_level)
<< "}\n";
}
}
}
/**
* This function is called within parse_egg(). It should call the appropriate
* function on the lexer to initialize the parser into the state associated
* with this object. If the object cannot be parsed into directly, it should
* return false.
*/
bool EggGroup::
egg_start_parse_body() {
egg_start_group_body();
return true;
}
/**
* This is called within update_under() after all the various under settings
* have been inherited directly from the parent node. It is responsible for
* adjusting these settings to reflect states local to the current node; for
* instance, an <Instance> node will force the UF_under_instance bit on.
*/
void EggGroup::
adjust_under() {
// If we have our own transform, it carries forward.
// As of 41801, this now also affects the local_coord flag, below. This
// means that a <Transform> entry within an <Instance> node transforms the
// instance itself.
if (has_transform()) {
_under_flags |= UF_under_transform;
// Our own transform also affects our node frame.
_node_frame =
new MatrixFrame(get_transform3d() * get_node_frame());
// To prevent trying to invert a sigular matrix
LMatrix4d mat;
bool invert_ok = mat.invert_from(get_node_frame());
if (invert_ok) {
_node_frame_inv =
new MatrixFrame(mat);
} else {
_node_frame_inv = nullptr;
}
_vertex_to_node =
new MatrixFrame(get_vertex_frame() * get_node_frame_inv());
_node_to_vertex =
new MatrixFrame(get_node_frame() * get_vertex_frame_inv());
}
if (is_instance_type()) {
_under_flags |= UF_under_instance;
if (_under_flags & UF_under_transform) {
// If we've reached an instance node and we're under a transform, that
// means we've just defined a local coordinate system.
_under_flags |= UF_local_coord;
}
// An instance node means that from this point and below, vertices are
// defined relative to this node. Thus, the node frame becomes the vertex
// frame.
_vertex_frame = _node_frame;
_vertex_frame_inv = _node_frame_inv;
_vertex_to_node = nullptr;
_node_to_vertex = nullptr;
}
}
/**
* This is called from within the egg code by transform(). It applies a
* transformation matrix to the current node in some sensible way, then
* continues down the tree.
*
* The first matrix is the transformation to apply; the second is its inverse.
* The third parameter is the coordinate system we are changing to, or
* CS_default if we are not changing coordinate systems.
*/
void EggGroup::
r_transform(const LMatrix4d &mat, const LMatrix4d &inv,
CoordinateSystem to_cs) {
if (has_transform() || get_group_type() == GT_joint) {
// Since we want to apply this transform to all matrices, including nested
// matrices, we can't simply premult it in and leave it, because that
// would leave the rotational component in the scene graph's matrix, and
// all nested matrices would inherit the same rotational component. So we
// have to premult and then postmult by the inverse to undo the rotational
// component each time.
LMatrix4d mat1 = mat;
LMatrix4d inv1 = inv;
// If we have a translation component, we should only apply it to the top
// matrix. All subsequent matrices get just the rotational component.
mat1.set_row(3, LVector3d(0.0, 0.0, 0.0));
inv1.set_row(3, LVector3d(0.0, 0.0, 0.0));
internal_set_transform(inv1 * get_transform3d() * mat);
if (_default_pose.has_transform()) {
LMatrix4d t = _default_pose.get_transform3d();
_default_pose.clear_transform();
_default_pose.add_matrix4(inv1 * t * mat);
}
EggGroupNode::r_transform(mat1, inv1, to_cs);
} else {
EggGroupNode::r_transform(mat, inv, to_cs);
}
// Convert the LOD description too.
if (has_lod()) {
_lod->transform(mat);
}
if (has_billboard_center()) {
_billboard_center = _billboard_center * mat;
}
}
/**
* The recursive implementation of flatten_transforms().
*/
void EggGroup::
r_flatten_transforms() {
EggGroupNode::r_flatten_transforms();
if (is_local_coord()) {
LMatrix4d mat = get_vertex_frame();
if (has_lod()) {
_lod->transform(mat);
}
if (get_billboard_type() != BT_none && !has_billboard_center()) {
// If we had a billboard without an explicit center, it was an implicit
// instance. Now it's not any more.
set_billboard_center(LPoint3d(0.0, 0.0, 0.0) * mat);
} else if (has_billboard_center()) {
_billboard_center = _billboard_center * mat;
}
}
if (get_group_type() == GT_instance) {
set_group_type(GT_group);
}
if (get_group_type() != GT_joint) {
internal_clear_transform();
}
}
/**
* This virtual method is inherited by EggTransform3d; it is called whenever
* the transform is changed.
*/
void EggGroup::
transform_changed() {
// Recompute all of the cached transforms at this node and below. We should
// probably make this smarter and do lazy evaluation of these transforms,
// rather than having to recompute the whole tree with every change to a
// parent node's transform.
update_under(0);
}
/**
*
*/
ostream &operator << (ostream &out, EggGroup::GroupType t) {
switch (t) {
case EggGroup::GT_invalid:
return out << "invalid group";
case EggGroup::GT_group:
return out << "group";
case EggGroup::GT_instance:
return out << "instance";
case EggGroup::GT_joint:
return out << "joint";
}
nassertr(false, out);
return out << "(**invalid**)";
}
/**
*
*/
ostream &operator << (ostream &out, EggGroup::DartType t) {
switch (t) {
case EggGroup::DT_none:
return out << "none";
case EggGroup::DT_sync:
return out << "sync";
case EggGroup::DT_nosync:
return out << "nosync";
case EggGroup::DT_structured:
return out << "structured";
case EggGroup::DT_default:
return out << "1";
}
nassertr(false, out);
return out << "(**invalid**)";
}
/**
*
*/
ostream &operator << (ostream &out, EggGroup::DCSType t) {
switch (t) {
case EggGroup::DC_unspecified:
return out << "unspecified";
case EggGroup::DC_none:
return out << "none";
case EggGroup::DC_local:
return out << "local";
case EggGroup::DC_net:
return out << "net";
case EggGroup::DC_no_touch:
return out << "no_touch";
case EggGroup::DC_default:
return out << "1";
}
nassertr(false, out);
return out << "(**invalid**)";
}
/**
*
*/
ostream &operator << (ostream &out, EggGroup::BillboardType t) {
switch (t) {
case EggGroup::BT_none:
return out << "none";
case EggGroup::BT_axis:
return out << "axis";
case EggGroup::BT_point_camera_relative:
return out << "point_eye";
case EggGroup::BT_point_world_relative:
return out << "point_world";
}
nassertr(false, out);
return out << "(**invalid**)";
}
/**
*
*/
ostream &operator << (ostream &out, EggGroup::CollisionSolidType t) {
switch (t) {
case EggGroup::CST_none:
return out << "None";
case EggGroup::CST_plane:
return out << "Plane";
case EggGroup::CST_polygon:
return out << "Polygon";
case EggGroup::CST_polyset:
return out << "Polyset";
case EggGroup::CST_sphere:
return out << "Sphere";
case EggGroup::CST_inv_sphere:
return out << "InvSphere";
case EggGroup::CST_tube:
return out << "Tube";
case EggGroup::CST_floor_mesh:
return out << "FloorMesh";
case EggGroup::CST_box:
return out << "Box";
}
nassertr(false, out);
return out << "(**invalid**)";
}
/**
*
*/
ostream &operator << (ostream &out, EggGroup::CollideFlags t) {
if (t == EggGroup::CF_none) {
return out << "none";
}
int bits = (int)t;
const char *space = "";
if (bits & EggGroup::CF_intangible) {
out << space << "intangible";
space = " ";
}
if (bits & EggGroup::CF_event) {
out << space << "event";
space = " ";
}
if (bits & EggGroup::CF_descend) {
out << space << "descend";
space = " ";
}
if (bits & EggGroup::CF_keep) {
out << space << "keep";
space = " ";
}
if (bits & EggGroup::CF_solid) {
out << space << "solid";
space = " ";
}
if (bits & EggGroup::CF_center) {
out << space << "center";
space = " ";
}
if (bits & EggGroup::CF_turnstile) {
out << space << "turnstile";
space = " ";
}
if (bits & EggGroup::CF_level) {
out << space << "level";
space = " ";
}
return out;
}
/**
*
*/
ostream &
operator << (ostream &out, EggGroup::BlendMode t) {
switch (t) {
case EggGroup::BM_unspecified:
return out << "unspecified";
case EggGroup::BM_none:
return out << "none";
case EggGroup::BM_add:
return out << "add";
case EggGroup::BM_subtract:
return out << "subtract";
case EggGroup::BM_inv_subtract:
return out << "inv_subtract";
case EggGroup::BM_min:
return out << "min";
case EggGroup::BM_max:
return out << "max";
}
return out << "**invalid EggGroup::BlendMode(" << (int)t << ")**";
}
/**
*
*/
ostream &
operator << (ostream &out, EggGroup::BlendOperand t) {
switch (t) {
case EggGroup::BO_unspecified:
return out << "unspecified";
case EggGroup::BO_zero:
return out << "zero";
case EggGroup::BO_one:
return out << "one";
case EggGroup::BO_incoming_color:
return out << "incomfing_color";
case EggGroup::BO_one_minus_incoming_color:
return out << "one_minus_incoming_color";
case EggGroup::BO_fbuffer_color:
return out << "fbuffer_color";
case EggGroup::BO_one_minus_fbuffer_color:
return out << "one_minus_fbuffer_color";
case EggGroup::BO_incoming_alpha:
return out << "incoming_alpha";
case EggGroup::BO_one_minus_incoming_alpha:
return out << "one_minus_incoming_alpha";
case EggGroup::BO_fbuffer_alpha:
return out << "fbuffer_alpha";
case EggGroup::BO_one_minus_fbuffer_alpha:
return out << "one_minus_fbuffer_alpha";
case EggGroup::BO_constant_color:
return out << "constant_color";
case EggGroup::BO_one_minus_constant_color:
return out << "one_minus_constant_color";
case EggGroup::BO_constant_alpha:
return out << "constant_alpha";
case EggGroup::BO_one_minus_constant_alpha:
return out << "one_minus_constant_alpha";
case EggGroup::BO_incoming_color_saturate:
return out << "incoming_color_saturate";
case EggGroup::BO_color_scale:
return out << "color_scale";
case EggGroup::BO_one_minus_color_scale:
return out << "one_minus_color_scale";
case EggGroup::BO_alpha_scale:
return out << "alpha_scale";
case EggGroup::BO_one_minus_alpha_scale:
return out << "one_minus_alpha_scale";
}
return out << "**invalid EggGroup::BlendOperand(" << (int)t << ")**";
}
| 27.406623 | 78 | 0.662116 | [
"mesh",
"render",
"object",
"model",
"transform",
"3d",
"solid"
] |
6bc7462c83344590c13c814eca074d1e26a42472 | 8,424 | hpp | C++ | lib-seeded/signature-verification-key.hpp | agricocb/seeded-crypto | 271a4d40f5fccaa65126dde7f818bfb8518eeb1a | [
"MIT"
] | null | null | null | lib-seeded/signature-verification-key.hpp | agricocb/seeded-crypto | 271a4d40f5fccaa65126dde7f818bfb8518eeb1a | [
"MIT"
] | null | null | null | lib-seeded/signature-verification-key.hpp | agricocb/seeded-crypto | 271a4d40f5fccaa65126dde7f818bfb8518eeb1a | [
"MIT"
] | null | null | null | #pragma once
#include <cassert>
#include <sodium.h>
#include <vector>
#include <string>
#include "sodium-buffer.hpp"
/**
* @brief A SignatureVerificationKey is used to verify that messages were
* signed by its corresponding SigningKey.
* SigningKeys generate _signatures_, and by verifying a message/signature
* pair the SignatureVerificationKey can confirm that the message was
* indeed signed using the SigningKey.
* The key pair of the SigningKey and SignatureVerificationKey is generated
* from a seed and a set of derivation specified options in
* @ref derivation_options_format.
*
* To derive a SignatureVerificationKey from a seed, first derive the
* corresponding SigningKey and then call SigningKey::getSignatureVerificationKey.
*
* @ingroup DerivedFromSeeds
*/
class SignatureVerificationKey {
public:
/**
* @brief The raw binary representation of the cryptographic key
*/
const std::vector<unsigned char> signatureVerificationKeyBytes;
/**
* @brief A @ref derivation_options_format string used to specify how this key is derived.
*/
const std::string derivationOptionsJson;
/**
* @brief Construct by passing the classes members
*
* @param keyBytes
* @param derivationOptionsJson
*/
SignatureVerificationKey(
const std::vector<unsigned char> &keyBytes,
const std::string& derivationOptionsJson
);
/**
* @brief Construct (reconstitute) a SignatureVerificationKey from JSON format,
* which may ahve been generated by calling toJson on another SignatureVerificationKey.
*
* @param signatureVerificationKeyAsJson
*/
static SignatureVerificationKey fromJson(
const std::string& signatureVerificationKeyAsJson
);
/**
* @brief Serialize this object to a JSON-formatted string
*
* It can be reconstituted by calling the constructor with this string.
*
* @param indent The number of characters to indent the JSON (optional)
* @param indent_char The character with which to indent the JSON (optional)
* @return const std::string
*/
const std::string toJson(
int indent = -1,
const char indent_char = ' '
) const;
/**
* This wrapper around LibSodium's signature-verification function
* is private because while the other static methods are _discouraged_,
* they will at least check that the caller is passing a key and
* signature of the correct length. Since they provide the exact same
* functionality after those checks are made, they should _always_
* be used and this method should only ever be called by them.
*/
private:
static bool verify(
const unsigned char* signatureVerificationKeyBytes,
const unsigned char* message,
const size_t messageLength,
const unsigned char* signature
);
public:
/**
* @brief *Avoid Using* Verify a message's signature using a
* raw libsodium verification key
*
* Instead of using this static method, we recommend you use the seal
* method on an instance of a SignatureVerificationKey object.
*
* @param signatureVerificationKeyBytes signatureVerificationKeyBytes The raw key bytes
* @param signatureVerificationKeyBytesLength The length of the raw key bytes
* @param message The message that was signed
* @param messageLength The length of the message that was signed
* @param signature The signature generated by corresponding SigningKey when
* by calling SigningKey::generateSignature with the same message.
* @param signatureLength The length of the signature
* @return true if the signature is valid indicating the message was indeed
* signed by the corresponding SigningKey
* @return false if the verification fails.
*/
static bool verify(
const unsigned char* signatureVerificationKeyBytes,
const size_t signatureVerificationKeyBytesLength,
const unsigned char* message,
const size_t messageLength,
const unsigned char* signature,
const size_t signatureLength
);
/**
* @brief *Avoid Using* Verify a message's signature using a
* raw libsodium verification key
*
* Instead of using this static method, we recommend you use the seal
* method on an instance of a SignatureVerificationKey object.
*
* @param signatureVerificationKeyBytes signatureVerificationKeyBytes The raw key bytes
* @param message The message that was signed
* @param messageLength The length of the message
* @param signature The signature generated by corresponding SigningKey when
* by calling SigningKey::generateSignature with the same message.
* @return true if the signature is valid indicating the message was indeed
* signed by the corresponding SigningKey
* @return false if the verification fails.
*/
static bool verify(
const std::vector<unsigned char>& signatureVerificationKeyBytes,
const unsigned char* message,
const size_t messageLength,
const std::vector<unsigned char>& signature
);
/**
* @brief Verify that a signature is valid in order to prove that a message
* has been signed with the SigningKey from which this SignatureVerificationKey
* was generated.
*
* @param message The message to verify the signature of
* @param messageLength The length of the message
* @param signature The signature generated by corresponding SigningKey when
* by calling SigningKey::generateSignature with the same message.
* @return true if the signature is valid indicating the message was indeed
* signed by the corresponding SigningKey
* @return false if the verification fails.
*/
bool verify(
const unsigned char* message,
const size_t messageLength,
const std::vector<unsigned char>& signature
) const;
/**
* @brief Verify that a signature is valid in order to prove that a message
* has been signed with the SigningKey from which this SignatureVerificationKey
* was generated.
*
* @param message The message to verify the signature of
* @param signature The signature generated by corresponding SigningKey when
* by calling SigningKey::generateSignature with the same message.
* @return true if the signature is valid indicating the message was indeed
* signed by the corresponding SigningKey
* @return false if the verification fails.
*/
bool verify(
const std::vector<unsigned char>& message,
const std::vector<unsigned char>& signature
) const;
/**
* @brief Verify that a signature is valid in order to prove that a message
* has been signed with the SigningKey from which this SignatureVerificationKey
* was generated.
*
* @param message The message to verify the signature of
* @param signature The signature generated by corresponding SigningKey when
* by calling SigningKey::generateSignature with the same message.
* @return true if the signature is valid indicating the message was indeed
* signed by the corresponding SigningKey
* @return false if the verification fails.
*/
bool verify(
const SodiumBuffer& message,
const std::vector<unsigned char>& signature
) const;
/**
* @brief Get the raw signature verification key as a byte vector.
*
* @return const std::vector<unsigned char>
*/
const std::vector<unsigned char> getKeyBytes() const;
/**
* @brief Get the raw signature-verification key as a string of hex digits
*
* @return const std::string a string containing only hex digits (and no "0x").
*/
const std::string getKeyBytesAsHexDigits() const;
/**
* @brief Get the JSON-formatted derivation options string used to generate
* the public-private key pair.
*
* @return const std::string in @ref derivation_options_format
*/
const std::string getDerivationOptionsJson() const {
return derivationOptionsJson;
}
/**
* @brief Serialize to byte array as a list of:
* (signatureVerificationKeyBytes, derivationOptionsJson)
*
* Stored in SodiumBuffer's fixed-length list format.
* Strings are stored as UTF8 byte arrays.
*/
const SodiumBuffer toSerializedBinaryForm() const;
/**
* @brief Deserialize from a byte array stored as a list of:
* (signatureVerificationKeyBytes, derivationOptionsJson)
*
* Stored in SodiumBuffer's fixed-length list format.
* Strings are stored as UTF8 byte arrays.
*/
static SignatureVerificationKey fromSerializedBinaryForm(const SodiumBuffer &serializedBinaryForm);
};
| 35.846809 | 101 | 0.73623 | [
"object",
"vector"
] |
6bce4786be37736f1a638b92acacd4c6595a20e0 | 21,122 | cpp | C++ | Engine/RendererObjectFactory.cpp | kristofe/VolumeRenderer | 653976ef8c80d05fd1059ebc0b3d3542649879fc | [
"MIT"
] | null | null | null | Engine/RendererObjectFactory.cpp | kristofe/VolumeRenderer | 653976ef8c80d05fd1059ebc0b3d3542649879fc | [
"MIT"
] | null | null | null | Engine/RendererObjectFactory.cpp | kristofe/VolumeRenderer | 653976ef8c80d05fd1059ebc0b3d3542649879fc | [
"MIT"
] | null | null | null | #include <assert.h>
#include "ImageUtils.h"
#include "Platform.h"
#include "Globals.h"
#include "Game.h"
#include "Mesh.h"
#include "Material.h"
#include "TextureFont.h"
#include "RendererObjectFactory.h"
////////////////////////////////////////////////////////////////////////////////
RendererObjectFactory* RendererObjectFactory::mInstance = NULL;
RendererObjectFactory& RendererObjectFactory::GetInstance()
{
if(mInstance == NULL)
{
mInstance = new RendererObjectFactory();
}
return *mInstance;
}
////////////////////////////////////////////////////////////////////////////////
RendererObjectFactory::RendererObjectFactory()
{
//mMaterialsDB = new std::map<const char*,GameID>();
//mMeshesDB = new std::map<const char*,GameID>();
//mModelsDB = new std::map<const char*,RendererModelID>();
//mTexturesDB = new std::map<const char*,RendererTextureID>();
}
////////////////////////////////////////////////////////////////////////////////
RendererObjectFactory::~RendererObjectFactory()
{
//SAFE_DELETE(mMaterialsDB);
//SAFE_DELETE(mMeshesDB);
//SAFE_DELETE(mModelsDB);
//SAFE_DELETE(mTexturesDB);
}
/*
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::CloneMesh(GameID id)
{
assert("CloneMesh() Not Implemented" && 0);
return NULL;
}
*/
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::GetMesh(std::string name)
{
std::map<std::string,GameID>::iterator it;
RendererObjectFactory& rf = RendererObjectFactory::GetInstance();
it = rf.mMeshesDB.find(name);
if(it != rf.mMeshesDB.end())//Mesh with desired name already exists
{
return (*it).second;
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::CloneMesh(GameID id, std::string name)
{
Mesh& m = RendererObjectFactory::GetMesh(id);
GameID meshID = RendererObjectFactory::CreateMesh(name.c_str());
Mesh& clone = RendererObjectFactory::GetMesh(meshID);
m.Clone(clone);
return clone.mGameID;
}
////////////////////////////////////////////////////////////////////////////////
void RendererObjectFactory::RemoveMesh(std::string name)
{
std::map<std::string,GameID>::iterator it;
RendererObjectFactory& rf = RendererObjectFactory::GetInstance();
it = rf.mMeshesDB.find(name);
if(it != rf.mMeshesDB.end())//Mesh with desired name already exists
{
rf.mMeshesDB.erase(it);
}
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::GetUnitPlaneMesh()
{
GameID id = RendererObjectFactory::GetMesh(QUOTEME(UNIT_PLANE_MESH));
if(id == (GameID)NULL)
{
id = RendererObjectFactory::CreateUnitPlaneMesh();
}
return id;
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::GetUnitCubeMesh()
{
GameID id = RendererObjectFactory::GetMesh(QUOTEME(UNIT_CUBE_MESH));
if(id == (GameID)NULL)
{
id = RendererObjectFactory::CreateUnitCubeMesh();
}
return id;
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::CreateMesh(std::string name)
{
//Do we check to see if there already is a default unit plane
GameID id = RendererObjectFactory::GetMesh(name);
if(id != (GameID)NULL)
{
return id;
}
Renderer& r = Game::GetInstance().GetRenderer();
//Mesh* newMesh = new Mesh();
Mesh& m = r.CreateMesh(name.c_str());
RendererObjectFactory& rf = RendererObjectFactory::GetInstance();
rf.mMeshesDB[name] = m.mGameID;
return m.mGameID;
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::CreateUnitPlaneMesh()
{
//Do we check to see if there already is a default unit plane
GameID id = RendererObjectFactory::GetMesh(QUOTEME(UNIT_PLANE_MESH));
if(id != (GameID)NULL)
{
return id;
}
id = RendererObjectFactory::CreateGridMesh(QUOTEME(UNIT_PLANE_MESH));
Game::GetInstance().GetRenderer().Retain(0,id);
return id;
/*
id = RendererObjectFactory::CreateMesh(QUOTEME(UNIT_PLANE_MESH));
Mesh& m = RendererObjectFactory::GetMesh(id);
m.mVertexCount = 4;
m.mNormalCount = 4;
m.mColorCount = 4;
m.mUVCount = 4;
m.mTriangleCount = 2;
m.mVertices = new Vector3[m.mVertexCount];
m.mNormals = new Vector3[m.mNormalCount];
m.mColors = new Color[m.mColorCount];
m.mUV = new Vector2[m.mUVCount];
m.mTriangles = new unsigned int[m.mTriangleCount * 3];
m.mVertices[0].Set(0,0,0);
m.mVertices[1].Set(1,0,0);
m.mVertices[2].Set(1,1,0);
m.mVertices[3].Set(0,1,0);
m.mNormals[0].Set(0,0,-1);
m.mNormals[1].Set(0,0,-1);
m.mNormals[2].Set(0,0,-1);
m.mNormals[3].Set(0,0,-1);
m.mColors[0].Set(1,1,1,1);
m.mColors[1].Set(1,1,1,1);
m.mColors[2].Set(1,1,1,1);
m.mColors[3].Set(1,1,1,1);
m.mUV[0].Set(0,0);
m.mUV[1].Set(1,0);
m.mUV[2].Set(1,1);
m.mUV[3].Set(0,1);
m.mTriangles[0] = 0;
m.mTriangles[1] = 2;
m.mTriangles[2] = 3;
m.mTriangles[3] = 0;
m.mTriangles[4] = 1;
m.mTriangles[5] = 2;
return m.mGameID;
*/
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::CreateUnitCubeMesh()
{
//This mesh has separate vertices per face... every face is independent
//Do we check to see if there already is a default unit plane
GameID id = RendererObjectFactory::GetMesh(QUOTEME(UNIT_CUBE_MESH));
if(id != (GameID)NULL)
{
return id;
}
id = RendererObjectFactory::CreateMesh(QUOTEME(UNIT_CUBE_MESH));
Game::GetInstance().GetRenderer().Retain(0,id);
Mesh& m = RendererObjectFactory::GetMesh(id);
m.mVertexCount = 4*6;
m.mNormalCount = 4*6;
m.mColorCount = 4*6;
m.mUVCount = 4*6;
m.mTriangleCount = 2*6;
m.mVertices = new Vector3[m.mVertexCount];
m.mNormals = new Vector3[m.mNormalCount];
m.mColors = new Color[m.mColorCount];
m.mUV = new Vector2[m.mUVCount];
m.mTriangles = new unsigned short[m.mTriangleCount * 3];
//Front face
m.mVertices[0].Set(-0.5f,-0.5f, 0.5f);//(0,0,0);
m.mVertices[1].Set( 0.5f,-0.5f, 0.5f);//(1,0,0);
m.mVertices[2].Set( 0.5f, 0.5f, 0.5f);//(1,1,0);
m.mVertices[3].Set(-0.5f, 0.5f, 0.5f);//(0,1,0);
m.mNormals[0].Set(0,0,1);
m.mNormals[1].Set(0,0,1);
m.mNormals[2].Set(0,0,1);
m.mNormals[3].Set(0,0,1);
m.mColors[0].Set(1.0f,1.0f,1.0f,1.0f);
m.mColors[1].Set(1.0f,1.0f,1.0f,1.0f);
m.mColors[2].Set(1.0f,1.0f,1.0f,1.0f);
m.mColors[3].Set(1.0f,1.0f,1.0f,1.0f);
m.mUV[0].Set(0,1);
m.mUV[1].Set(1,1);
m.mUV[2].Set(1,0);
m.mUV[3].Set(0,0);
m.mTriangles[0] = 0;
m.mTriangles[1] = 2;
m.mTriangles[2] = 3;
m.mTriangles[3] = 0;
m.mTriangles[4] = 1;
m.mTriangles[5] = 2;
//Back face
m.mVertices[4].Set(-0.5f,-0.5f,-0.5f);
m.mVertices[5].Set( 0.5f,-0.5f,-0.5f);
m.mVertices[6].Set( 0.5f, 0.5f,-0.5f);
m.mVertices[7].Set(-0.5f, 0.5f,-0.5f);
m.mNormals[4].Set(0,0,-1);
m.mNormals[5].Set(0,0,-1);
m.mNormals[6].Set(0,0,-1);
m.mNormals[7].Set(0,0,-1);
m.mColors[4].Set(1.0f,1.0f,1.0f,1.0f);
m.mColors[5].Set(1.0f,1.0f,1.0f,1.0f);
m.mColors[6].Set(1.0f,1.0f,1.0f,1.0f);
m.mColors[7].Set(1.0f,1.0f,1.0f,1.0f);
m.mUV[4].Set(0,1);
m.mUV[5].Set(1,1);
m.mUV[6].Set(1,0);
m.mUV[7].Set(0,0);
m.mTriangles[6] = 4;//add 6
m.mTriangles[7] = 7;
m.mTriangles[8] = 6;
m.mTriangles[9] = 4;
m.mTriangles[10] = 6;
m.mTriangles[11] = 5;
///////////////////////////////////////////////////////
//top face - x/z plane
m.mVertices[8].Set( -0.5f,0.5f,-0.5f);
m.mVertices[9].Set( 0.5f,0.5f,-0.5f);
m.mVertices[10].Set( 0.5f,0.5f, 0.5f);
m.mVertices[11].Set(-0.5f,0.5f, 0.5f);
m.mNormals[8].Set(0,1,0);
m.mNormals[9].Set(0,1,0);
m.mNormals[10].Set(0,1,0);
m.mNormals[11].Set(0,1,0);
m.mColors[8].Set(1,1,1,1);
m.mColors[9].Set(1,1,1,1);
m.mColors[10].Set(1,1,1,1);
m.mColors[11].Set(1,1,1,1);
m.mUV[8].Set(0,1);
m.mUV[9].Set(1,1);
m.mUV[10].Set(1,0);
m.mUV[11].Set(0,0);
m.mTriangles[12] = 8;//add 6
m.mTriangles[13] = 10;
m.mTriangles[14] = 11;
m.mTriangles[15] = 8;
m.mTriangles[16] = 9;
m.mTriangles[17] = 10;
//bottom face x/z plane - reorder indices
m.mVertices[12].Set(-0.5f,-0.5f,-0.5f);
m.mVertices[13].Set( 0.5f,-0.5f,-0.5f);
m.mVertices[14].Set( 0.5f,-0.5f, 0.5f);
m.mVertices[15].Set(-0.5f,-0.5f, 0.5f);
m.mNormals[12].Set(0,-1,0);
m.mNormals[13].Set(0,-1,0);
m.mNormals[14].Set(0,-1,0);
m.mNormals[15].Set(0,-1,0);
m.mColors[12].Set(1,1,1,1);
m.mColors[13].Set(1,1,1,1);
m.mColors[14].Set(1,1,1,1);
m.mColors[15].Set(1,1,1,1);
m.mUV[12].Set(0,1);
m.mUV[13].Set(1,1);
m.mUV[14].Set(1,0);
m.mUV[15].Set(0,0);
m.mTriangles[18] = 12;//add 6
m.mTriangles[19] = 15;
m.mTriangles[20] = 14;
m.mTriangles[21] = 12;
m.mTriangles[22] = 14;
m.mTriangles[23] = 13;
//left face y/z plane
m.mVertices[16].Set(-0.5f,-0.5f,-0.5f);
m.mVertices[17].Set(-0.5f, 0.5f,-0.5f);
m.mVertices[18].Set(-0.5f, 0.5f, 0.5f);
m.mVertices[19].Set(-0.5f,-0.5f, 0.5f);
m.mNormals[16].Set(-1,0,0);
m.mNormals[17].Set(-1,0,0);
m.mNormals[18].Set(-1,0,0);
m.mNormals[19].Set(-1,0,0);
m.mColors[16].Set(1,1,1,1);
m.mColors[17].Set(1,1,1,1);
m.mColors[18].Set(1,1,1,1);
m.mColors[19].Set(1,1,1,1);
m.mUV[16].Set(0,1);
m.mUV[17].Set(1,1);
m.mUV[18].Set(1,0);
m.mUV[19].Set(0,0);
m.mTriangles[24] = 16;//add 6
m.mTriangles[25] = 18;
m.mTriangles[26] = 19;
m.mTriangles[27] = 16;
m.mTriangles[28] = 17;
m.mTriangles[29] = 18;
//right face y/z
m.mVertices[20].Set(0.5f,-0.5f,-0.5f);
m.mVertices[21].Set(0.5f, 0.5f,-0.5f);
m.mVertices[22].Set(0.5f, 0.5f, 0.5f);
m.mVertices[23].Set(0.5f,-0.5f, 0.5f);
m.mNormals[20].Set(1,0,0);
m.mNormals[21].Set(1,0,0);
m.mNormals[22].Set(1,0,0);
m.mNormals[23].Set(1,0,0);
m.mColors[20].Set(1,1,1,1);
m.mColors[21].Set(1,1,1,1);
m.mColors[22].Set(1,1,1,1);
m.mColors[23].Set(1,1,1,1);
m.mUV[20].Set(0,1);
m.mUV[21].Set(1,1);
m.mUV[22].Set(1,0);
m.mUV[23].Set(0,0);
m.mTriangles[30] = 20;//add 6
m.mTriangles[31] = 23;
m.mTriangles[32] = 22;
m.mTriangles[33] = 20;
m.mTriangles[34] = 22;
m.mTriangles[35] = 21;
return m.mGameID;
}
////////////////////////////////////////////////////////////////////////////////
/*GameID RendererObjectFactory::CloneMaterial()
{
assert("CloneMaterial() Not Implemented" && false);
return NULL;
}*/
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::CreateMaterial(std::string name)
{
GameID id = RendererObjectFactory::GetMaterial(name);
if(id != (GameID)NULL)
{
return id;
}
Renderer& r = Game::GetInstance().GetRenderer();
Material& m = r.CreateMaterial(name.c_str());
m.mAmbient.Set(0.5,0.5,0.5,1);
m.mDiffuse.Set(1,1,1,1);
m.mTextureCount = 0;
RendererObjectFactory& rf = RendererObjectFactory::GetInstance();
rf.mMaterialsDB[name] = m.mGameID;
return m.mGameID;
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::GetMaterial(std::string name)
{
std::map<std::string,GameID>::iterator it;
RendererObjectFactory& rf = RendererObjectFactory::GetInstance();
it = rf.mMaterialsDB.find(name);
if(it != rf.mMaterialsDB.end())//Material with desired name already exists
{
return (*it).second;
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////////
void RendererObjectFactory::RemoveMaterial(std::string name)
{
std::map<std::string,GameID>::iterator it;
RendererObjectFactory& rf = RendererObjectFactory::GetInstance();
it = rf.mMaterialsDB.find(name);
if(it != rf.mMaterialsDB.end())//Material with desired name already exists
{
rf.mMaterialsDB.erase(it);
}
it = rf.mFontsDB.find(name);
if(it != rf.mFontsDB.end())//Material with desired name already exists
{
rf.mFontsDB.erase(it);
}
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::GetDefaultMaterial()
{
GameID id = RendererObjectFactory::GetMaterial(QUOTEME(DEFAULT_MATERIAL));
if(id != (GameID)NULL)
{
return id;
}
id = RendererObjectFactory::CreateMaterial(QUOTEME(DEFAULT_MATERIAL));
Game::GetInstance().GetRenderer().Retain(0,id);
return id;
}
////////////////////////////////////////////////////////////////////////////////
Mesh& RendererObjectFactory::GetMesh(GameID meshID)
{
return Game::GetInstance().GetRenderer().GetMesh(meshID);
}
////////////////////////////////////////////////////////////////////////////////
Material& RendererObjectFactory::GetMaterial(GameID matID)
{
return Game::GetInstance().GetRenderer().GetMaterial(matID);
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::CreateTexture(std::string name,std::string filename, bool delayLoad)
{
Renderer& r = Game::GetInstance().GetRenderer();
Texture& t = r.CreateTexture(name,filename,delayLoad);
//This should be in the RenderObjectFactory... the loading part. The uploading to GPU should be in the renderer.
if(!delayLoad)
RendererObjectFactory::ReadTextureFromDisk(filename,t);
RendererObjectFactory::GetInstance().mTexturesDB[t.mName.c_str()] = t.mGameID;
return t.mGameID;
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::GetTexture(std::string name)
{
std::map<std::string,GameID>::iterator it;
RendererObjectFactory& rf = RendererObjectFactory::GetInstance();
it = rf.mTexturesDB.find(name);
if(it != rf.mTexturesDB.end())
{
return (*it).second;
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////////
void RendererObjectFactory::RemoveTexture(std::string name)
{
//printf("Removing %s\n",name.c_str());
std::map<std::string,GameID>::iterator it;
RendererObjectFactory& rf = RendererObjectFactory::GetInstance();
it = rf.mTexturesDB.find(name);
if(it != rf.mTexturesDB.end())
{
rf.mTexturesDB.erase(it);
}
}
////////////////////////////////////////////////////////////////////////////////
Texture& RendererObjectFactory::GetTexture(GameID id)
{
return Game::GetInstance().GetRenderer().GetTexture(id);
}
////////////////////////////////////////////////////////////////////////////////
void RendererObjectFactory::ReadTextureFromDisk(std::string filename, Texture& tex)
{
//printf("Loading %s\n",tex.mName.c_str());
std::string fullpath;
std::string file = filename;
GetFullFilePathFromResource(file,fullpath);
tex.mSourceFileName = fullpath;
tex.mShortFileName = filename;
#ifndef TARGETIPHONE
read_png_file(fullpath.c_str(),tex);
#else
//tex.mNumberOfColors = 4;
//tex.mHasAlpha = true;
//tex.mBitsPerPixel = tex.mNumberOfColors*8;
//::GetTexture((char*)tex.mShortFileName.c_str(), &(tex.mPixelData), (int*)&(tex.mWidth), (int*)&(tex.mHeight));
//TODO: Detect if texture is PVR!!!
bool isPVR = false;
std::string extension = GetFileExtension(tex.mShortFileName);
if(ToUpper(extension) == "PVR")
isPVR = true;
if(isPVR)
{
::LoadTextureDataCompressed((char*)tex.mSourceFileName.c_str(),tex);
}
else
{
//::LoadTextureData((char*)tex.mShortFileName.c_str(),tex);
read_png_file(fullpath.c_str(),tex);
}
#endif
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::CreateTextureFont(std::string name)
{
GameID id = RendererObjectFactory::GetTextureFont(name);
if(id != 0)
{
return id;
}
Renderer& r = Game::GetInstance().GetRenderer();
TextureFont& font = r.CreateTextureFont(name);
RendererObjectFactory& rf = RendererObjectFactory::GetInstance();
rf.mFontsDB[name] = font.mGameID;
return font.mGameID;
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::GetTextureFont(std::string name)
{
std::map<std::string,GameID>::iterator it;
RendererObjectFactory& rf = RendererObjectFactory::GetInstance();
it = rf.mFontsDB.find(name);
if(it != rf.mFontsDB.end())//Material with desired name already exists
{
return (*it).second;
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////////
TextureFont& RendererObjectFactory::GetTextureFont(GameID fontID)
{
return Game::GetInstance().GetRenderer().GetTextureFont(fontID);
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::CreateGridMesh(std::string name, int widthInCells, int heightInCells, float width, float height)
{
int gridCellsCount = widthInCells*heightInCells;
GameID rid = RendererObjectFactory::CreateMesh(name);
Mesh& m = RendererObjectFactory::GetMesh(rid);
m.mVertexCount = gridCellsCount;
m.mNormalCount = gridCellsCount;
m.mColorCount = gridCellsCount;
m.mUVCount = gridCellsCount;
m.mUV2Count = gridCellsCount;
m.mTriangleCount = ((widthInCells-1)*(heightInCells-1))*2;//the 2 is for 2 tris per cell
m.mVertices = new Vector3[m.mVertexCount];
m.mNormals = new Vector3[m.mNormalCount];
m.mColors = new Color[m.mColorCount];
m.mUV = new Vector2[m.mUVCount];
m.mUV2 = new Vector2[m.mUV2Count];
m.mTriangles = new unsigned short[m.mTriangleCount*3];//the 3 is for 3 indices per triangle.. we aren't using any struct or class just a straight array of ints
float dx = 1.0f/(widthInCells-1);
float dy = 1.0f/(heightInCells-1);
float currX,currY;
currX = currY = 0.0f;
int index = 0;
for(int y = 0; y < heightInCells; y++)
{
for(int x = 0; x < widthInCells; x++)
{
index = y*widthInCells + x;
m.mVertices[index].Set(currX*width,currY*height,0.0f);
m.mColors[index].Set(1.0f,1.0f,1.0f,1.0f);
m.mUV[index].Set(currX/1.0f,currY/1.0f);
m.mUV2[index].Set(currX/1.0f,currY/1.0f);
currX = currX + dx;
}
currY = currY + dy;
currX = 0.0f;
}
int id = 0;
for(int y = 0; y < heightInCells-1; y++)
{
for(int x = 0; x < widthInCells-1; x++)
{
unsigned short i0 = (y + 0)*widthInCells + (x + 0);
unsigned short i1 = (y + 0)*widthInCells + (x + 1);
unsigned short i2 = (y + 1)*widthInCells + (x + 1);
unsigned short i3 = (y + 1)*widthInCells + (x + 0);
//3 2
//0 1
//CCW Vertex Ordering
m.mTriangles[id++] = i0;
m.mTriangles[id++] = i2;
m.mTriangles[id++] = i3;
m.mTriangles[id++] = i0;
m.mTriangles[id++] = i1;
m.mTriangles[id++] = i2;
}
}
return m.mGameID;
}
////////////////////////////////////////////////////////////////////////////////
GameID RendererObjectFactory::CreateQuadPoolMesh(std::string name, int quadCount, const Vector3& quadSize)
{
GameID rid = RendererObjectFactory::CreateMesh(name);
Mesh& m = RendererObjectFactory::GetMesh(rid);
m.mVertexCount = quadCount*4;
m.mNormalCount = quadCount*4;
m.mColorCount = quadCount*4;
m.mUVCount = quadCount*4;
//m.mUV2Count = quadCount*4;
m.mTriangleCount = quadCount*2;//the 2 is for 2 tris per cell
m.mVertices = new Vector3[m.mVertexCount];
m.mNormals = new Vector3[m.mNormalCount];
m.mColors = new Color[m.mColorCount];
m.mUV = new Vector2[m.mUVCount];
//m.mUV2 = new Vector2[m.mUV2Count];
m.mTriangles = new unsigned short[m.mTriangleCount*3];//the 3 is for 3 indices per triangle.. we aren't using any struct or class just a straight array of ints
float sx = quadSize.x * 0.5f;
float sy = quadSize.y * 0.5f;
for(int quadIndex = 0; quadIndex < quadCount; quadIndex++)
{
int index = RendererObjectFactory::QuadPoolMeshDataStartIndex(quadIndex);
m.mVertices[index + 0].Set(-sx,-sy, 0.0f);
m.mVertices[index + 1].Set( sx,-sy, 0.0f);
m.mVertices[index + 2].Set( sx, sy, 0.0f);
m.mVertices[index + 3].Set(-sx, sy, 0.0f);
m.mNormals[index + 0].Set(0,0,1);
m.mNormals[index + 1].Set(0,0,1);
m.mNormals[index + 2].Set(0,0,1);
m.mNormals[index + 3].Set(0,0,1);
m.mColors[index + 0].Set(1.0f,1.0f,1.0f,1.0f);
m.mColors[index + 1].Set(1.0f,1.0f,1.0f,1.0f);
m.mColors[index + 2].Set(1.0f,1.0f,1.0f,1.0f);
m.mColors[index + 3].Set(1.0f,1.0f,1.0f,1.0f);
m.mUV[index + 0].Set(0,1);
m.mUV[index + 1].Set(1,1);
m.mUV[index + 2].Set(1,0);
m.mUV[index + 3].Set(0,0);
int triIndex = RendererObjectFactory::QuadPoolMeshTriangleStartIndex(quadIndex);
m.mTriangles[triIndex + 0] = index + 0;
m.mTriangles[triIndex + 1] = index + 2;
m.mTriangles[triIndex + 2] = index + 3;
m.mTriangles[triIndex + 3] = index + 0;
m.mTriangles[triIndex + 4] = index + 1;
m.mTriangles[triIndex + 5] = index + 2;
}
return m.mGameID;
}
void RendererObjectFactory::RegisterMesh(GameID id,std::string name)
{
RendererObjectFactory::GetInstance().mMeshesDB[name] = id;
}
void RendererObjectFactory::RegisterMaterial(GameID id,std::string name)
{
RendererObjectFactory::GetInstance().mMaterialsDB[name] = id;
}
void RendererObjectFactory::RegisterTexture(GameID id,std::string name)
{
RendererObjectFactory::GetInstance().mTexturesDB[name] = id;
}
void RendererObjectFactory::RegisterTextureFont(GameID id,std::string name)
{
RendererObjectFactory::GetInstance().mFontsDB[name] = id;
}
| 28.351678 | 160 | 0.595824 | [
"mesh"
] |
6bd5649b97412ce328616f4a96d0686a4040c363 | 1,616 | cpp | C++ | code/src/log/cg_execution_log.cpp | mblufstein/pruebasOR | b43e63596643fe762f49fefffcc763c6a293a9cd | [
"MIT"
] | 2 | 2019-12-31T09:21:22.000Z | 2021-05-01T02:37:07.000Z | code/src/log/cg_execution_log.cpp | mblufstein/pruebasOR | b43e63596643fe762f49fefffcc763c6a293a9cd | [
"MIT"
] | null | null | null | code/src/log/cg_execution_log.cpp | mblufstein/pruebasOR | b43e63596643fe762f49fefffcc763c6a293a9cd | [
"MIT"
] | 2 | 2019-12-21T14:09:31.000Z | 2021-05-01T02:37:06.000Z | //
// Created by Gonzalo Lera Romero.
// Grupo de Optimizacion Combinatoria (GOC).
// Departamento de Computacion - Universidad de Buenos Aires.
//
#include "goc/log/cg_execution_log.h"
#include "goc/string/string_utils.h"
using namespace std;
using namespace nlohmann;
namespace goc
{
json CGExecutionLog::ToJSON() const
{
json j;
j["log_type"] = "cg"; // ID of the log type.
if (screen_output.IsSet()) j["screen_output"] = screen_output.Value();
if (time.IsSet()) j["time"] = time.Value().Amount(DurationUnit::Seconds);
if (status.IsSet()) j["status"] = STR(status.Value());
if (incumbent.IsSet()) j["incumbent"] = incumbent.Value();
if (incumbent_value.IsSet()) j["incumbent_value"] = incumbent_value.Value();
if (columns_added.IsSet()) j["columns_added"] = columns_added.Value();
if (iteration_count.IsSet()) j["iteration_count"] = iteration_count.Value();
if (pricing_time.IsSet()) j["pricing_time"] = pricing_time.Value();
if (lp_time.IsSet()) j["lp_time"] = lp_time.Value();
if (iterations.IsSet())
{
j["iterations"] = vector<json>();
for (auto& iteration: *iterations) j["iterations"].push_back(iteration);
}
return j;
}
ostream& operator<<(ostream& os, CGStatus status)
{
unordered_map<CGStatus, string> mapper = {{CGStatus::DidNotStart, "DidNotStart"},
{CGStatus::Infeasible, "Infeasible"},
{CGStatus::Unbounded, "Unbounded"},
{CGStatus::TimeLimitReached, "TimeLimitReached"},
{CGStatus::MemoryLimitReached, "MemoryLimitReached"},
{CGStatus::Optimum, "Optimum"}};
return os << mapper[status];
}
} // namespace goc | 33.666667 | 82 | 0.679455 | [
"vector"
] |
6bd8705ceaf179a8de04b0d887551c68d4ed90cb | 11,463 | cpp | C++ | 2020-2021/05_tsp_tests/tspstart.cpp | pantadeusz/meh | 16d2826330c9bfdb4c7a315f2f69ec33b464541d | [
"MIT"
] | null | null | null | 2020-2021/05_tsp_tests/tspstart.cpp | pantadeusz/meh | 16d2826330c9bfdb4c7a315f2f69ec33b464541d | [
"MIT"
] | 1 | 2019-10-18T07:14:26.000Z | 2019-10-18T18:54:26.000Z | 2020-2021/05_tsp_tests/tspstart.cpp | pantadeusz/meh | 16d2826330c9bfdb4c7a315f2f69ec33b464541d | [
"MIT"
] | 2 | 2019-10-24T08:50:00.000Z | 2020-03-29T06:10:20.000Z | /*
TSP z powrotem do punktu startowego
Zadanie do rozwiązania:
{(x0,y0),(x1,y1),...,(xn-1,yn-1)}
(dziedzina) Punkt roboczy, potencjalne rozwiązanie
(i0,i1,i2,...,in-1) -- lista kolejnych miast do odwiedzienia
Konstrukcja funkcji celu
Suma(odległość(miast))
Metoda modyfikacji rozwiązania
-*kolejna permutacja
- losowanie kolejnych poprawnych miast do odwiedzienia
-*losowa zamiana 2 miast miejscami w kolejności
- modyfikujemy jedno miasto i poprawa kolejnych miast tak aby żadne się nie powtórzyło
*/
/*
Generowanie nowych danych przykladowych:
for k in `seq 1 100`; do rm input_$k.txt; for i in `seq 1 $k`; do echo "miasto${i} $RANDOM $RANDOM" >> input_$k.txt; done; echo "-" >> input_$k.txt; done
Testowanie czasow wykonania
for k in `seq 1 13`; do cat input_$k.txt | time ./a.out; done
*/
#include <vector>
#include <iostream>
#include <random>
#include <algorithm>
#include <numeric>
#include <array>
#include <memory>
#include <functional>
#include <set>
#include <list>
#include <map>
#include <chrono>
// obiektowo-funkcyjny
std::random_device rd;
std::mt19937 r_mt19937(rd());
/* zadanie do rozwiązania */
struct City
{
std::string name; // nazwa miasta
std::array<double, 2> x; // wsp. miasta
/**
* Oblicza odleglosc do miasta
* */
double dist(const City &c)
{
return std::sqrt((c.x[0] - x[0]) * (c.x[0] - x[0]) + (c.x[1] - x[1]) * (c.x[1] - x[1]));
}
};
/**
* problem komiwojazera - zadanie
* */
class Problem : public std::vector<City>
{
};
/**
* lista kolejnych indeksów miast do odwiedzenia. Punkt roboczy, albo potencjalne rozwiązanie. Jest
* to zgodne z formatem wyjściowym rozwiązania.
* */
class Solution : public std::vector<int>
{
public:
Solution()
{
}
Solution(std::shared_ptr<Problem> p)
{
set_problem(p);
}
/**
* odwołujemy się do miast z problemu do rozwiażania
* */
std::shared_ptr<Problem> problem;
/**
* metoda pozwalająca na bezpieczne ustawienie problemu do rozwiązania.
* Inicjuje ona listę indeksów miast na kolejne wartości, czyli kolejność
* miast do odwiedzenia jest taka jak w podanym zadaniu.
* */
void set_problem(std::shared_ptr<Problem> p)
{
problem = p;
this->resize(p->size());
for (int i = 0; i < size(); i++)
(*this)[i] = i;
}
/**
* metoda licząca długość trasy odwiedzającej wszystkie miasta.
* To też jest nasza minimalizowana funkcja celu!!!
* */
double distance() const
{
double sum = 0.0;
for (unsigned i = 0; i < size(); i++)
{
sum += problem->at(at(i)).dist(problem->at(at((i + 1) % size())));
}
return sum;
}
/**
* Oblicza kolejne możliwe rozwiązanie. Ta metoda ma taką cechę, że
* pozwala na deterministyczne przejście po wszystkich permutacjach.
* Nadaje się więc do rozwiązania siłowego.
* */
Solution generate_next(std::function<void(void)> on_end = []() {}) const
{
Solution s = *this;
if (!std::next_permutation(s.begin(), s.end()))
on_end();
return s;
}
/**
* Generuje nam losowego sąsiada.
* */
Solution generate_random_neighbour() const
{
using namespace std;
uniform_int_distribution<int> uni((unsigned long)0, size() - 1);
Solution s = *this;
std::swap(s[uni(r_mt19937)], s[uni(r_mt19937)]);
return s;
}
void randomize()
{
using namespace std;
shuffle(this->begin(), this->end(), r_mt19937);
}
// dodaje 1 na zadanej wspolrzednej
Solution inc_axis(int ax) const
{
Solution nsol = *this;
int prevCityIdx = nsol.at(ax);
nsol[ax] = (nsol[ax] + 1) % size();
for (int i = 0; i < size(); i++)
{
if ((nsol[i] == nsol[ax]) && (i != ax))
{
nsol[i] = prevCityIdx;
break;
}
}
return nsol;
}
// odejmuje 1 na zadanej wspolrzednej
Solution dec_axis(int ax) const
{
Solution nsol = *this;
int prevCityIdx = nsol[ax];
nsol[ax] = (nsol[ax] + nsol.size() - 1) % size();
for (int i = size() - 1; i >= 0; i--)
{
// zmiana
if ((nsol[i] == nsol[ax]) && (i != ax))
{
nsol[i] = prevCityIdx;
break;
}
}
return nsol;
}
};
/**
* Wczytywanie problemu z strumienia wejściowego. Jeśli jako nazwę miasta poda się "-" to kończy wczytywać.
* */
std::istream &operator>>(std::istream &is, Problem &p)
{
using namespace std;
do
{
string name;
double x, y;
is >> name;
if (name == "-")
return is;
is >> x >> y;
p.push_back({name, {x, y}});
} while (true);
}
/**
* Wypisanie rozwiązania na standardowe wyjście
* */
std::ostream &operator<<(std::ostream &o, Solution &s)
{
o << "[" << s.distance() << "] ";
for (int i : s)
{
auto c = s.problem->at(i);
o << c.name << "(" << c.x[0] << "," << c.x[1] << ") ";
}
return o;
}
auto brute_force = [](auto problem) {
Solution sol(problem);
auto best = sol;
bool cont = true;
do
{
sol = sol.generate_next([&]() { cont = false; });
if (sol.distance() < best.distance())
best = sol;
// (można wykomentować aby nie zaśmiecało nam konsoli) //cout << sol << endl;
} while (cont);
return best;
};
auto hill_climbing_rand = [](auto problem, int iterations = 1000) {
using namespace std;
Solution best(problem);
best.randomize();
for (int i = 0; i < iterations; i++)
{
auto sol = best.generate_random_neighbour();
if (sol.distance() < best.distance())
{
cout << "found better: " << sol.distance() << endl;
best = sol;
}
};
return best;
};
auto hill_climbing_det = [](auto problem, int iterations = 1000) {
using namespace std;
Solution best(problem);
best.randomize();
for (int i = 0; i < iterations; i++)
{
vector<Solution> neighbours;
neighbours.push_back(best);
for (int a = 0; a < best.size(); a++)
{
neighbours.push_back(best.inc_axis(a));
neighbours.push_back(best.dec_axis(a));
}
sort(neighbours.begin(), neighbours.end(), [](auto &a, auto &b) {
return a.distance() > b.distance();
});
if (best == neighbours.back())
{
vector<Solution> best_neighbours;
if (best.distance() == neighbours.at(neighbours.size() - 2).distance())
{
for (int i = neighbours.size() - 1; (i >= 0) && (best.distance() == neighbours.at(i).distance()); i--)
best_neighbours.push_back(neighbours[i]);
using namespace std;
uniform_int_distribution<int> uni((unsigned long)0, best_neighbours.size() - 1);
best = best_neighbours.at(uni(r_mt19937));
}
else
{
break;
}
}
best = neighbours.back();
};
return best;
};
bool operator==(const Solution &a, const Solution &b)
{
for (int i = 0; i < a.size(); i++)
{
if (a[i] != b[i])
return false;
}
return true;
}
auto tabu = [](auto problem, int iterations = 100000, int tabusize = 500000) {
using namespace std;
Solution sol(problem);
sol.randomize();
list<Solution> tabu_list;
set<Solution> tabu_set;
tabu_list.push_back(sol);
tabu_set.insert(sol);
for (int i = 0; i < iterations; i++)
{
vector<Solution> neighbours; // sasiedzi nie w tabu
for (int i = 0; i < sol.size(); i++)
{
auto e1 = tabu_list.back().inc_axis(i);
auto e2 = tabu_list.back().dec_axis(i);
//if (std::find(tabu_list.begin(), tabu_list.end(), e1) == std::end(tabu_list))
// neighbours.push_back(e1);
//if (std::find(tabu_list.begin(), tabu_list.end(), e2) == std::end(tabu_list))
// neighbours.push_back(e2);
if (tabu_set.count(e1) == 0)
neighbours.push_back(e1);
if (tabu_set.count(e2) == 0)
neighbours.push_back(e2);
}
if (neighbours.size() == 0)
{
neighbours.push_back(tabu_list.front()); // try to fix the problem of the snake eating its tail
}
sort(neighbours.begin(), neighbours.end(), [](auto &a, auto &b) {
return a.distance() > b.distance();
});
tabu_list.push_back(neighbours.back());
tabu_set.insert(neighbours.back());
if (neighbours.back().distance() > neighbours[0].distance())
throw std::invalid_argument("not a great list");
if (sol.distance() > neighbours.back().distance())
{
sol = neighbours.back();
cout << "found better: " << sol.distance() << endl;
}
if (tabu_list.size() > tabusize)
{
tabu_set.erase(tabu_list.front());
tabu_list.pop_front(); // ograniczenie
}
};
return sol;
};
/**
* Funkcja main która implementuje aktualnie rozwiązanie metodą pełnego przeglądu.
* */
int main(int argc, char **argv)
{
using namespace std;
auto problem = make_shared<Problem>();
cin >> (*problem);
Solution sol(problem);
map<string, string> args;
string argname = "-m";
args[argname] = "tabu";
for (auto arg : vector<string>(argv + 1, argv + argc))
{
if (arg.size() && arg[0] == '-')
argname = arg;
else
args[argname] = arg;
}
if (args["-m"] == "hill_climb")
{
auto start = std::chrono::steady_clock::now();
auto best = hill_climbing_rand(problem, (args.count("-n") ? stoi(args["-n"]) : 1000));
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
cout << "hill_climb: " << elapsed_seconds.count() << " " << best << endl;
}
if (args["-m"] == "hill_climb_det")
{
auto start = std::chrono::steady_clock::now();
auto best = hill_climbing_det(problem, (args.count("-n") ? stoi(args["-n"]) : 1000));
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
cout << "hill_climb_det: " << elapsed_seconds.count() << " " << best << endl;
}
if (args["-m"] == "tabu")
{
auto start = std::chrono::steady_clock::now();
auto best = tabu(problem, (args.count("-n") ? stoi(args["-n"]) : 10000), (args.count("-tabusize") ? stoi(args["-tabusize"]) : 1000));
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
cout << "tabu: " << elapsed_seconds.count() << " " << best << endl;
}
if (args["-m"] == "full")
{
auto start = std::chrono::steady_clock::now();
auto best = brute_force(problem);
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
cout << "full: " << elapsed_seconds.count() << " " << best << endl;
}
return 0;
}
| 29.093909 | 153 | 0.545581 | [
"vector"
] |
6bda2e4a42526a9b17ea2e68519e75e824609300 | 1,606 | cpp | C++ | src/261.graph_valid_tree/code.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | 1 | 2016-07-02T17:44:10.000Z | 2016-07-02T17:44:10.000Z | src/261.graph_valid_tree/code.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | null | null | null | src/261.graph_valid_tree/code.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | 1 | 2019-12-21T04:57:15.000Z | 2019-12-21T04:57:15.000Z | class Solution {
public:
bool validTree(int n, vector<pair<int, int>>& edges) {
vector<int> degree(n, 0);
vector<vector<int>> graph(n, vector<int>(0));
for (int i = 0; i < edges.size(); i++) {
graph[edges[i].first].push_back(edges[i].second);
graph[edges[i].second].push_back(edges[i].first);
degree[edges[i].first]++;
degree[edges[i].second]++;
}
queue<int> q;
for (int i = 0; i < n; i++) {
if (degree[i] == 1) q.push(i);
}
while (!q.empty()) {
int cur = q.front();
q.pop();
degree[cur]--;
for (int i = 0; i < graph[cur].size(); i++) {
degree[graph[cur][i]]--;
if (degree[graph[cur][i]] == 1) q.push(graph[cur][i]);
}
}
for (int i = 0; i < n; i++) {
if (degree[i] > 0) return false;
}
vector<int> pre(n, 0);
for (int i = 0; i < n; i++) {
pre[i] = i;
}
for (int i = 0; i < edges.size(); i++) {
setUnion(pre, edges[i].first, edges[i].second);
}
int count = 0;
for (int i = 0; i < n; i++) {
if (setFind(pre, i) == i) count++;
}
return count == 1;
}
int setFind(vector<int>& pre, int x) {
if (pre[x] != x) {
pre[x] = setFind(pre, pre[x]);
}
return pre[x];
}
void setUnion(vector<int>& pre, int x, int y) {
x = setFind(pre, x);
y = setFind(pre, y);
pre[x] = y;
}
};
| 30.301887 | 70 | 0.412204 | [
"vector"
] |
6bdd0ba4a5dc793ee1b24e2ef4912654c9728bd3 | 2,266 | hpp | C++ | src/a2d/physics/rigidbody.hpp | ayles/A2D | 278b8e40be74c0f0257b1062f009995462f983fa | [
"MIT"
] | 17 | 2018-11-12T11:13:23.000Z | 2021-11-13T12:38:21.000Z | src/a2d/physics/rigidbody.hpp | ayles/A2D | 278b8e40be74c0f0257b1062f009995462f983fa | [
"MIT"
] | 1 | 2018-11-12T11:16:01.000Z | 2018-11-12T11:17:50.000Z | src/a2d/physics/rigidbody.hpp | ayles/A2D | 278b8e40be74c0f0257b1062f009995462f983fa | [
"MIT"
] | 3 | 2019-05-28T12:44:09.000Z | 2021-11-13T12:38:23.000Z | //
// Created by selya on 19.12.2018.
//
#ifndef A2D_RIGIDBODY_HPP
#define A2D_RIGIDBODY_HPP
#include <a2d/core/component.hpp>
#include <a2d/physics/physics.hpp>
#include <a2d/core/object2d.hpp>
#include <a2d/renderer/line.hpp>
namespace a2d {
class Rigidbody : public Component {
friend class PhysicsCollider;
friend class CircleCollider;
friend class BoxCollider;
friend class Object2D;
friend class Physics;
b2Body *body;
public:
enum BodyType {
DYNAMIC = b2_dynamicBody,
KINEMATIC = b2_kinematicBody,
STATIC = b2_staticBody,
};
BodyType GetType();
float GetMass();
float GetInertia();
Vector2f GetCenterOfMass();
float GetGravityScale();
Vector2f GetLinearVelocity();
float GetAngularVelocity();
float GetLinearDamping();
float GetAngularDamping();
bool IsFixedRotation();
bool IsAwake();
bool IsBullet();
bool IsSleepingAllowed();
void SetType(BodyType body_type);
void SetMass(float mass);
void SetInertia(float inertia);
void SetCenterOfMass(const Vector2f ¢er_of_mass);
void SetGravityScale(float gravity_scale);
void SetLinearVelocity(const Vector2f &velocity);
void SetAngularVelocity(float velocity);
void SetLinearDamping(float damping);
void SetAngularDamping(float damping);
void SetFixedRotation(bool rotation_fixed);
void SetAwake(bool awake);
void SetBullet(bool bullet);
void SetSleepingAllowed(bool sleeping_allowed);
void ApplyForce(const Vector2f &force, const Vector2f &point, bool wake = true);
void ApplyForceToCenter(const Vector2f &force, bool wake = true);
void ApplyLinearImpulse(const Vector2f &impulse, const Vector2f &point, bool wake = true);
void ApplyLinearImpulseToCenter(const Vector2f &impulse, bool wake = true);
void ApplyAngularImpulse(float impulse, bool wake = true);
void ApplyTorque(float torque, bool wake = true);
private:
void Initialize() override;
void OnEnable() override;
void OnDisable() override;
void OnDestroy() override;
bool internal_transform = false;
void Transform(const Vector2f &position, float rotation);
void PhysicsStep();
};
} //namespace a2d
#endif //A2D_RIGIDBODY_HPP
| 27.975309 | 94 | 0.717564 | [
"transform"
] |
6bdd201bc75879f4c910c17e45471c259fcbc24d | 11,723 | cpp | C++ | src/trainingset.cpp | yorickr/NeuralObjectClassification | dfc3893dfd41e6e33ce66a5edc6832a6f3ad0b52 | [
"MIT"
] | null | null | null | src/trainingset.cpp | yorickr/NeuralObjectClassification | dfc3893dfd41e6e33ce66a5edc6832a6f3ad0b52 | [
"MIT"
] | null | null | null | src/trainingset.cpp | yorickr/NeuralObjectClassification | dfc3893dfd41e6e33ce66a5edc6832a6f3ad0b52 | [
"MIT"
] | null | null | null | #include "../include/trainingset.h"
double angle( Point pt1, Point pt2, Point pt0 ) {
double dx1 = pt1.x - pt0.x;
double dy1 = pt1.y - pt0.y;
double dx2 = pt2.x - pt0.x;
double dy2 = pt2.y - pt0.y;
return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}
void drawSquares( Mat& image, const vector<vector<Point> >& squares ) {
for( size_t i = 0; i < squares.size(); i++ )
{
const Point* p = &squares[i][0];
int n = (int)squares[i].size();
polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, LINE_AA);
}
imshow("Square", image);
}
void read_directory(const string& name, vector<string>& v) {
DIR* dirp = opendir(name.c_str());
struct dirent * dp;
while ((dp = readdir(dirp)) != NULL) {
if ((strcmp(dp->d_name, ".DS_Store") != 0) && (strcmp(dp->d_name, ".") != 0) && (strcmp(dp->d_name, ".."))) {
v.push_back(dp->d_name);
}
}
closedir(dirp);
}
SetEntry::SetEntry(int id, int threshold_value, string label, vector<Mat> images) {
this->id = id;
this->threshold_value = threshold_value;
this->images = images;
this->label = label;
}
bool greatestVector(const vector<cv::Point>& lhs, const vector<cv::Point>& rhs)
{
return lhs.size() < rhs.size();
}
vector<Point> getGreatestVector(vector<vector<Point>> vectors) {
auto result = max_element(vectors.begin(), vectors.end(), greatestVector);
return vectors[distance(vectors.begin(), result)];
}
TrainingSet::TrainingSet(std::string directoryPath) {
this->directoryPath = directoryPath;
vector<string> directories;
read_directory(directoryPath, directories);
for (auto &m : directories) {
vector<string> files;
read_directory(directoryPath + "/" + m, files);
for (auto &n : files) {
filePaths.push_back(make_tuple<string,string>(string(m), string(directoryPath + "/" + m + "/" + n)));
}
}
string last_label = get<0>(filePaths.at(0));
int count = 0;
vector<Mat> images;
for (auto &m : filePaths) {
string &label = get<0>(m);
string &file_path = get<1>(m);
if (strcmp(label.c_str(), last_label.c_str()) != 0) {
// cout << "Label and last " << label << " " << last_label << endl;
int thresh = 25;
image_groups.push_back(SetEntry(count, thresh, last_label, images)); // pass a copy;
images.clear();
last_label = label;
count++;
}
Mat imag = imread(file_path, CV_LOAD_IMAGE_COLOR);
images.push_back(imag);
imgs.push_back(imag);
}
// catch the final one.
int thresh = 25;
image_groups.push_back(SetEntry(count, thresh, last_label, images)); // pass a copy;
}
string TrainingSet::get_label(int i) {
for (SetEntry &s : image_groups) {
if (s.id == i) {
return s.label;
}
}
return "";
}
Mat TrainingSet::get_image(int i) {
return imgs.at(i);
}
pair<Mat, Mat> TrainingSet::compute(double mmPerPixel) {
FeatureExtractor fe(mmPerPixel);
int amount_of_features = 9;
int amount_of_objects = image_groups.size();
int amount_of_images = amount_of_objects * image_groups.at(0).images.size();
// Matrix input_set(amount_of_images, amount_of_features);
// Matrix output_set(amount_of_images, amount_of_objects);
Mat input_set = Mat::zeros( Size(amount_of_features, amount_of_images), CV_32F);
Mat output_set = Mat::zeros( Size(amount_of_objects, amount_of_images), CV_32F);
int i = 0;
for (SetEntry &m : image_groups) {
cout << "Going through SetEntry " << m.label << " " << m.id << " which has a thresh value of " << m.threshold_value << endl;
int count = 0;
for (Mat &img: m.images) {
Mat gray_image;
cvtColor(img, gray_image, CV_BGR2GRAY);
bool circle = fe.calculate_if_circle(gray_image, m.threshold_value);
bool square = fe.calculate_if_square(gray_image, m.threshold_value);
int surface_area = fe.calculate_surface_area(gray_image, m.threshold_value);
int length = fe.calculate_length(gray_image, m.threshold_value);
int width = fe.calculate_width(gray_image, m.threshold_value);
double bending_energy = fe.calculate_bending_energy(gray_image, m.threshold_value);
double keypoint_count = fe.calculate_keypoints(gray_image, m.threshold_value);
double aspect_ratio = fe.calculate_aspect_ratio(gray_image, m.threshold_value);
double avg_gray = fe.calculate_average_gray_value(gray_image, m.threshold_value);
cout << "Image " << count << endl;
cout << "circle\t---\tsquare\t---\tsurface_area\t---\tlength\t---\twidth" << endl;
cout << "----------------------------------------------------" << endl;
cout << circle << "\t\t" << square << "\t\t" << surface_area << "\t\t\t" << length << "\t\t" << width << endl;
cout << "----------------------------------------------------" << endl;
cout << endl;
// add to input_set
input_set.at<float>(i, 0) = (float) circle;
input_set.at<float>(i, 1) = (float) square;
input_set.at<float>(i, 2) = (float) surface_area;
input_set.at<float>(i, 3) = (float) length;
input_set.at<float>(i, 4) = (float) width;
input_set.at<float>(i, 5) = bending_energy;
input_set.at<float>(i, 6) = aspect_ratio;
input_set.at<float>(i, 7) = keypoint_count;
input_set.at<float>(i, 8) = avg_gray;
output_set.at<float>(i, m.id) = (float) 1;
i++;
count++;
}
// cout << endl << endl;
}
return make_pair(input_set, output_set);
}
FeatureExtractor::FeatureExtractor(double mmPerPixel)
{
this->mmPerPixel = mmPerPixel;
}
// give this a gray_image
int FeatureExtractor::calculate_surface_area(Mat &img, int thresh) {
Mat bin;
threshold(img, bin, thresh, 255, THRESH_BINARY);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( bin, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) ); // only find external contours.
int sum = 0;
// Mat drawing = Mat::zeros( bin.size(), CV_8UC3 );
for( size_t i = 0; i< contours.size(); i++ )
{
// Scalar color( rand()&255, rand()&255, rand()&255 );
// drawContours( drawing, contours, i, color, FILLED, 8, hierarchy );
sum+= contourArea(contours[i]);
}
// imshow("Contour", drawing);
// cout << "Sum is " << sum << endl;
return sum * mmPerPixel;
}
// give this a gray_image
bool FeatureExtractor::calculate_if_square(Mat &img, int thresh) {
double aspect_ratio = calculate_aspect_ratio(img, thresh);
bool square = false;
if ((aspect_ratio < 1.15) && (aspect_ratio > 0.85)) {
square = true;
}
return square;
}
bool FeatureExtractor::calculate_if_circle(Mat &img, int thresh) {
Mat gray_image(img);
// GaussianBlur( gray_image, gray_image, Size(9, 9), 2, 2 );
// Mat drawing = Mat::zeros(gray_image.size(), CV_8UC3);
vector<Vec3f> circles;
HoughCircles(gray_image, circles, HOUGH_GRADIENT, 1, 50, thresh, thresh*3, 30, 100);
// for( size_t i = 0; i < circles.size(); i++ )
// {
// Vec3i c = circles[i];
// circle( drawing, Point(c[0], c[1]), c[2], Scalar(0,0,255), 3, LINE_AA);
// circle( drawing, Point(c[0], c[1]), 2, Scalar(0,255,0), 3, LINE_AA);
// }
// imshow("Found circles", drawing);
bool circle = circles.size() > 0;
// cout << "Is circle? " << circle << endl;
return circle;
}
int FeatureExtractor::calculate_length(Mat & img, int thresh)
{
Mat bin;
threshold(img, bin, thresh, 255, THRESH_BINARY);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(bin, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
auto contour = getGreatestVector(contours);
RotatedRect boundaryRotatedBox = minAreaRect(contour);
return boundaryRotatedBox.size.height * mmPerPixel;
}
int FeatureExtractor::calculate_width(Mat & img, int thresh)
{
Mat bin;
threshold(img, bin, thresh, 255, THRESH_BINARY);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(bin, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
auto contour = getGreatestVector(contours);
RotatedRect boundaryRotatedBox = minAreaRect(contour);
return boundaryRotatedBox.size.width * mmPerPixel;
}
double FeatureExtractor::calculate_keypoints(Mat &img, int thresh) {
SimpleBlobDetector::Params params;
// Change thresholds
params.minThreshold = thresh;
params.maxThreshold = 255;
vector<KeyPoint> keypoints;
Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create(params);
detector->detect( img, keypoints);
// Mat im_with_keypoints;
// drawKeypoints( img, keypoints, im_with_keypoints, Scalar(0,0,255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS );
// cout << keypoints.size() << endl;
// Show blobs
// imshow("keypoints", im_with_keypoints );
// waitKey(300);
return (double) keypoints.size();
}
double FeatureExtractor::calculate_aspect_ratio(Mat &img, int thresh) {
Mat bin;
threshold(img, bin, thresh, 255, THRESH_BINARY);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( bin, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) ); // only find external contours.
vector<Point> largest_contour;
// Mat drawing = Mat::zeros( bin.size(), CV_8UC3 );
int last_contour_area = numeric_limits<int>::min();
for( size_t i = 0; i< contours.size(); i++ )
{
// Scalar color( rand()&255, rand()&255, rand()&255 );
// drawContours( drawing, contours, i, color, FILLED, 8, hierarchy );
int area = contourArea(contours[i]);
if (area > last_contour_area) {
largest_contour = contours[i];
last_contour_area = area;
}
}
RotatedRect r = minAreaRect(largest_contour);
// cout << "Rect " << r.size << endl;
int max = r.size.width;
int min = r.size.height;
if (min > max) {
int temp = max;
max = min;
min = temp;
}
return (double)max / min;
}
double FeatureExtractor::calculate_average_gray_value(Mat &img, int thresh) {
int total = img.rows * img.cols;
double avg = 0.0;
for (int r = 0; r < img.rows; r++) {
for (int c = 0; c < img.cols; c++) {
avg += img.at<uchar>(r, c);
}
}
return (double) avg/total;
}
double FeatureExtractor::calculate_bending_energy(Mat & img, int thresh)
{
Mat bin;
threshold(img, bin, thresh, 255, THRESH_BINARY);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(bin, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
/*
Mat drawing = Mat::zeros(bin.size(), CV_8UC3);
for (size_t i = 0; i < contours.size(); i++) {
drawContours(drawing, contours, (int)i, Scalar(rand() % 255, rand() % 255, rand() % 255));
}*/
auto contour = getGreatestVector(contours);
//imshow("Contour: " + to_string(contour.size()), drawing);
return bendingEnergy(contour);
}
int FeatureExtractor::calculate_perimeter(Mat & img, int thresh)
{
Mat bin;
threshold(img, bin, thresh, 255, THRESH_BINARY);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(bin, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
auto contour = getGreatestVector(contours);
return (int)contour.size() * mmPerPixel;
}
| 34.378299 | 133 | 0.621854 | [
"vector"
] |
6be0e78b6db50eab5fc9826d7ebb115062a24bc1 | 2,796 | cpp | C++ | 2d-object-tracking/server/src/application.cpp | cognitivesystems/smartcamera | 5374193260e6385becfe8086a70d21d650314beb | [
"BSD-2-Clause"
] | 1 | 2017-03-27T16:14:59.000Z | 2017-03-27T16:14:59.000Z | 2d-object-tracking/server/src/application.cpp | cognitivesystems/smartcamera | 5374193260e6385becfe8086a70d21d650314beb | [
"BSD-2-Clause"
] | null | null | null | 2d-object-tracking/server/src/application.cpp | cognitivesystems/smartcamera | 5374193260e6385becfe8086a70d21d650314beb | [
"BSD-2-Clause"
] | null | null | null | #include <fstream>
#include <bcm_host.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <thrift/concurrency/ThreadManager.h>
#include <thrift/concurrency/PosixThreadFactory.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TSimpleServer.h>
#include <thrift/server/TThreadPoolServer.h>
#include <thrift/server/TNonblockingServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TTransportUtils.h>
#include <glipf/sources/v4l2-camera.h>
#include <glipf/sources/opencv-video-source.h>
#include "threshold-contours-handler.h"
using glipf::sources::FrameSource;
using glipf::sources::OpenCvVideoSource;
using glipf::sources::V4L2Camera;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace apache::thrift::server;
using std::string;
using std::vector;
int main() {
bcm_host_init();
// Read configuration
std::ifstream ifs("server.json");
boost::property_tree::ptree config;
boost::property_tree::read_json(ifs, config);
vector<GLfloat> intrinsicsData, extrinsicsData;
boost::optional<string> videoFileName = config.get_optional<string>("videoFile");
std::unique_ptr<FrameSource> frameSource;
if (videoFileName)
frameSource.reset(new OpenCvVideoSource(*videoFileName));
else
frameSource.reset(new V4L2Camera(std::make_pair(640, 480)));
for (auto& val : config.get_child("intrinsics"))
intrinsicsData.push_back(val.second.get_value<GLfloat>());
for (auto& val : config.get_child("extrinsics"))
extrinsicsData.push_back(val.second.get_value<GLfloat>());
glm::mat4x3 intrinsicsMatrix =
glm::transpose(glm::make_mat3x4(intrinsicsData.data()));
glm::mat4x4 extrinsicsMatrix =
glm::transpose(glm::make_mat4x4(extrinsicsData.data()));
glm::mat4x3 mvpMatrix = intrinsicsMatrix * extrinsicsMatrix;
glm::mat4 expandedProjectionMatrix(glm::vec4(mvpMatrix[0], 0.0),
glm::vec4(mvpMatrix[1], 0.0),
glm::vec4(mvpMatrix[2], 0.0),
glm::vec4(mvpMatrix[3], 1.0));
// Configure and start Thrift RPC server
boost::shared_ptr<ThresholdContoursHandler> handler(new ThresholdContoursHandler(std::move(frameSource),
expandedProjectionMatrix));
boost::shared_ptr<TProcessor> processor(new glipf::ThresholdContoursProcessor(handler));
boost::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TNonblockingServer server(processor, protocolFactory, 9090);
server.serve();
return 0;
}
| 33.285714 | 110 | 0.712089 | [
"vector"
] |
6be89d8a9f4fb1353c9f563a6f35351a6647993c | 40,943 | cpp | C++ | profiler/src/ProfilerEngine/Datadog.Profiler.Native/CorProfilerCallback.cpp | cwe1ss/dd-trace-dotnet | ed74cf794cb02fb698567052caae973870b82428 | [
"Apache-2.0"
] | null | null | null | profiler/src/ProfilerEngine/Datadog.Profiler.Native/CorProfilerCallback.cpp | cwe1ss/dd-trace-dotnet | ed74cf794cb02fb698567052caae973870b82428 | [
"Apache-2.0"
] | null | null | null | profiler/src/ProfilerEngine/Datadog.Profiler.Native/CorProfilerCallback.cpp | cwe1ss/dd-trace-dotnet | ed74cf794cb02fb698567052caae973870b82428 | [
"Apache-2.0"
] | null | null | null | // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2022 Datadog, Inc.
// from dotnet coreclr includes
#include "cor.h"
#include "corprof.h"
// end
#include "CorProfilerCallback.h"
#include <inttypes.h>
#ifdef _WINDOWS
#include <VersionHelpers.h>
#include <windows.h>
#endif
#include "AppDomainStore.h"
#include "ApplicationStore.h"
#include "ClrLifetime.h"
#include "Configuration.h"
#include "EnvironmentVariables.h"
#include "FrameStore.h"
#include "IMetricsSender.h"
#include "IMetricsSenderFactory.h"
#include "LibddprofExporter.h"
#include "Log.h"
#include "ManagedThreadList.h"
#include "OpSysTools.h"
#include "OsSpecificApi.h"
#include "ProfilerEngineStatus.h"
#include "RuntimeIdStore.h"
#include "SamplesAggregator.h"
#include "StackSamplerLoopManager.h"
#include "StackSnapshotsBufferManager.h"
#include "SymbolsResolver.h"
#include "ThreadsCpuManager.h"
#include "WallTimeProvider.h"
#include "shared/src/native-src/environment_variables.h"
#include "shared/src/native-src/loader.h"
#include "shared/src/native-src/pal.h"
#include "shared/src/native-src/string.h"
// The following macros are used to construct the profiler file:
#ifdef _WINDOWS
#define LIBRARY_FILE_EXTENSION ".dll"
#elif LINUX
#define LIBRARY_FILE_EXTENSION ".so"
#elif MACOS
#define LIBRARY_FILE_EXTENSION ".dylib"
#else
Error("unknown platform");
#endif
#ifdef BIT64
#define PROFILER_LIBRARY_BINARY_FILE_NAME WStr("Datadog.AutoInstrumentation.Profiler.Native.x64" LIBRARY_FILE_EXTENSION)
#else
#define PROFILER_LIBRARY_BINARY_FILE_NAME WStr("Datadog.AutoInstrumentation.Profiler.Native.x86" LIBRARY_FILE_EXTENSION)
#endif
const std::vector<shared::WSTRING> CorProfilerCallback::ManagedAssembliesToLoad_AppDomainDefault_ProcNonIIS = {
WStr("Datadog.AutoInstrumentation.Profiler.Managed"),
};
// None for now:
const std::vector<shared::WSTRING> CorProfilerCallback::ManagedAssembliesToLoad_AppDomainNonDefault_ProcNonIIS;
const std::vector<shared::WSTRING> CorProfilerCallback::ManagedAssembliesToLoad_AppDomainDefault_ProcIIS = {
WStr("Datadog.AutoInstrumentation.Profiler.Managed"),
};
// None for now:
const std::vector<shared::WSTRING> CorProfilerCallback::ManagedAssembliesToLoad_AppDomainNonDefault_ProcIIS;
// Static helpers
IClrLifetime* CorProfilerCallback::GetClrLifetime()
{
return _this->_pClrLifetime.get();
}
// Initialization
CorProfilerCallback* CorProfilerCallback::_this = nullptr;
CorProfilerCallback::CorProfilerCallback()
{
// Keep track of the one and only ICorProfilerCallback implementation.
// It will be used as root for other services
_this = this;
_pClrLifetime = std::make_unique<ClrLifetime>(&_isInitialized);
}
// Cleanup
CorProfilerCallback::~CorProfilerCallback()
{
DisposeInternal();
_this = nullptr;
}
bool CorProfilerCallback::InitializeServices()
{
_metricsSender = IMetricsSenderFactory::Create();
_pConfiguration = std::make_unique<Configuration>();
_pAppDomainStore = std::make_unique<AppDomainStore>(_pCorProfilerInfo);
_pFrameStore = std::make_unique<FrameStore>(_pCorProfilerInfo);
// Create service instances
_pThreadsCpuManager = RegisterService<ThreadsCpuManager>();
_pManagedThreadList = RegisterService<ManagedThreadList>(_pCorProfilerInfo);
_pSymbolsResolver = RegisterService<SymbolsResolver>(_pCorProfilerInfo, _pThreadsCpuManager);
_pStackSnapshotsBufferManager = RegisterService<StackSnapshotsBufferManager>(_pThreadsCpuManager, _pSymbolsResolver);
auto* pRuntimeIdStore = RegisterService<RuntimeIdStore>();
auto* pWallTimeProvider = RegisterService<WallTimeProvider>(_pConfiguration.get(), _pFrameStore.get(), _pAppDomainStore.get(), pRuntimeIdStore);
_pStackSamplerLoopManager = RegisterService<StackSamplerLoopManager>(
_pCorProfilerInfo,
_pConfiguration.get(),
_metricsSender,
_pClrLifetime.get(),
_pThreadsCpuManager,
_pStackSnapshotsBufferManager,
_pManagedThreadList,
_pSymbolsResolver,
pWallTimeProvider);
// The different elements of the libddprof pipeline are created.
// Note: each provider will be added to the aggregator in the Start() function.
if (_pConfiguration->IsFFLibddprofEnabled())
{
_pApplicationStore = std::make_unique<ApplicationStore>(_pConfiguration.get());
_pExporter = std::make_unique<LibddprofExporter>(_pConfiguration.get(), _pApplicationStore.get());
auto* pSamplesAggregrator = RegisterService<SamplesAggregator>(_pConfiguration.get(), _pExporter.get(), _metricsSender.get());
pSamplesAggregrator->Register(pWallTimeProvider);
}
auto started = StartServices();
if (!started)
{
Log::Warn("One or multiple services failed to start. Stopping all services.");
StopServices();
}
return started;
}
bool CorProfilerCallback::StartServices()
{
bool result = true;
bool success = true;
for (auto const& service : _services)
{
auto name = service->GetName();
success = service->Start();
if (success)
{
Log::Info(name, " started successfully.");
}
else
{
Log::Error(name, " failed to start.");
}
result &= success;
}
return result;
}
bool CorProfilerCallback::DisposeServices()
{
bool result = StopServices();
// Delete all services instances in reverse order of their creation
// to avoid using a deleted service...
// keep loader as static singleton for now
shared::Loader::DeleteSingletonInstance();
_services.clear();
_pThreadsCpuManager = nullptr;
_pStackSnapshotsBufferManager = nullptr;
_pStackSamplerLoopManager = nullptr;
_pManagedThreadList = nullptr;
_pSymbolsResolver = nullptr;
return result;
}
bool CorProfilerCallback::StopServices()
{
// We need to destroy items here in the reverse order to what they have
// been initialized in the Initialize() method.
bool result = true;
bool success = true;
// stop all services
for (size_t i = _services.size(); i > 0; i--)
{
const auto& service = _services[i - 1];
const auto* name = service->GetName();
success = service->Stop();
if (success)
{
Log::Info(name, " stopped successfully.");
}
else
{
Log::Error(name, " failed to stop.");
}
result &= success;
}
return result;
}
void CorProfilerCallback::DisposeInternal(void)
{
// This method is called from the destructor as well as from the Shutdown callback.
// Most operations here are idempotent - calling them multiple time is benign.
// However, we defensively use an additional flag to make this entire method idempotent as a whole.
// Note the race here. _isInitialized protects DisposeInternal() from being called multiple times sequentially.
// It does NOT protect against concurrent invocations!
bool isInitialized = _isInitialized.load();
Log::Info("CorProfilerCallback::DisposeInternal() invoked. _isInitialized = ", isInitialized);
if (isInitialized)
{
ProfilerEngineStatus::WriteIsProfilerEngineActive(false);
_isInitialized.store(false);
// From that time, we need to ensure that ALL native threads are stop and don't call back to managed world
// So, don't sleep before stopping the threads
DisposeServices();
ICorProfilerInfo4* pCorProfilerInfo = _pCorProfilerInfo;
if (pCorProfilerInfo != nullptr)
{
pCorProfilerInfo->Release();
_pCorProfilerInfo = nullptr;
}
// So we are about to turn off the Native Profiler Engine.
// We signaled that to the anyone who is interested (e.g. the TraceContextTracking library) using ProfilerEngineStatus::WriteIsProfilerEngineActive(..),
// which included flushing thread buffers. However, it is possible that a reader of ProfilerEngineStatus::GetReadPtrIsProfilerEngineActive()
// (e.g. the TraceContextTracking library) just started doing something that requires the engine to be present.
// Engine unloads are extremely rare, and so components are not expected synchronize with a potential unload process.
// So we will now pause the unload process and allow other threads to run for a long time (hundreds of milliseconds).
// This will allow any users of the Engine who missed the above WriteIsProfilerEngineActive(..) notification to finsh doing whatecer they are doing.
// This is not a guarantee, but it makes problems extremely unlikely.
constexpr std::chrono::microseconds EngineShutdownSafetyPeriodMS = std::chrono::microseconds(500);
Log::Debug("CorProfilerCallback::DisposeInternal(): Starting a pause of ",
EngineShutdownSafetyPeriodMS.count(), " millisecs to allow ongoing Profiler Engine usage operations to complete.");
std::this_thread::sleep_for(EngineShutdownSafetyPeriodMS);
Log::Debug("CorProfilerCallback::DisposeInternal(): Pause completed.");
}
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::QueryInterface(REFIID riid, void** ppvObject)
{
if (ppvObject == nullptr)
{
return E_POINTER;
}
if (riid == __uuidof(IUnknown) || riid == __uuidof(ICorProfilerCallback) // 176FBED1-A55C-4796-98CA-A9DA0EF883E7
|| riid == __uuidof(ICorProfilerCallback2) // 8A8CC829-CCF2-49fe-BBAE-0F022228071A
|| riid == __uuidof(ICorProfilerCallback3) // 4FD2ED52-7731-4b8d-9469-03D2CC3086C5
|| riid == __uuidof(ICorProfilerCallback4) // 7B63B2E3-107D-4d48-B2F6-F61E229470D2
|| riid == __uuidof(ICorProfilerCallback5) // 8DFBA405-8C9F-45F8-BFFA-83B14CEF78B5
|| riid == __uuidof(ICorProfilerCallback6) // FC13DF4B-4448-4F4F-950C-BA8D19D00C36
|| riid == __uuidof(ICorProfilerCallback7) // F76A2DBA-1D52-4539-866C-2AA518F9EFC3
|| riid == __uuidof(ICorProfilerCallback8) // 5BED9B15-C079-4D47-BFE2-215A140C07E0
|| riid == __uuidof(ICorProfilerCallback9) // 27583EC3-C8F5-482F-8052-194B8CE4705A
|| riid == __uuidof(ICorProfilerCallback10)) // CEC5B60E-C69C-495F-87F6-84D28EE16FFB
{
*ppvObject = this;
this->AddRef();
return S_OK;
}
*ppvObject = nullptr;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE CorProfilerCallback::AddRef(void)
{
ULONG refCount = _refCount.fetch_add(1) + 1;
return refCount;
}
ULONG STDMETHODCALLTYPE CorProfilerCallback::Release(void)
{
ULONG refCount = _refCount.fetch_sub(1) - 1;
if (refCount == 0)
{
delete this;
}
return refCount;
}
ULONG STDMETHODCALLTYPE CorProfilerCallback::GetRefCount(void) const
{
ULONG refCount = _refCount.load();
return refCount;
}
void CorProfilerCallback::InspectRuntimeCompatibility(IUnknown* corProfilerInfoUnk)
{
IUnknown* tstVerProfilerInfo;
if (S_OK == corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo11), (void**)&tstVerProfilerInfo))
{
_isNet46OrGreater = true;
Log::Info("ICorProfilerInfo11 available. Profiling API compatibility: .NET Core 5.0 or later.");
tstVerProfilerInfo->Release();
}
else if (S_OK == corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo10), (void**)&tstVerProfilerInfo))
{
_isNet46OrGreater = true;
Log::Info("ICorProfilerInfo10 available. Profiling API compatibility: .NET Core 3.0 or later.");
tstVerProfilerInfo->Release();
}
else if (S_OK == corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo9), (void**)&tstVerProfilerInfo))
{
_isNet46OrGreater = true;
Log::Info("ICorProfilerInfo9 available. Profiling API compatibility: .NET Core 2.2 or later.");
tstVerProfilerInfo->Release();
}
else if (S_OK == corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo8), (void**)&tstVerProfilerInfo))
{
_isNet46OrGreater = true;
Log::Info("ICorProfilerInfo8 available. Profiling API compatibility: .NET Fx 4.7.2 or later.");
tstVerProfilerInfo->Release();
}
else if (S_OK == corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo7), (void**)&tstVerProfilerInfo))
{
_isNet46OrGreater = true;
Log::Info("ICorProfilerInfo7 available. Profiling API compatibility: .NET Fx 4.6.1 or later.");
tstVerProfilerInfo->Release();
}
else if (S_OK == corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo6), (void**)&tstVerProfilerInfo))
{
_isNet46OrGreater = true;
Log::Info("ICorProfilerInfo6 available. Profiling API compatibility: .NET Fx 4.6 or later.");
tstVerProfilerInfo->Release();
}
else if (S_OK == corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo5), (void**)&tstVerProfilerInfo))
{
Log::Info("ICorProfilerInfo5 available. Profiling API compatibility: .NET Fx 4.5.2 or later.");
tstVerProfilerInfo->Release();
}
else if (S_OK == corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo4), (void**)&tstVerProfilerInfo))
{
Log::Info("ICorProfilerInfo4 available. Profiling API compatibility: .NET Fx 4.5 or later.");
tstVerProfilerInfo->Release();
}
else if (S_OK == corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo3), (void**)&tstVerProfilerInfo))
{
Log::Info("ICorProfilerInfo3 available. Profiling API compatibility: .NET Fx 4.0 or later.");
tstVerProfilerInfo->Release();
}
else if (S_OK == corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo2), (void**)&tstVerProfilerInfo))
{
Log::Info("ICorProfilerInfo2 available. Profiling API compatibility: .NET Fx 2.0 or later.");
tstVerProfilerInfo->Release();
}
else if (S_OK == corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo), (void**)&tstVerProfilerInfo))
{
Log::Info("ICorProfilerInfo available. Profiling API compatibility: .NET Fx 2 or later.");
tstVerProfilerInfo->Release();
}
else
{
Log::Info("No ICorProfilerInfoXxx available.");
}
}
const char* CorProfilerCallback::SysInfoProcessorArchitectureToStr(WORD wProcArch)
{
switch (wProcArch)
{
case PROCESSOR_ARCHITECTURE_AMD64:
return "x64 AMD or Intel";
case PROCESSOR_ARCHITECTURE_ARM:
return "ARM";
case PROCESSOR_ARCHITECTURE_ARM64:
return "ARM64";
case PROCESSOR_ARCHITECTURE_IA64:
return "Intel Itanium-based";
case PROCESSOR_ARCHITECTURE_INTEL:
return "x86";
default:
return "Unknown architecture";
}
}
void CorProfilerCallback::InspectProcessorInfo(void)
{
#ifdef _WINDOWS
BOOL isWow64Process;
if (IsWow64Process(GetCurrentProcess(), &isWow64Process))
{
Log::Info("IsWow64Process : ", (isWow64Process ? "True" : "False"));
}
Log::Info("IsWindowsServer: ", (IsWindowsServer() ? "True" : "False"), ".");
SYSTEM_INFO systemInfo;
GetNativeSystemInfo(&systemInfo);
Log::Info("GetNativeSystemInfo results:"
" wProcessorArchitecture=\"",
SysInfoProcessorArchitectureToStr(systemInfo.wProcessorArchitecture), "\"",
"(=", systemInfo.wProcessorArchitecture, ")",
", dwPageSize=", systemInfo.dwPageSize,
", lpMinimumApplicationAddress=0x", std::setw(16), std::setfill('0'), std::hex, systemInfo.lpMinimumApplicationAddress,
", lpMaximumApplicationAddress=0x", std::setw(16), std::setfill('0'), std::hex, systemInfo.lpMaximumApplicationAddress,
", dwActiveProcessorMask=0x", std::hex, systemInfo.dwActiveProcessorMask, std::dec,
", dwNumberOfProcessors=", systemInfo.dwNumberOfProcessors,
", dwProcessorType=", std::dec, systemInfo.dwProcessorType,
", dwAllocationGranularity=", systemInfo.dwAllocationGranularity,
", wProcessorLevel=", systemInfo.wProcessorLevel,
", wProcessorRevision=", std::dec, systemInfo.wProcessorRevision);
#else
// Running under non-Windows OS. Inspect Processor Info is currently not supported
#endif
}
void CorProfilerCallback::InspectRuntimeVersion(ICorProfilerInfo4* pCorProfilerInfo)
{
USHORT clrInstanceId;
COR_PRF_RUNTIME_TYPE runtimeType;
USHORT majorVersion;
USHORT minorVersion;
USHORT buildNumber;
USHORT qfeVersion;
HRESULT hr = pCorProfilerInfo->GetRuntimeInformation(
&clrInstanceId,
&runtimeType,
&majorVersion,
&minorVersion,
&buildNumber,
&qfeVersion,
0,
nullptr,
nullptr);
if (FAILED(hr))
{
Log::Info("Initializing the Profiler: Exact runtime version could not be obtained (0x", std::hex, hr, std::dec, ")");
}
else
{
Log::Info("Initializing the Profiler: Reported runtime version : { clrInstanceId: ", clrInstanceId,
", runtimeType:",
((runtimeType == COR_PRF_DESKTOP_CLR) ? "DESKTOP_CLR"
: (runtimeType == COR_PRF_CORE_CLR)
? "CORE_CLR"
: (std::string("unknown(") + std::to_string(runtimeType) + std::string(")"))),
", majorVersion: ", majorVersion,
", minorVersion: ", minorVersion,
", buildNumber: ", buildNumber,
", qfeVersion: ", qfeVersion,
" }.");
}
}
void CorProfilerCallback::ConfigureDebugLog(void)
{
// For now we want debug log to be ON by default. In future releases, this may require explicit opt-in.
// For that, change 'IsLogDebugEnabledDefault' to be initialized to 'false' by default (@ToDo).
constexpr const bool IsLogDebugEnabledDefault = false;
bool isLogDebugEnabled;
shared::WSTRING isLogDebugEnabledStr = shared::GetEnvironmentValue(EnvironmentVariables::DebugLogEnabled);
// no environment variable set
if (isLogDebugEnabledStr.empty())
{
Log::Info("No \"", EnvironmentVariables::DebugLogEnabled, "\" environment variable has been found.",
" Enable debug log = ", IsLogDebugEnabledDefault, " (default).");
isLogDebugEnabled = IsLogDebugEnabledDefault;
}
else
{
if (!shared::TryParseBooleanEnvironmentValue(isLogDebugEnabledStr, isLogDebugEnabled))
{
// invalid value for environment variable
Log::Info("Non boolean value \"", isLogDebugEnabledStr, "\" for \"",
EnvironmentVariables::DebugLogEnabled, "\" environment variable.",
" Enable debug log = ", IsLogDebugEnabledDefault, " (default).");
isLogDebugEnabled = IsLogDebugEnabledDefault;
}
else
{
// take environment variable into account
Log::Info("Enable debug log = ", isLogDebugEnabled, " from (", EnvironmentVariables::DebugLogEnabled, " environment variable)");
}
}
if (isLogDebugEnabled)
{
Log::EnableDebug();
}
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::Initialize(IUnknown* corProfilerInfoUnk)
{
Log::Info("CorProfilerCallback is initializing.");
ConfigureDebugLog();
// Log some important environment info:
CorProfilerCallback::InspectProcessorInfo();
CorProfilerCallback::InspectRuntimeCompatibility(corProfilerInfoUnk);
// Initialize _pCorProfilerInfo:
if (corProfilerInfoUnk == nullptr)
{
Log::Info("No IUnknown is passed to CorProfilerCallback::Initialize(). The profiler will not run.");
return E_FAIL;
}
HRESULT hr = corProfilerInfoUnk->QueryInterface(__uuidof(ICorProfilerInfo4), (void**)&_pCorProfilerInfo);
if (hr == E_NOINTERFACE)
{
Log::Error("This runtime does not support any ICorProfilerInfo4+ interface. .NET Framework 4.5 or later is required.");
return E_FAIL;
}
else if (FAILED(hr))
{
Log::Error("An error occurred while obtaining the ICorProfilerInfo interface from the CLR: 0x", std::hex, hr, std::dec, ".");
return E_FAIL;
}
// Log some more important environment info:
CorProfilerCallback::InspectRuntimeVersion(_pCorProfilerInfo);
// Init global state:
OpSysTools::InitHighPrecisionTimer();
// Init global services:
if (!InitializeServices())
{
Log::Error("Failed to initialize all services (at least one failed). Stopping the profiler initialization.");
return E_FAIL;
}
shared::LoaderResourceMonikerIDs loaderResourceMonikerIDs;
OsSpecificApi::InitializeLoaderResourceMonikerIDs(&loaderResourceMonikerIDs);
// Loader options
const auto loader_rewrite_module_entrypoint_enabled = shared::GetEnvironmentValue(shared::environment::loader_rewrite_module_entrypoint_enabled);
const auto loader_rewrite_module_initializer_enabled = shared::GetEnvironmentValue(shared::environment::loader_rewrite_module_initializer_enabled);
const auto loader_rewrite_mscorlib_enabled = shared::GetEnvironmentValue(shared::environment::loader_rewrite_mscorlib_enabled);
const auto loader_ngen_enabled = shared::GetEnvironmentValue(shared::environment::loader_ngen_enabled);
shared::LoaderOptions loaderOptions;
loaderOptions.IsNet46OrGreater = _isNet46OrGreater;
loaderOptions.RewriteModulesEntrypoint = loader_rewrite_module_entrypoint_enabled != WStr("0") && loader_rewrite_module_entrypoint_enabled != WStr("false");
loaderOptions.RewriteModulesInitializers = loader_rewrite_module_initializer_enabled != WStr("0") && loader_rewrite_module_initializer_enabled != WStr("false");
loaderOptions.RewriteMSCorLibMethods = loader_rewrite_mscorlib_enabled != WStr("0") && loader_rewrite_mscorlib_enabled != WStr("false");
loaderOptions.DisableNGENImagesSupport = loader_ngen_enabled == WStr("0") || loader_ngen_enabled == WStr("false");
loaderOptions.LogDebugIsEnabled = Log::IsDebugEnabled();
loaderOptions.LogDebugCallback = [](const std::string& str) { Log::Debug(str); };
loaderOptions.LogInfoCallback = [](const std::string& str) { Log::Info(str); };
loaderOptions.LogErrorCallback = [](const std::string& str) { Log::Error(str); };
shared::Loader::CreateNewSingletonInstance(_pCorProfilerInfo,
loaderOptions,
loaderResourceMonikerIDs,
PROFILER_LIBRARY_BINARY_FILE_NAME,
ManagedAssembliesToLoad_AppDomainDefault_ProcNonIIS,
ManagedAssembliesToLoad_AppDomainNonDefault_ProcNonIIS,
ManagedAssembliesToLoad_AppDomainDefault_ProcIIS,
ManagedAssembliesToLoad_AppDomainNonDefault_ProcIIS);
// Configure which profiler callbacks we want to receive by setting the event mask:
const DWORD eventMask =
shared::Loader::GetSingletonInstance()->GetLoaderProfilerEventMask() |
COR_PRF_MONITOR_THREADS |
COR_PRF_ENABLE_STACK_SNAPSHOT;
hr = _pCorProfilerInfo->SetEventMask(eventMask);
if (FAILED(hr))
{
Log::Error("SetEventMask(0x", std::hex, eventMask, ") returned an unexpected result: 0x", std::hex, hr, std::dec, ".");
return E_FAIL;
}
// Initialization complete:
_isInitialized.store(true);
ProfilerEngineStatus::WriteIsProfilerEngineActive(true);
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::Shutdown(void)
{
Log::Info("CorProfilerCallback::Shutdown()");
// dump all threads time
_pThreadsCpuManager->LogCpuTimes();
// DisposeInternal() already respects the _isInitialized flag.
// If any code is added directly here, remember to respect _isInitialized as required.
DisposeInternal();
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::AppDomainCreationStarted(AppDomainID appDomainId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::AppDomainCreationFinished(AppDomainID appDomainId, HRESULT hrStatus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::AppDomainShutdownStarted(AppDomainID appDomainId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::AppDomainShutdownFinished(AppDomainID appDomainId, HRESULT hrStatus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::AssemblyLoadStarted(AssemblyID assemblyId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::AssemblyLoadFinished(AssemblyID assemblyId, HRESULT hrStatus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::AssemblyUnloadStarted(AssemblyID assemblyId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::AssemblyUnloadFinished(AssemblyID assemblyId, HRESULT hrStatus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ModuleLoadStarted(ModuleID moduleId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ModuleLoadFinished(ModuleID moduleId, HRESULT hrStatus)
{
if (false == _isInitialized.load())
{
// If this CorProfilerCallback has not yet initialized, or if it has already shut down, then this callback is a No-Op.
return S_OK;
}
if (_pConfiguration->IsFFLibddprofEnabled())
{
return S_OK;
}
return shared::Loader::GetSingletonInstance()->InjectLoaderToModuleInitializer(moduleId);
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ModuleUnloadStarted(ModuleID moduleId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ModuleUnloadFinished(ModuleID moduleId, HRESULT hrStatus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ModuleAttachedToAssembly(ModuleID moduleId, AssemblyID AssemblyId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ClassLoadStarted(ClassID classId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ClassLoadFinished(ClassID classId, HRESULT hrStatus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ClassUnloadStarted(ClassID classId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ClassUnloadFinished(ClassID classId, HRESULT hrStatus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::FunctionUnloadStarted(FunctionID functionId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::JITCompilationStarted(FunctionID functionId, BOOL fIsSafeToBlock)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::JITCompilationFinished(FunctionID functionId, HRESULT hrStatus, BOOL fIsSafeToBlock)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::JITCachedFunctionSearchStarted(FunctionID functionId, BOOL* pbUseCachedFunction)
{
if (false == _isInitialized.load())
{
// If this CorProfilerCallback has not yet initialized, or if it has already shut down, then this callback is a No-Op.
return S_OK;
}
if (_pConfiguration->IsFFLibddprofEnabled())
{
return S_OK;
}
return shared::Loader::GetSingletonInstance()->HandleJitCachedFunctionSearchStarted(functionId, pbUseCachedFunction);
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::JITCachedFunctionSearchFinished(FunctionID functionId, COR_PRF_JIT_CACHE result)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::JITFunctionPitched(FunctionID functionId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::JITInlining(FunctionID callerId, FunctionID calleeId, BOOL* pfShouldInline)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ThreadCreated(ThreadID threadId)
{
Log::Debug("Callback invoked: ThreadCreated(threadId=0x", std::hex, threadId, std::dec, ")");
if (false == _isInitialized.load())
{
// If this CorProfilerCallback has not yet initialized, or if it has already shut down, then this callback is a No-Op.
return S_OK;
}
_pManagedThreadList->GetOrCreateThread(threadId);
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ThreadDestroyed(ThreadID threadId)
{
Log::Debug("Callback invoked: ThreadDestroyed(threadId=0x", std::hex, threadId, std::dec, ")");
if (false == _isInitialized.load())
{
// If this CorProfilerCallback has not yet initialized, or if it has already shut down, then this callback is a No-Op.
return S_OK;
}
ManagedThreadInfo* pThreadInfo;
if (_pManagedThreadList->UnregisterThread(threadId, &pThreadInfo))
{
// The docs require that we do not allow to destroy a thread while it is being stack-walked.
// TO ensure this, SetThreadDestroyed(..) acquires the StackWalkLock associated with this ThreadInfo.
pThreadInfo->SetThreadDestroyed();
pThreadInfo->Release();
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ThreadAssignedToOSThread(ThreadID managedThreadId, DWORD osThreadId)
{
Log::Debug("Callback invoked: ThreadAssignedToOSThread(managedThreadId=0x", std::hex, managedThreadId, ", osThreadId=", std::dec, osThreadId, ")");
if (false == _isInitialized.load())
{
// If this CorProfilerCallback has not yet initialized, or if it has already shut down, then this callback is a No-Op.
return S_OK;
}
HANDLE origOsThreadHandle;
HRESULT hr = _pCorProfilerInfo->GetHandleFromThread(managedThreadId, &origOsThreadHandle);
if (hr != S_OK)
{
Log::Debug("GetHandleFromThread() failed.");
return hr;
}
HANDLE dupOsThreadHandle;
#ifdef _WINDOWS
HANDLE hProcess = OpSysTools::GetCurrentProcess();
auto success = ::DuplicateHandle(hProcess, origOsThreadHandle, hProcess, &dupOsThreadHandle, THREAD_ALL_ACCESS, false, 0);
if (!success)
{
Log::Debug("DuplicateHandle() failed.");
return E_FAIL;
}
#else
dupOsThreadHandle = origOsThreadHandle;
#endif
_pManagedThreadList->SetThreadOsInfo(managedThreadId, osThreadId, dupOsThreadHandle);
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ThreadNameChanged(ThreadID threadId, ULONG cchName, WCHAR name[])
{
if (false == _isInitialized.load())
{
// If this CorProfilerCallback has not yet initialized, or if it has already shut down, then this callback is a No-Op.
return S_OK;
}
auto pThreadName = (cchName == 0)
? new shared::WSTRING()
: new shared::WSTRING(name, cchName);
Log::Debug("CorProfilerCallback::ThreadNameChanged(threadId=0x", std::hex, threadId, std::dec, ", name=\"", *pThreadName, "\")");
_pManagedThreadList->SetThreadName(threadId, pThreadName);
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RemotingClientInvocationStarted(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RemotingClientSendingMessage(GUID* pCookie, BOOL fIsAsync)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RemotingClientReceivingReply(GUID* pCookie, BOOL fIsAsync)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RemotingClientInvocationFinished(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RemotingServerReceivingMessage(GUID* pCookie, BOOL fIsAsync)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RemotingServerInvocationStarted(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RemotingServerInvocationReturned(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RemotingServerSendingReply(GUID* pCookie, BOOL fIsAsync)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::UnmanagedToManagedTransition(FunctionID functionId, COR_PRF_TRANSITION_REASON reason)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ManagedToUnmanagedTransition(FunctionID functionId, COR_PRF_TRANSITION_REASON reason)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RuntimeSuspendStarted(COR_PRF_SUSPEND_REASON suspendReason)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RuntimeSuspendFinished(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RuntimeSuspendAborted(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RuntimeResumeStarted(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RuntimeResumeFinished(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RuntimeThreadSuspended(ThreadID threadId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RuntimeThreadResumed(ThreadID threadId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::MovedReferences(ULONG cMovedObjectIDRanges, ObjectID oldObjectIDRangeStart[], ObjectID newObjectIDRangeStart[], ULONG cObjectIDRangeLength[])
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ObjectAllocated(ObjectID objectId, ClassID classId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ObjectsAllocatedByClass(ULONG cClassCount, ClassID classIds[], ULONG cObjects[])
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ObjectReferences(ObjectID objectId, ClassID classId, ULONG cObjectRefs, ObjectID objectRefIds[])
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RootReferences(ULONG cRootRefs, ObjectID rootRefIds[])
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionThrown(ObjectID thrownObjectId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionSearchFunctionEnter(FunctionID functionId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionSearchFunctionLeave(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionSearchFilterEnter(FunctionID functionId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionSearchFilterLeave(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionSearchCatcherFound(FunctionID functionId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionOSHandlerEnter(UINT_PTR __unused)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionOSHandlerLeave(UINT_PTR __unused)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionUnwindFunctionEnter(FunctionID functionId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionUnwindFunctionLeave(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionUnwindFinallyEnter(FunctionID functionId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionUnwindFinallyLeave(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionCatcherEnter(FunctionID functionId, ObjectID objectId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionCatcherLeave(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::COMClassicVTableCreated(ClassID wrappedClassId, REFGUID implementedIID, void* pVTable, ULONG cSlots)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::COMClassicVTableDestroyed(ClassID wrappedClassId, REFGUID implementedIID, void* pVTable)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionCLRCatcherFound(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ExceptionCLRCatcherExecute(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::GarbageCollectionStarted(int cGenerations, BOOL generationCollected[], COR_PRF_GC_REASON reason)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::SurvivingReferences(ULONG cSurvivingObjectIDRanges, ObjectID objectIDRangeStart[], ULONG cObjectIDRangeLength[])
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::GarbageCollectionFinished(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::FinalizeableObjectQueued(DWORD finalizerFlags, ObjectID objectID)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::RootReferences2(ULONG cRootRefs, ObjectID rootRefIds[], COR_PRF_GC_ROOT_KIND rootKinds[], COR_PRF_GC_ROOT_FLAGS rootFlags[], UINT_PTR rootIds[])
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::HandleCreated(GCHandleID handleId, ObjectID initialObjectId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::HandleDestroyed(GCHandleID handleId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::InitializeForAttach(IUnknown* pCorProfilerInfoUnk, void* pvClientData, UINT cbClientData)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ProfilerAttachComplete(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ProfilerDetachSucceeded(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ReJITCompilationStarted(FunctionID functionId, ReJITID rejitId, BOOL fIsSafeToBlock)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::GetReJITParameters(ModuleID moduleId, mdMethodDef methodId, ICorProfilerFunctionControl* pFunctionControl)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ReJITCompilationFinished(FunctionID functionId, ReJITID rejitId, HRESULT hrStatus, BOOL fIsSafeToBlock)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ReJITError(ModuleID moduleId, mdMethodDef methodId, FunctionID functionId, HRESULT hrStatus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::MovedReferences2(ULONG cMovedObjectIDRanges, ObjectID oldObjectIDRangeStart[], ObjectID newObjectIDRangeStart[], SIZE_T cObjectIDRangeLength[])
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::SurvivingReferences2(ULONG cSurvivingObjectIDRanges, ObjectID objectIDRangeStart[], SIZE_T cObjectIDRangeLength[])
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ConditionalWeakTableElementReferences(ULONG cRootRefs, ObjectID keyRefIds[], ObjectID valueRefIds[], GCHandleID rootIds[])
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::GetAssemblyReferences(const WCHAR* wszAssemblyPath, ICorProfilerAssemblyReferenceProvider* pAsmRefProvider)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::ModuleInMemorySymbolsUpdated(ModuleID moduleId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::DynamicMethodJITCompilationStarted(FunctionID functionId, BOOL fIsSafeToBlock, LPCBYTE pILHeader, ULONG cbILHeader)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::DynamicMethodJITCompilationFinished(FunctionID functionId, HRESULT hrStatus, BOOL fIsSafeToBlock)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::DynamicMethodUnloaded(FunctionID functionId)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::EventPipeEventDelivered(EVENTPIPE_PROVIDER provider,
DWORD eventId,
DWORD eventVersion,
ULONG cbMetadataBlob,
LPCBYTE metadataBlob,
ULONG cbEventData,
LPCBYTE eventData,
LPCGUID pActivityId,
LPCGUID pRelatedActivityId,
ThreadID eventThread,
ULONG numStackFrames,
UINT_PTR stackFrames[])
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfilerCallback::EventPipeProviderCreated(EVENTPIPE_PROVIDER provider)
{
return S_OK;
}
| 34.147623 | 191 | 0.712429 | [
"vector"
] |
6beeab6b83fcd50248359092f5db9c4cbac99756 | 3,159 | cpp | C++ | Alien Engine/Alien Engine/PanelLayout.cpp | OverPowered-Team/Alien-GameEngine | 713a8846a95fdf253d0869bdcad4ecd006b2e166 | [
"MIT"
] | 7 | 2020-02-20T15:11:11.000Z | 2020-05-19T00:29:04.000Z | Alien Engine/Alien Engine/PanelLayout.cpp | OverPowered-Team/Alien-GameEngine | 713a8846a95fdf253d0869bdcad4ecd006b2e166 | [
"MIT"
] | 125 | 2020-02-29T17:17:31.000Z | 2020-05-06T19:50:01.000Z | Alien Engine/Alien Engine/PanelLayout.cpp | OverPowered-Team/Alien-GameEngine | 713a8846a95fdf253d0869bdcad4ecd006b2e166 | [
"MIT"
] | 1 | 2020-05-19T00:29:06.000Z | 2020-05-19T00:29:06.000Z | #include "PanelLayout.h"
#include "Application.h"
#include "ShortCutManager.h"
#include "ModuleUI.h"
#include "mmgr/mmgr.h"
PanelLayout::PanelLayout(const std::string& panel_name, const SDL_Scancode& key1_down, const SDL_Scancode& key2_repeat, const SDL_Scancode& key3_repeat_extra)
: Panel(panel_name, key1_down, key2_repeat, key3_repeat_extra)
{
shortcut = App->shortcut_manager->AddShortCut("Edit Layout", key1_down, std::bind(&PanelLayout::ChangePanel, this), key2_repeat, key3_repeat_extra);
}
PanelLayout::~PanelLayout()
{
}
void PanelLayout::PanelLogic()
{
if (is_editor_panel) {
PanelLayoutEditor();
}
else {
PanelSaveNewLayout();
}
}
void PanelLayout::ChangePanel()
{
enabled = !enabled;
is_editor_panel = true;
}
void PanelLayout::PanelLayoutEditor()
{
ImGui::OpenPopup(panel_name.c_str());
ImGui::SetNextWindowSize({ 270, 200 });
if (ImGui::BeginPopupModal(panel_name.c_str(), &enabled, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove))
{
ImGui::BeginChild("", { 260,0 }, true, ImGuiWindowFlags_AlwaysVerticalScrollbar);
ImGui::Text("");
ImGui::SameLine(23);
ImGui::Text("Layout Name");
ImGui::Spacing();
std::vector<Layout*>::iterator item = App->ui->layouts.begin();
for (; item != App->ui->layouts.end(); ++item) {
if (*item != nullptr) {
if ((*item)->name == "Default")
continue;
ImGui::Text("");
ImGui::SameLine(5);
ImGui::SetNextItemWidth(120);
static char name[20];
memcpy(name, (*item)->name.data(), 20);
ImGui::PushID(*item);
if (ImGui::InputText("##Layout Name", name, 20, ImGuiInputTextFlags_AutoSelectAll)) {
(*item)->name = std::string(name);
}
ImGui::PopID();
ImGui::SameLine(142);
ImGui::PushID(item - App->ui->layouts.begin());
if (ImGui::Button("Remove Layout")) {
ImGui::PopID();
ImGui::EndChild();
ImGui::EndPopup();
if ((*item) == App->ui->active_layout) {
App->ui->ResetImGui();
App->ui->DeleteLayout(*item);
App->ui->LoadActiveLayout();
ImGui::NewFrame();
}
else {
App->ui->DeleteLayout(*item);
}
return;
}
ImGui::PopID();
}
}
ImGui::EndChild();
ImGui::EndPopup();
}
}
void PanelLayout::PanelSaveNewLayout()
{
ImGui::OpenPopup(panel_name.c_str());
ImGui::SetNextWindowSize({ 218, 85 });
if (ImGui::BeginPopupModal(panel_name.c_str(), &enabled, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove))
{
ImGui::SetNextItemWidth(120);
static char name[20];
memcpy(name, new_layout_name.data(), 20);
if (ImGui::InputText("Layout Name", name, 20, ImGuiInputTextFlags_AutoSelectAll)) {
new_layout_name = std::string(name);
}
ImGui::Spacing();
ImGui::NewLine();
ImGui::SameLine(80);
if (ImGui::Button("Create")) {
ChangeEnable();
Layout* layout = new Layout(new_layout_name.data());
App->ui->layouts.push_back(layout);
layout->active = true;
App->ui->active_layout->active = false;
App->ui->active_layout = layout;
App->ui->SaveLayout(layout);
new_layout_name = "New Layout";
}
ImGui::EndPopup();
}
}
| 26.771186 | 158 | 0.667616 | [
"vector"
] |
6bef240d628702335522cf13ed71ef0455a5a9c8 | 2,600 | hh | C++ | gltracesim/src/vmemory.hh | JRPan/gltracesim | 79708f503047922538ca2983392c0e9f99a4345a | [
"BSD-3-Clause"
] | 11 | 2018-06-12T01:38:52.000Z | 2021-05-21T19:53:27.000Z | gltracesim/src/vmemory.hh | JRPan/gltracesim | 79708f503047922538ca2983392c0e9f99a4345a | [
"BSD-3-Clause"
] | null | null | null | gltracesim/src/vmemory.hh | JRPan/gltracesim | 79708f503047922538ca2983392c0e9f99a4345a | [
"BSD-3-Clause"
] | 3 | 2019-03-31T15:00:50.000Z | 2021-12-07T22:05:03.000Z | #ifndef __GLTRACESIM_VMEMORY_HH__
#define __GLTRACESIM_VMEMORY_HH__
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <bitset>
#include <random>
#include <json/json.h>
#include "util/addr_range.hh"
#include "util/addr_range_map.hh"
namespace gltracesim {
class VirtualMemoryManager;
/**
* @brief
*/
typedef std::unique_ptr<VirtualMemoryManager> VirtualMemoryManagerPtr;
/**
* @brief The VirtualMemoryManager class
*
* Reverse memory allocator, given a virtual address, allocate a fake physical
* address.
*
*/
class VirtualMemoryManager
{
public:
/**
* @brief VirtualMemoryManager
* @param name
*/
VirtualMemoryManager(const Json::Value ¶ms);
/**
* @brief ~VirtualMemoryManager
*/
~VirtualMemoryManager();
public:
/**
* @brief get_name
* @return
*/
uint64_t translate(uint64_t vaddr);
/**
* @brief get_name
* @return
*/
void alloc(const AddrRange &vaddr_range);
/**
* @brief get_name
* @return
*/
void free(const AddrRange &vaddr_range);
private:
/**
* @brief get_free_page
* @param i
* @param j
*/
void find_free_page(size_t &i, size_t &j);
/**
* @brief get_num_free_pages
* @return
*/
size_t get_num_free_pages() const;
/**
* @brief get_page_addr
* @param addr
* @return
*/
uint64_t get_page_addr(uint64_t addr) const
{
return (addr & page_addr_umask);
}
/**
* @brief get_page_offset
* @param addr
* @return
*/
uint64_t get_page_offset(uint64_t addr) const
{
return (addr & ~page_addr_umask);
}
private:
/**
* @brief base_addr
*/
uint64_t base_addr;
/**
* @brief page_size
*/
uint64_t page_size;
/**
* @brief page_addr_umask
*/
uint64_t page_addr_umask;
/**
* @brief fragmented
*/
bool fragmented;
/**
* @brief rand_engine
*/
std::mt19937 rand_engine;
/**
* @brief translation_t
*/
typedef AddrRangeMap<uint64_t> translation_t;
/**
* @brief translation
*/
translation_t translation;
#define STATE_T_SIZE 256
/**
* @brief state_t
*
* 256 * 4kB page == 1MB state;
*
*/
typedef std::bitset<STATE_T_SIZE> state_t;
/**
* @brief free_list
*/
std::vector<state_t> free_list;
/**
* @brief allocated
*/
size_t allocated;
};
} // end namespace gltracesim
#endif // __GLTRACESIM_VMEMORY_HH__
| 15.853659 | 78 | 0.589615 | [
"vector"
] |
6bf706c8a2a87e0759b7d7aa37cfbcd97825d60a | 3,632 | cc | C++ | zircon/system/utest/sysinfo/main.cc | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 1 | 2019-10-09T10:50:57.000Z | 2019-10-09T10:50:57.000Z | zircon/system/utest/sysinfo/main.cc | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 5 | 2020-09-06T09:02:06.000Z | 2022-03-02T04:44:22.000Z | zircon/system/utest/sysinfo/main.cc | ZVNexus/fuchsia | c5610ad15208208c98693618a79c705af935270c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Fuchsia 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 <fcntl.h>
#include <unistd.h>
#include <fuchsia/sysinfo/c/fidl.h>
#include <lib/fdio/fd.h>
#include <lib/fdio/fdio.h>
#include <lib/fdio/directory.h>
#include <lib/zx/channel.h>
#include <zircon/boot/image.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/object.h>
#include <unittest/unittest.h>
#define SYSINFO_PATH "/dev/misc/sysinfo"
bool get_root_resource_succeeds() {
BEGIN_TEST;
// Get the resource handle from the driver.
int fd = open(SYSINFO_PATH, O_RDWR);
ASSERT_GE(fd, 0, "Can't open sysinfo");
zx::channel channel;
ASSERT_EQ(fdio_get_service_handle(fd, channel.reset_and_get_address()), ZX_OK,
"Failed to get channel");
zx_handle_t root_resource;
zx_status_t status;
ASSERT_EQ(fuchsia_sysinfo_DeviceGetRootResource(channel.get(), &status, &root_resource), ZX_OK,
"Failed to get root resource");
ASSERT_EQ(status, ZX_OK, "Failed to get root resource");
// Make sure it's a resource with the expected rights.
zx_info_handle_basic_t info;
ASSERT_EQ(zx_object_get_info(root_resource, ZX_INFO_HANDLE_BASIC, &info,
sizeof(info), nullptr, nullptr),
ZX_OK, "Can't get handle info");
EXPECT_EQ(info.type, ZX_OBJ_TYPE_RESOURCE, "Unexpected type");
EXPECT_EQ(info.rights, ZX_RIGHT_TRANSFER, "Unexpected rights");
// Clean up.
EXPECT_EQ(zx_handle_close(root_resource), ZX_OK);
END_TEST;
}
bool get_board_name_succeeds() {
BEGIN_TEST;
// Get the resource handle from the driver.
int fd = open(SYSINFO_PATH, O_RDWR);
ASSERT_GE(fd, 0, "Can't open sysinfo");
zx::channel channel;
ASSERT_EQ(fdio_get_service_handle(fd, channel.reset_and_get_address()), ZX_OK,
"Failed to get channel");
// Test fuchsia_sysinfo_DeviceGetBoardName().
char board_name[ZBI_BOARD_NAME_LEN];
zx_status_t status;
size_t actual_size;
zx_status_t fidl_status = fuchsia_sysinfo_DeviceGetBoardName(channel.get(), &status, board_name,
sizeof(board_name), &actual_size);
ASSERT_EQ(fidl_status, ZX_OK, "Failed to get board name");
ASSERT_EQ(status, ZX_OK, "Failed to get board name");
ASSERT_LE(actual_size, sizeof(board_name), "GetBoardName returned too much data");
EXPECT_NE(0, board_name[0], "board name is empty");
END_TEST;
}
bool get_interrupt_controller_info_succeeds() {
BEGIN_TEST;
// Get the resource handle from the driver.
int fd = open(SYSINFO_PATH, O_RDWR);
ASSERT_GE(fd, 0, "Can't open sysinfo");
zx::channel channel;
ASSERT_EQ(fdio_get_service_handle(fd, channel.reset_and_get_address()), ZX_OK,
"Failed to get channel");
// Test fuchsia_sysinfo_DeviceGetInterruptControllerInfo().
fuchsia_sysinfo_InterruptControllerInfo info;
zx_status_t status;
ASSERT_EQ(fuchsia_sysinfo_DeviceGetInterruptControllerInfo(channel.get(), &status, &info),
ZX_OK, "Failed to get interrupt controller info");
ASSERT_EQ(status, ZX_OK, "Failed to get interrupt controller info");
EXPECT_NE(info.type, fuchsia_sysinfo_InterruptControllerType_UNKNOWN,
"interrupt controller type is unknown");
END_TEST;
}
BEGIN_TEST_CASE(sysinfo_tests)
RUN_TEST(get_root_resource_succeeds)
RUN_TEST(get_board_name_succeeds)
RUN_TEST(get_interrupt_controller_info_succeeds)
END_TEST_CASE(sysinfo_tests)
| 34.923077 | 100 | 0.706222 | [
"object"
] |
6bf71496898aac69dcd61011b3915bd9a2258c16 | 1,244 | cpp | C++ | sdk/keyvault/azure-security-keyvault-keys/src/key_vault_key.cpp | katmsft/azure-sdk-for-cpp | d99f3ab8e62fff5c65c49aea91aba3c2a422a7d1 | [
"MIT"
] | null | null | null | sdk/keyvault/azure-security-keyvault-keys/src/key_vault_key.cpp | katmsft/azure-sdk-for-cpp | d99f3ab8e62fff5c65c49aea91aba3c2a422a7d1 | [
"MIT"
] | null | null | null | sdk/keyvault/azure-security-keyvault-keys/src/key_vault_key.cpp | katmsft/azure-sdk-for-cpp | d99f3ab8e62fff5c65c49aea91aba3c2a422a7d1 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#include "azure/keyvault/keys/key_vault_key.hpp"
#include <azure/core/internal/json.hpp>
using namespace Azure::Security::KeyVault::Keys;
namespace {
void ParseStringOperationsToKeyOperations(
std::vector<KeyOperation>& keyOperations,
std::vector<std::string> const& stringOperations)
{
for (std::string const& operation : stringOperations)
{
keyOperations.emplace_back(KeyOperation(operation));
}
}
} // namespace
KeyVaultKey Details::KeyVaultKeyDeserialize(
std::string const& name,
Azure::Core::Http::RawResponse const& rawResponse)
{
auto body = rawResponse.GetBody();
auto jsonParser = Azure::Core::Internal::Json::json::parse(body);
KeyVaultKey key(name);
auto const& jsonKey = jsonParser["key"];
{
auto keyOperationVector = jsonKey["key_ops"].get<std::vector<std::string>>();
std::vector<KeyOperation> keyOperations;
ParseStringOperationsToKeyOperations(keyOperations, keyOperationVector);
key.Key.SetKeyOperations(keyOperations);
}
key.Key.Id = jsonKey["kid"].get<std::string>();
key.Key.KeyType = Details::KeyTypeFromString(jsonKey["kty"].get<std::string>());
return key;
}
| 28.930233 | 82 | 0.731511 | [
"vector"
] |
6bfa872294a0a647999df19bfbe444c69aeea472 | 13,522 | cpp | C++ | geobuf.cpp | pavanraotk/tippecanoe | d64ac19f115bef509f34cfc685ff27644e033e3c | [
"BSD-2-Clause"
] | null | null | null | geobuf.cpp | pavanraotk/tippecanoe | d64ac19f115bef509f34cfc685ff27644e033e3c | [
"BSD-2-Clause"
] | null | null | null | geobuf.cpp | pavanraotk/tippecanoe | d64ac19f115bef509f34cfc685ff27644e033e3c | [
"BSD-2-Clause"
] | null | null | null | #include <stdio.h>
#include <string>
#include <limits.h>
#include <pthread.h>
#include "mvt.hpp"
#include "serial.hpp"
#include "geobuf.hpp"
#include "geojson.hpp"
#include "projection.hpp"
#include "main.hpp"
#include "protozero/varint.hpp"
#include "protozero/pbf_reader.hpp"
#include "protozero/pbf_writer.hpp"
#include "milo/dtoa_milo.h"
#include "jsonpull/jsonpull.h"
#define POINT 0
#define MULTIPOINT 1
#define LINESTRING 2
#define MULTILINESTRING 3
#define POLYGON 4
#define MULTIPOLYGON 5
struct queued_feature {
protozero::pbf_reader pbf{};
size_t dim = 0;
double e = 0;
std::vector<std::string> *keys = NULL;
std::vector<struct serialization_state> *sst = NULL;
int layer = 0;
std::string layername = "";
};
static std::vector<queued_feature> feature_queue;
void ensureDim(size_t dim) {
if (dim < 2) {
fprintf(stderr, "Geometry has fewer than 2 dimensions: %zu\n", dim);
exit(EXIT_FAILURE);
}
}
serial_val readValue(protozero::pbf_reader &pbf) {
serial_val sv;
sv.type = mvt_null;
sv.s = "null";
while (pbf.next()) {
switch (pbf.tag()) {
case 1:
sv.type = mvt_string;
sv.s = pbf.get_string();
break;
case 2:
sv.type = mvt_double;
sv.s = milo::dtoa_milo(pbf.get_double());
break;
case 3:
sv.type = mvt_double;
sv.s = std::to_string(pbf.get_uint64());
break;
case 4:
sv.type = mvt_double;
sv.s = std::to_string(-(long long) pbf.get_uint64());
break;
case 5:
sv.type = mvt_bool;
if (pbf.get_bool()) {
sv.s = "true";
} else {
sv.s = "false";
}
break;
case 6:
sv.type = mvt_string; // stringified JSON
sv.s = pbf.get_string();
if (sv.s == "null") {
sv.type = mvt_null;
}
break;
default:
pbf.skip();
}
}
return sv;
}
drawvec readPoint(std::vector<long long> &coords, size_t dim, double e) {
ensureDim(dim);
long long x, y;
projection->project(coords[0] / e, coords[1] / e, 32, &x, &y);
drawvec dv;
dv.push_back(draw(VT_MOVETO, x, y));
return dv;
}
drawvec readLinePart(std::vector<long long> &coords, size_t dim, double e, size_t start, size_t end, bool closed) {
ensureDim(dim);
drawvec dv;
std::vector<long long> prev;
std::vector<double> p;
prev.resize(dim);
p.resize(dim);
for (size_t i = start; i + dim - 1 < end; i += dim) {
if (i + dim - 1 >= coords.size()) {
fprintf(stderr, "Internal error: line segment %zu vs %zu\n", i + dim - 1, coords.size());
exit(EXIT_FAILURE);
}
for (size_t d = 0; d < dim; d++) {
prev[d] += coords[i + d];
p[d] = prev[d] / e;
}
long long x, y;
projection->project(p[0], p[1], 32, &x, &y);
if (i == start) {
dv.push_back(draw(VT_MOVETO, x, y));
} else {
dv.push_back(draw(VT_LINETO, x, y));
}
}
if (closed && dv.size() > 0) {
dv.push_back(draw(VT_LINETO, dv[0].x, dv[0].y));
}
return dv;
}
drawvec readLine(std::vector<long long> &coords, size_t dim, double e, bool closed) {
return readLinePart(coords, dim, e, 0, coords.size(), closed);
}
drawvec readMultiLine(std::vector<long long> &coords, std::vector<int> &lengths, size_t dim, double e, bool closed) {
if (lengths.size() == 0) {
return readLinePart(coords, dim, e, 0, coords.size(), closed);
}
drawvec dv;
size_t here = 0;
for (size_t i = 0; i < lengths.size(); i++) {
drawvec dv2 = readLinePart(coords, dim, e, here, here + lengths[i] * dim, closed);
here += lengths[i] * dim;
for (size_t j = 0; j < dv2.size(); j++) {
dv.push_back(dv2[j]);
}
}
return dv;
}
drawvec readMultiPolygon(std::vector<long long> &coords, std::vector<int> &lengths, size_t dim, double e) {
ensureDim(dim);
if (lengths.size() == 0) {
return readLinePart(coords, dim, e, 0, coords.size(), true);
}
size_t polys = lengths[0];
size_t n = 1;
size_t here = 0;
drawvec dv;
for (size_t i = 0; i < polys; i++) {
size_t rings = lengths[n++];
for (size_t j = 0; j < rings; j++) {
drawvec dv2 = readLinePart(coords, dim, e, here, here + lengths[n] * dim, true);
here += lengths[n] * dim;
n++;
for (size_t k = 0; k < dv2.size(); k++) {
dv.push_back(dv2[k]);
}
}
dv.push_back(draw(VT_CLOSEPATH, 0, 0)); // mark that the next ring is outer
}
return dv;
}
struct drawvec_type {
drawvec dv{};
int type = 0;
};
std::vector<drawvec_type> readGeometry(protozero::pbf_reader &pbf, size_t dim, double e, std::vector<std::string> &keys) {
std::vector<drawvec_type> ret;
std::vector<long long> coords;
std::vector<int> lengths;
int type = -1;
while (pbf.next()) {
switch (pbf.tag()) {
case 1:
type = pbf.get_enum();
break;
case 2: {
auto pi = pbf.get_packed_uint32();
for (auto it = pi.first; it != pi.second; ++it) {
lengths.push_back(*it);
}
break;
}
case 3: {
auto pi = pbf.get_packed_sint64();
for (auto it = pi.first; it != pi.second; ++it) {
coords.push_back(*it);
}
break;
}
case 4: {
protozero::pbf_reader geometry_reader(pbf.get_message());
std::vector<drawvec_type> dv2 = readGeometry(geometry_reader, dim, e, keys);
for (size_t i = 0; i < dv2.size(); i++) {
ret.push_back(dv2[i]);
}
break;
}
default:
pbf.skip();
}
}
drawvec_type dv;
if (type == POINT) {
dv.dv = readPoint(coords, dim, e);
} else if (type == MULTIPOINT) {
dv.dv = readLine(coords, dim, e, false);
} else if (type == LINESTRING) {
dv.dv = readLine(coords, dim, e, false);
} else if (type == POLYGON) {
dv.dv = readMultiLine(coords, lengths, dim, e, true);
} else if (type == MULTIPOLYGON) {
dv.dv = readMultiPolygon(coords, lengths, dim, e);
} else {
// GeometryCollection
return ret;
}
dv.type = type / 2 + 1;
ret.push_back(dv);
return ret;
}
void readFeature(protozero::pbf_reader &pbf, size_t dim, double e, std::vector<std::string> &keys, struct serialization_state *sst, int layer, std::string layername) {
std::vector<drawvec_type> dv;
long long id = 0;
bool has_id = false;
std::vector<serial_val> values;
std::map<std::string, serial_val> other;
std::vector<std::string> full_keys;
std::vector<serial_val> full_values;
while (pbf.next()) {
switch (pbf.tag()) {
case 1: {
protozero::pbf_reader geometry_reader(pbf.get_message());
std::vector<drawvec_type> dv2 = readGeometry(geometry_reader, dim, e, keys);
for (size_t i = 0; i < dv2.size(); i++) {
dv.push_back(dv2[i]);
}
break;
}
case 11: {
static bool warned = false;
if (!warned) {
fprintf(stderr, "Non-numeric feature IDs not supported\n");
warned = true;
}
pbf.skip();
break;
}
case 12:
has_id = true;
id = pbf.get_sint64();
if (id < 0) {
static bool warned = false;
if (!warned) {
fprintf(stderr, "Out of range feature id %lld\n", id);
warned = true;
}
has_id = false;
}
break;
case 13: {
protozero::pbf_reader value_reader(pbf.get_message());
values.push_back(readValue(value_reader));
break;
}
case 14: {
std::vector<size_t> properties;
auto pi = pbf.get_packed_uint32();
for (auto it = pi.first; it != pi.second; ++it) {
properties.push_back(*it);
}
for (size_t i = 0; i + 1 < properties.size(); i += 2) {
if (properties[i] >= keys.size()) {
fprintf(stderr, "Out of bounds key: %zu in %zu\n", properties[i], keys.size());
exit(EXIT_FAILURE);
}
if (properties[i + 1] >= values.size()) {
fprintf(stderr, "Out of bounds value: %zu in %zu\n", properties[i + 1], values.size());
exit(EXIT_FAILURE);
}
full_keys.push_back(keys[properties[i]]);
full_values.push_back(values[properties[i + 1]]);
}
values.clear();
break;
}
case 15: {
std::vector<size_t> misc;
auto pi = pbf.get_packed_uint32();
for (auto it = pi.first; it != pi.second; ++it) {
misc.push_back(*it);
}
for (size_t i = 0; i + 1 < misc.size(); i += 2) {
if (misc[i] >= keys.size()) {
fprintf(stderr, "Out of bounds key: %zu in %zu\n", misc[i], keys.size());
exit(EXIT_FAILURE);
}
if (misc[i + 1] >= values.size()) {
fprintf(stderr, "Out of bounds value: %zu in %zu\n", misc[i + 1], values.size());
exit(EXIT_FAILURE);
}
other.insert(std::pair<std::string, serial_val>(keys[misc[i]], values[misc[i + 1]]));
}
values.clear();
break;
}
default:
pbf.skip();
}
}
for (size_t i = 0; i < dv.size(); i++) {
serial_feature sf;
sf.layer = layer;
sf.layername = layername;
sf.segment = sst->segment;
sf.has_id = has_id;
sf.id = id;
sf.has_tippecanoe_minzoom = false;
sf.has_tippecanoe_maxzoom = false;
sf.feature_minzoom = false;
sf.seq = *(sst->layer_seq);
sf.geometry = dv[i].dv;
sf.t = dv[i].type;
sf.full_keys = full_keys;
sf.full_values = full_values;
auto tip = other.find("tippecanoe");
if (tip != other.end()) {
json_pull *jp = json_begin_string(tip->second.s.c_str());
json_object *o = json_read_tree(jp);
if (o != NULL) {
json_object *min = json_hash_get(o, "minzoom");
if (min != NULL && (min->type == JSON_STRING || min->type == JSON_NUMBER)) {
sf.has_tippecanoe_minzoom = true;
sf.tippecanoe_minzoom = atoi(min->string);
}
json_object *max = json_hash_get(o, "maxzoom");
if (max != NULL && (max->type == JSON_STRING || max->type == JSON_NUMBER)) {
sf.has_tippecanoe_maxzoom = true;
sf.tippecanoe_maxzoom = atoi(max->string);
}
json_object *tlayer = json_hash_get(o, "layer");
if (tlayer != NULL && (tlayer->type == JSON_STRING || tlayer->type == JSON_NUMBER)) {
sf.layername = tlayer->string;
}
}
json_free(o);
json_end(jp);
}
serialize_feature(sst, sf);
}
}
struct queue_run_arg {
size_t start;
size_t end;
size_t segment;
queue_run_arg(size_t start1, size_t end1, size_t segment1)
: start(start1), end(end1), segment(segment1) {
}
};
void *run_parse_feature(void *v) {
struct queue_run_arg *qra = (struct queue_run_arg *) v;
for (size_t i = qra->start; i < qra->end; i++) {
struct queued_feature &qf = feature_queue[i];
readFeature(qf.pbf, qf.dim, qf.e, *qf.keys, &(*qf.sst)[qra->segment], qf.layer, qf.layername);
}
return NULL;
}
void runQueue() {
if (feature_queue.size() == 0) {
return;
}
std::vector<struct queue_run_arg> qra;
std::vector<pthread_t> pthreads;
pthreads.resize(CPUS);
for (size_t i = 0; i < CPUS; i++) {
*((*(feature_queue[0].sst))[i].layer_seq) = *((*(feature_queue[0].sst))[0].layer_seq) + feature_queue.size() * i / CPUS;
qra.push_back(queue_run_arg(
feature_queue.size() * i / CPUS,
feature_queue.size() * (i + 1) / CPUS,
i));
}
for (size_t i = 0; i < CPUS; i++) {
if (pthread_create(&pthreads[i], NULL, run_parse_feature, &qra[i]) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
for (size_t i = 0; i < CPUS; i++) {
void *retval;
if (pthread_join(pthreads[i], &retval) != 0) {
perror("pthread_join");
}
}
// Lack of atomicity is OK, since we are single-threaded again here
long long was = *((*(feature_queue[0].sst))[CPUS - 1].layer_seq);
*((*(feature_queue[0].sst))[0].layer_seq) = was;
feature_queue.clear();
}
void queueFeature(protozero::pbf_reader &pbf, size_t dim, double e, std::vector<std::string> &keys, std::vector<struct serialization_state> *sst, int layer, std::string layername) {
struct queued_feature qf;
qf.pbf = pbf;
qf.dim = dim;
qf.e = e;
qf.keys = &keys;
qf.sst = sst;
qf.layer = layer;
qf.layername = layername;
feature_queue.push_back(qf);
if (feature_queue.size() > CPUS * 500) {
runQueue();
}
}
void outBareGeometry(drawvec const &dv, int type, struct serialization_state *sst, int layer, std::string layername) {
serial_feature sf;
sf.layer = layer;
sf.layername = layername;
sf.segment = sst->segment;
sf.has_id = false;
sf.has_tippecanoe_minzoom = false;
sf.has_tippecanoe_maxzoom = false;
sf.feature_minzoom = false;
sf.seq = (*sst->layer_seq);
sf.geometry = dv;
sf.t = type;
serialize_feature(sst, sf);
}
void readFeatureCollection(protozero::pbf_reader &pbf, size_t dim, double e, std::vector<std::string> &keys, std::vector<struct serialization_state> *sst, int layer, std::string layername) {
while (pbf.next()) {
switch (pbf.tag()) {
case 1: {
protozero::pbf_reader feature_reader(pbf.get_message());
queueFeature(feature_reader, dim, e, keys, sst, layer, layername);
break;
}
default:
pbf.skip();
}
}
}
void parse_geobuf(std::vector<struct serialization_state> *sst, const char *src, size_t len, int layer, std::string layername) {
protozero::pbf_reader pbf(src, len);
size_t dim = 2;
double e = 1e6;
std::vector<std::string> keys;
while (pbf.next()) {
switch (pbf.tag()) {
case 1:
keys.push_back(pbf.get_string());
break;
case 2:
dim = pbf.get_int64();
break;
case 3:
e = pow(10, pbf.get_int64());
break;
case 4: {
protozero::pbf_reader feature_collection_reader(pbf.get_message());
readFeatureCollection(feature_collection_reader, dim, e, keys, sst, layer, layername);
break;
}
case 5: {
protozero::pbf_reader feature_reader(pbf.get_message());
queueFeature(feature_reader, dim, e, keys, sst, layer, layername);
break;
}
case 6: {
protozero::pbf_reader geometry_reader(pbf.get_message());
std::vector<drawvec_type> dv = readGeometry(geometry_reader, dim, e, keys);
for (size_t i = 0; i < dv.size(); i++) {
// Always on thread 0
outBareGeometry(dv[i].dv, dv[i].type, &(*sst)[0], layer, layername);
}
break;
}
default:
pbf.skip();
}
}
runQueue();
}
| 23.193825 | 190 | 0.62757 | [
"geometry",
"vector"
] |
6bff446a61bbef3c399a655ccd082f20b2ef2936 | 2,096 | hpp | C++ | stan/math/rev/fun/sd.hpp | nicokist/math | d47c331a693a3d5ebc4453360743b9353a8e3ed1 | [
"BSD-3-Clause"
] | null | null | null | stan/math/rev/fun/sd.hpp | nicokist/math | d47c331a693a3d5ebc4453360743b9353a8e3ed1 | [
"BSD-3-Clause"
] | null | null | null | stan/math/rev/fun/sd.hpp | nicokist/math | d47c331a693a3d5ebc4453360743b9353a8e3ed1 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_REV_FUN_SD_HPP
#define STAN_MATH_REV_FUN_SD_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/typedefs.hpp>
#include <stan/math/prim/fun/inv_sqrt.hpp>
#include <cmath>
#include <vector>
namespace stan {
namespace math {
/**
* Return the sample standard deviation of the specified std vector, column
* vector, row vector, or matrix.
*
* @tparam R number of rows, can be Eigen::Dynamic
* @tparam C number of columns, can be Eigen::Dynamic
* @param[in] m input matrix
* @return sample standard deviation of specified matrix
* @throw domain error size is not greater than zero.
*/
template <typename T, require_container_vt<is_var, T>* = nullptr>
var sd(const T& m) {
check_nonzero_size("sd", "m", m);
if (m.size() == 1) {
return 0;
}
return apply_vector_unary<T>::reduce(m, [](const auto& dtrs_map) {
using std::sqrt;
using T_map = std::decay_t<decltype(dtrs_map)>;
using T_vi = promote_scalar_t<vari*, T_map>;
using T_d = promote_scalar_t<double, T_map>;
vari** varis = ChainableStack::instance_->memalloc_.alloc_array<vari*>(
dtrs_map.size());
double* partials = ChainableStack::instance_->memalloc_.alloc_array<double>(
dtrs_map.size());
Eigen::Map<T_vi> varis_map(varis, dtrs_map.rows(), dtrs_map.cols());
Eigen::Map<T_d> partials_map(partials, dtrs_map.rows(), dtrs_map.cols());
varis_map = dtrs_map.vi();
T_d dtrs_val = varis_map.val();
double mean = dtrs_val.mean();
T_d diff = dtrs_val.array() - mean;
double sum_of_squares = diff.squaredNorm();
double size_m1 = dtrs_map.size() - 1;
double sd = sqrt(sum_of_squares / size_m1);
if (sum_of_squares < 1e-20) {
partials_map.fill(inv_sqrt(static_cast<double>(dtrs_map.size())));
} else {
partials_map = diff.array() / (sd * size_m1);
}
return var(new stored_gradient_vari(sd, dtrs_map.size(), varis, partials));
});
}
} // namespace math
} // namespace stan
#endif
| 32.246154 | 80 | 0.686546 | [
"vector"
] |
d401d2134b3539b4eafe7bf23ef56e5bb6c09287 | 7,084 | cpp | C++ | sparta/src/sparta.cpp | criusx/map | 7a934d1721ac1257503f7f324b54eb898750ab0d | [
"MIT"
] | null | null | null | sparta/src/sparta.cpp | criusx/map | 7a934d1721ac1257503f7f324b54eb898750ab0d | [
"MIT"
] | null | null | null | sparta/src/sparta.cpp | criusx/map | 7a934d1721ac1257503f7f324b54eb898750ab0d | [
"MIT"
] | null | null | null | // <sparta> -*- C++ -*-
/*!
* \file sparta.cpp
* \brief Instantiation of globals and static members from all various sparta
* headers which don't have enough code to warrant their own source files.
*
* Additionally, anything requiring a strict static initialization order must
* exist here.
*/
#include "sparta/sparta.hpp"
#include <cstdint>
#include <array>
#include <functional>
#include <memory>
#include <string>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <vector>
#include "sparta/utils/StaticInit.hpp"
#include "sparta/simulation/ParameterSet.hpp"
#include "sparta/simulation/Clock.hpp"
#include "sparta/utils/Tag.hpp"
#include "sparta/utils/KeyValue.hpp"
#include "sparta/functional/Register.hpp"
#include "sparta/functional/ArchData.hpp"
#include "sparta/functional/DataView.hpp"
#include "sparta/utils/StringManager.hpp"
#include "sparta/log/categories/CategoryManager.hpp"
#include "sparta/simulation/TreeNode.hpp"
#include "sparta/simulation/GlobalTreeNode.hpp"
#include "sparta/kernel/Scheduler.hpp"
#include "sparta/pevents/PEventHelper.hpp"
#include "sparta/report/format/Text.hpp"
#include "sparta/pairs/PairCollectorTreeNode.hpp"
#include "sparta/simulation/Unit.hpp"
#include "sparta/kernel/SleeperThread.hpp"
#include "sparta/utils/Colors.hpp"
#include "sparta/parsers/ConfigParser.hpp"
#include "sparta/kernel/Vertex.hpp"
#include "sparta/simulation/ResourceContainer.hpp"
#include "sparta/kernel/SleeperThreadBase.hpp"
#include "sparta/utils/Utils.hpp"
#include "sparta/serialization/checkpoint/Checkpoint.hpp"
namespace sparta {
static int static_init_counter = 0;
SpartaStaticInitializer::SpartaStaticInitializer()
{
if(0 == static_init_counter++){
// initialize statics
// ORDER IS CRITICAL
// These must be uninitialized in reverse order in ~SpartaStaticInitializer
//std::cout << "SpartaStaticInitializer CONSTRUCTING" << std::endl;
color::ColorScheme::_GBL_COLOR_SCHEME = new color::ColorScheme();
StringManager::_GBL_string_manager = new StringManager();
ArchData::all_archdatas_ = new (std::remove_pointer<decltype(ArchData::all_archdatas_)>::type)();
TreeNode::statics_ = new TreeNode::TreeNodeStatics();
}
}
SpartaStaticInitializer::~SpartaStaticInitializer()
{
if(0 == --static_init_counter){
// uninit statics (in reverse order)
//std::cout << "SpartaStaticInitializer DESTROYING" << std::endl;
delete TreeNode::statics_;
delete ArchData::all_archdatas_;
delete StringManager::_GBL_string_manager;
delete color::ColorScheme::_GBL_COLOR_SCHEME;
}
}
namespace color {
sparta::color::ColorScheme* ColorScheme::_GBL_COLOR_SCHEME;
}
sparta::StringManager* StringManager::_GBL_string_manager;
namespace log {
// Category Strings
constexpr char categories::WARN_STR[];
constexpr char categories::DEBUG_STR[];
constexpr char categories::PARAMETERS_STR[];
const std::string* const categories::WARN = StringManager::getStringManager().internString(WARN_STR);
const std::string* const categories::DEBUG = StringManager::getStringManager().internString(DEBUG_STR);
const std::string* const categories::PARAMETERS = StringManager::getStringManager().internString(PARAMETERS_STR);
const std::string* const categories::NONE = StringManager::getStringManager().EMPTY;
}
}
namespace sparta {
// ResouceContainer
std::string ResourceContainer::getResourceTypeRaw() const {
return typeid(*resource_).name();
}
std::string ResourceContainer::getResourceType() const {
return getResourceTypeName_();
}
std::string ResourceContainer::getResourceTypeName_() const {
return demangle(typeid(*resource_).name());
}
}
SPARTA_PARAMETER_BODY;
SPARTA_CLOCK_BODY;
SPARTA_TAG_BODY;
SPARTA_KVPAIR_BODY;
SPARTA_REGISTER_BODY;
namespace sparta {
// ArchData
constexpr char sparta::ArchData::Line::QUICK_CHECKPOINT_PREFIX[];
std::vector<const sparta::ArchData*>* sparta::ArchData::all_archdatas_ = nullptr;
}
SPARTA_DATAVIEW_BODY;
SPARTA_GLOBAL_TREENODE_BODY;
SPARTA_CHECKPOINT_BODY;
SPARTA_UNIT_BODY;
namespace sparta {
// TreeNode
TreeNode::TreeNodeStatics* TreeNode::statics_ = nullptr;
//std::vector<TreeNode::WeakPtr> TreeNode::parentless_nodes_;
//std::vector<TreeNode::WeakPtr> TreeNode::all_nodes_;
TreeNode::node_uid_type TreeNode::next_node_uid_ = 0;
TreeNode::TagsMap TreeNode::global_tags_map_;
uint32_t TreeNode::teardown_errors_ = 0;
const TreeNode::node_uid_type TreeNode::MAX_NODE_UID = 0xffffffffffff;
constexpr char TreeNode::GROUP_NAME_BUILTIN[];
constexpr char TreeNode::GROUP_NAME_NONE[];
constexpr char TreeNode::NODE_NAME_VIRTUAL_GLOBAL[];
constexpr char TreeNode::LOCATION_NODE_SEPARATOR_ATTACHED;
constexpr char TreeNode::LOCATION_NODE_SEPARATOR_EXPECTING;
constexpr char TreeNode::LOCATION_NODE_SEPARATOR_UNATTACHED;
constexpr char TreeNode::NODE_NAME_NONE[];
const std::string TreeNode::DEBUG_DUMP_SECTION_DIVIDER = \
"================================================================================\n";
const std::vector<std::pair<const char*, std::function<void (std::string&)>>> TreeNode::TREE_NODE_PATTERN_SUBS =
{
// Escape original parens
{"(", [](std::string& s){replaceSubstring(s, "(", "\\(");}},
{")", [](std::string& s){replaceSubstring(s, ")", "\\)");}},
// Escape original brackets
{"[", [](std::string& s){replaceSubstring(s, "[", "\\[");}},
{"]", [](std::string& s){replaceSubstring(s, "]", "\\]");}},
// Replace glob-like wildcards with captured-regex replacements
{"*", [](std::string& s){replaceSubstring(s, "*", "(.*)");}},
{"?", [](std::string& s){replaceSubstring(s, "?", "(.?)");}},
{"+", [](std::string& s){replaceSubstring(s, "+", "(.+)");}}
// Disabled because supporting capture will require more complext expression
// parsing
//{"[!", [](std::string& s){replaceSubstring(patexp, "[!", "[^")
};
// Scheduler
Scheduler _GBL_scheduler;
constexpr char Scheduler::NODE_NAME[];
const Scheduler::Tick Scheduler::INDEFINITE = 0xFFFFFFFFFFFFFFFFull;
std::unique_ptr<sparta::SleeperThreadBase> SleeperThread::sleeper_thread_;
uint32_t Vertex::global_id_ = 0;
// KeyPairs
constexpr char sparta::PairCollectorTreeNode::COLLECTABLE_DESCRIPTION[];
namespace pevents {
//pevents
//PEventHelper.h
std::array<std::string, 2> pevents::PEventProtection::PEventProtectedAttrs {{"ev", "cyc"}};
}
namespace report {
namespace format {
// Text
const char Text::DEFAULT_REPORT_PREFIX[] = "Report ";
}
}
namespace ConfigParser {
constexpr char ConfigParser::OPTIONAL_PARAMETER_KEYWORD[];
}
}
| 35.777778 | 121 | 0.679983 | [
"vector"
] |
d4096fb30eb0b0130732b502460f02be70d3297f | 8,442 | cpp | C++ | pinto/src/PintoManager.cpp | pathorn/sirikata | 5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa | [
"BSD-3-Clause"
] | 1 | 2016-05-09T03:34:51.000Z | 2016-05-09T03:34:51.000Z | pinto/src/PintoManager.cpp | pathorn/sirikata | 5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa | [
"BSD-3-Clause"
] | null | null | null | pinto/src/PintoManager.cpp | pathorn/sirikata | 5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa | [
"BSD-3-Clause"
] | null | null | null | /* Sirikata
* PintoManager.cpp
*
* Copyright (c) 2010, Ewen Cheslack-Postava
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata 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 "PintoManager.hpp"
#include <sirikata/core/network/StreamListenerFactory.hpp>
#include "Options.hpp"
#include <sirikata/core/options/CommonOptions.hpp>
#include <sirikata/core/network/Message.hpp> // parse/serializePBJMessage
#include "Protocol_MasterPinto.pbj.hpp"
#include <sirikata/space/QueryHandlerFactory.hpp>
using namespace Sirikata::Network;
#define PINTO_LOG(lvl, msg) SILOG(pinto,lvl,msg)
namespace Sirikata {
PintoManager::PintoManager(PintoContext* ctx)
: mContext(ctx),
mStrand(ctx->ioService->createStrand()),
mLastTime(Time::null()),
mDt(Duration::milliseconds((int64)1))
{
String listener_protocol = GetOptionValue<String>(OPT_PINTO_PROTOCOL);
String listener_protocol_options = GetOptionValue<String>(OPT_PINTO_PROTOCOL_OPTIONS);
OptionSet* listener_protocol_optionset = StreamListenerFactory::getSingleton().getOptionParser(listener_protocol)(listener_protocol_options);
mListener = StreamListenerFactory::getSingleton().getConstructor(listener_protocol)(mStrand, listener_protocol_optionset);
String listener_host = GetOptionValue<String>(OPT_PINTO_HOST);
String listener_port = GetOptionValue<String>(OPT_PINTO_PORT);
Address listenAddress(listener_host, listener_port);
PINTO_LOG(debug, "Listening on " << listenAddress.toString());
mListener->listen(
listenAddress,
std::tr1::bind(&PintoManager::newStreamCallback,this,_1,_2)
);
mLocCache = new PintoManagerLocationServiceCache();
String handler_type = GetOptionValue<String>(OPT_PINTO_HANDLER_TYPE);
String handler_options = GetOptionValue<String>(OPT_PINTO_HANDLER_OPTIONS);
mQueryHandler = QueryHandlerFactory<ServerProxSimulationTraits>(handler_type, handler_options);
bool static_objects = false;
mQueryHandler->initialize(mLocCache, mLocCache, static_objects);
}
PintoManager::~PintoManager() {
delete mListener;
delete mQueryHandler;
delete mStrand;
}
void PintoManager::start() {
}
void PintoManager::stop() {
mListener->close();
}
void PintoManager::newStreamCallback(Stream* newStream, Stream::SetCallbacks& setCallbacks) {
using std::tr1::placeholders::_1;
using std::tr1::placeholders::_2;
PINTO_LOG(debug,"New space server connection.");
setCallbacks(
std::tr1::bind(&PintoManager::handleClientConnection, this, newStream, _1, _2),
std::tr1::bind(&PintoManager::handleClientReceived, this, newStream, _1, _2),
std::tr1::bind(&PintoManager::handleClientReadySend, this, newStream)
);
mClients[newStream] = ClientData();
}
void PintoManager::handleClientConnection(Sirikata::Network::Stream* stream, Network::Stream::ConnectionStatus status, const std::string &reason) {
if (status == Network::Stream::Disconnected) {
// Unregister region and query, remove from clients list.
mLocCache->removeSpaceServer( mClients[stream].server);
mClientsByQuery.erase( mClients[stream].query );
delete mClients[stream].query;
mClients.erase(stream);
tick();
}
}
void PintoManager::handleClientReceived(Sirikata::Network::Stream* stream, Chunk& data, const Network::Stream::PauseReceiveCallback& pause) {
Sirikata::Protocol::MasterPinto::PintoMessage msg;
bool parsed = parsePBJMessage(&msg, data);
if (!parsed) {
PINTO_LOG(error, "Couldn't parse message from client.");
return;
}
ClientData& cdata = mClients[stream];
if (msg.has_server()) {
PINTO_LOG(debug, "Associated connection with space server " << msg.server().server());
cdata.server = msg.server().server();
TimedMotionVector3f default_loc( Time::null(), MotionVector3f( Vector3f::zero(), Vector3f::zero() ) );
BoundingSphere3f default_region(BoundingSphere3f::null());
float32 default_max = 0.f;
SolidAngle default_min_angle(SolidAngle::Max);
// FIXME max_results
mLocCache->addSpaceServer(cdata.server, default_loc, default_region, default_max);
Query* query = mQueryHandler->registerQuery(default_loc, default_region, default_max, default_min_angle);
cdata.query = query;
mClientsByQuery[query] = stream;
query->setEventListener(this);
}
else {
if (cdata.server == NullServerID) {
PINTO_LOG(error, "Received initial message from client without a ServerID.");
stream->close();
mClients.erase(stream);
return;
}
}
if (msg.has_region()) {
PINTO_LOG(debug, "Received region update from " << cdata.server << ": " << msg.region().bounds());
mLocCache->updateSpaceServerRegion(cdata.server, msg.region().bounds());
cdata.query->region( msg.region().bounds() );
}
if (msg.has_largest()) {
PINTO_LOG(debug, "Received largest object update from " << cdata.server << ": " << msg.largest().radius());
mLocCache->updateSpaceServerMaxSize(cdata.server, msg.largest().radius());
cdata.query->maxSize( msg.largest().radius() );
}
if (msg.has_query()) {
PINTO_LOG(debug, "Received query update from " << cdata.server << ": " << msg.query().min_angle());
cdata.query->angle( SolidAngle(msg.query().min_angle()) );
// FIXME max results
}
tick();
}
void PintoManager::handleClientReadySend(Sirikata::Network::Stream* stream) {
}
void PintoManager::tick() {
mLastTime += mDt;
mQueryHandler->tick(mLastTime);
}
void PintoManager::queryHasEvents(Query* query) {
typedef std::deque<QueryEvent> QueryEventList;
Network::Stream* stream = mClientsByQuery[query];
ClientData& cdata = mClients[stream];
QueryEventList evts;
query->popEvents(evts);
Sirikata::Protocol::MasterPinto::PintoResponse msg;
while(!evts.empty()) {
const QueryEvent& evt = evts.front();
//PINTO_LOG(debug, "Event generated for server " << cdata.server << ": " << evt.id() << (evt.type() == QueryEvent::Added ? " added" : " removed"));
Sirikata::Protocol::MasterPinto::IPintoUpdate update = msg.add_update();
for(uint32 aidx = 0; aidx < evt.additions().size(); aidx++) {
Sirikata::Protocol::MasterPinto::IPintoResult result = update.add_change();
result.set_addition(true);
result.set_server(evt.additions()[aidx].id());
}
for(uint32 ridx = 0; ridx < evt.removals().size(); ridx++) {
Sirikata::Protocol::MasterPinto::IPintoResult result = update.add_change();
result.set_addition(false);
result.set_server(evt.removals()[ridx].id());
}
evts.pop_front();
}
String serialized = serializePBJMessage(msg);
stream->send( MemoryReference(serialized), ReliableOrdered );
}
} // namespace Sirikata
| 38.372727 | 155 | 0.69936 | [
"object"
] |
d409a7d12bb608a8415e72888bf3581f028fbd93 | 9,193 | cpp | C++ | src/talker.cpp | michael081906/ros-project-robotic-polishing | 12f02befa244dc2cfdb3e3e5f89c8d3f25fde7bb | [
"BSD-3-Clause"
] | 5 | 2020-10-01T19:59:23.000Z | 2022-02-09T02:48:53.000Z | src/talker.cpp | michael081906/Robotic-polishing | 12f02befa244dc2cfdb3e3e5f89c8d3f25fde7bb | [
"BSD-3-Clause"
] | 1 | 2021-01-08T07:20:12.000Z | 2021-01-08T07:33:21.000Z | src/talker.cpp | michael081906/Robotic-polishing | 12f02befa244dc2cfdb3e3e5f89c8d3f25fde7bb | [
"BSD-3-Clause"
] | 4 | 2020-12-03T12:47:33.000Z | 2022-01-28T06:25:37.000Z | // "Copyright [2017] <Michael Kam>"
/** @file talker.cpp
* @brief This talker.cpp is a ros node that subscribes point cloud and
* computes the trajectory f
*
* @author Michael Kam (michael081906)
* @bug No known bugs.
* @copyright GNU Public License.
*
* talker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* talker 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 talker. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <s_hull_pro.h>
#include <pclIo.h>
#include <pclVoxel.h>
#include <pclMlsSmoothing.h>
#include <pclPassThrough.h>
#include <pclStatisticalOutlierRemoval.h>
#include <pclFastTriangular.h>
#include <pclCloudViewer.h>
#include <findNearestPoint.h>
#include <delaunay3.h>
#include <dijkstraPQ.h>
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/filters/radius_outlier_removal.h>
#include <pcl/filters/conditional_removal.h>
#include <pcl_ros/point_cloud.h>
#include <sensor_msgs/PointCloud2.h>
#include <robotic_polishing/Trajectory.h> // This header name name from the project name in CmakeList.txt, not physical folder name
#include <pcl_conversions/pcl_conversions.h>
#include <pcl_ros/transforms.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <sys/types.h>
#include <math.h>
#include <time.h>
#include <set>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <hash_set>
#include <iostream>
#include <queue>
#include <stack>
#include <limits>
#include <algorithm>
typedef pcl::PointCloud<pcl::PointXYZ> PointCloud;
PointCloud pointcloud_in;
PointCloud pointcloud_out;
/** @brief callback is a callback function that subscribes the point cloud data
* and uses tf to transform to world coordinate
* @param[in] cloud sensor_msgs::PointCloud2Ptr that contains point cloud information
* @return none
*/
void callback(const sensor_msgs::PointCloud2Ptr& cloud) {
pcl::fromROSMsg(*cloud, pointcloud_in); // copy sensor_msg::Pointcloud message into pcl::PointCloud
// tf::Transform transformKinect;
tf::Pose transformKinect;
transformKinect.setOrigin(tf::Vector3(0.3, 0.0, 0.0));
tf::Matrix3x3 rotationMatrix(0, 0, 1, -1, 0, 0, 0, -1, 0);
// tf::Matrix3x3 rotationMatrix(1, 0, 0, 0, 1, 0, 0, 0, 1);
transformKinect.setBasis(rotationMatrix);
// tf::Quaternion q;
// TODO: (Michael) What is Quaternion;
// transformKinect.setRotation(tf::Quaternion(0, 0, 0, 1));
pcl_ros::transformPointCloud(pointcloud_in, pointcloud_out, transformKinect);
}
/** @brief get_joints is a callback function that subscribe the joint position data
* and set it into joints vector
* @param[in] data sensor_msgs::JointState that contains joint position
* @return none
*/
/** @brief find is a service for computing trajectory based on a start and an end point.
* @param[in] req is a request that contains coordinates of start and end point.
* @param[in] res is a response that contains trajectory information
* @return none
*/
bool find(robotic_polishing::Trajectory::Request &req,
robotic_polishing::Trajectory::Response &res) {
// 0. Initialization
pclIo pclLoad;
pclCloudViewer pclView;
pclPassThrough pt;
pclVoxel vx;
pclStatistOutRev sor;
pclMlsSmoothing mls;
pclFastTriangular ft;
pcl::PolygonMesh triangles;
pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normal(
new pcl::PointCloud<pcl::PointNormal>);
// pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_out(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_out;
cloud_out = pointcloud_out.makeShared();
pt.setInputCloud(*cloud_out);
pt.setFilterZlimit(0, 10);
pt.filterProcess(*cloud_out);
// 4. Down sample the point cloud
ROS_INFO(" 4. Down sampling the point cloud, please wait...");
vx.setInputCloud(*cloud_out);
vx.setLeafSize(0.01, 0.01, 0.01);
vx.filterProcess(*cloud_out);
ROS_INFO(" Down sampling completed");
/****************************************************************************
pcl::visualization::CloudViewer viewer("Cloud of Raw data");
viewer.showCloud(cloud_out);
int user_data = 0;
do {
user_data++;
} while (!viewer.wasStopped());
// ****************************************************************************/
// pub_pcl.publish(cloud_out);
// 2. Remove the noise of point cloud
ROS_INFO("2. Removing the noise of point cloud, please wait...");
sor.setInputCloud(*cloud_out);
sor.setMeanK(50);
sor.setStddevMulThresh(1);
sor.filterProcess(*cloud_out);
//*******************************************************************
// 2017.11.9 Added Michael
pcl::RadiusOutlierRemoval<pcl::PointXYZ> outrem;
// build the filter
outrem.setInputCloud(cloud_out);
outrem.setRadiusSearch(0.5);
outrem.setMinNeighborsInRadius(30);
// apply filter
outrem.filter(*cloud_out);
//*******************************************************************
ROS_INFO(" Removing completed");
/*****************************************************************/
// 3. Extract certain region of point cloud
// 5. Smooth the point cloud
ROS_INFO(" 5. Smoothing the point cloud, please wait...");
mls.setInputCloud(*cloud_out);
mls.setSearchRadius(0.05);
mls.mlsProcess(*cloud_with_normal);
// 7. Mesh the obstacle
ROS_INFO(" 7. Meshing the obstacle, please wait...");
ft.setInputCloud(*cloud_with_normal);
ft.setSearchRadius(0.05);
ft.reconctruct(triangles);
std::vector<int> gp33 = ft.getSegID();
int sizegp3 = gp33.size();
int sizePointCloud = cloud_with_normal->size();
// 8. Show the result
// pclView.display(triangles);
// 9.mergeHanhsPoint
ROS_INFO(" 9. Merging point of selected point, please wait...");
findNearestPoint mg;
std::vector<int> selectedPoint;
// mg.readtext("./src/Robotic-polishing/kidney3dots3_pointCluster.txt");
mg.setPosition(req.start);
mg.setPosition(req.end);
mg.setInputCloud(*cloud_with_normal);
mg.findNearestProcess(selectedPoint);
std::vector<int> size3;
size3 = ft.getSegID();
ROS_INFO(" 10. Delaunay3 function...");
std::vector<Triad> triads;
// std::vector<Shx> ptsOut;
delaunay3 dy3;
dy3.setInputCloud(*cloud_with_normal);
dy3.putPointCloudIntoShx();
dy3.processDelaunay(triads);
// dy3.getShx(ptsOut);
// write_Triads(triads, "triangles.txt");
// write_Shx(ptsOut, "pts.txt");
int start = selectedPoint[0];
int end = selectedPoint[1];
std::vector<int> path;
dijkstraPQ dPQ(size3.size());
dPQ.setInputCloud(*cloud_with_normal);
dPQ.setTri(triads);
dPQ.computeWeight();
dPQ.shortestPath(start, end);
dPQ.returnDijkstraPath(start, end, path);
std::vector<int>::iterator route = path.begin();
while (route != path.end()) {
ROS_INFO("%d ", *route);
// std::cout << *route << " ";
++route;
}
// std::cout << std::endl;
std::vector<position> POS;
dPQ.returnDijkstraPathPosition(start, end, POS);
std::vector<position>::iterator routePos = POS.begin();
float px, py, pz;
while (routePos != POS.end()) {
ROS_INFO("%f ", (*routePos).x);
// std::cout << (*routePos).x << " "; // p.80
px = (*routePos).x;
res.path_x.push_back(px);
++routePos;
}
// std::cout << std::endl;
routePos = POS.begin();
while (routePos != POS.end()) {
ROS_INFO("%f ", (*routePos).y);
// std::cout << (*routePos).y << " ";
py = (*routePos).y;
res.path_y.push_back(py);
++routePos;
}
// std::cout << std::endl;
routePos = POS.begin();
while (routePos != POS.end()) {
ROS_INFO("%f ", (*routePos).z);
// std::cout << (*routePos).z << " ";
pz = (*routePos).z;
res.path_z.push_back(pz);
++routePos;
}
//---------------------------------------------------//
return true;
}
/**
* This tutorial demonstrates simple sending of messages over the ROS system.
*/
int main(int argc, char **argv) {
ros::init(argc, argv, "talker");
ros::NodeHandle n, nh;
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
// ros::Publisher pub_pcl = nh.advertise<PointCloud>("test", 10);
ros::Subscriber sub_pcl = n.subscribe("camera/depth/points", 20, &callback);
ros::ServiceServer service = n.advertiseService("FindTrajectory", &find);
ros::Rate loop_rate(10);
int count = 0;
while (ros::ok()) {
std_msgs::String msg;
std::stringstream ss;
ss << "hello world " << count;
msg.data = ss.str();
ROS_INFO("%s", msg.data.c_str());
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
++count;
}
return 0;
}
| 32.832143 | 132 | 0.662678 | [
"mesh",
"vector",
"transform"
] |
d40b4f4c05749c0563f123baa55d8f8f84af9a58 | 4,956 | cpp | C++ | Code/Piezo/Sources/albumsong.cpp | ehopperdietzel/CuarzoOS | 6202cc6658550828ca9e8527ba29d539c31f65c1 | [
"Apache-2.0"
] | 5 | 2017-08-18T03:23:09.000Z | 2021-08-15T23:12:10.000Z | Code/Piezo/Sources/albumsong.cpp | ehopperdietzel/CuarzoOS | 6202cc6658550828ca9e8527ba29d539c31f65c1 | [
"Apache-2.0"
] | 1 | 2017-12-09T16:00:58.000Z | 2017-12-09T16:41:27.000Z | Code/Piezo/Sources/albumsong.cpp | ehopperdietzel/CuarzoOS | 6202cc6658550828ca9e8527ba29d539c31f65c1 | [
"Apache-2.0"
] | 2 | 2018-07-23T20:11:00.000Z | 2018-09-24T21:37:08.000Z | #include "albumsong.h"
#include <QDebug>
//Creates the song
AlbumSong::AlbumSong(QVariantMap data, bool logged)
{
setAttribute(Qt::WA_Hover);
setFixedHeight(35);
setStyleSheet("AlbumSong{border-bottom:1px solid #EEE;border-radius:0px}");
number->setStyleSheet("color:#888");
number->setFixedWidth(15);
duration->setStyleSheet("color:#888");
layout->setMargin(8);
if(logged){
sync = new OpButton(":/Resources/Images/upload-border.png", bSize, bSize);
connect(sync,SIGNAL(pressed()),this,SLOT(syncClicked()));
layout->addWidget(sync);
}
layout->addWidget(number);
layout->addWidget(name,10);
layout->addWidget(duration);
setData(data);
}
//Set the songs data
void AlbumSong::setData(QVariantMap data)
{
id = data["id"].toString();
name->changeText(data["title"].toString());
number->setText(QString::number(data["track"].toInt()));
duration->setText(r.timeFromSecconds((int)data["duration"].toInt()));
if(!data["local"].toBool())
{
//sync->setIcon(QIcon(":/Resources/Images/download-border.svg"));
}
else if(!data["cloud"].toBool())
{
//sync->setIcon(QIcon(":/Resources/Images/upload-border.svg"));
}
else if(data["cloud"].toBool() && data["local"].toBool())
{
//sync->setIcon(QIcon(":/Resources/Images/success.svg"));
}
}
void AlbumSong::setLocation(QString location)
{
if(location == "local")
{
if(sync != nullptr)
{
sync->deleteLater();
sync = nullptr;
}
}
else if(location == "cloud")
{
//new OpButton(":/Resources/Images/upload-border.png", bSize, bSize)
}
else if(location == "all")
{
}
}
//Set the focus blue color
void AlbumSong::setSelected(bool op)
{
if(op)
{
setStyleSheet("AlbumSong{border-bottom:1px solid transparent;background:"+blue+";border-radius:5px}");
duration->setStyleSheet("color:#FFF");
number->setStyleSheet("color:#FFF");
name->setStyleSheet("color:#FFF");
if(sync != nullptr)
sync->setIcon(QIcon(":/Resources/Images/upload-border-sel.png"));
if(pie != nullptr)
pie->setColor(Qt::white);
if(status != nullptr)
status->setPixmap(QPixmap(":/Resources/Images/volume-high-sel.png"));
if(more != nullptr)
more->setIcon(QIcon(":/Resources/Images/more-sel.png"));
}
else
{
setStyleSheet("AlbumSong{border-bottom:1px solid #EEE;background:transparent;border-radius:0px}");
duration->setStyleSheet("color:#888");
number->setStyleSheet("color:#888");
name->setStyleSheet("color:#444");
if(sync != nullptr)
sync->setIcon(QIcon(":/Resources/Images/upload-border.png"));
if(pie != nullptr)
pie->setColor(Qt::gray);
if(status != nullptr)
status->setPixmap(QPixmap(":/Resources/Images/volume-high.png"));
if(more != nullptr)
more->setIcon(QIcon(":/Resources/Images/more-small.png"));
//if(data["local"] && !data["cloud"]) sync->setColor(blue);
//if(!data["local"] && data["cloud"]) sync->setColor(red);
//if(data["local"] && data["cloud"]) sync->setColor(blue);
}
isSelected = op;
}
//Display the playing icon
void AlbumSong::setPlaying(bool isPlaying)
{
if(isPlaying)
{
if(isSelected)status = new Icon(":/Resources/Images/volume-high-sel.png",bSize, bSize);
if(!isSelected)status = new Icon(":/Resources/Images/volume-high.png",bSize, bSize);
layout->insertWidget(1,status);
number->hide();
status->show();
}
else
{
number->show();
if(status != nullptr)
status->hide();
status->deleteLater();
status = nullptr;
}
}
//Events
void AlbumSong::syncClicked()
{
syncSong(id);
pie = new Pie(0,19);
layout->insertWidget(0,pie);
}
void AlbumSong::piePressed()
{
cancelDownload(id);
pie->deleteLater();
pie = nullptr;
sync->show();
}
void AlbumSong::morePressed()
{
showSongMenu(id);
}
void AlbumSong::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::RightButton)
{
songRightClicked(id);
}
else
{
songSelected(id);
}
}
void AlbumSong::mouseDoubleClickEvent(QMouseEvent *event)
{
songPlayed(id);
}
void AlbumSong::enterEvent(QEvent * event)
{
if(isSelected){
more = new OpButton(":/Resources/Images/more-sel.png", bSize, bSize);
}
else
{
more = new OpButton(":/Resources/Images/more-small.png", bSize, bSize);
}
connect(more,SIGNAL(released()),this,SLOT(morePressed()));
layout->insertWidget(layout->count()-1,more);
duration->hide();
}
void AlbumSong::leaveEvent(QEvent * event)
{
more->deleteLater();
more = nullptr;
duration->show();
}
| 24.904523 | 110 | 0.597256 | [
"solid"
] |
d40dc834fc2ea78f285778b24b2b9360a2e80821 | 9,125 | cpp | C++ | train/data.cpp | wincle/NPD | bbad16b488f6fab77a358a2e2a5337bec4bd17a5 | [
"BSD-3-Clause"
] | 120 | 2016-03-09T02:03:51.000Z | 2021-11-16T13:55:43.000Z | train/data.cpp | wincle/NPD | bbad16b488f6fab77a358a2e2a5337bec4bd17a5 | [
"BSD-3-Clause"
] | 15 | 2016-03-09T02:09:42.000Z | 2018-07-10T03:19:23.000Z | train/data.cpp | wincle/NPD | bbad16b488f6fab77a358a2e2a5337bec4bd17a5 | [
"BSD-3-Clause"
] | 84 | 2016-03-08T11:41:35.000Z | 2020-08-08T06:46:21.000Z | #include "data.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <omp.h>
using namespace cv;
DataSet::DataSet(){
const Options& opt = Options::GetInstance();
int i;
for(i=0;i<opt.numThreads;i++){
x[i]=0;
y[i]=0;
srand(time(0)+i);
factor[i] = 1.+(float)(rand()%50)/100.0;
step[i] = 12+rand()%12;
tranType[i]=0;
win[i]=opt.objSize;
current_id[i] = i;
}
numPixels = opt.objSize * opt.objSize;
feaDims = numPixels * (numPixels - 1) / 2;
}
void DataSet::LoadDataSet(DataSet& pos, DataSet& neg, int stages){
const Options& opt = Options::GetInstance();
printf("Loading Pos data\n");
pos.LoadPositiveDataSet(opt.faceDBFile,stages);
printf("Pos data finish %d\n",pos.size);
printf("Loading Neg data\n");
neg.LoadNegativeDataSet(opt.nonfaceDBFile,pos.size*opt.negRatio,stages);
printf("Neg data finish %d\n",neg.size);
}
void DataSet::LoadPositiveDataSet(const string& positive,int stages){
const Options& opt = Options::GetInstance();
FILE *file;
vector<int> is_flip;
char buff[300];
vector<string> path;
vector<Rect> bboxes;
if(!opt.augment || stages == 0){
file = fopen(positive.c_str(), "r");
while (fscanf(file, "%s", buff) > 0) {
path.push_back(string(buff));
Rect bbox;
fscanf(file, "%d%d%d%d", &bbox.x, &bbox.y, &bbox.width, &bbox.height);
bboxes.push_back(bbox);
is_flip.push_back(0);
}
}
else{
file = fopen(opt.tmpfile.c_str(), "r");
while (fscanf(file, "%s", buff) > 0) {
path.push_back(string(buff));
Rect bbox;
int flip;
fscanf(file, "%d%d%d%d%d", &bbox.x, &bbox.y, &bbox.width, &bbox.height, &flip);
is_flip.push_back(flip);
bboxes.push_back(bbox);
}
}
fclose(file);
const int n = path.size();
size = n;
if(!opt.augment || stages != 0){
imgs.resize(size);
#pragma omp parallel for
for (int i = 0; i < n; i++) {
Mat origin = imread(path[i], CV_LOAD_IMAGE_GRAYSCALE);
if (!origin.data) {
printf("Can not open %s",path[i].c_str());
}
Mat tmp = origin.clone();
if(is_flip[i])
flip(tmp,tmp,1);
Mat face = tmp(bboxes[i]);
Mat img;
cv::resize(face, img, Size(opt.objSize, opt.objSize));
imgs[i] = img.clone();
}
}
else
{
FILE* tmpfile = fopen(opt.tmpfile.c_str(),"w");
size = size*10;
imgs.resize(size);
#pragma omp parallel for
for(int i = 0; i < n; i++) {
Mat origin = imread(path[i], CV_LOAD_IMAGE_GRAYSCALE);
if (!origin.data) {
printf("Can not open %s",path[i].c_str());
}
int type = 0;
int stmp,xtmp,ytmp;
int s = bboxes[i].width;
while(type < 5){
srand(time(0)+type);
do{
stmp = s*((float)(rand()%20)/100.0+0.9);
xtmp = bboxes[i].x+s*((float)(rand()%10)/100.0-0.05);
ytmp = bboxes[i].y+s*((float)(rand()%10)/100.0-0.05);
}while(xtmp<0 || ytmp<0 || (xtmp+stmp)>origin.cols || (ytmp+stmp)>origin.rows);
Rect rect(xtmp,ytmp,stmp,stmp);
fprintf(tmpfile,"%s %d %d %d %d 0\n",path[i].c_str(),xtmp,ytmp,stmp,stmp);
Mat face = origin(rect);
Mat img;
cv::resize(face, img, Size(opt.objSize, opt.objSize));
imgs[i*10+type]=img.clone();
type ++;
}
flip(origin,origin,1);
bboxes[i].x = origin.cols - bboxes[i].x - bboxes[i].width;
while(type < 10){
srand(time(0)+type);
do{
stmp = s*((float)(rand()%20)/100.0+0.9);
xtmp = bboxes[i].x+s*((float)(rand()%10)/100.0-0.05);
ytmp = bboxes[i].y+s*((float)(rand()%10)/100.0-0.05);
}while(xtmp<0 || ytmp<0 || (xtmp+stmp)>origin.cols || (ytmp+stmp)>origin.rows);
Rect rect(xtmp,ytmp,stmp,stmp);
fprintf(tmpfile,"%s %d %d %d %d 1\n",path[i].c_str(),xtmp,ytmp,stmp,stmp);
Mat face = origin(rect);
Mat img;
cv::resize(face, img, Size(opt.objSize, opt.objSize));
imgs[i*10+type]=img.clone();
type ++;
}
}
fclose(tmpfile);
}
random_shuffle(imgs.begin(),imgs.end());
initWeights();
}
void DataSet::LoadNegativeDataSet(const string& negative, int pos_num, int stages){
const Options& opt = Options::GetInstance();
FILE* file = fopen(negative.c_str(), "r");
char buff[256];
list.clear();
while (fscanf(file, "%s", buff) > 0) {
list.push_back(buff);
}
size = pos_num;
random_shuffle(list.begin(),list.end());
imgs.reserve(size + opt.numThreads);
initWeights();
for(int k = 0; k<opt.numThreads ; k++){
Mat img = imread(list[k],CV_LOAD_IMAGE_GRAYSCALE);
NegImgs.push_back(img.clone());
}
if(stages == 0)
MoreNeg(size);
}
void DataSet::MoreNeg(const int n){
const Options& opt = Options::GetInstance();
if(opt.useInitHard){
FILE *file = fopen(opt.initNeg.c_str(), "r");
int count = 0;
char buff[300];
while (fscanf(file, "%s", buff) > 0 && count < n) {
Mat img = imread(buff,CV_LOAD_IMAGE_GRAYSCALE);
imgs.push_back(img);
count ++;
}
if(count != n)
printf("hd imgs not enough!\n");
}
else{
int pool_size = opt.numThreads;
vector<Mat> region_pool(pool_size);
int st = 0;
int need = n - st;
while(st<n){
for(int i = 0;i<pool_size;i++){
region_pool[i] = NextImage(i);
imgs.push_back(region_pool[i].clone());
st++;
}
}
random_shuffle(imgs.begin(),imgs.end());
}
}
Mat DataSet::NextImage(int i) {
const Options& opt = Options::GetInstance();
Mat img = NegImgs[i];
const int width = img.cols;
const int height = img.rows;
Rect roi(x[i],y[i],win[i],win[i]);
Mat crop_img = img(roi);
Mat region;
resize(crop_img,region,Size(opt.objSize,opt.objSize));
switch(tranType[i]){
case 0:
break;
case 1:
flip(region, region, 0);
transpose(region, region);
break;
case 2:
flip(region, region, -1);
break;
case 3:
flip(region, region, 1);
transpose(region, region);
break;
case 4:
flip(region, region, 1);
break;
case 5:
flip(region, region, -1);
transpose(region, region);
break;
case 6:
flip(region, region, -1);
flip(region, region, 1);
break;
case 7:
flip(region, region, 0);
transpose(region, region);
flip(region, region, 1);
break;
default:
printf("error type!\n");
break;
}
//Next State
x[i]+=step[i];
if(x[i]>(width-win[i])){
x[i] = 0;
y[i]+=step[i];
if(y[i]>(height-win[i])){
y[i] = 0;
win[i]*=factor[i];
if(win[i]>width || win[i]>height){
win[i]=opt.objSize;
tranType[i]++;
if(tranType[i]>7){
tranType[i] = 0;
current_id[i]+=opt.numThreads;
if(current_id[i]>=list.size()){
current_id[i]=i;
Mat tmg = imread(list[current_id[i]],CV_LOAD_IMAGE_GRAYSCALE);
NegImgs[i] = tmg.clone();
srand(time(0)+i);
factor[i] = 1.+(float)(rand()%50)/100.0;
step[i] = 12+rand()%12;
}
else{
Mat tmg = imread(list[current_id[i]],CV_LOAD_IMAGE_GRAYSCALE);
NegImgs[i] = tmg.clone();
}
}
}
}
}
return region;
}
void DataSet::ImgClear(){
imgs.clear();
vector<Mat> blank;
imgs.swap(blank);
}
void DataSet::Remove(vector<int> PassIndex){
const Options& opt = Options::GetInstance();
int passNum = PassIndex.size();
vector<Mat> tmpImgs;
float* tmpFx = new float[size+opt.numThreads];
for(int i = 0;i<size+opt.numThreads;i++)
tmpFx[i] = 0;
for(int i = 0;i<passNum;i++){
tmpImgs.push_back(imgs[PassIndex[i]]);
tmpFx[i] = Fx[PassIndex[i]];
}
memcpy(Fx,tmpFx,(size+opt.numThreads)*sizeof(float));
imgs = tmpImgs;
size = passNum;
delete []tmpFx;
}
Mat DataSet::ExtractPixel(){
Options& opt = Options::GetInstance();
int numThreads = opt.numThreads;
omp_set_num_threads(numThreads);
size_t height = opt.objSize;
size_t width = opt.objSize;
size_t numPixels = height * width;
size_t numImgs = size;
size_t feaDims = numPixels * (numPixels - 1) / 2;
Mat fea = Mat(numPixels,numImgs,CV_8UC1);
#pragma omp parallel for
for(int k = 0; k < numImgs; k++)
{
int x,y;
Mat img = imgs[k];
for(int i = 0; i < numPixels; i++)
{
y = i%opt.objSize;
x = i/opt.objSize;
fea.at<uchar>(i,k) = img.at<uchar>(x,y);
}
}
return fea;
}
void DataSet::initWeights(){
Options& opt = Options::GetInstance();
W = new float[size];
for(int i = 0;i<size;i++)
W[i]=1./size;
Fx = new float[size+opt.numThreads];
for(int i = 0;i<size;i++)
Fx[i]=0;
}
void DataSet::CalcWeight(int y, int maxWeight){
float s = 0;
for(int i = 0;i<size;i++){
W[i]=min(exp(-y*Fx[i]),float(maxWeight));
s += W[i];
}
if (s == 0)
for(int i = 0;i<size;i++)
W[i]=1/size;
else
for(int i = 0;i<size;i++)
W[i]/=s;
}
void DataSet::Clear(){
delete []W;
delete []Fx;
}
| 25.277008 | 87 | 0.564384 | [
"vector"
] |
d424e87da111aeb02207785424b115396678220a | 26,972 | hpp | C++ | lib/base.hpp | adamsol/Pyxell | 15f4e4918853a408fcf6a6d65ffd0be6f2b772a6 | [
"MIT"
] | 46 | 2018-08-31T03:37:49.000Z | 2022-03-08T19:31:35.000Z | lib/base.hpp | adamsol/Pyxell | 15f4e4918853a408fcf6a6d65ffd0be6f2b772a6 | [
"MIT"
] | 14 | 2020-11-01T04:28:55.000Z | 2021-06-02T16:37:05.000Z | lib/base.hpp | adamsol/Pyxell | 15f4e4918853a408fcf6a6d65ffd0be6f2b772a6 | [
"MIT"
] | 5 | 2020-11-17T21:40:33.000Z | 2021-05-30T06:04:51.000Z |
#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <ctime>
#include <limits>
#include <functional>
#include <iostream>
#include <iterator>
#include <memory>
#include <optional>
#include <random>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "indy256/bigint.h"
#include "tsl/ordered_map.h"
#include "tsl/ordered_set.h"
using namespace std::literals::string_literals;
// https://github.com/godotengine/godot/pull/33376
#if defined(__MINGW32__) || (defined(_MSC_VER) && _MSC_VER < 1900 && defined(_TWO_DIGIT_EXPONENT)) && !defined(_UCRT)
unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT);
#endif
/* Types */
using Unknown = void*;
using Void = void;
using Int = long long;
using Float = double;
using Char = char;
using Bool = bool;
/* Rational */
struct Rat
{
bigint numerator, denominator;
Rat(): denominator(1) {}
Rat(long long n): numerator(n), denominator(1) {}
Rat(const bigint& n): numerator(n), denominator(1) {}
Rat(const std::string& s)
{
std::size_t p = s.find('.');
if (p == s.npos) {
numerator = bigint(s);
denominator = bigint(1);
} else {
numerator = bigint(s.substr(0, p) + s.substr(p+1));
denominator = bigint('1' + std::string(s.size()-p-1, '0'));
reduce();
}
}
void reduce()
{
if (denominator != 1 && denominator != -1) {
bigint d = gcd(numerator, denominator);
if (d != 1 && d != -1) {
numerator /= d;
denominator /= d;
}
}
numerator.sign *= denominator.sign;
denominator.sign = 1;
}
Rat& operator *= (const Rat& other)
{
numerator *= other.numerator;
denominator *= other.denominator;
reduce();
return *this;
}
Rat& operator /= (const Rat& other)
{
numerator *= other.denominator;
denominator *= other.numerator;
reduce();
return *this;
}
Rat& operator %= (const Rat& other)
{
numerator = (numerator * other.denominator) % (other.numerator * denominator);
denominator *= other.denominator;
reduce();
return *this;
}
Rat& operator += (const Rat& other)
{
if (denominator == other.denominator) {
numerator += other.numerator;
} else {
numerator *= other.denominator;
numerator += denominator * other.numerator;
denominator *= other.denominator;
}
reduce();
return *this;
}
Rat& operator -= (const Rat& other)
{
if (denominator == other.denominator) {
numerator -= other.numerator;
} else {
numerator *= other.denominator;
numerator -= denominator * other.numerator;
denominator *= other.denominator;
}
reduce();
return *this;
}
operator double () const
{
return numerator.doubleValue() / denominator.doubleValue();
}
bool operator == (const Rat& other) const { return numerator == other.numerator && denominator == other.denominator; }
bool operator != (const Rat& other) const { return numerator != other.numerator || denominator != other.denominator; }
bool operator < (const Rat& other) const { return numerator * other.denominator < denominator * other.numerator; }
bool operator > (const Rat& other) const { return numerator * other.denominator > denominator * other.numerator; }
bool operator <= (const Rat& other) const { return numerator * other.denominator <= denominator * other.numerator; }
bool operator >= (const Rat& other) const { return numerator * other.denominator >= denominator * other.numerator; }
};
Rat operator * (Rat a, const Rat& b)
{
return a *= b;
}
Rat operator / (Rat a, const Rat& b)
{
return a /= b;
}
Rat operator % (Rat a, const Rat& b)
{
return a %= b;
}
Rat operator + (Rat a, const Rat& b)
{
return a += b;
}
Rat operator - (Rat a, const Rat& b)
{
return a -= b;
}
Rat operator - (Rat a)
{
if (!a.numerator.isZero()) {
a.numerator.sign = -a.numerator.sign;
}
return a;
}
namespace std
{
template <>
struct hash<Rat>
{
size_t operator () (const Rat& x) const
{
std::size_t seed = 0;
for (int e: x.numerator.z) {
seed ^= hash<int>()(e) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
for (int e: x.denominator.z) {
seed ^= hash<int>()(e) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
}
/* Wrapper around shared_ptr for proper comparison operators and hash function */
template <typename T>
struct custom_ptr
{
std::shared_ptr<T> p;
custom_ptr() {}
custom_ptr(std::shared_ptr<T> p): p(p) {}
T& operator * () const { return *p; }
T* operator -> () const { return p.get(); }
};
template <typename T> bool operator == (const custom_ptr<T>& lhs, const custom_ptr<T>& rhs) { return *lhs == *rhs; }
template <typename T> bool operator != (const custom_ptr<T>& lhs, const custom_ptr<T>& rhs) { return *lhs != *rhs; }
template <typename T> bool operator < (const custom_ptr<T>& lhs, const custom_ptr<T>& rhs) { return *lhs < *rhs; }
template <typename T> bool operator > (const custom_ptr<T>& lhs, const custom_ptr<T>& rhs) { return *lhs > *rhs; }
template <typename T> bool operator <= (const custom_ptr<T>& lhs, const custom_ptr<T>& rhs) { return *lhs <= *rhs; }
template <typename T> bool operator >= (const custom_ptr<T>& lhs, const custom_ptr<T>& rhs) { return *lhs >= *rhs; }
/* String */
struct String: public custom_ptr<std::string>
{
using iterator = typename std::string::iterator;
using custom_ptr<std::string>::custom_ptr;
String(Char x)
{
this->p = std::make_shared<std::string>(1, x);
}
};
template <typename... Args>
String make_string(Args&&... args)
{
return String(std::make_shared<std::string>(std::forward<Args>(args)...));
}
namespace std
{
template <>
struct hash<String>
{
size_t operator () (const String& x) const
{
return hash<std::string>()(*x);
}
};
}
/* Array */
template <typename T>
struct Array: public custom_ptr<std::vector<T>>
{
using iterator = typename std::vector<T>::iterator;
using custom_ptr<std::vector<T>>::custom_ptr;
Array(const Array<Unknown>& x)
{
this->p = std::make_shared<std::vector<T>>();
}
template <typename U>
Array(const Array<U>& x)
{
this->p = std::make_shared<std::vector<T>>(x->begin(), x->end());
}
};
template <typename T>
Array<T> make_array(std::initializer_list<T> x)
{
return Array<T>(std::make_shared<std::vector<T>>(x));
}
template <typename T, typename... Args>
Array<T> make_array(Args&&... args)
{
return Array<T>(std::make_shared<std::vector<T>>(std::forward<Args>(args)...));
}
/* Set */
template <typename T>
struct Set: public custom_ptr<tsl::ordered_set<T>>
{
using iterator = typename tsl::ordered_set<T>::iterator;
using custom_ptr<tsl::ordered_set<T>>::custom_ptr;
Set(const Set<Unknown>& x)
{
this->p = std::make_shared<tsl::ordered_set<T>>();
}
template <typename U>
Set(const Set<U>& x)
{
this->p = std::make_shared<tsl::ordered_set<T>>(x->begin(), x->end());
}
};
template <typename T>
Set<T> make_set(std::initializer_list<T> x)
{
return Set<T>(std::make_shared<tsl::ordered_set<T>>(x));
}
template <typename T, typename... Args>
Set<T> make_set(Args&&... args)
{
return Set<T>(std::make_shared<tsl::ordered_set<T>>(std::forward<Args>(args)...));
}
/* Dict */
template <typename K, typename V>
struct Dict: public custom_ptr<tsl::ordered_map<K, V>>
{
using iterator = typename tsl::ordered_map<K, V>::iterator;
using custom_ptr<tsl::ordered_map<K, V>>::custom_ptr;
Dict(const Dict<Unknown, Unknown>& x)
{
this->p = std::make_shared<tsl::ordered_map<K, V>>();
}
template <typename L, typename W>
Dict(const Dict<L, W>& x)
{
this->p = std::make_shared<tsl::ordered_map<K, V>>(x->begin(), x->end());
}
};
template <typename K, typename V>
Dict<K, V> make_dict(std::initializer_list<std::pair<const K, V>> x)
{
auto r = Dict<K, V>(std::make_shared<tsl::ordered_map<K, V>>());
for (auto&& p: x) {
r->insert_or_assign(p.first, p.second);
}
return r;
}
template <typename K, typename V, typename... Args>
Dict<K, V> make_dict(Args&&... args)
{
return Dict<K, V>(std::make_shared<tsl::ordered_map<K, V>>(std::forward<Args>(args)...));
}
/* Generator */
template <typename T>
struct GeneratorValue
{
T value;
};
template <>
struct GeneratorValue<Void>
{
};
template <typename T>
struct GeneratorBase: GeneratorValue<T>
{
int state = 0;
virtual void run() {
state = -1;
}
T next(Int n = 1) {
while (n-- && state != -1) {
run();
}
if constexpr (!std::is_same<T, Void>::value) {
return this->value;
}
}
};
template <typename T>
using Generator = std::shared_ptr<GeneratorBase<T>>;
/* Nullable */
template <typename T>
struct Nullable: public std::optional<T>
{
using std::optional<T>::optional;
operator bool () = delete; // so that null isn't displayed as false
Nullable(const Nullable<Unknown>& x): std::optional<T>() {}
};
template <typename T>
bool operator == (const Nullable<T>& lhs, const Nullable<T>& rhs)
{
return static_cast<std::optional<T>>(lhs) == static_cast<std::optional<T>>(rhs);
}
template <typename T>
bool operator != (const Nullable<T>& lhs, const Nullable<T>& rhs)
{
return static_cast<std::optional<T>>(lhs) != static_cast<std::optional<T>>(rhs);
}
template <typename T>
struct std::hash<Nullable<T>>
{
std::size_t operator () (const Nullable<T>& x) const
{
return hash<std::optional<T>>()(x);
}
};
/* Tuple */
template <typename... T>
using Tuple = std::tuple<T...>;
// https://www.variadic.xyz/2018/01/15/hashing-stdpair-and-stdtuple/
// https://stackoverflow.com/a/15124153
// https://stackoverflow.com/a/7115547
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1406r0.html
template<typename... T>
struct std::hash<Tuple<T...>>
{
template<typename E>
std::size_t get_hash(const E& x) const
{
return std::hash<E>()(x);
}
template<std::size_t I>
void combine_hash(std::size_t& seed, const Tuple<T...>& x) const
{
seed ^= get_hash(std::get<I>(x)) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
if constexpr(I+1 < sizeof...(T)) {
combine_hash<I+1>(seed, x);
}
}
std::size_t operator () (const Tuple<T...>& x) const
{
std::size_t seed = 0;
combine_hash<0>(seed, x);
return seed;
}
};
/* Class */
template <typename... T>
using Object = std::shared_ptr<T...>;
/* Arithmetic operators */
Int floordiv(Int a, Int b)
{
if (b < 0) {
return floordiv(-a, -b);
}
if (a < 0) {
a -= b - 1;
}
return a / b;
}
Rat floordiv(const Rat& a, const Rat& b)
{
if (b.numerator.sign < 0) {
return floordiv(-a, -b);
}
bigint c = a.numerator * b.denominator;
bigint d = b.numerator * a.denominator;
if (c.sign < 0) {
c -= d - 1;
}
Rat r;
r.numerator = c / d;
return r;
}
Int mod(Int a, Int b)
{
if (b < 0) {
return -mod(-a, -b);
}
Int r = a % b;
if (r < 0) {
r += b;
}
return r;
}
Rat mod(const Rat& a, const Rat& b)
{
if (b.numerator.sign < 0) {
return -mod(-a, -b);
}
Rat r = a % b;
if (r.numerator.sign < 0) {
r += b;
}
return r;
}
Int pow(Int b, Int e)
{
if (e < 0) {
return b == -1 && e % 2 == -1 ? -1 : b == 1 || b == -1 ? 1 : 0;
}
Int r = 1;
while (e > 0) {
if (e & 1) {
r *= b;
}
b *= b;
e >>= 1;
}
return r;
}
Rat pow(Rat b, Int e)
{
if (e < 0) {
std::swap(b.numerator, b.denominator);
e = -e;
}
Rat r = 1;
while (e > 0) {
if (e & 1) {
r *= b;
}
b *= b;
e >>= 1;
}
return r;
}
Int bitNot(Int a)
{
return ~a;
}
Int bitShift(Int a, Int b)
{
return b >= 0 ? a << b : a >> -b;
}
Int bitAnd(Int a, Int b)
{
return a & b;
}
Int bitXor(Int a, Int b)
{
return a ^ b;
}
Int bitOr(Int a, Int b)
{
return a | b;
}
/* Container operators */
String concat(const String& a, const String& b)
{
return make_string(*a + *b);
}
template <typename T>
Array<T> concat(const Array<T>& a, const Array<T>& b)
{
auto r = make_array<T>(*a);
r->insert(r->end(), b->begin(), b->end());
return r;
}
template <typename T>
Set<T> concat(const Set<T>& a, const Set<T>& b)
{
auto r = make_set<T>(*a);
r->insert(b->begin(), b->end());
return r;
}
template <typename K, typename V>
Dict<K, V> concat(const Dict<K, V>& a, const Dict<K, V>& b)
{
auto r = make_dict<K, V>(*a);
for (auto&& e: *b) {
r->insert_or_assign(e.first, e.second);
}
return r;
}
template <typename T>
Set<T> difference(const Set<T>& a, const Set<T>& b)
{
auto r = make_set<T>();
// https://stackoverflow.com/a/22711060
std::copy_if(a->begin(), a->end(), std::inserter(*r, r->begin()),
[&b](const T& e) { return b->find(e) == b->end(); });
return r;
}
template <typename T>
Set<T> intersection(const Set<T>& a, const Set<T>& b)
{
auto r = make_set<T>();
std::copy_if(a->begin(), a->end(), std::inserter(*r, r->begin()),
[&b](const T& e) { return b->find(e) != b->end(); });
return r;
}
template <typename T>
T multiply(const T& v, Int m)
{
m = std::max(m, 0LL);
auto r = T(v.size()*m, typename T::value_type());
for (std::size_t i = 0; i < v.size(); ++i) {
for (std::size_t j = 0; j < m; ++j) {
r[j*v.size()+i] = v[i];
}
}
return r;
}
String multiply(const String& x, Int m)
{
return make_string(multiply(*x, m));
}
template <typename T>
Array<T> multiply(const Array<T>& x, Int m)
{
return make_array<T>(multiply(*x, m));
}
template <typename T>
T slice(const T& v, const Nullable<Int>& a, const Nullable<Int>& b, Int step)
{
Int length = v.size();
Int start;
if (a.has_value()) {
start = a.value();
if (start < 0) {
start += length;
}
start += step > 0 ? 0 : 1;
} else {
start = step > 0 ? 0 : length;
}
start = std::clamp(start, 0LL, length);
Int end;
if (b.has_value()) {
end = b.value();
if (end < 0) {
end += length;
}
end += step > 0 ? 0 : 1;
} else {
end = step > 0 ? length : 0;
}
end = std::clamp(end, 0LL, length);
auto r = T();
if (step > 0) {
for (Int i = start; i < end; i += step) {
r.push_back(v[i]);
}
} else {
for (Int i = start; i > end; i += step) {
r.push_back(v[i-1]);
}
}
return r;
}
String slice(const String& x, const Nullable<Int>& a, const Nullable<Int>& b, Int c)
{
return make_string(slice(*x, a, b, c));
}
template <typename T>
Array<T> slice(const Array<T>& x, const Nullable<Int>& a, const Nullable<Int>& b, Int c)
{
return make_array<T>(slice(*x, a, b, c));
}
/* Container methods */
template <typename T>
Nullable<typename T::value_type> get(const custom_ptr<T>& x, Int i)
{
if (i < 0) {
i += x->size();
}
if (0 <= i && i < x->size()) {
return Nullable<typename T::value_type>((*x)[i]);
} else {
return Nullable<typename T::value_type>();
}
}
/* String methods */
Array<String> split(const String& x, const String& y)
{
auto r = make_array<String>();
std::size_t start = 0;
while (true) {
auto end = x->find(*y, start);
if (y->empty()) {
end += 1;
} else if (end == std::string::npos) {
end = x->size();
}
r->push_back(make_string(x->substr(start, end-start)));
if (end == x->size()) {
return r;
}
start = end + y->size();
}
}
Nullable<Int> find(const String& x, const String& y, Int i)
{
if (i < 0) {
i += x->size();
}
auto p = x->find(*y, i);
if (p != std::string::npos) {
return Nullable<Int>(p);
} else {
return Nullable<Int>();
}
}
Int count(const String& x, Char e)
{
return std::count(x->begin(), x->end(), e);
}
Bool has(const String& x, const String& y)
{
return x->find(*y) != std::string::npos;
}
Bool starts(const String& x, const String& y)
{
return x->rfind(*y, 0) == 0;
}
Bool ends(const String& x, const String& y)
{
return x->find(*y, x->size() - y->size()) != std::string::npos;
}
/* Array methods */
String join(const Array<Char>& x, const String& sep)
{
if (sep->size() == 0) {
return make_string(x->begin(), x->end());
}
auto r = make_string();
for (auto it = x->begin(); it != x->end(); ++it) {
if (it != x->begin()) {
r->append(*sep);
}
r->push_back(*it);
}
return r;
}
String join(const Array<String>& x, const String& sep)
{
auto r = make_string();
for (auto it = x->begin(); it != x->end(); ++it) {
if (it != x->begin()) {
r->append(*sep);
}
r->append(**it);
}
return r;
}
String join(const Array<Unknown>& x, const String& sep)
{
return sep;
}
template <typename T>
Void push(const Array<T>& x, const T& e)
{
x->push_back(e);
}
template <typename T>
Void insert(const Array<T>& x, Int p, const T& e)
{
if (p < 0) {
p += x->size();
}
x->insert(x->begin()+p, e);
}
template <typename T>
Void extend(const Array<T>& x, const Array<T>& y)
{
x->reserve(x->size() + y->size());
x->insert(x->end(), y->begin(), y->end());
}
template <typename T>
T pop(const Array<T>& x)
{
auto r = x->back();
x->pop_back();
return r;
}
template <typename T>
Void erase(const Array<T>& x, Int p, Int n)
{
if (p < 0) {
p += x->size();
}
x->erase(x->begin()+p, x->begin()+p+n);
}
template <typename T>
Void clear(const Array<T>& x)
{
x->clear();
}
template <typename T>
Array<T> reverse(const Array<T>& x)
{
std::reverse(x->begin(), x->end());
return x;
}
template <typename T, typename K>
Array<T> sort(const Array<T>& x, Bool reverse, std::function<K(T)> key)
{
if (reverse) {
std::stable_sort(x->begin(), x->end(), [&](const T& a, const T& b) { return key(a) > key(b); });
} else {
std::stable_sort(x->begin(), x->end(), [&](const T& a, const T& b) { return key(a) < key(b); });
}
return x;
}
template <typename T>
Array<T> copy(const Array<T>& x)
{
return make_array<T>(*x);
}
template <typename T>
Nullable<Int> find(const Array<T>& x, const T& e, Int i)
{
if (i < 0) {
i += x->size();
}
for (; i < x->size(); ++i) {
if ((*x)[i] == e) {
return Nullable<Int>(i);
}
}
return Nullable<Int>();
}
template <typename T>
Int count(const Array<T>& x, const T& e)
{
return std::count(x->begin(), x->end(), e);
}
template <typename T>
Bool has(const Array<T>& x, const T& e)
{
return std::find(x->begin(), x->end(), e) != x->end();
}
/* Set methods */
template <typename T>
Void add(const Set<T>& x, const T& e)
{
x->insert(e);
}
template <typename T>
Void union_(const Set<T>& x, const Set<T>& y)
{
x->insert(y->begin(), y->end());
}
template <typename T>
Void subtract(const Set<T>& x, const Set<T>& y)
{
for (auto&& e: *y) {
x->unordered_erase(e);
}
}
template <typename T>
Void intersect(const Set<T>& x, const Set<T>& y)
{
subtract(x, difference(x, y));
}
template <typename T>
T pop(const Set<T>& x)
{
auto r = x->back();
x->pop_back();
return r;
}
template <typename T>
Void remove(const Set<T>& x, const T& e)
{
x->unordered_erase(e);
}
template <typename T>
Void clear(const Set<T>& x)
{
x->clear();
}
template <typename T>
Set<T> copy(const Set<T>& x)
{
return make_set<T>(*x);
}
template <typename T>
bool has(const Set<T>& x, const T& e)
{
return x->find(e) != x->end();
}
/* Dict methods */
template <typename K, typename V>
Void update(const Dict<K, V>& x, const Dict<K, V>& y)
{
for (auto&& e: *y) {
x->insert_or_assign(e.first, e.second);
}
}
template <typename K, typename V>
Nullable<V> get(const Dict<K, V>& x, const K& e)
{
auto it = x->find(e);
if (it != x->end()) {
return Nullable<V>(it->second);
} else {
return Nullable<V>();
}
}
template <typename K, typename V>
Tuple<K, V> pop(const Dict<K, V>& x)
{
auto r = x->back();
x->pop_back();
return r;
}
template <typename K, typename V>
Void remove(const Dict<K, V>& x, const K& e)
{
x->unordered_erase(e);
}
template <typename K, typename V>
Void clear(const Dict<K, V>& x)
{
x->clear();
}
template <typename K, typename V>
Dict<K, V> copy(const Dict<K, V>& x)
{
return make_dict<K, V>(*x);
}
template <typename K, typename V>
Bool has(const Dict<K, V>& x, const K& e)
{
return x->find(e) != x->end();
}
/* Conversion to String */
template <typename T> String toString(const Array<T>& x);
template <typename T> String toString(const Set<T>& x);
template <typename K, typename V> String toString(const Dict<K, V>& x);
template <typename T> String toString(const Nullable<T>& x);
template <std::size_t I = 0, typename... T> String toString(const Tuple<T...>& x);
template <typename T> String toString(const Object<T>& x);
String toString(Int x)
{
return make_string(std::to_string(x));
}
String toString(const Rat& x)
{
if (x.denominator == 1) {
return make_string(x.numerator.to_string());
}
Int d = x.denominator.to_string().size() + 6; // at least 6 digits after the decimal point
Rat y = floordiv(x.numerator.sign < 0 ? -x : x, pow(Rat(10), -d));
std::string s = y.numerator.to_string();
if (s.size() <= d) {
s.insert(0, d - s.size() + 1, '0');
}
s.insert(s.size() - d, ".");
char l = s.back();
s.pop_back();
if (l >= '5') {
while (s.back() == '9') {
s.pop_back();
}
s.back() += 1;
}
while (s.back() == '0') {
s.pop_back();
}
if (x.numerator.sign < 0) {
s.insert(0, "-");
}
return make_string(s);
}
String toString(Float x)
{
static char buffer[25];
sprintf(buffer, "%.15g", x);
return make_string(buffer);
}
String toString(Bool x)
{
return make_string(x ? "true" : "false");
}
std::string transform_character_to_display(char c)
{
switch (c) {
case '\\': return "\\\\";
case '\n': return "\\n";
case '\r': return "\\r";
case '\t': return "\\t";
case '\0': return "\\0";
}
return std::string(1, c);
}
String toString(Char x)
{
auto r = make_string();
r->append("'");
if (x == '\'') {
r->append("\\'");
} else {
r->append(transform_character_to_display(x));
}
r->append("'");
return r;
}
String toString(const String& x)
{
auto r = make_string();
r->append("\"");
for (auto c: *x) {
if (c == '"') {
r->append("\\\"");
} else {
r->append(transform_character_to_display(c));
}
}
r->append("\"");
return r;
}
template <typename T>
String toString(const Array<T>& x)
{
auto r = make_string();
r->append("[");
for (std::size_t i = 0; i < x->size(); ++i) {
if (i > 0) {
r->append(", ");
}
r->append(*toString((*x)[i]));
}
r->append("]");
return r;
}
template <typename T>
String toString(const Set<T>& x)
{
auto r = make_string();
r->append("{");
for (auto it = x->begin(); it != x->end(); ++it) {
if (it != x->begin()) {
r->append(", ");
}
r->append(*toString(*it));
}
r->append("}");
return r;
}
template <typename K, typename V>
String toString(const Dict<K, V>& x)
{
if (x->empty()) {
return make_string("{:}");
}
auto r = make_string();
r->append("{");
for (auto it = x->begin(); it != x->end(); ++it) {
if (it != x->begin()) {
r->append(", ");
}
r->append(*toString(it->first));
r->append(": ");
r->append(*toString(it->second));
}
r->append("}");
return r;
}
template <typename T>
String toString(const Nullable<T>& x)
{
if (x.has_value()) {
return toString(x.value());
} else {
return make_string("null");
}
}
template <std::size_t I /* = 0 is already in the declaration */, typename... T>
String toString(const Tuple<T...>& x)
{
// https://stackoverflow.com/a/54225452
auto r = make_string();
if constexpr(I == 0) {
r->append("(");
}
r->append(*toString(std::get<I>(x)));
if constexpr(I+1 < sizeof...(T)) {
r->append(", ");
r->append(*toString<I+1>(x));
} else {
r->append(")");
}
return r;
}
template <typename T>
String toString(const Object<T>& x)
{
return make_string("<" + *reinterpret_cast<String (*)(Object<T>)>(x->toString())(x) + ">");
}
/* Conversion to Int */
Int toInt(Int x)
{
return x;
}
Int toInt(const Rat& x)
{
return x.numerator.longValue() / x.denominator.longValue();
}
Int toInt(Float x)
{
return static_cast<Int>(x);
}
Int toInt(const String& x)
{
return std::stoll(*x);
}
/* Conversion to Rat */
Rat toRat(const String& x)
{
return Rat(*x);
}
/* Conversion to Float */
Float toFloat(const String& x)
{
return std::stod(*x);
}
/* Standard output */
Void write(const String& x)
{
std::cout << *x;
}
/* Standard input */
String read()
{
auto r = make_string();
std::cin >> *r;
return r;
}
String readLine()
{
auto r = make_string();
std::getline(std::cin, *r);
return r;
}
Int readInt()
{
Int r;
std::cin >> r;
return r;
}
Rat readRat()
{
return Rat(*read());
}
Float readFloat()
{
Float r;
std::cin >> r;
return r;
}
Char readChar()
{
Char r;
std::cin >> r;
return r;
}
/* Random numbers */
std::mt19937_64 generator(time(nullptr));
void seed(Int x)
{
generator.seed(x);
}
Int _rand()
{
return generator() & std::numeric_limits<Int>::max();
}
Int randInt(Int r)
{
return _rand() % r;
}
Float randFloat(Float r)
{
return _rand() * r / std::numeric_limits<Int>::max();
}
| 20.892332 | 122 | 0.546863 | [
"object",
"vector"
] |
d429bab6c9c90fa68fd8440209b645be27b0d495 | 4,664 | cpp | C++ | Classes/Manager/Sound/SoundMgr.cpp | WeHaveCookie/EnchantedForest | c17e3e1adf3bc0c1ef5afaef3126fd169ea99768 | [
"MIT"
] | null | null | null | Classes/Manager/Sound/SoundMgr.cpp | WeHaveCookie/EnchantedForest | c17e3e1adf3bc0c1ef5afaef3126fd169ea99768 | [
"MIT"
] | null | null | null | Classes/Manager/Sound/SoundMgr.cpp | WeHaveCookie/EnchantedForest | c17e3e1adf3bc0c1ef5afaef3126fd169ea99768 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "SoundMgr.h"
#include "Manager/File/FileMgr.h"
#include "Utils/wcharUtils.h"
SoundMgr* SoundMgr::s_singleton = NULL;
SoundMgr::SoundMgr()
:Manager(ManagerType::Enum::Sound)
{
s_singleton = this;
}
SoundMgr::~SoundMgr()
{
delete m_musics;
delete m_sounds;
}
void SoundMgr::init()
{
m_processTime = sf::Time::Zero;
m_musics = new MusicComponentPool(10);
m_sounds = new SoundComponentPool(244);
}
void SoundMgr::process(const float dt)
{
sf::Clock clock;
m_sounds->process(dt);
m_musics->process(dt);
m_processTime = clock.getElapsedTime();
}
void SoundMgr::end()
{
free(m_sounds);
free(m_musics);
}
void SoundMgr::showImGuiWindow(bool* window)
{
if (ImGui::Begin("SoundMgr", window))
{
std::vector<std::wstring> files;
FileMgr::GetFilesInDirectory(files, L"Data/Sound/Ambiant", L".ogg");
char** musicsLabel = (char**)malloc(sizeof(char*) * files.size());
static int musicID = 0;
for (unsigned int i = 0; i < files.size(); i++)
{
musicsLabel[i] = (char*)malloc(sizeof(char) * files[i].size() + 1); // +1 for null terminated
strcpy(musicsLabel[i], WideChartoAscii(files[i]).c_str());
}
ImGui::Combo("Music", &musicID, (const char**)musicsLabel, files.size());
ImGui::SameLine();
if (ImGui::Button("Create###1"))
{
SoundMgr::getSingleton()->addMusic(musicsLabel[musicID], false, true);
}
for (unsigned int i = 0; i < files.size(); i++)
{
free(musicsLabel[i]);
}
free(musicsLabel);
{
std::vector<std::wstring> files;
FileMgr::GetFilesInDirectory(files, L"Data/Sound/FX", L".ogg");
char** soundsLabel = (char**)malloc(sizeof(char*) * files.size());
static int soundID = 0;
for (unsigned int i = 0; i < files.size(); i++)
{
soundsLabel[i] = (char*)malloc(sizeof(char) * files[i].size() + 1); // +1 for null terminated
strcpy(soundsLabel[i], WideChartoAscii(files[i]).c_str());
}
ImGui::Combo("Sound", &soundID, (const char**)soundsLabel, files.size());
ImGui::SameLine();
if (ImGui::Button("Create###2"))
{
SoundMgr::getSingleton()->addSound(soundsLabel[soundID], false, true);
}
for (unsigned int i = 0; i < files.size(); i++)
{
free(soundsLabel[i]);
}
free(soundsLabel);
}
if(ImGui::CollapsingHeader("Musics"))
{
for (auto& music : m_musics->getMusicsUsed())
{
ImGui::Text("%i : %s", music->getUID(), music->getName());
if (ImGui::IsItemClicked())
{
music->showInfo();
}
ImGui::SameLine();
std::string label = "Play###MP" + std::to_string(music->getUID());
if (ImGui::Button(label.c_str()))
{
music->setPlay(true);
}
ImGui::SameLine();
label = "Stop###MS" + std::to_string(music->getUID());
if (ImGui::Button(label.c_str()))
{
music->stop();
}
ImGui::SameLine();
bool loop = music->isLoop();
label = "Loop###ML" + std::to_string(music->getUID());
ImGui::Checkbox(label.c_str(), &loop);
music->setLoop(loop);
ImGui::SameLine();
label = "Delete###MD" + std::to_string(music->getUID());
if (ImGui::Button(label.c_str()))
{
removeMusic(music->getUID());
}
}
}
if (ImGui::CollapsingHeader("Sounds"))
{
for (auto& sound : m_sounds->getSoundsUsed())
{
ImGui::Text("%i : %s", sound->getUID(), sound->getName());
if (ImGui::IsItemClicked())
{
sound->showInfo();
}
ImGui::SameLine();
std::string label = "Play###SP" + std::to_string(sound->getUID());
if (ImGui::Button(label.c_str()))
{
sound->setPlay(true);
}
ImGui::SameLine();
label = "Stop###SS" + std::to_string(sound->getUID());
if (ImGui::Button(label.c_str()))
{
sound->stop();
}
ImGui::SameLine();
bool loop = sound->isLoop();
label = "Loop###SL" + std::to_string(sound->getUID());
ImGui::Checkbox(label.c_str(), &loop);
sound->setLoop(loop);
ImGui::SameLine();
label = "Delete###SD" + std::to_string(sound->getUID());
if (ImGui::Button(label.c_str()))
{
removeSound(sound->getUID());
}
}
}
}
ImGui::End();
}
uint32_t SoundMgr::addSound(const char* path, bool loop, bool persistent)
{
return m_sounds->create(path, loop, persistent);
}
uint32_t SoundMgr::addMusic(const char* path, bool loop, bool persistent)
{
return m_musics->create(path, loop, persistent);
}
void SoundMgr::removeSound(uint32_t id)
{
m_sounds->release(id);
}
void SoundMgr::removeMusic(uint32_t id)
{
m_musics->release(id);
}
SoundComponent* SoundMgr::getSound(uint32_t id)
{
return m_sounds->getSound(id);
}
MusicComponent* SoundMgr::getMusic(uint32_t id)
{
return m_musics->getMusic(id);
} | 22.862745 | 97 | 0.620497 | [
"vector"
] |
2d6cf714fd41aceff8249ee14d558e019b6d9885 | 7,505 | cpp | C++ | 3DEngine/src/3D Engine/Components/Base/Transform.cpp | tobbep1997/Bitfrost_2.0 | a092db19d4658062554b7df759f28439fc1ad4f8 | [
"Apache-2.0"
] | null | null | null | 3DEngine/src/3D Engine/Components/Base/Transform.cpp | tobbep1997/Bitfrost_2.0 | a092db19d4658062554b7df759f28439fc1ad4f8 | [
"Apache-2.0"
] | null | null | null | 3DEngine/src/3D Engine/Components/Base/Transform.cpp | tobbep1997/Bitfrost_2.0 | a092db19d4658062554b7df759f28439fc1ad4f8 | [
"Apache-2.0"
] | null | null | null | #include "3DEngine/EnginePCH.h"
#include "Transform.h"
float constexpr GetNewValueInNewRange(float value, float rangeMin, float rangeMax, float newRangeMin, float newRangeMax)
{
if (value > rangeMax)
{
return newRangeMax;
}
else
{
return ((value - rangeMin) * ((newRangeMax - newRangeMin) / (rangeMax - rangeMin))) + newRangeMin;
}
}
float constexpr valueInRange(float value, float min, float max)
{
return ((value - min) / (max - min));
}
void Transform::p_calcWorldMatrix()
{
using namespace DirectX;
XMMATRIX translation = DirectX::XMMatrixIdentity();
XMMATRIX scaling = DirectX::XMMatrixIdentity();
XMMATRIX rotation = DirectX::XMMatrixIdentity();
translation = XMMatrixTranslation(this->p_position.x, this->p_position.y, this->p_position.z);
scaling = XMMatrixScaling(this->p_scale.x, this->p_scale.y, this->p_scale.z);
if (p_physicsRotation._11 == INT16_MIN)
{
rotation = XMMatrixRotationRollPitchYaw(this->p_rotation.x, this->p_rotation.y, this->p_rotation.z);
//rotation = rotation * p_forcedRotation;
}
else
{
rotation = XMLoadFloat3x3(&p_physicsRotation);
}
XMMATRIX worldMatrix;
if (DirectX::XMMatrixIsIdentity(p_forcedWorld))
worldMatrix = XMMatrixTranspose(XMMatrixMultiply(scaling * rotation * translation, m_modelTransform));
else
worldMatrix = p_forcedWorld;
//XMMATRIX worldMatrix = XMMatrixTranspose(rotation * scaling * translation);
if (m_parent)
worldMatrix = XMMatrixMultiply(XMLoadFloat4x4A(&m_parent->GetWorldmatrix()), worldMatrix);
XMStoreFloat4x4A(&this->p_worldMatrix, worldMatrix);
}
void Transform::p_calcWorldMatrixForOutline(const float & lenght)
{
using namespace DirectX;
float scaleBy = GetNewValueInNewRange(lenght, 1.0f, 30.0f, 1.3f, 3.3f);
//scaleBy = 1.3f;
//valueInRange(lenght, 1.3f, 2.1f);
XMMATRIX translation = XMMatrixTranslation(this->p_position.x, this->p_position.y, this->p_position.z);
XMMATRIX scaling;
scaling = XMMatrixScaling(this->p_scale.x * scaleBy, this->p_scale.y * scaleBy, this->p_scale.z * scaleBy);
XMMATRIX rotation;
rotation = DirectX::XMMatrixIdentity();
if (p_physicsRotation._11 == INT16_MIN)
{
rotation = XMMatrixRotationRollPitchYaw(this->p_rotation.x, this->p_rotation.y, this->p_rotation.z);
//rotation = rotation * p_forcedRotation;
}
else
{
rotation = XMLoadFloat3x3(&p_physicsRotation);
}
XMMATRIX worldMatrix;
if (DirectX::XMMatrixIsIdentity(p_forcedWorld))
worldMatrix = XMMatrixTranspose(XMMatrixMultiply(scaling * rotation * translation, m_modelTransform));
else
worldMatrix = p_forcedWorld;
//XMMATRIX worldMatrix = XMMatrixTranspose(rotation * scaling * translation);
if (m_parent)
worldMatrix = XMMatrixMultiply(XMLoadFloat4x4A(&m_parent->GetWorldmatrix()), worldMatrix);
XMStoreFloat4x4A(&this->p_worldMatrix, worldMatrix);
}
void Transform::p_calcWorldMatrixForInsideOutline(const float& lenght)
{
using namespace DirectX;
float scaleBy = GetNewValueInNewRange(lenght, 1.0f, 30.0f, 1.0f, 2.5f);
//scaleBy = 1;
XMMATRIX translation = XMMatrixTranslation(this->p_position.x, this->p_position.y, this->p_position.z);
XMMATRIX scaling;
scaling = XMMatrixScaling(this->p_scale.x * scaleBy, this->p_scale.y * scaleBy, this->p_scale.z * scaleBy);
XMMATRIX rotation;
rotation = DirectX::XMMatrixIdentity();
if (p_physicsRotation._11 == INT16_MIN)
{
rotation = XMMatrixRotationRollPitchYaw(this->p_rotation.x, this->p_rotation.y, this->p_rotation.z);
//rotation = rotation * p_forcedRotation;
}
else
{
rotation = XMLoadFloat3x3(&p_physicsRotation);
}
XMMATRIX worldMatrix;
if (DirectX::XMMatrixIsIdentity(p_forcedWorld))
worldMatrix = XMMatrixTranspose(XMMatrixMultiply(scaling * rotation * translation, m_modelTransform));
else
worldMatrix = p_forcedWorld;
//XMMATRIX worldMatrix = XMMatrixTranspose(rotation * scaling * translation);
if (m_parent)
worldMatrix = XMMatrixMultiply(XMLoadFloat4x4A(&m_parent->GetWorldmatrix()), worldMatrix);
XMStoreFloat4x4A(&this->p_worldMatrix, worldMatrix);
}
Transform::Transform()
{
p_position = DirectX::XMFLOAT4A(0, 0, 0, 1);
p_rotation = DirectX::XMFLOAT4A(0, 0, 0, 1);
p_scale = DirectX::XMFLOAT4A(1, 1, 1, 1);
p_forcedWorld = DirectX::XMMatrixIdentity();
m_modelTransform = DirectX::XMMatrixIdentity();
p_physicsRotation._11 = INT16_MIN;
m_parent = nullptr;
}
Transform::~Transform()
{
}
void Transform::SetParent(Transform & parent)
{
this->m_parent = &parent;
}
const Transform & Transform::GetParent() const
{
return *this->m_parent;
}
void Transform::SetPosition(const DirectX::XMFLOAT4A & pos)
{
this->p_position = pos;
}
void Transform::SetPosition(const float & x, const float & y, const float & z, const float & w)
{
this->SetPosition(DirectX::XMFLOAT4A(x, y, z, w));
}
void Transform::Translate(const DirectX::XMFLOAT3 & translation)
{
this->p_position.x += translation.x;
this->p_position.y += translation.y;
this->p_position.z += translation.z;
}
void Transform::Translate(const float & x, const float & y, const float & z)
{
this->p_position.x += x;
this->p_position.y += y;
this->p_position.z += z;
}
void Transform::SetScale(const DirectX::XMFLOAT4A & scale)
{
this->p_scale = scale;
}
void Transform::SetScale(const float & x, const float & y, const float & z, const float & w)
{
this->SetScale(DirectX::XMFLOAT4A(x, y, z, w));
}
void Transform::AddScale(const DirectX::XMFLOAT3 & scale)
{
this->p_scale.x += scale.x;
this->p_scale.y += scale.y;
this->p_scale.z += scale.z;
}
void Transform::AddScale(const float & x, const float & y, const float & z)
{
this->p_scale.x += x;
this->p_scale.y += y;
this->p_scale.z += z;
}
void Transform::SetRotation(const DirectX::XMFLOAT4A & rot)
{
this->p_rotation = rot;
}
void Transform::SetRotation(const float & x, const float & y, const float & z, const float & w)
{
this->SetRotation(DirectX::XMFLOAT4A(x, y, z, w));
}
void Transform::AddRotation(const DirectX::XMFLOAT4A & rot)
{
this->p_rotation.x += rot.x;
this->p_rotation.y += rot.y;
this->p_rotation.z += rot.z;
this->p_rotation.w += rot.w;
}
void Transform::AddRotation(const float & x, const float & y, const float & z, const float & w)
{
this->p_rotation.x += x;
this->p_rotation.y += y;
this->p_rotation.z += z;
this->p_rotation.w += w;
}
const Transform* Transform::GetTransform()
{
return this;
}
const DirectX::XMFLOAT4A & Transform::GetPosition() const
{
return this->p_position;
}
const DirectX::XMFLOAT4A & Transform::GetScale() const
{
return this->p_scale;
}
const DirectX::XMFLOAT4A & Transform::GetEulerRotation() const
{
return this->p_rotation;
}
DirectX::XMFLOAT4X4A Transform::GetWorldmatrix()
{
this->p_calcWorldMatrix();
return this->p_worldMatrix;
}
DirectX::XMFLOAT4X4A Transform::GetWorldMatrixForOutline(const DirectX::XMFLOAT4A & pos)
{
float lenght = GetLenghtToObject(pos);
this->p_calcWorldMatrixForOutline(lenght);
return this->p_worldMatrix;
}
DirectX::XMFLOAT4X4A Transform::GetWorldMatrixForInsideOutline(const DirectX::XMFLOAT4A& pos)
{
float lenght = GetLenghtToObject(pos);
this->p_calcWorldMatrixForInsideOutline(lenght);
return this->p_worldMatrix;
}
float Transform::GetLenghtToObject(const DirectX::XMFLOAT4A& pos)
{
DirectX::XMVECTOR vec1 = DirectX::XMLoadFloat4A(&pos);
DirectX::XMVECTOR vec2 = DirectX::XMLoadFloat4A(&this->p_position);
DirectX::XMVECTOR vecSubs = DirectX::XMVectorSubtract(vec1, vec2);
DirectX::XMVECTOR lenght = DirectX::XMVector4Length(vecSubs);
return DirectX::XMVectorGetX(lenght);
}
| 25.87931 | 120 | 0.73551 | [
"transform"
] |
2d6d6bacc645bddb96dd233f020cb8c3e7aedd42 | 5,057 | cpp | C++ | third_party/WebKit/Source/modules/payments/PaymentEventDataConversion.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/modules/payments/PaymentEventDataConversion.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/modules/payments/PaymentEventDataConversion.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 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 "modules/payments/PaymentEventDataConversion.h"
#include "bindings/core/v8/ToV8ForCore.h"
#include "modules/payments/PaymentCurrencyAmount.h"
#include "modules/payments/PaymentDetailsModifier.h"
#include "modules/payments/PaymentItem.h"
#include "modules/payments/PaymentMethodData.h"
#include "modules/payments/PaymentRequestEventInit.h"
#include "platform/bindings/ScriptState.h"
#include "public/platform/modules/payments/WebPaymentMethodData.h"
#include "public/platform/modules/payments/WebPaymentRequestEventData.h"
namespace blink {
namespace {
PaymentCurrencyAmount ToPaymentCurrencyAmount(
const WebPaymentCurrencyAmount& web_amount) {
PaymentCurrencyAmount amount;
amount.setCurrency(web_amount.currency);
amount.setValue(web_amount.value);
amount.setCurrencySystem(web_amount.currency_system);
return amount;
}
PaymentItem ToPaymentItem(const WebPaymentItem& web_item) {
PaymentItem item;
item.setLabel(web_item.label);
item.setAmount(ToPaymentCurrencyAmount(web_item.amount));
item.setPending(web_item.pending);
return item;
}
PaymentDetailsModifier ToPaymentDetailsModifier(
ScriptState* script_state,
const WebPaymentDetailsModifier& web_modifier) {
PaymentDetailsModifier modifier;
Vector<String> supported_methods;
for (const auto& web_method : web_modifier.supported_methods) {
supported_methods.push_back(web_method);
}
modifier.setSupportedMethods(supported_methods);
modifier.setTotal(ToPaymentItem(web_modifier.total));
HeapVector<PaymentItem> additional_display_items;
for (const auto& web_item : web_modifier.additional_display_items) {
additional_display_items.push_back(ToPaymentItem(web_item));
}
modifier.setAdditionalDisplayItems(additional_display_items);
return modifier;
}
ScriptValue StringDataToScriptValue(ScriptState* script_state,
const WebString& stringified_data) {
if (!script_state->ContextIsValid())
return ScriptValue();
ScriptState::Scope scope(script_state);
v8::Local<v8::Value> v8_value;
if (!v8::JSON::Parse(script_state->GetIsolate(),
V8String(script_state->GetIsolate(), stringified_data))
.ToLocal(&v8_value)) {
return ScriptValue();
}
return ScriptValue(script_state, v8_value);
}
PaymentMethodData ToPaymentMethodData(
ScriptState* script_state,
const WebPaymentMethodData& web_method_data) {
PaymentMethodData method_data;
Vector<String> supported_methods;
for (const auto& method : web_method_data.supported_methods) {
supported_methods.push_back(method);
}
method_data.setSupportedMethods(supported_methods);
method_data.setData(
StringDataToScriptValue(script_state, web_method_data.stringified_data));
return method_data;
}
} // namespace
PaymentRequestEventInit PaymentEventDataConversion::ToPaymentRequestEventInit(
ScriptState* script_state,
const WebPaymentRequestEventData& web_event_data) {
DCHECK(script_state);
PaymentRequestEventInit event_data;
if (!script_state->ContextIsValid())
return event_data;
ScriptState::Scope scope(script_state);
event_data.setTopLevelOrigin(web_event_data.top_level_origin);
event_data.setPaymentRequestOrigin(web_event_data.payment_request_origin);
event_data.setPaymentRequestId(web_event_data.payment_request_id);
HeapVector<PaymentMethodData> method_data;
for (const auto& md : web_event_data.method_data) {
method_data.push_back(ToPaymentMethodData(script_state, md));
}
event_data.setMethodData(method_data);
event_data.setTotal(ToPaymentCurrencyAmount(web_event_data.total));
HeapVector<PaymentDetailsModifier> modifiers;
for (const auto& modifier : web_event_data.modifiers) {
modifiers.push_back(ToPaymentDetailsModifier(script_state, modifier));
}
event_data.setModifiers(modifiers);
event_data.setInstrumentKey(web_event_data.instrument_key);
return event_data;
}
CanMakePaymentEventInit PaymentEventDataConversion::ToCanMakePaymentEventInit(
ScriptState* script_state,
const WebCanMakePaymentEventData& web_event_data) {
DCHECK(script_state);
CanMakePaymentEventInit event_data;
if (!script_state->ContextIsValid())
return event_data;
ScriptState::Scope scope(script_state);
event_data.setTopLevelOrigin(web_event_data.top_level_origin);
event_data.setPaymentRequestOrigin(web_event_data.payment_request_origin);
HeapVector<PaymentMethodData> method_data;
for (const auto& md : web_event_data.method_data) {
method_data.push_back(ToPaymentMethodData(script_state, md));
}
event_data.setMethodData(method_data);
HeapVector<PaymentDetailsModifier> modifiers;
for (const auto& modifier : web_event_data.modifiers) {
modifiers.push_back(ToPaymentDetailsModifier(script_state, modifier));
}
event_data.setModifiers(modifiers);
return event_data;
}
} // namespace blink
| 35.612676 | 79 | 0.792565 | [
"vector"
] |
2d6e3dd2c13fbf0f20778b6e864ceebc8fe7ced7 | 953 | cpp | C++ | kickstart/2021/round b/increasing_substring.cpp | Surya-06/My-Solutions | 58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806 | [
"MIT"
] | null | null | null | kickstart/2021/round b/increasing_substring.cpp | Surya-06/My-Solutions | 58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806 | [
"MIT"
] | null | null | null | kickstart/2021/round b/increasing_substring.cpp | Surya-06/My-Solutions | 58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <limits>
#include <utility>
#include <map>
#include <stack>
#include <memory>
#include <cmath>
#include <set>
#include <unordered_map>
#include <tuple>
#define in scanf
#define out printf
// Problem:
typedef long long int llint;
typedef long double ldouble;
std::vector<int> __calc__ () {
int n;
std::cin >> n;
std::string input;
std::cin >> input ;
std::vector<int> answer ( n , 0 );
answer[0]=1;
for ( int i=1 ; i<n ; i++ ){
answer[i] = input[i] > input[i-1] ? answer[i-1]+1 : 1 ;
}
return std::move(answer);
}
int main() {
int t;
std::cin >> t;
for ( int i=1 ; i<=t ; i++ ){
std::vector<int> answer = __calc__();
std::cout << "Case #" << i << ": " ;
for ( const int& j : answer )
std::cout << j << " ";
std::cout << std::endl;
}
return 0;
}
| 19.854167 | 63 | 0.539349 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.