text
string
size
int64
token_count
int64
#include <bits/stdc++.h> #ifdef LOCAL #include "code/formatting.hpp" #else #define debug(...) (void)0 #endif using namespace std; static_assert(sizeof(int) == 4 && sizeof(long) == 8); using P = array<int, 2>; int main() { ios::sync_with_stdio(false), cin.tie(nullptr); int N; cin >> N; vector<P> pts(N); for (auto& [x, y] : pts) { cin >> x >> y; } sort(begin(pts), end(pts)); auto contains = [&](int x, int y) { auto it = lower_bound(begin(pts), end(pts), P{x, y}); return it != end(pts) && *it == P{x, y}; }; int ans = 0; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { auto [x0, y0] = pts[i]; auto [x1, y1] = pts[j]; if (x0 != x1 && y0 != y1) { if (contains(x0, y1) && contains(x1, y0)) { ans++; } } } } ans /= 2; cout << ans << '\n'; return 0; }
968
389
// gf256.cpp - originally written and placed in the public domain by Wei Dai #include "pch.h" #include "gf256.h" NAMESPACE_BEGIN(CryptoPP) GF256::Element GF256::Multiply(Element a, Element b) const { word result = 0, t = b; for (unsigned int i=0; i<8; i++) { result <<= 1; if (result & 0x100) result ^= m_modulus; t <<= 1; if (t & 0x100) result ^= a; } return (GF256::Element) result; } GF256::Element GF256::MultiplicativeInverse(Element a) const { Element result = a; for (int i=1; i<7; i++) result = Multiply(Square(result), a); return Square(result); } NAMESPACE_END
603
288
#include "utilities/Utilities.h" #include <NvCloth/Range.h> TEST_LEAK_FIXTURE(Range) TEST_F(Range, Constructor) { nv::cloth::Range<char> char_range; EXPECT_EQ(char_range.size(), 0); EXPECT_NULLPTR(char_range.begin()); EXPECT_NULLPTR(char_range.end()); nv::cloth::Range<char> a((char*)0x123, (char*)0x456); nv::cloth::Range<char> b(a); EXPECT_EQ(b.begin(), a.begin()); EXPECT_EQ(b.end(), a.end()); } TEST_F(Range, Size) { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range(&char_array[0], &char_array[0] + char_array.size()); EXPECT_EQ(char_array.size(), char_range.size()); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range(&float_array[0], &float_array[0] + float_array.size()); EXPECT_EQ(float_array.size(), float_range.size()); } TEST_F(Range, Empty) { { nv::cloth::Range<char> char_range; EXPECT_TRUE(char_range.empty()); nv::cloth::Range<float> float_range; EXPECT_TRUE(float_range.empty()); } { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range = CreateRange(char_array); EXPECT_FALSE(char_range.empty()); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range = CreateRange(float_array); EXPECT_FALSE(float_range.empty()); } } TEST_F(Range, Pop) { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range(&char_array[0], &char_array[0] + char_array.size()); EXPECT_EQ(&char_array.front(), &char_range.front()); EXPECT_EQ(&char_array.back(), &char_range.back()); char_range.popBack(); EXPECT_EQ(&char_array.back() - 1, &char_range.back()); char_range.popFront(); EXPECT_EQ(&char_array.front() + 1, &char_range.front()); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range(&float_array[0], &float_array[0] + float_array.size()); EXPECT_EQ(&float_array.front(), &float_range.front()); EXPECT_EQ(&float_array.back(), &float_range.back()); float_range.popBack(); EXPECT_EQ(&float_array.back() - 1, &float_range.back()); float_range.popFront(); EXPECT_EQ(&float_array.front() + 1, &float_range.front()); } TEST_F(Range, BeginEnd) { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range(&char_array[0], &char_array[0]+char_array.size()); EXPECT_EQ(&char_array[0], char_range.begin()); EXPECT_EQ(&char_array[0] + char_array.size(), char_range.end()); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range(&float_array[0], &float_array[0] + float_array.size()); EXPECT_EQ(&float_array[0], float_range.begin()); EXPECT_EQ(&float_array[0] + float_array.size(), float_range.end()); } TEST_F(Range, FrontBack) { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range(&char_array[0], &char_array[0] + char_array.size()); EXPECT_EQ(&char_array.front(), &char_range.front()); EXPECT_EQ(&char_array.back(), &char_range.back()); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range(&float_array[0], &float_array[0] + float_array.size()); EXPECT_EQ(&float_array.front(), &float_range.front()); EXPECT_EQ(&float_array.back(), &float_range.back()); } TEST_F(Range, ArrayOperator) { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range(&char_array[0], &char_array[0] + char_array.size()); EXPECT_EQ(&char_array[0], &char_range[0]); EXPECT_EQ(&char_array[99], &char_range[99]); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range(&float_array[0], &float_array[0] + float_array.size()); EXPECT_EQ(&float_array[0], &float_range[0]); EXPECT_EQ(&float_array[99], &float_range[99]); }
3,822
1,625
#include "ftpretrcommand.h" #include <QFile> #include <QSslSocket> FtpRetrCommand::FtpRetrCommand(QObject *parent, const QString &fileName, qint64 seekTo) : FtpCommand(parent) { this->fileName = fileName; this->seekTo = seekTo; file = 0; } FtpRetrCommand::~FtpRetrCommand() { if (m_started) { if (file && file->isOpen() && file->atEnd()) { emit reply("226 Closing data connection."); } else { emit reply("550 Requested action not taken; file unavailable."); } } } void FtpRetrCommand::startImplementation() { file = new QFile(fileName, this); if (!file->open(QIODevice::ReadOnly)) { deleteLater(); return; } emit reply("150 File status okay; about to open data connection."); if (seekTo) { file->seek(seekTo); } // For encryted SSL sockets, we need to use the encryptedBytesWritten() // signal, see the QSslSocket documentation to for reasons why. if (m_socket->isEncrypted()) { connect(m_socket, SIGNAL(encryptedBytesWritten(qint64)), this, SLOT(refillSocketBuffer(qint64))); } else { connect(m_socket, SIGNAL(bytesWritten(qint64)), this, SLOT(refillSocketBuffer(qint64))); } refillSocketBuffer(128*1024); } void FtpRetrCommand::refillSocketBuffer(qint64 bytes) { if (!file->atEnd()) { m_socket->write(file->read(bytes)); } else { m_socket->disconnectFromHost(); } }
1,478
511
// // MailStreamTest.cpp // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "MailStreamTest.h" #include "Poco/CppUnit/TestCaller.h" #include "Poco/CppUnit/TestSuite.h" #include "Poco/Net/MailStream.h" #include "Poco/StreamCopier.h" #include <sstream> using Poco::Net::MailInputStream; using Poco::Net::MailOutputStream; using Poco::StreamCopier; MailStreamTest::MailStreamTest(const std::string& name): CppUnit::TestCase(name) { } MailStreamTest::~MailStreamTest() { } void MailStreamTest::testMailInputStream() { std::istringstream istr( "From: john.doe@no.domain\r\n" "To: jane.doe@no.domain\r\n" "Subject: test\r\n" "\r\n" "This is a test.\r\n" "\rThis.is.\ngarbage\r.\r\n" ".This line starts with a period.\r\n" "..and this one too\r\n" "..\r\n" ".\r\n" ); MailInputStream mis(istr); std::ostringstream ostr; StreamCopier::copyStream(mis, ostr); std::string s(ostr.str()); assertTrue (s == "From: john.doe@no.domain\r\n" "To: jane.doe@no.domain\r\n" "Subject: test\r\n" "\r\n" "This is a test.\r\n" "\rThis.is.\ngarbage\r.\r\n" ".This line starts with a period.\r\n" ".and this one too\r\n" ".\r\n" ); } void MailStreamTest::testMailOutputStream() { std::string msg( "From: john.doe@no.domain\r\n" "To: jane.doe@no.domain\r\n" "Subject: test\r\n" "\r\n" "This is a test.\r\n" "\rThis.is.\ngarbage\r.\r\n" ".This line starts with a period.\r\n" "\r\n" ".and this one too\r\n" ".\r\n" ); std::ostringstream ostr; MailOutputStream mos(ostr); mos << msg; mos.close(); std::string s(ostr.str()); assertTrue (s == "From: john.doe@no.domain\r\n" "To: jane.doe@no.domain\r\n" "Subject: test\r\n" "\r\n" "This is a test.\r\n" "\rThis.is.\ngarbage\r.\r\n" "..This line starts with a period.\r\n" "\r\n" "..and this one too\r\n" "..\r\n" ".\r\n" ); } void MailStreamTest::setUp() { } void MailStreamTest::tearDown() { } CppUnit::Test* MailStreamTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MailStreamTest"); CppUnit_addTest(pSuite, MailStreamTest, testMailInputStream); CppUnit_addTest(pSuite, MailStreamTest, testMailOutputStream); return pSuite; }
2,292
1,080
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // onnxruntime dependencies #include <core/session/onnxruntime_c_api.h> #include <random> #include "command_args_parser.h" #include "performance_runner.h" #include <google/protobuf/stubs/common.h> using namespace onnxruntime; const OrtApi* g_ort = NULL; #ifdef _WIN32 int real_main(int argc, wchar_t* argv[]) { #else int real_main(int argc, char* argv[]) { #endif g_ort = OrtGetApiBase()->GetApi(ORT_API_VERSION); perftest::PerformanceTestConfig test_config; if (!perftest::CommandLineParser::ParseArguments(test_config, argc, argv)) { perftest::CommandLineParser::ShowUsage(); return -1; } Ort::Env env{nullptr}; try { OrtLoggingLevel logging_level = test_config.run_config.f_verbose ? ORT_LOGGING_LEVEL_VERBOSE : ORT_LOGGING_LEVEL_WARNING; env = Ort::Env(logging_level, "Default"); } catch (const Ort::Exception& e) { fprintf(stderr, "Error creating environment: %s \n", e.what()); return -1; } if(test_config.machine_config.provider_type_name == onnxruntime::kOpenVINOExecutionProvider){ if(test_config.run_config.concurrent_session_runs != 1){ fprintf(stderr, "OpenVINO doesn't support more than 1 session running simultaneously default value of 1 will be set \n"); test_config.run_config.concurrent_session_runs = 1; } if(test_config.run_config.execution_mode == ExecutionMode::ORT_PARALLEL){ fprintf(stderr, "OpenVINO doesn't support parallel executor using sequential executor\n"); test_config.run_config.execution_mode = ExecutionMode::ORT_SEQUENTIAL; } } std::random_device rd; perftest::PerformanceRunner perf_runner(env, test_config, rd); auto status = perf_runner.Run(); if (!status.IsOK()) { printf("Run failed:%s\n", status.ErrorMessage().c_str()); return -1; } perf_runner.SerializeResult(); return 0; } #ifdef _WIN32 int wmain(int argc, wchar_t* argv[]) { #else int main(int argc, char* argv[]) { #endif int retval = -1; try { retval = real_main(argc, argv); } catch (std::exception& ex) { fprintf(stderr, "%s\n", ex.what()); retval = -1; } ::google::protobuf::ShutdownProtobufLibrary(); return retval; }
2,335
818
/* * MIT License * * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>, Tatyana Borisova <tanusshhka@mail.ru> * * This file is part of QtProtobuf project https://git.semlanik.org/semlanik/qtprotobuf * * 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 "protobufclassgenerator.h" #include "utils.h" #include <iostream> #include <google/protobuf/descriptor.h> #include <google/protobuf/io/zero_copy_stream.h> using namespace ::QtProtobuf::generator; using namespace ::google::protobuf; using namespace ::google::protobuf::io; using namespace ::google::protobuf::compiler; ProtobufClassGenerator::ProtobufClassGenerator(const Descriptor *message, std::unique_ptr<::google::protobuf::io::ZeroCopyOutputStream> out) : ClassGeneratorBase(message->full_name(), std::move(out)) , mMessage(message) { } void ProtobufClassGenerator::printCopyFunctionality() { assert(mMessage != nullptr); mPrinter.Print({{"classname", mClassName}}, Templates::CopyConstructorTemplate); Indent(); for (int i = 0; i < mMessage->field_count(); i++) { printField(mMessage->field(i), Templates::CopyFieldTemplate); } Outdent(); mPrinter.Print(Templates::SimpleBlockEnclosureTemplate); mPrinter.Print({{"classname", mClassName}}, Templates::AssignmentOperatorTemplate); Indent(); for (int i = 0; i < mMessage->field_count(); i++) { printField(mMessage->field(i), Templates::CopyFieldTemplate); } mPrinter.Print(Templates::AssignmentOperatorReturnTemplate); Outdent(); mPrinter.Print(Templates::SimpleBlockEnclosureTemplate); } void ProtobufClassGenerator::printMoveSemantic() { assert(mMessage != nullptr); mPrinter.Print({{"classname", mClassName}}, Templates::MoveConstructorTemplate); Indent(); for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (isComplexType(field) || field->is_repeated()) { printField(field, Templates::MoveComplexFieldTemplate); } else { if (field->type() != FieldDescriptor::TYPE_ENUM) { printField(field, Templates::MoveFieldTemplate); } else { printField(field, Templates::EnumMoveFieldTemplate); } } } Outdent(); mPrinter.Print(Templates::SimpleBlockEnclosureTemplate); mPrinter.Print({{"classname", mClassName}}, Templates::MoveAssignmentOperatorTemplate); Indent(); for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (isComplexType(field) || field->is_repeated()) { printField(field, Templates::MoveComplexFieldTemplate); } else { if (field->type() != FieldDescriptor::TYPE_ENUM) { printField(field, Templates::MoveFieldTemplate); } else { printField(field, Templates::EnumMoveFieldTemplate); } } } mPrinter.Print(Templates::AssignmentOperatorReturnTemplate); Outdent(); mPrinter.Print(Templates::SimpleBlockEnclosureTemplate); } void ProtobufClassGenerator::printComparisonOperators() { assert(mMessage != nullptr); bool isFirst = true; PropertyMap properties; mPrinter.Print({{"type", mClassName}}, Templates::EqualOperatorTemplate); if (mMessage->field_count() <= 0) { mPrinter.Print("true"); } for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (producePropertyMap(field, properties)) { if (!isFirst) { mPrinter.Print("\n&& "); } else { Indent(); Indent(); isFirst = false; } mPrinter.Print(properties, Templates::EqualOperatorPropertyTemplate); } } //Only if at least one field "copied" if (!isFirst) { Outdent(); Outdent(); } mPrinter.Print(";\n"); mPrinter.Print(Templates::SimpleBlockEnclosureTemplate); mPrinter.Print({{"type", mClassName}}, Templates::NotEqualOperatorTemplate); } void ProtobufClassGenerator::printIncludes() { assert(mMessage != nullptr); mPrinter.Print(Templates::DefaultProtobufIncludesTemplate); std::set<std::string> existingIncludes; for (int i = 0; i < mMessage->field_count(); i++) { printInclude(mMessage->field(i), existingIncludes); } } void ProtobufClassGenerator::printInclude(const FieldDescriptor *field, std::set<std::string> &existingIncludes) { assert(field != nullptr); std::string newInclude; const char *includeTemplate; switch (field->type()) { case FieldDescriptor::TYPE_MESSAGE: if ( field->is_map() ) { newInclude = "QMap"; assert(field->message_type() != nullptr); assert(field->message_type()->field_count() == 2); printInclude(field->message_type()->field(0), existingIncludes); printInclude(field->message_type()->field(1), existingIncludes); includeTemplate = Templates::ExternalIncludeTemplate; } else { std::string typeName = field->message_type()->name(); utils::tolower(typeName); newInclude = typeName; includeTemplate = Templates::InternalIncludeTemplate; } break; case FieldDescriptor::TYPE_BYTES: newInclude = "QByteArray"; includeTemplate = Templates::ExternalIncludeTemplate; break; case FieldDescriptor::TYPE_STRING: newInclude = "QString"; includeTemplate = Templates::ExternalIncludeTemplate; break; case FieldDescriptor::TYPE_ENUM: { EnumVisibility enumVisibily = getEnumVisibility(field, mMessage); if (enumVisibily == GLOBAL_ENUM) { includeTemplate = Templates::GlobalEnumIncludeTemplate; } else if (enumVisibily == NEIGHBOUR_ENUM) { includeTemplate = Templates::InternalIncludeTemplate; std::string fullEnumName = field->enum_type()->full_name(); std::vector<std::string> fullEnumNameParts; utils::split(fullEnumName, fullEnumNameParts, '.'); std::string enumTypeOwner = fullEnumNameParts.at(fullEnumNameParts.size() - 2); utils::tolower(enumTypeOwner); newInclude = enumTypeOwner; } else { return; } } break; default: return; } if (existingIncludes.find(newInclude) == std::end(existingIncludes)) { mPrinter.Print({{"include", newInclude}}, includeTemplate); existingIncludes.insert(newInclude); } } void ProtobufClassGenerator::printField(const FieldDescriptor *field, const char *fieldTemplate) { assert(field != nullptr); std::map<std::string, std::string> propertyMap; if (producePropertyMap(field, propertyMap)) { mPrinter.Print(propertyMap, fieldTemplate); } } bool ProtobufClassGenerator::producePropertyMap(const FieldDescriptor *field, PropertyMap &propertyMap) { assert(field != nullptr); std::string typeName = getTypeName(field, mMessage); if (typeName.size() <= 0) { std::cerr << "Type " << field->type_name() << " is not supported by Qt Generator" " please look at https://doc.qt.io/qt-5/qtqml-typesystem-basictypes.html" " for details" << std::endl; return false; } std::string typeNameLower(typeName); utils::tolower(typeNameLower); std::string capProperty = field->camelcase_name(); capProperty[0] = static_cast<char>(::toupper(capProperty[0])); std::string typeNameNoList = typeName; if (field->is_repeated() && !field->is_map()) { if(field->type() == FieldDescriptor::TYPE_MESSAGE || field->type() == FieldDescriptor::TYPE_ENUM) { typeNameNoList.resize(typeNameNoList.size() - strlen(Templates::ListSuffix)); } else { typeNameNoList.resize(typeNameNoList.size() - strlen("List")); } } propertyMap = {{"type", typeName}, {"type_lower", typeNameLower}, {"property_name", field->camelcase_name()}, {"property_name_cap", capProperty}, {"type_nolist", typeNameNoList} }; return true; } bool ProtobufClassGenerator::isListType(const FieldDescriptor *field) { assert(field != nullptr); return field && field->is_repeated() && field->type() == FieldDescriptor::TYPE_MESSAGE; } bool ProtobufClassGenerator::isComplexType(const FieldDescriptor *field) { assert(field != nullptr); return field->type() == FieldDescriptor::TYPE_MESSAGE || field->type() == FieldDescriptor::TYPE_STRING || field->type() == FieldDescriptor::TYPE_BYTES; } void ProtobufClassGenerator::printConstructor() { std::string parameterList; for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); std::string fieldTypeName = getTypeName(field, mMessage); std::string fieldName = field->camelcase_name(); fieldName[0] = static_cast<char>(::tolower(fieldName[0])); if (field->is_repeated() || field->is_map()) { parameterList += "const " + fieldTypeName + " &" + fieldName + " = {}"; } else { switch (field->type()) { case FieldDescriptor::TYPE_DOUBLE: case FieldDescriptor::TYPE_FLOAT: parameterList += fieldTypeName + " " + fieldName + " = " + "0.0"; break; case FieldDescriptor::TYPE_FIXED32: case FieldDescriptor::TYPE_FIXED64: case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_SINT32: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_UINT32: case FieldDescriptor::TYPE_UINT64: parameterList += fieldTypeName + " " + fieldName + " = " + "0"; break; case FieldDescriptor::TYPE_BOOL: parameterList += fieldTypeName + " " + fieldName + " = " + "false"; break; case FieldDescriptor::TYPE_BYTES: case FieldDescriptor::TYPE_STRING: case FieldDescriptor::TYPE_MESSAGE: parameterList += "const " + fieldTypeName + " &" + fieldName + " = {}"; break; default: parameterList += fieldTypeName + " " + fieldName + " = " + "{}"; break; } } parameterList += ", "; } mPrinter.Print({{"classname", mClassName}, {"parameter_list", parameterList}}, Templates::ProtoConstructorTemplate); } void ProtobufClassGenerator::printMaps() { Indent(); for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field->is_map()) { std::string keyType = getTypeName(field->message_type()->field(0), mMessage); std::string valueType = getTypeName(field->message_type()->field(1), mMessage); const char *mapTemplate = Templates::MapTypeUsingTemplate; if (field->message_type()->field(1)->type() == FieldDescriptor::TYPE_MESSAGE) { mapTemplate = Templates::MessageMapTypeUsingTemplate; } mPrinter.Print({{"classname",field->message_type()->name()}, {"key", keyType}, {"value", valueType}}, mapTemplate); } } Outdent(); } void ProtobufClassGenerator::printLocalEmumsMetaTypesDeclaration() { for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field == nullptr || field->enum_type() == nullptr) continue; if (field->type() == FieldDescriptor::TYPE_ENUM && isLocalMessageEnum(mMessage, field)) { mPrinter.Print({{"classname", mClassName + "::" + field->enum_type()->name() + Templates::ListSuffix}, {"namespaces", mNamespacesColonDelimited}}, Templates::DeclareMetaTypeTemplate); } } } void ProtobufClassGenerator::printMapsMetaTypesDeclaration() { for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field->is_map()) { mPrinter.Print({{"classname", field->message_type()->name()}, {"namespaces", mNamespacesColonDelimited + "::" + mClassName}}, Templates::DeclareMetaTypeTemplate); } } } void ProtobufClassGenerator::printProperties() { assert(mMessage != nullptr); //private section Indent(); for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); const char *propertyTemplate = Templates::PropertyTemplate; if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_map() && !field->is_repeated()) { propertyTemplate = Templates::MessagePropertyTemplate; } printField(field, propertyTemplate); } //Generate extra QmlListProperty that is mapped to list for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field->type() == FieldDescriptor::TYPE_MESSAGE && field->is_repeated() && !field->is_map()) { printField(field, Templates::QmlListPropertyTemplate); } } Outdent(); printQEnums(mMessage); //public section printPublic(); printMaps(); //Body Indent(); printConstructor(); printCopyFunctionality(); printMoveSemantic(); printComparisonOperators(); for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field->type() == FieldDescriptor::TYPE_MESSAGE) { if (!field->is_map() && !field->is_repeated()) { printField(field, Templates::GetterMessageTemplate); } } printField(field, Templates::GetterTemplate); if (field->is_repeated()) { printField(field, Templates::GetterContainerExtraTemplate); if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_map()) { printField(field, Templates::QmlListGetterTemplate); } } } for (int i = 0; i < mMessage->field_count(); i++) { auto field = mMessage->field(i); switch (field->type()) { case FieldDescriptor::TYPE_MESSAGE: if (!field->is_map() && !field->is_repeated()) { printField(field, Templates::SetterTemplateMessageType); } printField(field, Templates::SetterTemplateComplexType); break; case FieldDescriptor::FieldDescriptor::TYPE_STRING: case FieldDescriptor::FieldDescriptor::TYPE_BYTES: printField(field, Templates::SetterTemplateComplexType); break; default: printField(field, Templates::SetterTemplateSimpleType); break; } } Outdent(); mPrinter.Print(Templates::SignalsBlockTemplate); Indent(); for (int i = 0; i < mMessage->field_count(); i++) { printField(mMessage->field(i), Templates::SignalTemplate); } Outdent(); } void ProtobufClassGenerator::printListType() { mPrinter.Print({{"classname", mClassName}}, Templates::ComplexListTypeUsingTemplate); } void ProtobufClassGenerator::printClassMembers() { Indent(); for (int i = 0; i < mMessage->field_count(); i++) { printField(mMessage->field(i), Templates::MemberTemplate); } Outdent(); } std::set<std::string> ProtobufClassGenerator::extractModels() const { std::set<std::string> extractedModels; for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field->is_repeated() && field->type() == FieldDescriptor::TYPE_MESSAGE) { std::string typeName = field->message_type()->name(); extractedModels.insert(typeName); } } return extractedModels; } void ProtobufClassGenerator::run() { printPreamble(); printIncludes(); printNamespaces(); printClassDeclaration(); printProperties(); printPrivate(); printClassMembers(); encloseClass(); printListType(); encloseNamespaces(); printMetaTypeDeclaration(); printMapsMetaTypesDeclaration(); printLocalEmumsMetaTypesDeclaration(); }
17,985
5,178
// Copyright (C) 2020-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include <details/ie_exception.hpp> #include "arm_converter/arm_converter.hpp" #include <ngraph/runtime/reference/one_hot.hpp> namespace ArmPlugin { template <typename Indices, typename OutputType> void wrap_one_hot(const Indices* arg, OutputType* out, const ngraph::Shape& in_shape, const ngraph::Shape& out_shape, size_t one_hot_axis, const OutputType* on_values, const OutputType* off_values) { ngraph::runtime::reference::one_hot(arg, out, in_shape, out_shape, one_hot_axis, on_values[0], off_values[0]); } template<> Converter::Conversion::Ptr Converter::Convert(const opset::OneHot& node) { auto make = [&] (auto refFunction) { return MakeConversion(refFunction, node.input(0), node.output(0), node.get_input_shape(0), node.get_output_shape(0), static_cast<size_t>(node.get_axis()), node.input(2), node.input(3)); }; ngraph::element::Type_t outType = node.get_output_element_type(0); switch (node.get_input_element_type(0)) { case ngraph::element::Type_t::u8 : switch (outType) { case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::uint8_t, std::uint8_t>); case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::uint8_t, std::int16_t>); case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::uint8_t, std::uint16_t>); case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::uint8_t, std::int32_t>); case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::uint8_t, float>); default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {}; } case ngraph::element::Type_t::i16 : switch (outType) { case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::int16_t, std::uint8_t>); case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::int16_t, std::int16_t>); case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::int16_t, std::uint16_t>); case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::int16_t, std::int32_t>); case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::int16_t, float>); default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {}; } case ngraph::element::Type_t::u16 : switch (outType) { case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::uint16_t, std::uint8_t>); case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::uint16_t, std::int16_t>); case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::uint16_t, std::uint16_t>); case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::uint16_t, std::int32_t>); case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::uint16_t, float>); default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {}; } case ngraph::element::Type_t::u32 : switch (outType) { case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::uint32_t, std::uint8_t>); case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::uint32_t, std::int16_t>); case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::uint32_t, std::uint16_t>); case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::uint32_t, std::int32_t>); case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::uint32_t, float>); default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {}; } case ngraph::element::Type_t::i32 : switch (outType) { case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::int32_t, std::uint8_t>); case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::int32_t, std::int16_t>); case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::int32_t, std::uint16_t>); case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::int32_t, std::int32_t>); case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::int32_t, float>); default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {}; } default: THROW_IE_EXCEPTION << "Unsupported Type: " << node.get_input_element_type(0); return {}; } } } // namespace ArmPlugin
5,302
1,764
/* * Copyright (C) 2017 The Android Open Source Project * * 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 LOG_NDEBUG 0 #define LOG_TAG "MPEG2ExtractorBundle" #include <utils/Log.h> #include <media/MediaExtractorPluginHelper.h> #include <media/stagefright/MediaDefs.h> #include "MPEG2PSExtractor.h" #include "MPEG2TSExtractor.h" namespace android { struct CDataSource; static const char *extensions[] = { "m2p", "m2ts", "mts", "ts", NULL }; extern "C" { // This is the only symbol that needs to be exported __attribute__ ((visibility ("default"))) ExtractorDef GETEXTRACTORDEF() { return { EXTRACTORDEF_VERSION, UUID("3d1dcfeb-e40a-436d-a574-c2438a555e5f"), 1, "MPEG2-PS/TS Extractor", { .v3 = { []( CDataSource *source, float *confidence, void **, FreeMetaFunc *) -> CreatorFunc { DataSourceHelper helper(source); if (SniffMPEG2TS(&helper, confidence)) { return []( CDataSource *source, void *) -> CMediaExtractor* { return wrap(new MPEG2TSExtractor(new DataSourceHelper(source)));}; } else if (SniffMPEG2PS(&helper, confidence)) { return []( CDataSource *source, void *) -> CMediaExtractor* { return wrap(new MPEG2PSExtractor(new DataSourceHelper(source)));}; } return NULL; }, extensions } }, }; } } // extern "C" } // namespace android
2,326
674
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference when the project is build. Please check https:// Docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from https://www.nuget.org/packages/Aspose.Tasks/, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using https://forum.aspose.com/c/tasks */ #include "EvaluationDateTimeLimitations.h" #include <Tsk.h> #include <TaskCollection.h> #include <Task.h> #include <system/type_info.h> #include <system/string.h> #include <system/shared_ptr.h> #include <system/reflection/method_base.h> #include <system/object.h> #include <system/date_time.h> #include <saving/Enums/SaveFileFormat.h> #include <Project.h> #include <Key.h> #include <enums/TaskKey.h> #include "RunExamples.h" using namespace Aspose::Tasks::Saving; namespace Aspose { namespace Tasks { namespace Examples { namespace CPP { namespace Licensing { RTTI_INFO_IMPL_HASH(2704315891u, ::Aspose::Tasks::Examples::CPP::Licensing::EvaluationDateTimeLimitations, ThisTypeBaseTypesInfo); void EvaluationDateTimeLimitations::Run() { System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName()); // ExStart:DateTimeLimitations // Create a prject instance System::SharedPtr<Project> project1 = System::MakeObject<Project>(); // Define Tasks System::SharedPtr<Task> task1 = project1->get_RootTask()->get_Children()->Add(u"Task1"); task1->Set(Tsk::ActualStart(), System::DateTime::Parse(u"06-Apr-2010")); System::SharedPtr<Task> task2 = project1->get_RootTask()->get_Children()->Add(u"Task2"); task2->Set(Tsk::ActualStart(), System::DateTime::Parse(u"10-Apr-2010")); // Save the Project as XML project1->Save(u"EvalProject_out.xml", Aspose::Tasks::Saving::SaveFileFormat::XML); // ExEnd:DateTimeLimitations } } // namespace Licensing } // namespace CPP } // namespace Examples } // namespace Tasks } // namespace Aspose
2,220
735
/* * Copyright 2016 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // // The unittest header must be included before va_x11.h (which might be included // indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers // define 'Bool' and 'None' preprocessor types. Gtest uses the same names // to define some struct placeholders. Thus, this creates a compile conflict // if X defines them before gtest. Hence, the include order requirement here // is the only fix for this right now. // // See bug filed on gtest at https://github.com/google/googletest/issues/371 // for more details. // #include "common/factory_unittest.h" // primary header #include "vaapiencoder_vp8.h" namespace YamiMediaCodec { class VaapiEncoderVP8Test : public FactoryTest<IVideoEncoder, VaapiEncoderVP8> { protected: /* invoked by gtest before the test */ virtual void SetUp() { return; } /* invoked by gtest after the test */ virtual void TearDown() { return; } }; #define VAAPIENCODER_VP8_TEST(name) \ TEST_F(VaapiEncoderVP8Test, name) VAAPIENCODER_VP8_TEST(Factory) { FactoryKeys mimeTypes; mimeTypes.push_back(YAMI_MIME_VP8); doFactoryTest(mimeTypes); } }
1,797
584
#pragma once #include "EntityRegistry.hxx" #include "EntitySet.hxx" namespace BrokenBytes::Cyanite::Engine { struct Component { Component(std::string name) { this->_name = name; } protected: std::string _name; private: friend class EntityRegistry; friend struct EntitySet; friend struct Entity; auto Name() const->std::string { return this->_name; } }; }
462
128
#include "b.hpp" CommandVertex::CommandVertex(std::string specifier, std::string exec, std::vector<std::string> dependencies) : specifier(specifier) , exec(exec) , dependencies(dependencies) {}; void CommandVertex::run() { // Takes a C string as a formal parameter system(this->exec.c_str()); } bool proper(std::string line) { if (line.empty() || line[0] == '#') { return false; } for (int i = 1; i < line.size(); i++) { if (line[i] != ' ') { if (line[i] == '#' || line[i] == '\t') { return false; } else if (isalpha(line[i])) { return true; } } } return false; } std::vector<std::string> get_proper_lines(std::string filepath) { std::vector<std::string> lines; std::ifstream file(filepath); std::string line; if (!file.is_open()) { std::runtime_error("Error while opening the file"); } // Get only if not a comment while (std::getline(file, line)) { if (proper(line)) { lines.push_back(line); } } if (file.bad()) { std::runtime_error("Error while reading the file"); } return lines; } std::vector<std::string> split(std::string str, char delimiter) { std::vector<std::string> internal; // Turn the string into a stream std::stringstream ss(str); std::string token; while(getline(ss, token, delimiter)) { std::string_view ref = token; ref.remove_prefix(std::min(ref.find_first_not_of(" "), ref.size())); ref.remove_suffix(std::min(ref.find_first_not_of(" "), ref.size())); internal.push_back(std::string(ref)); } return internal; } Graph build_graph(std::vector<std::string> lines, char delimiter) { Graph cmds; for (int i = 0; i < lines.size(); i++) { if (lines[i].find(DELIMITER) != std::string::npos) { std::vector<std::string> all = split(lines[i], delimiter); // std::string std::string specifier = all[0]; // Exec std::string_view sv = lines[i + 1]; sv.remove_prefix(std::min(sv.find_first_not_of(" "), sv.size())); std::string exec = std::string(sv); // Dependencies std::vector<std::string> dependencies; for (std::string item : split(all[1], ' ')) { std::string ref = item; dependencies.push_back(ref); } // Create the command and push it onto the cmds CommandVertex cmd = CommandVertex(specifier, exec, dependencies); cmd.indegree = dependencies.size(); cmds.push_back(cmd); } else { continue; } } return cmds; } CommandVertex get_vertex(Graph g, std::string specifier) { for (int i = 0; i < g.size(); i++) { if (g[i].specifier == specifier) { return g[i]; } } throw("The vertex does not exist in the graph"); } std::vector<std::string> get_all_dependencies(Graph g, std::string specifier) { std::vector<std::string> subgraph; std::set<std::string> visited; std::vector<std::string> vertices; vertices.push_back(specifier); while (vertices.size() != 0) { std::string vertex = vertices.back(); vertices.pop_back(); if (visited.find(vertex) == visited.end()) { visited.insert(vertex); subgraph.push_back(vertex); // TODO: Should be optimized, `std::map`? // NOTE: Though, `std::map` uses the built-in hasher that has // a bad performance due to backward compatibility std::vector<std::string> deps = get_vertex(g, vertex).dependencies; for (std::string dep_name : deps) { vertices.push_back(dep_name); } } } return subgraph; } std::vector<CommandVertex> topological_sort(Graph g) { std::vector<CommandVertex> no_incoming; // Keep track of the vertices with no incoming edges for (CommandVertex vertex : g) { if (vertex.indegree == 0) { no_incoming.push_back(vertex); } } // Define a topological ordering std::vector<CommandVertex> tlogical_ordering; // As long as there exists a vertex with no incoming edges while (no_incoming.size() > 0) { // Add the vertex to the ordering and remove it from the vector CommandVertex vertex = no_incoming.back(); no_incoming.pop_back(); tlogical_ordering.push_back(vertex); // Decrement the indegree of the neighbors of the removed vertex for (int i = 0; i < g.size(); i++) { // Get all dependencies std::vector<std::string> deps = g[i].dependencies; // `std::find` is more efficient than `std::count` since it stops // the search once the element is found if (std::find(deps.begin(), deps.end(), vertex.specifier) != deps.end()) { g[i].indegree -= 1; if (g[i].indegree == 0) { no_incoming.push_back(g[i]); } } } } // If we have all vertices, we are done if (tlogical_ordering.size() == g.size()) { return tlogical_ordering; } // Otherwise, we have a cycle throw std::logic_error("Circular dependencies"); } int main(int argc, char **argv) { // The system looks for the file `b.txt` std::vector<std::string> lines = get_proper_lines("b.txt"); // Build a dependency graph Graph dependency_graph = build_graph(lines, DELIMITER); // Validate the command line arguments if (argc == 1) { return 0; } if (argc != 2) { throw std::invalid_argument("Redundant arguments"); } // Get the specifier std::string specifier = argv[1]; // Make sure the command exists // If it does, construct the subgraph, construct the topological ordering, // and execute the commands bool exists = false; for (int i = 0; i < dependency_graph.size(); i++) { if (dependency_graph[i].specifier == std::string(specifier)) { // It exists exists = true; // If there are no dependencies, the associated command // gets executed if (dependency_graph[i].dependencies.empty()) { dependency_graph[i].run(); } else { // If there are some dependencies, a subgraph gets constructed // and the topological ordering is created // Finally, we iterate over all dependencies and run them std::vector<std::string> dependencies = get_all_dependencies(dependency_graph, specifier); // Create a subgraph of the command and all associated // dependencies Graph subgraph; for (std::string dep : dependencies) { subgraph.push_back(get_vertex(dependency_graph, dep)); } // Return the topological ordering of the graph subgraph = topological_sort(subgraph); subgraph.pop_back(); // Run the commands in a topological order for (CommandVertex vertex : subgraph) { std::cout << vertex.specifier << std::endl; vertex.run(); } } } } if (!exists) { throw std::invalid_argument("The specifier does not exist"); } }
7,739
2,233
/***************************************************************************** Copyright (C) 1994-2000 the Omega Project Team Copyright (C) 2005-2011 Chun Chen All Rights Reserved. Purpose: Notes: History: *****************************************************************************/ #include <omega/omega_core/oc_i.h> #include <algorithm> namespace omega { void Problem:: problem_merge(Problem &p2) { int newLocation[maxVars]; int i,e2; resurrectSubs(); p2.resurrectSubs(); setExternals(); p2.setExternals(); assert(safeVars == p2.safeVars); if(DBUG) { fprintf(outputFile,"Merging:\n"); printProblem(); fprintf(outputFile,"and\n"); p2.printProblem(); } for(i=1; i<= p2.safeVars; i++) { assert(p2.var[i] > 0) ; newLocation[i] = forwardingAddress[p2.var[i]]; } for(; i<= p2.nVars; i++) { int j = ++(nVars); newLocation[i] = j; zeroVariable(j); var[j] = -1; } newLocation[0] = 0; for (e2 = p2.nEQs - 1; e2 >= 0; e2--) { int e1 = newEQ(); eqnnzero(&(EQs[e1]), nVars); for(i=0;i<=p2.nVars;i++) EQs[e1].coef[newLocation[i]] = p2.EQs[e2].coef[i]; } for (e2 = p2.nGEQs - 1; e2 >= 0; e2--) { int e1 = newGEQ(); eqnnzero(&(GEQs[e1]), nVars); GEQs[e1].touched = 1; for(i=0;i<=p2.nVars;i++) GEQs[e1].coef[newLocation[i]] = p2.GEQs[e2].coef[i]; } int w = -1; for (i = 1; i <= nVars; i++) if (var[i] < 0) var[i] = w--; if(DBUG) { fprintf(outputFile,"to get:\n"); printProblem(); } } void Problem::chainUnprotect() { int i, e; int unprotect[maxVars]; int any = 0; for (i = 1; i <= safeVars; i++) { unprotect[i] = (var[i] < 0); for (e = nSUBs - 1; e >= 0; e--) if (SUBs[e].coef[i]) unprotect[i] = 0; } for (i = 1; i <= safeVars; i++) if (unprotect[i]) any=1; if (!any) return; if (DBUG) { fprintf(outputFile, "Doing chain reaction unprotection\n"); printProblem(); for (i = 1; i <= safeVars; i++) if (unprotect[i]) fprintf(outputFile, "unprotecting %s\n", variable(i)); } for (i = 1; i <= safeVars; i++) if (unprotect[i]) { /* wild card */ if (i < safeVars) { int j = safeVars; std::swap(var[i], var[j]); for (e = nGEQs - 1; e >= 0; e--) { GEQs[e].touched = 1; std::swap(GEQs[e].coef[i], GEQs[e].coef[j]); } for (e = nEQs - 1; e >= 0; e--) std::swap(EQs[e].coef[i], EQs[e].coef[j]); for (e = nSUBs - 1; e >= 0; e--) std::swap(SUBs[e].coef[i], SUBs[e].coef[j]); std::swap(unprotect[i], unprotect[j]); i--; } safeVars--; } if (DBUG) { fprintf(outputFile, "After chain reactions\n"); printProblem(); } } void Problem::resurrectSubs() { if (nSUBs > 0 && !pleaseNoEqualitiesInSimplifiedProblems) { int i, e, n, m,mbr; mbr = 0; for (e = nGEQs - 1; e >= 0; e--) if (GEQs[e].color) mbr=1; for (e = nEQs - 1; e >= 0; e--) if (EQs[e].color) mbr=1; if (nMemories) mbr = 1; assert(!mbr || mayBeRed); if (DBUG) { fprintf(outputFile, "problem reduced, bringing variables back to life\n"); if(mbr && !mayBeRed) fprintf(outputFile, "Red equations we don't expect\n"); printProblem(); } if (DBUG && nEQs > 0) fprintf(outputFile,"This is wierd: problem has equalities\n"); for (i = 1; i <= safeVars; i++) if (var[i] < 0) { /* wild card */ if (i < safeVars) { int j = safeVars; std::swap(var[i], var[j]); for (e = nGEQs - 1; e >= 0; e--) { GEQs[e].touched = 1; std::swap(GEQs[e].coef[i], GEQs[e].coef[j]); } for (e = nEQs - 1; e >= 0; e--) std::swap(EQs[e].coef[i], EQs[e].coef[j]); for (e = nSUBs - 1; e >= 0; e--) std::swap(SUBs[e].coef[i], SUBs[e].coef[j]); i--; } safeVars--; } m = nSUBs; n = nVars; if (n < safeVars + m) n = safeVars + m; for (e = nGEQs - 1; e >= 0; e--) { if (singleVarGEQ(&GEQs[e])) { i = abs(GEQs[e].key); if (i >= safeVars + 1) GEQs[e].key += (GEQs[e].key > 0 ? m : -m); } else { GEQs[e].touched = true; GEQs[e].key = 0; } } for (i = nVars; i >= safeVars + 1; i--) { var[i + m] = var[i]; for (e = nGEQs - 1; e >= 0; e--) GEQs[e].coef[i + m] = GEQs[e].coef[i]; for (e = nEQs - 1; e >= 0; e--) EQs[e].coef[i + m] = EQs[e].coef[i]; for (e = nSUBs - 1; e >= 0; e--) SUBs[e].coef[i + m] = SUBs[e].coef[i]; } for (i = safeVars + m; i >= safeVars + 1; i--) { for (e = nGEQs - 1; e >= 0; e--) GEQs[e].coef[i] = 0; for (e = nEQs - 1; e >= 0; e--) EQs[e].coef[i] = 0; for (e = nSUBs - 1; e >= 0; e--) SUBs[e].coef[i] = 0; } nVars += m; safeVars += m; for (e = nSUBs - 1; e >= 0; e--) var[safeVars -m + 1 + e] = SUBs[e].key; for (i = 1; i <= safeVars; i++) forwardingAddress[var[i]] = i; if (DBUG) { fprintf(outputFile,"Ready to wake substitutions\n"); printProblem(); } for (e = nSUBs - 1; e >= 0; e--) { int neweq = newEQ(); eqnncpy(&(EQs[neweq]), &(SUBs[e]), nVars); EQs[neweq].coef[safeVars -m + 1 + e] = -1; EQs[neweq].color = EQ_BLACK; if (DBUG) { fprintf(outputFile, "brought back: "); printEQ(&EQs[neweq]); fprintf(outputFile, "\n"); } } nSUBs = 0; if (DBUG) { fprintf(outputFile, "variables brought back to life\n"); printProblem(); } } coalesce(); recallRedMemories(); cleanoutWildcards(); } void Problem::reverseProtectedVariables() { int v1,v2,e,i; coef_t t; for (v1 = 1; v1 <= safeVars; v1++) { v2 = safeVars+1-v1; if (v2>=v1) break; for(e=0;e<nEQs;e++) { t = EQs[e].coef[v1]; EQs[e].coef[v1] = EQs[e].coef[v2]; EQs[e].coef[v2] = t; } for(e=0;e<nGEQs;e++) { t = GEQs[e].coef[v1]; GEQs[e].coef[v1] = GEQs[e].coef[v2]; GEQs[e].coef[v2] = t; GEQs[e].touched = 1; } for(e=0;e<nSUBs;e++) { t = SUBs[e].coef[v1]; SUBs[e].coef[v1] = SUBs[e].coef[v2]; SUBs[e].coef[v2] = t; } } for (i = 1; i <= safeVars; i++) forwardingAddress[var[i]] = i; for (i = 0; i < nSUBs; i++) forwardingAddress[SUBs[i].key] = -i - 1; } void Problem::ordered_elimination(int symbolic) { int i,j,e; int isDead[maxmaxGEQs]; for(e=0;e<nEQs;e++) isDead[e] = 0; if (!variablesInitialized) { initializeVariables(); } for(i=nVars;i>symbolic;i--) for(e=0;e<nEQs;e++) if (EQs[e].coef[i] == 1 || EQs[e].coef[i] == -1) { for(j=nVars;j>i;j--) if (EQs[e].coef[j]) break; if (i==j) { doElimination(e, i); isDead[e] = 1; break; } } for(e=nEQs-1;e>=0;e--) if (isDead[e]) { nEQs--; if (e < nEQs) eqnncpy(&EQs[e], &EQs[nEQs], nVars); } for (i = 1; i <= safeVars; i++) forwardingAddress[var[i]] = i; for (i = 0; i < nSUBs; i++) forwardingAddress[SUBs[i].key] = -i - 1; } coef_t Problem::checkSum() const { coef_t cs; int e; cs = 0; for(e=0;e<nGEQs;e++) { coef_t c = GEQs[e].coef[0]; cs += c*c*c; } return cs; } void Problem::coalesce() { int e, e2, colors; int isDead[maxmaxGEQs]; int foundSomething = 0; colors = 0; for (e = 0; e < nGEQs; e++) if (GEQs[e].color) colors++; if (colors < 2) return; for (e = 0; e < nGEQs; e++) isDead[e] = 0; for (e = 0; e < nGEQs; e++) if (!GEQs[e].touched) for (e2 = e + 1; e2 < nGEQs; e2++) if (!GEQs[e2].touched && GEQs[e].key == -GEQs[e2].key && GEQs[e].coef[0] == -GEQs[e2].coef[0]) { int neweq = newEQ(); eqnncpy(&EQs[neweq], &GEQs[e], nVars); EQs[neweq].color = GEQs[e].color || GEQs[e2].color; foundSomething++; isDead[e] = 1; isDead[e2] = 1; } for (e = nGEQs - 1; e >= 0; e--) if (isDead[e]) { deleteGEQ(e); } if (DEBUG && foundSomething) { fprintf(outputFile, "Coalesced GEQs into %d EQ's:\n", foundSomething); printProblem(); } } } // namespace
8,312
3,888
#include "lowmc_tfhe.h" #include <iostream> namespace LOWMC { void LOWMC_256_128_63_14_TFHE::encrypt_key() { secret_key_encrypted.init(params.key_size_bits, context); for (size_t i = 0; i < params.key_size_bits; i++) { uint8_t bit = (secret_key[i / 8] >> (7 - i % 8)) & 1; bootsSymEncrypt(&secret_key_encrypted[i], bit, he_sk); } } TFHECiphertextVec LOWMC_256_128_63_14_TFHE::HE_decrypt( std::vector<uint8_t>& ciphertexts, size_t bits) { size_t num_block = ceil((double)bits / params.cipher_size_bits); LowMC lowmc(use_m4ri); block iv = 0; TFHECiphertextVec result(bits, context); for (size_t i = 0; i < num_block; i++) { std::cout << "round 0" << std::endl; TFHECiphertextVec state; if (use_m4ri) { state = secret_key_encrypted; MultiplyWithGF2Matrix(lowmc.m4ri_KeyMatrices[0], state); } else state = MultiplyWithGF2Matrix(lowmc.KeyMatrices[0], secret_key_encrypted); addConstant(state, ctr(iv, i + 1)); for (unsigned r = 1; r <= rounds; ++r) { std::cout << "round " << r << std::endl; sboxlayer(state); if (use_m4ri) { MultiplyWithGF2Matrix(lowmc.m4ri_LinMatrices[r - 1], state); MultiplyWithGF2MatrixAndAdd(lowmc.m4ri_KeyMatrices[r], secret_key_encrypted, state); } else { MultiplyWithGF2Matrix(lowmc.LinMatrices[r - 1], state); MultiplyWithGF2MatrixAndAdd(lowmc.KeyMatrices[r], secret_key_encrypted, state); } addConstant(state, lowmc.roundconstants[r - 1]); } // add cipher for (size_t k = 0; k < blocksize && i * blocksize + k < bits; k++) { size_t ind = i * blocksize + k; int32_t bit = (ciphertexts[ind / 8] >> (7 - ind % 8)) & 1; if (!bit) lweCopy(&result[ind], &state[k], he_pk->params->in_out_params); else bootsNOT(&result[ind], &state[k], he_pk); } } return result; } std::vector<uint8_t> LOWMC_256_128_63_14_TFHE::decrypt_result( TFHECiphertextVec& ciphertexts) { size_t size = ceil((double)ciphertexts.size() / 8); std::vector<uint8_t> res(size, 0); for (size_t i = 0; i < ciphertexts.size(); i++) { uint8_t bit = bootsSymDecrypt(&ciphertexts[i], he_sk) & 0xFF; res[i / 8] |= (bit << (7 - i % 8)); } return res; } TFHECiphertextVec LOWMC_256_128_63_14_TFHE::MultiplyWithGF2Matrix( const std::vector<keyblock>& matrix, const TFHECiphertextVec& key) { TFHECiphertextVec out(params.cipher_size_bits, context); for (unsigned i = 0; i < params.cipher_size_bits; ++i) { bool init = false; for (unsigned j = 0; j < params.key_size_bits; ++j) { if (!matrix[i][j]) continue; if (!init) { lweCopy(&out[i], &key[j], he_pk->params->in_out_params); init = true; } else bootsXOR(&out[i], &out[i], &key[j], he_pk); } } return out; } void LOWMC_256_128_63_14_TFHE::MultiplyWithGF2MatrixAndAdd( const std::vector<keyblock>& matrix, const TFHECiphertextVec& key, TFHECiphertextVec& state) { for (unsigned i = 0; i < params.cipher_size_bits; ++i) { for (unsigned j = 0; j < params.key_size_bits; ++j) { if (!matrix[i][j]) continue; bootsXOR(&state[i], &state[i], &key[j], he_pk); } } } void LOWMC_256_128_63_14_TFHE::MultiplyWithGF2Matrix( const std::vector<block>& matrix, TFHECiphertextVec& state) { TFHECiphertextVec out(params.cipher_size_bits, context); for (unsigned i = 0; i < params.cipher_size_bits; ++i) { bool init = false; for (unsigned j = 0; j < params.cipher_size_bits; ++j) { if (!matrix[i][j]) continue; if (!init) { lweCopy(&out[i], &state[j], he_pk->params->in_out_params); init = true; } else bootsXOR(&out[i], &out[i], &state[j], he_pk); } } state = out; } void LOWMC_256_128_63_14_TFHE::addConstant(TFHECiphertextVec& state, const block& constant) { for (size_t i = 0; i < params.cipher_size_bits; i++) { if (!constant[i]) continue; bootsNOT(&state[i], &state[i], he_pk); } } void LOWMC_256_128_63_14_TFHE::sboxlayer(TFHECiphertextVec& state) { for (unsigned i = 0; i < numofboxes; i++) { // invSbox(state[i * 3], state[i* 3 + 1], state[i * 3 + 2]); Sbox(state[i * 3], state[i * 3 + 1], state[i * 3 + 2]); } } void LOWMC_256_128_63_14_TFHE::Sbox(LweSample& a, LweSample& b, LweSample& c) { TFHECiphertext r_a(context); bootsAND(r_a, &b, &c, he_pk); bootsXOR(r_a, r_a, &a, he_pk); bootsXOR(r_a, r_a, &b, he_pk); bootsXOR(r_a, r_a, &c, he_pk); TFHECiphertext r_b(context); bootsAND(r_b, &a, &c, he_pk); bootsXOR(r_b, r_b, &b, he_pk); bootsXOR(r_b, r_b, &c, he_pk); TFHECiphertext r_c(context); bootsAND(r_c, &a, &b, he_pk); bootsXOR(r_c, r_c, &c, he_pk); lweCopy(&a, r_a, he_pk->params->in_out_params); lweCopy(&b, r_b, he_pk->params->in_out_params); lweCopy(&c, r_c, he_pk->params->in_out_params); } void LOWMC_256_128_63_14_TFHE::invSbox(LweSample& a, LweSample& b, LweSample& c) { TFHECiphertext r_a(context); bootsAND(r_a, &b, &c, he_pk); bootsXOR(r_a, r_a, &b, he_pk); bootsXOR(r_a, r_a, &c, he_pk); bootsXOR(r_a, r_a, &a, he_pk); TFHECiphertext r_b(context); bootsAND(r_b, &a, &c, he_pk); bootsXOR(r_b, r_b, &b, he_pk); TFHECiphertext r_c(context); bootsAND(r_c, &a, &b, he_pk); bootsXOR(r_c, r_c, &b, he_pk); bootsXOR(r_c, r_c, &c, he_pk); lweCopy(&a, r_a, he_pk->params->in_out_params); lweCopy(&b, r_b, he_pk->params->in_out_params); lweCopy(&c, r_c, he_pk->params->in_out_params); } void LOWMC_256_128_63_14_TFHE::MultiplyWithGF2MatrixAndAdd( const mzd_t* matrix, const TFHECiphertextVec& key, TFHECiphertextVec& state) { rci_t k = floor(log2(matrix->ncols)) - 2; if (k < 1) k = 1; std::vector<rci_t> L(1 << k); TFHECiphertextVec T(1 << k, context); L[0] = 0; for (rci_t i = 0; i < matrix->ncols; i += k) { if (i + k > matrix->ncols) k = matrix->ncols - i; for (rci_t j = 1; j < 1 << k; j++) { rci_t rowneeded = i + m4ri_codebook[k]->inc[j - 1]; L[m4ri_codebook[k]->ord[j]] = j; if (j == 1) lweCopy(&T[j], &key[rowneeded], he_pk->params->in_out_params); else bootsXOR(&T[j], &T[j - 1], &key[rowneeded], he_pk); } for (rci_t j = 0; j < matrix->nrows; j++) { rci_t x = L[mzd_read_bits_int(matrix, j, i, k)]; if (!x) continue; bootsXOR(&state[j], &state[j], &T[x], he_pk); } } } void LOWMC_256_128_63_14_TFHE::MultiplyWithGF2Matrix(const mzd_t* matrix, TFHECiphertextVec& state) { TFHECiphertextVec out(params.cipher_size_bits, context); rci_t k = floor(log2(matrix->ncols)) - 2; if (k < 1) k = 1; block init = 0; std::vector<rci_t> L(1 << k); TFHECiphertextVec T(1 << k, context); L[0] = 0; for (rci_t i = 0; i < matrix->ncols; i += k) { if (i + k > matrix->ncols) k = matrix->ncols - i; for (rci_t j = 1; j < 1 << k; j++) { rci_t rowneeded = i + m4ri_codebook[k]->inc[j - 1]; L[m4ri_codebook[k]->ord[j]] = j; if (j == 1) lweCopy(&T[j], &state[rowneeded], he_pk->params->in_out_params); else bootsXOR(&T[j], &T[j - 1], &state[rowneeded], he_pk); } for (rci_t j = 0; j < matrix->nrows; j++) { rci_t x = L[mzd_read_bits_int(matrix, j, i, k)]; if (!x) continue; if (init[j] == 0) { lweCopy(&out[j], &T[x], he_pk->params->in_out_params); init[j] = 1; } else bootsXOR(&out[j], &out[j], &T[x], he_pk); } } state = out; } } // namespace LOWMC
7,698
3,548
#include "SceneManager.hpp" #include "MenuScene.hpp" #include "NewGameScene.hpp" #include "LoadGameScene.hpp" #include "SettingsScene.hpp" #include "RenderScene.hpp" #ifndef __EMSCRIPTEN__ #include "MultiplayerScene.hpp" #include "MakeRoomScene.hpp" #include "JoinRoomScene.hpp" #endif SceneManager::SceneManager(struct nk_context *ctx, const std::string path) : _currentScene(nullptr) { auto menuScene = new MenuScene("menu", path, ctx); auto newGameScene = new NewGameScene("newgame", path, ctx); auto loadGameScene = new LoadGameScene("loadgame", path, ctx); auto settingsScene = new SettingsScene("settings", path, ctx); auto renderScene = new RenderScene("render", path, ctx); #ifndef __EMSCRIPTEN__ auto multiScene = new MultiplayerScene("multi", path, ctx); auto makeRoomScene = new MakeRoomScene("makeroom", path, ctx); auto joinRoomScene = new JoinRoomScene("joinroom", path, ctx); #endif _sceneDB[menuScene->getName()] = menuScene; _sceneDB[newGameScene->getName()] = newGameScene; _sceneDB[loadGameScene->getName()] = loadGameScene; _sceneDB[settingsScene->getName()] = settingsScene; _sceneDB[renderScene->getName()] = renderScene; #ifndef __EMSCRIPTEN__ _sceneDB[multiScene->getName()] = multiScene; _sceneDB[makeRoomScene->getName()] = makeRoomScene; _sceneDB[joinRoomScene->getName()] = joinRoomScene; #endif this->setCurrent("menu"); } SceneManager::~SceneManager() noexcept { for (auto it = _sceneDB.begin(); it != _sceneDB.end(); it++) { if ((*it).second != nullptr) { (*it).second->Destroy(); delete (*it).second; } (*it).second = nullptr; } _sceneDB.clear(); } SceneType SceneManager::Render(struct nk_font *smallfont, struct nk_font *normal) { return _currentScene->Render(smallfont, normal); } bool SceneManager::setCurrent(const std::string & name) { auto it = _sceneDB.find(name); if (it == _sceneDB.end()) { return false; } if (_currentScene != it->second) { _currentScene = it->second; } return true; } BaseScene* SceneManager::getScenePointer(const std::string & name) { auto it = _sceneDB.find(name); if (it == _sceneDB.end()) { return nullptr; } return it->second; }
2,238
783
// // kfilter.cpp // carma_pack // // Created by Brandon Kelly on 6/27/13. // Copyright (c) 2013 Brandon Kelly. All rights reserved. // #include <random.hpp> #include "include/kfilter.hpp" // Global random number generator object, instantiated in random.cpp extern boost::random::mt19937 rng; // Object containing some common random number generators. extern RandomGenerator RandGen; // Reset the Kalman Filter for a CAR(1) process void KalmanFilter1::Reset() { mean(0) = 0.0; var(0) = sigsqr_ / (2.0 * omega_) + yerr_(0) * yerr_(0); yconst_ = 0.0; yslope_ = 0.0; current_index_ = 1; } // Perform one iteration of the Kalman Filter for a CAR(1) process to update it void KalmanFilter1::Update() { double rho, var_ratio, previous_var; rho = exp(-1.0 * omega_ * dt_(current_index_-1)); previous_var = var(current_index_-1) - yerr_(current_index_-1) * yerr_(current_index_-1); var_ratio = previous_var / var(current_index_-1); // Update the Kalman filter mean mean(current_index_) = rho * mean(current_index_-1) + rho * var_ratio * (y_(current_index_-1) - mean(current_index_-1)); // Update the Kalman filter variance var(current_index_) = sigsqr_ / (2.0 * omega_) * (1.0 - rho * rho) + rho * rho * previous_var * (1.0 - var_ratio); // add in contribution to variance from measurement errors var(current_index_) += yerr_(current_index_) * yerr_(current_index_); current_index_++; } // Initialize the coefficients used for interpolation and backcasting assuming a CAR(1) process void KalmanFilter1::InitializeCoefs(double time, unsigned int itime, double ymean, double yvar) { yconst_ = 0.0; yslope_ = exp(-std::abs(time_(itime) - time) * omega_); var[itime] = sigsqr_ / (2.0 * omega_) * (1.0 - yslope_ * yslope_) + yerr_(itime) * yerr_(itime); current_index_ = itime + 1; } // Update the coefficients used for interpolation and backcasting, assuming a CAR(1) process void KalmanFilter1::UpdateCoefs() { double rho = exp(-1.0 * dt_(current_index_-1) * omega_); double previous_var = var(current_index_-1) - yerr_(current_index_-1) * yerr_(current_index_-1); double var_ratio = previous_var / var(current_index_-1); yslope_ *= rho * (1.0 - var_ratio); yconst_ = yconst_ * rho * (1.0 - var_ratio) + rho * var_ratio * y_[current_index_-1]; var(current_index_) = sigsqr_ / (2.0 * omega_) * (1.0 - rho * rho) + rho * rho * previous_var * (1.0 - var_ratio) + yerr_(current_index_) * yerr_(current_index_); current_index_++; } // Return the predicted value and its variance at time assuming a CAR(1) process std::pair<double, double> KalmanFilter1::Predict(double time) { double rho, var_ratio, previous_var; double ypredict_mean, ypredict_var, yprecision; unsigned int ipredict = 0; while (time > time_(ipredict)) { // find the index where time_ > time for the first time ipredict++; if (ipredict == time_.n_elem) { // time is greater than last element of time_, so do forecasting break; } } // Run the Kalman filter up to the point time_[ipredict-1] Reset(); for (int i=1; i<ipredict; i++) { Update(); } if (ipredict == 0) { // backcasting, so initialize the conditional mean and variance to the stationary values ypredict_mean = 0.0; ypredict_var = sigsqr_ / (2.0 * omega_); } else { // predict the value of the time series at time, given the earlier values double dt = time - time_[ipredict-1]; rho = exp(-dt * omega_); previous_var = var(ipredict-1) - yerr_(ipredict-1) * yerr_(ipredict-1); var_ratio = previous_var / var(ipredict-1); // initialize the conditional mean and variance ypredict_mean = rho * mean(ipredict-1) + rho * var_ratio * (y_(ipredict-1) - mean(ipredict-1)); ypredict_var = sigsqr_ / (2.0 * omega_) * (1.0 - rho * rho) + rho * rho * previous_var * (1.0 - var_ratio); } if (ipredict == time_.n_elem) { // Forecasting, so we're done: no need to run interpolation steps std::pair<double, double> ypredict(ypredict_mean, ypredict_var); return ypredict; } yprecision = 1.0 / ypredict_var; ypredict_mean *= yprecision; // Either backcasting or interpolating, so need to calculate coefficients of linear filter as a function of // the predicted time series value, then update the running conditional mean and variance of the predicted // time series value InitializeCoefs(time, ipredict, 0.0, 0.0); yprecision += yslope_ * yslope_ / var(ipredict); ypredict_mean += yslope_ * (y_(ipredict) - yconst_) / var(ipredict); for (int i=ipredict+1; i<time_.n_elem; i++) { UpdateCoefs(); yprecision += yslope_ * yslope_ / var(i); ypredict_mean += yslope_ * (y_(i) - yconst_) / var(i); } ypredict_var = 1.0 / yprecision; ypredict_mean *= ypredict_var; std::pair<double, double> ypredict(ypredict_mean, ypredict_var); return ypredict; } // Reset the Kalman Filter for a CARMA(p,q) process void KalmanFilterp::Reset() { // Initialize the matrix of Eigenvectors. We will work with the state vector // in the space spanned by the Eigenvectors because in this space the state // transition matrix is diagonal, so the calculation of the matrix exponential // is fast. arma::cx_mat EigenMat(p_,p_); EigenMat.row(0) = arma::ones<arma::cx_rowvec>(p_); EigenMat.row(1) = omega_.st(); for (int i=2; i<p_; i++) { EigenMat.row(i) = strans(arma::pow(omega_, i)); } // Input vector under original state space representation arma::cx_vec Rvector = arma::zeros<arma::cx_vec>(p_); Rvector(p_-1) = 1.0; // Transform the input vector to the rotated state space representation. // The notation R and J comes from Belcher et al. (1994). arma::cx_vec Jvector(p_); Jvector = arma::solve(EigenMat, Rvector); // Transform the moving average coefficients to the space spanned by EigenMat. rotated_ma_coefs_ = ma_coefs_ * EigenMat; // Calculate the stationary covariance matrix of the state vector. for (int i=0; i<p_; i++) { for (int j=i; j<p_; j++) { // Only fill in upper triangle of StateVar because of symmetry StateVar_(i,j) = -sigsqr_ * Jvector(i) * std::conj(Jvector(j)) / (omega_(i) + std::conj(omega_(j))); } } StateVar_ = arma::symmatu(StateVar_); // StateVar is symmetric PredictionVar_ = StateVar_; // One-step state prediction error state_vector_.zeros(); // Initial state is set to zero // Initialize the Kalman mean and variance. These are the forecasted value // for the measured time series values and its variance, conditional on the // previous measurements mean(0) = 0.0; var(0) = std::real( arma::as_scalar(rotated_ma_coefs_ * StateVar_ * rotated_ma_coefs_.t()) ); var(0) += yerr_(0) * yerr_(0); // Add in measurement error contribution innovation_ = y_(0); // The innovation current_index_ = 1; } // Perform one iteration of the Kalman Filter for a CARMA(p,q) process to update it void KalmanFilterp::Update() { // First compute the Kalman Gain kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / var(current_index_-1); // Now update the state vector state_vector_ += kalman_gain_ * innovation_; // Update the state one-step prediction error variance PredictionVar_ -= var(current_index_-1) * (kalman_gain_ * kalman_gain_.t()); // Predict the next state rho_ = arma::exp(omega_ * dt_(current_index_-1)); state_vector_ = rho_ % state_vector_; // Update the predicted state variance matrix PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_; // Now predict the observation and its variance. mean(current_index_) = std::real( arma::as_scalar(rotated_ma_coefs_ * state_vector_) ); var(current_index_) = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) ); var(current_index_) += yerr_(current_index_) * yerr_(current_index_); // Add in measurement error contribution // Finally, update the innovation innovation_ = y_(current_index_) - mean(current_index_); current_index_++; } // Predict the time series at the input time given the measured time series, assuming a CARMA(p,q) process std::pair<double, double> KalmanFilterp::Predict(double time) { unsigned int ipredict = 0; while (time > time_(ipredict)) { // find the index where time_ > time for the first time ipredict++; if (ipredict == time_.n_elem) { // time is greater than last element of time_, so do forecasting break; } } // Run the Kalman filter up to the point time_[ipredict-1] Reset(); for (int i=1; i<ipredict; i++) { Update(); } double ypredict_mean, ypredict_var, yprecision; if (ipredict == 0) { // backcasting, so initialize the conditional mean and variance to the stationary values ypredict_mean = 0.0; ypredict_var = std::real( arma::as_scalar(rotated_ma_coefs_ * StateVar_ * rotated_ma_coefs_.t()) ); } else { // predict the value of the time series at time, given the earlier values kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / var(ipredict-1); state_vector_ += kalman_gain_ * innovation_; PredictionVar_ -= var(ipredict-1) * (kalman_gain_ * kalman_gain_.t()); double dt = std::abs(time - time_(ipredict-1)); rho_ = arma::exp(omega_ * dt); state_vector_ = rho_ % state_vector_; PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_; // initialize the conditional mean and variance ypredict_mean = std::real( arma::as_scalar(rotated_ma_coefs_ * state_vector_) ); ypredict_var = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) ); } if (ipredict == time_.n_elem) { // Forecasting, so we're done: no need to run interpolation steps std::pair<double, double> ypredict(ypredict_mean, ypredict_var); return ypredict; } yprecision = 1.0 / ypredict_var; ypredict_mean *= yprecision; // Either backcasting or interpolating, so need to calculate coefficients of linear filter as a function of // the predicted time series value, then update the running conditional mean and variance of the predicted // time series value InitializeCoefs(time, ipredict, ypredict_mean / yprecision, ypredict_var); yprecision += yslope_ * yslope_ / var(ipredict); ypredict_mean += yslope_ * (y_(ipredict) - yconst_) / var(ipredict); for (int i=ipredict+1; i<time_.n_elem; i++) { UpdateCoefs(); yprecision += yslope_ * yslope_ / var(i); ypredict_mean += yslope_ * (y_(i) - yconst_) / var(i); } ypredict_var = 1.0 / yprecision; ypredict_mean *= ypredict_var; std::pair<double, double> ypredict(ypredict_mean, ypredict_var); return ypredict; } // Initialize the coefficients needed for computing the Kalman Filter at future times as a function of // the time series at time, where time_(itime-1) < time < time_(itime) void KalmanFilterp::InitializeCoefs(double time, unsigned int itime, double ymean, double yvar) { kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / yvar; // initialize the coefficients for predicting the state vector at coefs(time_predict|time_predict) state_const_ = state_vector_ - kalman_gain_ * ymean; state_slope_ = kalman_gain_; // update the state one-step prediction error variance PredictionVar_ -= yvar * (kalman_gain_ * kalman_gain_.t()); // coefs(time_predict|time_predict) --> coefs(time[i+1]|time_predict) double dt = std::abs(time_(itime) - time); rho_ = arma::exp(omega_ * dt); state_const_ = rho_ % state_const_; state_slope_ = rho_ % state_slope_; // update the predicted state covariance matrix PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_; // compute the coefficients for the linear filter at time[ipredict], and compute the variance in the predicted // y[ipredict] yconst_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_const_) ); yslope_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_slope_) ); var(itime) = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) ) + yerr_(itime) * yerr_(itime); current_index_ = itime + 1; } // Update the coefficients need for computing the Kalman Filter at future times as a function of the // time series value at some earlier time void KalmanFilterp::UpdateCoefs() { kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / var(current_index_-1); // update the coefficients for predicting the state vector at coefs(i|i-1) --> coefs(i|i) state_const_ += kalman_gain_ * (y_(current_index_-1) - yconst_); state_slope_ -= kalman_gain_ * yslope_; // update the state one-step prediction error variance PredictionVar_ -= var(current_index_-1) * (kalman_gain_ * kalman_gain_.t()); // compute the one-step state prediction coefficients: coefs(i|i) --> coefs(i+1|i) rho_ = arma::exp(omega_ * dt_(current_index_-1)); state_const_ = rho_ % state_const_; state_slope_ = rho_ % state_slope_; // update the predicted state covariance matrix PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_; // compute the coefficients for the linear filter at time[ipredict], and compute the variance in the predicted // y[ipredict] yconst_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_const_) ); yslope_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_slope_) ); var(current_index_) = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) ) + yerr_(current_index_) * yerr_(current_index_); current_index_++; }
14,209
4,951
#include "Dicom_util.h" #include "logging/Log.h" #include <dcmtk/dcmdata/dcelem.h> #include <dcmtk/dcmdata/dcitem.h> #include <dcmtk/dcmdata/dcpath.h> #include <dcmtk/dcmdata/dcsequen.h> #include <stdexcept> static DcmObject* get_object(DcmPath* path) { DcmPathNode* last_element = path->back(); if(last_element == nullptr) { throw std::runtime_error("Invalid tag path."); } DcmObject* object = last_element->m_obj; if(object == nullptr) { throw std::runtime_error("Invalid tag path."); } return object; } static void set_element_value(const OFList<DcmPath*>& paths, const std::string& value) { bool error = false; for(DcmPath* path : paths) { DcmPathNode* last_element = path->back(); if(last_element == nullptr) { error = true; continue; } auto element = dynamic_cast<DcmElement*>(last_element->m_obj); if(element == nullptr) { error = true; continue; } OFCondition status = element->putString(value.c_str()); if(status.bad()) { Log::error(std::string("Failed to set element value. Reason: ") + status.text()); error = true; continue; } } if(error) { throw std::runtime_error("At least one error occurred, check log for details."); } } void Dicom_util::set_element(const std::string& tag_path, const std::string& value, DcmDataset& dataset) { DcmPathProcessor path_proc; OFCondition status = path_proc.findOrCreatePath(&dataset, tag_path.c_str(), true); if(status.bad()) { throw std::runtime_error(status.text()); } OFList<DcmPath*> foundPaths; auto resultCount = path_proc.getResults(foundPaths); if(resultCount == 0) { throw std::runtime_error("Tag path not found."); } DcmObject* object = get_object(foundPaths.front()); if(!object->isLeaf()) { if(!value.empty()) { throw std::runtime_error("Can't set value for non-leaf element."); } return; } set_element_value(foundPaths, value); } void Dicom_util::edit_element(const std::string& tag_path, const std::string& value, DcmDataset& dataset) { DcmPathProcessor path_proc; OFCondition status = path_proc.findOrCreatePath(&dataset, tag_path.c_str(), false); if(status.bad()) { throw std::runtime_error(status.text()); } OFList<DcmPath*> foundPaths; auto resultCount = path_proc.getResults(foundPaths); if(resultCount == 0) { throw std::runtime_error("Tag path not found."); } DcmObject* object = get_object(foundPaths.front()); if(!object->isLeaf()) { throw std::runtime_error("Can't edit non-leaf element."); } set_element_value(foundPaths, value); } void Dicom_util::delete_element(const std::string& tag_path, DcmDataset& dataset) { DcmPathProcessor path_proc; unsigned int resultCount = 0; OFCondition status = path_proc.findOrDeletePath(&dataset, tag_path.c_str(), resultCount); if(status.bad()) { throw std::runtime_error(status.text()); } } int Dicom_util::get_index_nr(DcmObject& object) { DcmObject* parent = object.getParent(); if(!parent) { return 0; } const DcmEVR vr = parent->ident(); if(vr == EVR_item || vr == EVR_dataset) { auto item = static_cast<DcmItem*>(parent); auto elementCount = item->getNumberOfValues(); for(auto i = 0u; i < elementCount; ++i) { if(item->getElement(i) == &object) { return i; } } } else if(vr == EVR_SQ) { auto sq = static_cast<DcmSequenceOfItems*>(parent); auto itemCount = sq->getNumberOfValues(); for(auto i = 0u; i < itemCount; ++i) { if(sq->getItem(i) == &object) { return i; } } } Log::error("Could not get index of object. Parent VR: " + std::to_string(vr)); return -1; }
4,071
1,322
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <mpi.h> #include <petsc.h> #include <Underworld/Function/src/FunctionIO.hpp> #include <Underworld/Function/src/ParticleCoordinate.hpp> #include <Underworld/Function/src/Function.hpp> extern "C" { #include <StGermain/libStGermain/src/StGermain.h> #include <StgDomain/libStgDomain/src/StgDomain.h> #include <StgFEM/libStgFEM/src/StgFEM.h> #include <PICellerator/libPICellerator/src/PICellerator.h> #include <gLucifer/Base/src/Base.h> #include "types.h" #include <gLucifer/Base/src/DrawingObject.h> } #include "SwarmViewer.h" /* Textual name of this class - This is a global pointer which is used for times when you need to refer to class and not a particular instance of a class */ const Type lucSwarmViewer_Type = (char*) "lucSwarmViewer"; void _lucSwarmViewer_SetFn( void* _self, Fn::Function* fn_colour, Fn::Function* fn_mask, Fn::Function* fn_size, Fn::Function* fn_opacity ){ lucSwarmViewer* self = (lucSwarmViewer*)_self; lucSwarmViewer_cppdata* cppdata = (lucSwarmViewer_cppdata*) self->cppdata; // setup fn input. first make particle coordinate std::shared_ptr<ParticleCoordinate> particleCoord = std::make_shared<ParticleCoordinate>( self->swarm->particleCoordVariable ); // grab first particle for sample data particleCoord->index() = 0; // record fns, and also throw in a min/max guy where required if (fn_colour) { Fn::Function::func func = fn_colour->getFunction(particleCoord.get()); const FunctionIO* io = dynamic_cast<const FunctionIO*>(func(particleCoord.get())); if( !io ) throw std::invalid_argument("Provided function does not appear to return a valid result."); if( io->size() != 1 ) throw std::invalid_argument("Provided function must return a scalar result."); // ok we've made it this far, switch out for MinMax version cppdata->fn_colour = std::make_shared<Fn::MinMax>(fn_colour); cppdata->func_colour = cppdata->fn_colour->getFunction(particleCoord.get()); } if (fn_mask) { cppdata->fn_mask = fn_mask; cppdata->func_mask = cppdata->fn_mask->getFunction(particleCoord.get()); const FunctionIO* io = dynamic_cast<const FunctionIO*>(cppdata->func_mask(particleCoord.get())); if( !io ) throw std::invalid_argument("Provided function does not appear to return a valid result."); if( io->size() != 1 ) throw std::invalid_argument("Provided function must return a scalar result."); } if (fn_size) { Fn::Function::func func = fn_size->getFunction(particleCoord.get()); const FunctionIO* io = dynamic_cast<const FunctionIO*>(func(particleCoord.get())); if( !io ) throw std::invalid_argument("Provided function does not appear to return a valid result."); if( io->size() != 1 ) throw std::invalid_argument("Provided function must return a scalar result."); // ok we've made it this far, switch out for MinMax version cppdata->fn_size = std::make_shared<Fn::MinMax>(fn_size); cppdata->func_size = cppdata->fn_size->getFunction(particleCoord.get()); } if (fn_opacity) { Fn::Function::func func = fn_opacity->getFunction(particleCoord.get()); const FunctionIO* io = dynamic_cast<const FunctionIO*>(func(particleCoord.get())); if( !io ) throw std::invalid_argument("Provided function does not appear to return a valid result."); if( io->size() != 1 ) throw std::invalid_argument("Provided function must return a scalar result."); // ok we've made it this far, switch out for MinMax version cppdata->fn_opacity = std::make_shared<Fn::MinMax>(fn_opacity); cppdata->func_opacity = cppdata->fn_opacity->getFunction(particleCoord.get()); } } /* Private Constructor: This will accept all the virtual functions for this class as arguments. */ lucSwarmViewer* _lucSwarmViewer_New( LUCSWARMVIEWER_DEFARGS ) { lucSwarmViewer* self; /* Call private constructor of parent - this will set virtual functions of parent and continue up the hierarchy tree. At the beginning of the tree it will allocate memory of the size of object and initialise all the memory to zero. */ assert( _sizeOfSelf >= sizeof(lucSwarmViewer) ); self = (lucSwarmViewer*) _lucDrawingObject_New( LUCDRAWINGOBJECT_PASSARGS ); self->_plotParticle = _plotParticle; self->_setParticleColour = _setParticleColour; self->cppdata = (void*) new lucSwarmViewer_cppdata; return self; } void _lucSwarmViewer_Init( lucSwarmViewer* self, GeneralSwarm* swarm, lucColourMap* opacityColourMap) { self->swarm = swarm; /* Create a default colour component mapping, full range black->white */ self->opacityColourMap = opacityColourMap; self->geomType = lucPointType; /* Draws points by default */ } void _lucSwarmViewer_Delete( void* drawingObject ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; if (self->cppdata) delete (lucSwarmViewer_cppdata*)self->cppdata; _lucDrawingObject_Delete( self ); } void _lucSwarmViewer_Print( void* drawingObject, Stream* stream ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; _lucDrawingObject_Print( self, stream ); } void* _lucSwarmViewer_Copy( void* drawingObject, void* dest, Bool deep, Name nameExt, PtrMap* ptrMap) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; lucSwarmViewer* newDrawingObject; newDrawingObject = (lucSwarmViewer*) _lucDrawingObject_Copy( self, dest, deep, nameExt, ptrMap ); /* TODO */ abort(); return (void*) newDrawingObject; } void* _lucSwarmViewer_DefaultNew( Name name ) { /* Variables set in this function */ SizeT _sizeOfSelf = sizeof(lucSwarmViewer); Type type = lucSwarmViewer_Type; Stg_Class_DeleteFunction* _delete = _lucSwarmViewer_Delete; Stg_Class_PrintFunction* _print = _lucSwarmViewer_Print; Stg_Class_CopyFunction* _copy = NULL; Stg_Component_DefaultConstructorFunction* _defaultConstructor = _lucSwarmViewer_DefaultNew; Stg_Component_ConstructFunction* _construct = _lucSwarmViewer_AssignFromXML; Stg_Component_BuildFunction* _build = _lucSwarmViewer_Build; Stg_Component_InitialiseFunction* _initialise = _lucSwarmViewer_Initialise; Stg_Component_ExecuteFunction* _execute = _lucSwarmViewer_Execute; Stg_Component_DestroyFunction* _destroy = _lucSwarmViewer_Destroy; lucDrawingObject_SetupFunction* _setup = _lucSwarmViewer_Setup; lucDrawingObject_DrawFunction* _draw = _lucSwarmViewer_Draw; lucDrawingObject_CleanUpFunction* _cleanUp = lucDrawingObject_CleanUp; lucSwarmViewer_PlotParticleFunction* _plotParticle = _lucSwarmViewer_PlotParticle; lucSwarmViewer_SetParticleColourFunction* _setParticleColour = _lucSwarmViewer_SetParticleColour; /* Variables that are set to ZERO are variables that will be set either by the current _New function or another parent _New function further up the hierachy */ AllocationType nameAllocationType = NON_GLOBAL /* default value NON_GLOBAL */; return (void*) _lucSwarmViewer_New( LUCSWARMVIEWER_PASSARGS ); } void _lucSwarmViewer_AssignFromXML( void* drawingObject, Stg_ComponentFactory* cf, void* data ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; GeneralSwarm* swarm; /* Construct Parent */ _lucDrawingObject_AssignFromXML( self, cf, data ); swarm = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"Swarm", GeneralSwarm, True, data ) ; _lucSwarmViewer_Init( self, swarm, Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"OpacityColourMap", lucColourMap, False, data) ); } void _lucSwarmViewer_Build( void* drawingObject, void* data ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; _lucDrawingObject_Build( self, data ); } void _lucSwarmViewer_Initialise( void* drawingObject, void* data ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; /* Initialise Parent */ _lucDrawingObject_Initialise( self, data ); } void _lucSwarmViewer_Execute( void* drawingObject, void* data ) {} void _lucSwarmViewer_Destroy( void* drawingObject, void* data ) {} void _lucSwarmViewer_Setup( void* drawingObject, lucDatabase* database, void* _context ) {} void _lucSwarmViewer_Draw( void* drawingObject, lucDatabase* database, void* _context ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; GeneralSwarm* swarm = self->swarm; Particle_Index particleLocalCount = swarm->particleLocalCount; Particle_Index lParticle_I; lucSwarmViewer_cppdata* cppdata = (lucSwarmViewer_cppdata*) self->cppdata; /* reset the min/max values */ if (cppdata->fn_colour) cppdata->fn_colour->reset(); if (cppdata->fn_size) cppdata->fn_size->reset(); if (cppdata->fn_opacity) cppdata->fn_opacity->reset(); // setup fn_io. std::shared_ptr<ParticleCoordinate> particleCoord = std::make_shared<ParticleCoordinate>( self->swarm->particleCoordVariable ); for ( lParticle_I = 0 ; lParticle_I < particleLocalCount ; lParticle_I++) { particleCoord->index() = lParticle_I; /* note we need to cast object to const version to ensure it selects const data() method */ const double* coord = const_cast<const ParticleCoordinate*>(particleCoord.get())->data(); /* Test to see if this particle should be drawn */ if ( cppdata->fn_mask && !cppdata->func_mask(particleCoord.get())->at<bool>()) continue; /* Export particle position */ float coordf[3] = {(float)coord[0],(float) coord[1], swarm->dim == 3 ? (float)coord[2] : 0.0f}; lucDatabase_AddVertices(database, 1, self->geomType, coordf); if (cppdata->fn_colour) { /* evaluate function */ float valuef = cppdata->func_colour(particleCoord.get())->at<float>(); lucDatabase_AddValues(database, 1, self->geomType, lucColourValueData, NULL, &valuef); } if (cppdata->fn_size) { /* evaluate function */ float valuef = cppdata->func_size(particleCoord.get())->at<float>(); lucDatabase_AddValues(database, 1, self->geomType, lucSizeData, NULL, &valuef); } } /* Set the value range */ if (cppdata->fn_colour) lucGeometryData_Setup(database->data[self->geomType][lucColourValueData], cppdata->fn_colour->getMinGlobal(), cppdata->fn_colour->getMaxGlobal()); /* Dynamic Scale Colour Maps */ if ( self->colourMap && self->colourMap->minimum == self->colourMap->maximum && cppdata->fn_colour ) lucColourMap_SetMinMax( self->colourMap, self->colourMap->minimum, self->colourMap->maximum ); } void lucSwarmViewer_SetColourComponent(void* object, lucDatabase* database, SwarmVariable* var, Particle_Index lParticle_I, lucGeometryDataType type, lucColourMap* colourMap) { #if 0 lucSwarmViewer* self = (lucSwarmViewer*)object; if (var && colourMap) { double value; lucColour colour; SwarmVariable_ValueAt( var, lParticle_I, &value ); //lucColourMap_GetColourFromValue( colourMap, value, &colour, self->opacity ); /* Extract and overwrite component value */ if (type == lucRedValueData) self->colour.red = colour.red; if (type == lucGreenValueData) self->colour.green = colour.green; if (type == lucBlueValueData) self->colour.blue = colour.blue; if (type == lucOpacityValueData) self->colour.opacity = colour.opacity; /* Export particle value */ float valuef = value; lucDatabase_AddValues(database, 1, self->geomType, type, colourMap, &valuef); } #endif } /* Default Swarm Viewer Implementation */ void _lucSwarmViewer_SetParticleColour( void* drawingObject, lucDatabase* database, Particle_Index lParticle_I ) { // lucSwarmViewer* self = (lucSwarmViewer*) drawingObject; // SwarmVariable* colourVariable = self->colourVariable; // SwarmVariable* opacityVariable = self->opacityVariable; // lucColourMap* colourMap = self->colourMap; // double colourValue; // // /* Get colour value if there is a colourVariable and a colourMap */ // if ( colourVariable && colourMap ) // { // SwarmVariable_ValueAt( colourVariable, lParticle_I, &colourValue ); // lucColourMap_GetColourFromValue( colourMap, colourValue, &self->colour, self->opacity ); // /* Export particle colour value */ // float valuef = colourValue; // if (database) lucDatabase_AddValues(database, 1, self->geomType, lucColourValueData, colourMap, &valuef); // } // // /* Get Opacity Value */ // lucSwarmViewer_SetColourComponent(self, database, opacityVariable, lParticle_I, lucOpacityValueData, self->opacityColourMap); // // lucColour_SetColour( &self->colour, self->opacity ); } void _lucSwarmViewer_PlotParticle( void* drawingObject, lucDatabase* database, Particle_Index lParticle_I ) { // lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; // float size = 1.0; //= self->pointSize; // if (self->sizeVariable) // { // size = lucSwarmViewer_GetScalar(self->sizeVariable, lParticle_I, size); // lucDatabase_AddValues(database, 1, self->geomType, lucSizeData, NULL, &size); // } } float lucSwarmViewer_GetScalar( SwarmVariable* variable, Particle_Index lParticle_I, float defaultVal ){ abort(); } SwarmVariable* lucSwarmViewer_InitialiseVariable(void* object, Name variableName, Bool scalarRequired, void* data ){ abort(); } void lucSwarmViewer_UpdateVariables( void *drawingObject ){ abort(); } ;
15,082
4,840
/* * Copyright 2021 Kioshi Morosin <glam@hex.lc> * * 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 "math_compiler.h" #include <wasm-stack.h> #include <binaryen-c.h> #include "globals.h" #define GLAM_COMPILER_TRACE(msg) GLAM_TRACE("[compiler] " << msg) void module_visitor::visit_module() { GLAM_COMPILER_TRACE("visit_module"); this->module = BinaryenModuleCreate(); // we import memory and table from the core module so we can indirect-call functions BinaryenAddMemoryImport(module, "memory", "env", "memory", 0); BinaryenAddTableImport(module, "table", "env", "table"); } void module_visitor::visit_export(const std::string &inner_name, const std::string &outer_name) { GLAM_COMPILER_TRACE("visit_export " << inner_name << " -> " << outer_name); auto exp = new wasm::Export; exp->name = outer_name; exp->value = inner_name; exp->kind = wasm::ExternalKind::Function; module->addExport(exp); } function_visitor *module_visitor::visit_function(const std::string &name, wasm::Signature sig) { GLAM_COMPILER_TRACE("visit_function " << name); auto fv = new function_visitor(this); this->children.push_back(fv); fv->parent = this; fv->func->name = name; fv->func->type = sig; return fv; } template <typename T> compiled_fxn<T> module_visitor::visit_end() { GLAM_COMPILER_TRACE("visit_end module"); uint32_t globalFlags = 0; uint32_t totalArenaSize = 0; std::for_each(children.begin(), children.end(), [&](function_visitor *fv) { globalFlags |= fv->flags; totalArenaSize += fv->arena_size; }); // add fake function imports so binaryen is aware of the function types. increases binary size but i'm not sure // of a better way to do this (using stack IR). if (globalFlags & function_visitor::USES_MPCx1) { GLAM_COMPILER_TRACE("uses mpcx1"); BinaryenType ii[2] = { BinaryenTypeInt32(), BinaryenTypeInt32() }; auto fakeType = BinaryenTypeCreate(ii, 2); BinaryenAddFunctionImport(module, "_operator_nop1", "env", "_operator_nop1", fakeType, BinaryenTypeInt32()); } if (globalFlags & function_visitor::USES_MPCx2) { GLAM_COMPILER_TRACE("uses mpcx2"); BinaryenType iii[3] = { BinaryenTypeInt32(), BinaryenTypeInt32(), BinaryenTypeInt32() }; auto fakeType = BinaryenTypeCreate(iii, 3); BinaryenAddFunctionImport(module, "_operator_nop2", "env", "_operator_nop2", fakeType, BinaryenTypeInt32()); } if (globalFlags & function_visitor::USES_F64x2) { GLAM_COMPILER_TRACE("uses f64x2"); BinaryenType ddi[3] = { BinaryenTypeFloat64(), BinaryenTypeFloat64(), BinaryenTypeInt32() }; auto fakeType = BinaryenTypeCreate(ddi, 3); BinaryenAddFunctionImport(module, "_operator_nop2d", "env", "_operator_nop2", fakeType, BinaryenTypeInt32()); } if (globalFlags & function_visitor::USES_F64x4) { GLAM_COMPILER_TRACE("uses f64x4"); BinaryenType ddddi[5] = { BinaryenTypeFloat64(), BinaryenTypeFloat64(), BinaryenTypeFloat64(), BinaryenTypeFloat64(), BinaryenTypeInt32() }; auto fakeType = BinaryenTypeCreate(ddddi, 5); BinaryenAddFunctionImport(module, "_operator_nop4", "env", "_operator_nop4", fakeType, BinaryenTypeInt32()); } if (globalFlags & (function_visitor::USES_F64x2 | function_visitor::USES_F64x4 | function_visitor::USES_MPCx1 | function_visitor::USES_MPCx2)) { GLAM_COMPILER_TRACE("uses arena"); BinaryenAddGlobalImport(module, "_arena", "env", "_arena", wasm::Type::i32, false); } auto result = BinaryenModuleAllocateAndWrite(module, nullptr); compiled_fxn<T> fxn(entry_point, fxn_name, parameter_name, result.binary, result.binaryBytes, totalArenaSize); BinaryenModuleDispose(module); std::for_each(children.begin(), children.end(), [&](function_visitor *fv) { delete fv; }); fxn.install(result.binary, result.binaryBytes); free(result.binary); GLAM_COMPILER_TRACE("compilation complete"); return fxn; } void module_visitor::abort() { GLAM_COMPILER_TRACE("mv: aborting early"); std::for_each(children.begin(), children.end(), [&](function_visitor *fv) { delete fv; }); BinaryenModuleDispose(module); } function_visitor::function_visitor(module_visitor *_parent): parent(_parent) { this->func = new wasm::Function; auto nop = parent->module->allocator.alloc<wasm::Nop>(); nop->type = wasm::Type::none; this->func->body = nop; this->func->stackIR = std::make_unique<wasm::StackIR>(); } void function_visitor::visit_entry_point() { GLAM_COMPILER_TRACE("visit_entry_point " << func->name.str); parent->entry_point = func->name.str; } void function_visitor::visit_float(double d) { GLAM_COMPILER_TRACE("visit_float " << d); auto c = parent->module->allocator.alloc<wasm::Const>(); c->type = wasm::Type::f64; c->value = wasm::Literal(d); visit_basic(c); } void function_visitor::visit_complex(std::complex<double> z) { visit_float(z.real()); visit_float(z.imag()); } void function_visitor::visit_basic(wasm::Expression *inst) { inst->finalize(); auto si = parent->module->allocator.alloc<wasm::StackInst>(); si->op = wasm::StackInst::Basic; si->type = inst->type; si->origin = inst; func->stackIR->push_back(si); } void function_visitor::visit_complex(const mp_complex &z) { auto ptr = std::find(local_consts.begin(), local_consts.end(), z); if (ptr == local_consts.end()) { local_consts.push_back(z); } visit_global_get("_complex_" + std::to_string(ptr - local_consts.begin())); } template <typename T> void function_visitor::visit_ptr(T *ptr) { auto c = parent->module->allocator.alloc<wasm::Const>(); c->type = wasm::Type::i32; c->value = wasm::Literal(static_cast<int32_t>(reinterpret_cast<uintptr_t>(ptr))); visit_basic(c); } void function_visitor::visit_global_get(const std::string &name) { auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>(); globalGet->type = wasm::Type::i32; globalGet->name = name; } void function_visitor::visit_mpcx2(morpheme_mpcx2 *morph) { GLAM_COMPILER_TRACE("visit_mpcx2"); arena_size += 2; flags |= USES_MPCx2; auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>(); globalGet->type = wasm::Type::i32; globalGet->name = "_arena"; visit_basic(globalGet); visit_ptr(morph); auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>(); callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }), wasm::Type::i32); // (iii)->i callIndirect->table = "table"; callIndirect->isReturn = false; callIndirect->type = wasm::Type::i32; visit_basic(callIndirect); } void function_visitor::visit_mpcx1(morpheme_mpcx1 *morph) { GLAM_COMPILER_TRACE("visit_mpcx1"); arena_size++; flags |= USES_MPCx1; auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>(); globalGet->type = wasm::Type::i32; globalGet->name = "_arena"; visit_basic(globalGet); visit_ptr(morph); auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>(); callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::i32, wasm::Type::i32 }), wasm::Type::i32); // (ii)->i callIndirect->table = "table"; callIndirect->isReturn = false; callIndirect->type = wasm::Type::i32; visit_basic(callIndirect); } bool function_visitor::visit_variable_mp(const std::string &name) { GLAM_COMPILER_TRACE("visit_variable_mp " << name); if (name == parent->parameter_name) { auto localGet = parent->module->allocator.alloc<wasm::LocalGet>(); localGet->type = wasm::Type::i32; localGet->index = 0; visit_basic(localGet); return true; } else { auto ptr = globals::consts_mp.find(name); if (ptr == globals::consts_mp.end()) { return false; } else { visit_ptr(ptr->second); return true; } } } void function_visitor::visit_binary_splat(wasm::BinaryOp op) { auto localSetD = parent->module->allocator.alloc<wasm::LocalSet>(); localSetD->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSetD); auto localSetC = parent->module->allocator.alloc<wasm::LocalSet>(); localSetC->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSetC); auto localSetB = parent->module->allocator.alloc<wasm::LocalSet>(); localSetB->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSetB); auto localGetC = parent->module->allocator.alloc<wasm::LocalGet>(); localGetC->index = localSetC->index; localGetC->type = wasm::Type::f64; visit_basic(localGetC); auto inst = parent->module->allocator.alloc<wasm::Binary>(); inst->type = wasm::Type::f64; inst->op = op; visit_basic(inst); auto localGetB = parent->module->allocator.alloc<wasm::LocalGet>(); localGetB->index = localSetB->index; localGetB->type = wasm::Type::f64; visit_basic(localGetB); auto localGetD = parent->module->allocator.alloc<wasm::LocalGet>(); localGetD->index = localSetD->index; localGetD->type = wasm::Type::f64; visit_basic(localGetD); visit_basic(inst); } void function_visitor::visit_add() { GLAM_COMPILER_TRACE("visit_add (dp)"); if (flags & GEN_SIMD) { } else { visit_unwrap(); visit_binary_splat(wasm::AddFloat64); } } void function_visitor::visit_sub() { GLAM_COMPILER_TRACE("visit_sub (dp)"); if (flags & GEN_SIMD) { } else { visit_unwrap(); visit_binary_splat(wasm::SubFloat64); } } void function_visitor::visit_mul() { GLAM_COMPILER_TRACE("visit_mul (dp)"); if (flags & GEN_SIMD) { } else { visit_unwrap(); wasm::Index i = visit_binary(); auto localGetC = parent->module->allocator.alloc<wasm::LocalGet>(); localGetC->index = i + 1; localGetC->type = wasm::Type::f64; auto mul = parent->module->allocator.alloc<wasm::Binary>(); mul->type = wasm::Type::f64; mul->op = wasm::MulFloat64; auto localGetB = parent->module->allocator.alloc<wasm::LocalGet>(); localGetB->index = i + 2; localGetB->type = wasm::Type::f64; auto localGetA = parent->module->allocator.alloc<wasm::LocalGet>(); localGetA->index = i + 3; localGetA->type = wasm::Type::f64; auto localGetD = parent->module->allocator.alloc<wasm::LocalGet>(); localGetD->index = i; localGetD->type = wasm::Type::f64; auto add = parent->module->allocator.alloc<wasm::Binary>(); add->type = wasm::Type::f64; add->op = wasm::AddFloat64; auto sub = parent->module->allocator.alloc<wasm::Binary>(); sub->type = wasm::Type::f64; sub->op = wasm::SubFloat64; visit_basic(localGetC); visit_basic(mul); visit_basic(localGetB); visit_basic(localGetD); visit_basic(mul); visit_basic(sub); visit_basic(localGetA); visit_basic(localGetD); visit_basic(mul); visit_basic(localGetB); visit_basic(localGetC); visit_basic(mul); visit_basic(add); } } void function_visitor::visit_div() { GLAM_COMPILER_TRACE("visit_div (dp)"); if (flags & GEN_SIMD) { } else { // we use a morpheme here because division is hard visit_f64x4(&_fmorpheme_div); } } void function_visitor::visit_f64x2(morpheme_f64x2 *morph) { GLAM_COMPILER_TRACE("visit_f64x2"); visit_unwrap(); arena_size++; flags |= USES_F64x2; auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>(); globalGet->name = "_arena"; globalGet->type = wasm::Type::i32; visit_basic(globalGet); visit_ptr(morph); auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>(); callIndirect->type = wasm::Type::i32; callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::f64, wasm::Type::f64, wasm::Type::i32 }), wasm::Type::i32); // (ddi)->i callIndirect->table = "table"; callIndirect->isReturn = false; visit_basic(callIndirect); needs_unwrap = true; } wasm::Index function_visitor::visit_binary() { flags |= USES_BINARY; // (a, b) (c, d) wasm::Index var = wasm::Builder::addVar(func, wasm::Type::f64); auto localSet1 = parent->module->allocator.alloc<wasm::LocalSet>(); localSet1->index = var; visit_basic(localSet1); auto localSet2 = parent->module->allocator.alloc<wasm::LocalSet>(); localSet2->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSet2); auto localSet3 = parent->module->allocator.alloc<wasm::LocalSet>(); localSet3->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSet3); auto localSet4 = parent->module->allocator.alloc<wasm::LocalSet>(); localSet4->index = wasm::Builder::addVar(func, wasm::Type::f64); localSet4->type = wasm::Type::f64; visit_basic(localSet4); return var; } void function_visitor::visit_unwrap() { if (needs_unwrap) { GLAM_COMPILER_TRACE("visit_unwrap"); this->flags |= USES_UNWRAP; visit_dupi32(); auto loadIm = parent->module->allocator.alloc<wasm::Load>(); loadIm->type = wasm::Type::f64; loadIm->offset = 8; // get the imaginary part first loadIm->bytes = 8; loadIm->isAtomic = false; visit_basic(loadIm); auto localSet = parent->module->allocator.alloc<wasm::LocalSet>(); localSet->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSet); auto loadRe = parent->module->allocator.alloc<wasm::Load>(); loadRe->type = wasm::Type::f64; loadRe->offset = 0; loadRe->bytes = 8; loadRe->isAtomic = false; visit_basic(loadRe); auto localGet1 = parent->module->allocator.alloc<wasm::LocalGet>(); localGet1->index = localSet->index; localGet1->type = wasm::Type::f64; visit_basic(localGet1); needs_unwrap = false; } } void function_visitor::visit_f64x4(morpheme_f64x4 *morph) { GLAM_COMPILER_TRACE("visit_f64x4"); visit_unwrap(); arena_size++; flags |= USES_F64x4; auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>(); globalGet->name = "_arena"; globalGet->type = wasm::Type::i32; visit_basic(globalGet); visit_ptr(morph); auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>(); callIndirect->type = wasm::Type::i32; callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::f64, wasm::Type::f64, wasm::Type::f64, wasm::Type::f64, wasm::Type::i32 }), wasm::Type::i32); // (ddddi)->i callIndirect->table = "table"; callIndirect->isReturn = false; visit_basic(callIndirect); needs_unwrap = true; } void function_visitor::visit_fxncall(const std::string &name) { uintptr_t ptr = globals::fxn_table[name]; assert(ptr); // should never fail, the parser checks first GLAM_COMPILER_TRACE("visit_fxncall " << name << " @ " << ptr); auto c = parent->module->allocator.alloc<wasm::Const>(); c->type = wasm::Type::i32; c->value = wasm::Literal(static_cast<uint32_t>(ptr)); visit_basic(c); // todo for now we assume that it's also a double-precision fxn, i.e. it is (f64, f64)->i32 auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>(); callIndirect->isReturn = false; callIndirect->sig = wasm::Signature({ wasm::Type::f64, wasm::Type::f64 }, wasm::Type::i32); callIndirect->table = "table"; callIndirect->type = wasm::Type::i32; visit_basic(callIndirect); needs_unwrap = true; } bool function_visitor::visit_variable_dp(const std::string &name) { GLAM_COMPILER_TRACE("visit_variable_dp " << name); visit_unwrap(); if (name == parent->parameter_name) { auto localGet = parent->module->allocator.alloc<wasm::LocalGet>(); localGet->type = wasm::Type::f64; localGet->index = 0; visit_basic(localGet); localGet = parent->module->allocator.alloc<wasm::LocalGet>(); localGet->type = wasm::Type::f64; localGet->index = 1; visit_basic(localGet); return true; } else { auto z = globals::consts_dp.find(name); if (z == globals::consts_dp.end()) { return false; } else { visit_complex(z->second); return true; } } } void function_visitor::visit_dupi32() { // wasm doesn't have a dup opcode so this is what we have to do auto localTee = parent->module->allocator.alloc<wasm::LocalSet>(); localTee->type = wasm::Type::i32; localTee->index = wasm::Builder::addVar(func, wasm::Type::i32); visit_basic(localTee); auto localGet0 = parent->module->allocator.alloc<wasm::LocalGet>(); localGet0->type = wasm::Type::i32; localGet0->index = localTee->index; visit_basic(localGet0); } void function_visitor::visit_dupf64() { flags |= USES_DUPF64; auto localTee = parent->module->allocator.alloc<wasm::LocalSet>(); localTee->type = wasm::Type::f64; localTee->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localTee); auto localGet0 = parent->module->allocator.alloc<wasm::LocalGet>(); localGet0->type = wasm::Type::f64; localGet0->index = localTee->index; visit_basic(localGet0); } function_visitor::~function_visitor() noexcept { delete this->func; } std::string function_visitor::visit_end() { GLAM_COMPILER_TRACE("visit_end function"); if (!needs_unwrap) { // now we actually need to wrap GLAM_COMPILER_TRACE("wrapping complex"); visit_f64x2(&_fmorpheme_wrap); } auto ret = parent->module->allocator.alloc<wasm::Return>(); visit_basic(ret); parent->module->addFunction(func); return func->name.c_str(); } std::map<std::string, morpheme_f64x2 *> math_compiler_dp::unary_morphemes = { std::make_pair("sin", &_fmorpheme_sin), std::make_pair("cos", &_fmorpheme_cos), std::make_pair("tan", &_fmorpheme_tan), std::make_pair("sinh", &_fmorpheme_sinh), std::make_pair("cosh", &_fmorpheme_cosh), std::make_pair("tanh", &_fmorpheme_tanh) }; std::map<std::string, morpheme_f64x4 *> math_compiler_dp::binary_morphemes = { std::make_pair("^", &_fmorpheme_exp) }; void math_compiler_dp::visit_operator(function_visitor *fv, const std::string &op) { GLAM_COMPILER_TRACE("compiling operator " << op); if (op == "+") { fv->visit_add(); return; } else if (op == "-") { fv->visit_sub(); return; } else if (op == "*") { fv->visit_mul(); return; } else if (op == "/") { fv->visit_div(); return; } else { auto iter1 = unary_morphemes.find(op); if (iter1 != unary_morphemes.end()) { fv->visit_f64x2(*iter1->second); return; } else { auto iter2 = binary_morphemes.find(op); if (iter2 != binary_morphemes.end()) { fv->visit_f64x4(*iter2->second); return; } } } GLAM_COMPILER_TRACE("unrecognized operator"); abort(); } fxn<std::complex<double>, compiled_fxn<std::complex<double>>> math_compiler_dp::compile(const emscripten::val &stack) { module_visitor mv(fxn_name, parameter_name); mv.visit_module(); auto fv = mv.visit_function(name, wasm::Signature({ wasm::Type::f64, wasm::Type::f64 }, wasm::Type::i32)); const auto len = stack["length"].as<size_t>(); assert(len > 0); for (size_t i = 0; i < len; i++) { emscripten::val stackObj = stack[i]; auto type = stackObj["type"].as<int32_t>(); auto value = stackObj["value"].as<std::string>(); switch (type) { case 0: // NUMBER // we take advantage of boost's parsing even if we don't want a multiprecision complex number fv->visit_complex(mp_complex(value).convert_to<std::complex<double>>()); break; case 1: // IDENTIFIER if (!fv->visit_variable_dp(value)) { mv.abort(); abort(); } break; case 2: // OPERATOR visit_operator(fv, value); break; case 3: // FXNCALL fv->visit_fxncall(value); break; default: GLAM_COMPILER_TRACE("unrecognized stack object " << type); mv.abort(); abort(); } } fv->visit_entry_point(); auto f_name = fv->visit_end(); mv.visit_export(f_name, name); return mv.visit_end<std::complex<double>>(); }
21,644
7,738
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 <modules/base/processors/meshcreator.h> #include <inviwo/core/datastructures/geometry/basicmesh.h> #include <inviwo/core/datastructures/geometry/simplemeshcreator.h> #include <inviwo/core/interaction/events/pickingevent.h> #include <inviwo/core/interaction/events/mouseevent.h> #include <inviwo/core/interaction/events/touchevent.h> #include <inviwo/core/interaction/events/wheelevent.h> namespace inviwo { const ProcessorInfo MeshCreator::processorInfo_{ "org.inviwo.MeshCreator", // Class identifier "Mesh Creator", // Display name "Mesh Creation", // Category CodeState::Stable, // Code state Tags::CPU, // Tags }; const ProcessorInfo MeshCreator::getProcessorInfo() const { return processorInfo_; } MeshCreator::MeshCreator() : Processor() , outport_("outport") , position1_("position1", "Start Position", vec3(0.0f, 0.0f, 0.0f), vec3(-50.0f), vec3(50.0f)) , position2_("position2", "Stop Position", vec3(1.0f, 0.0f, 0.0f), vec3(-50.0f), vec3(50.0f)) , basis_("Basis", "Basis and offset") , normal_("normal", "Normal", vec3(0.0f, 0.0f, 1.0f), vec3(-50.0f), vec3(50.0f)) , color_("color", "Color", vec4(1.0f, 1.0f, 1.0f, 1.0f), vec4(0.0f), vec4(1.0f), vec4(0.01f), InvalidationLevel::InvalidOutput, PropertySemantics::Color) , torusRadius1_("torusRadius1_", "Torus Radius 1", 1.0f) , torusRadius2_("torusRadius2_", "Torus Radius 2", 0.3f) , meshScale_("scale", "Size scaling", 1.f, 0.01f, 10.f) , meshRes_("res", "Mesh resolution", vec2(16), vec2(1), vec2(1024)) , meshType_("meshType", "Mesh Type") , enablePicking_("enablePicking", "Enable Picking", false) , picking_(this, 1, [&](PickingEvent* p) { if (enablePicking_) handlePicking(p); }) , camera_("camera", "Camera") , pickingUpdate_{[](PickingEvent*){}} { addPort(outport_); meshType_.addOption("sphere", "Sphere", MeshType::Sphere); meshType_.addOption("colorsphere", "Color Sphere", MeshType::ColorSphere); meshType_.addOption("cube_basic_mesh", "Cube (Basic Mesh)", MeshType::CubeBasicMesh); meshType_.addOption("cube", "Cube (Simple Mesh)", MeshType::CubeSimpleMesh); meshType_.addOption("linecube", "Line cube", MeshType::LineCube); meshType_.addOption("linecubeadjacency", "Line cube adjacency", MeshType::LineCubeAdjacency); meshType_.addOption("plane", "Plane", MeshType::Plane); meshType_.addOption("disk", "Disk", MeshType::Disk); meshType_.addOption("cone", "Cone", MeshType::Cone); meshType_.addOption("cylinder", "Cylinder", MeshType::Cylinder); meshType_.addOption("arrow", "Arrow", MeshType::Arrow); meshType_.addOption("coordaxes", "Coordinate Indicator", MeshType::CoordAxes); meshType_.addOption("torus", "Torus", MeshType::Torus); meshType_.addOption("sphereopt", "Sphere with Position", MeshType::SphereOpt); util::hide(position1_, position2_, normal_, basis_, color_ , torusRadius1_ , torusRadius2_); util::show(meshScale_, meshRes_); meshType_.set(MeshType::Sphere); meshType_.setCurrentStateAsDefault(); meshType_.onChange([this]() { auto updateNone = [](PickingEvent*) {}; auto getDelta = [this](PickingEvent* p) { auto currNDC = p->getNDC(); auto prevNDC = p->getPreviousNDC(); // Use depth of initial press as reference to move in the image plane. auto refDepth = p->getPressedDepth(); currNDC.z = refDepth; prevNDC.z = refDepth; auto corrWorld = camera_.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(currNDC)); auto prevWorld = camera_.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(prevNDC)); return (corrWorld - prevWorld); }; auto updatePosition1 = [this, getDelta](PickingEvent* p) { position1_.set(position1_.get() + getDelta(p)); }; auto updatePosition1and2 = [this, getDelta](PickingEvent* p) { auto delta = getDelta(p); position1_.set(position1_.get() + delta); position2_.set(position2_.get() + delta); }; auto updateBasis = [this, getDelta](PickingEvent* p) { basis_.offset_.set(basis_.offset_.get() + getDelta(p)); }; util::hide(position1_, position2_, normal_, basis_, meshScale_, meshRes_, color_, torusRadius1_, torusRadius2_); switch (meshType_.get()) { case MeshType::Sphere: { pickingUpdate_ = updateNone; util::show(meshScale_, meshRes_); break; } case MeshType::ColorSphere: { pickingUpdate_ = updatePosition1; util::show(position1_, meshScale_); break; } case MeshType::CubeBasicMesh: { pickingUpdate_ = updatePosition1and2; util::show(position1_, position2_, color_); break; } case MeshType::CubeSimpleMesh: { pickingUpdate_ = updatePosition1and2; util::show(position1_, position2_); break; } case MeshType::LineCube: { pickingUpdate_ = updateBasis; util::show(basis_, color_); break; } case MeshType::LineCubeAdjacency: { pickingUpdate_ = updateBasis; util::show(basis_, color_); break; } case MeshType::Plane: { pickingUpdate_ = updatePosition1; util::show(position1_, normal_, meshScale_, meshRes_, color_); break; } case MeshType::Disk: { pickingUpdate_ = updatePosition1; util::show(position1_, normal_, meshScale_, meshRes_, color_); break; } case MeshType::Cone: { pickingUpdate_ = updatePosition1and2; util::show(position1_, position2_, meshScale_, meshRes_, color_); break; } case MeshType::Cylinder: { pickingUpdate_ = updatePosition1and2; util::show(position1_, position2_, meshScale_, meshRes_, color_); break; } case MeshType::Arrow: { pickingUpdate_ = updatePosition1and2; util::show(position1_, position2_, meshScale_, meshRes_, color_); break; } case MeshType::CoordAxes: { pickingUpdate_ = updatePosition1; util::show(position1_, meshScale_); break; } case MeshType::Torus: { pickingUpdate_ = updatePosition1; util::show(position1_,torusRadius1_, torusRadius2_,meshRes_,color_); break; } case MeshType::SphereOpt: { pickingUpdate_ = updatePosition1; util::show(position1_, meshScale_, color_); break; } default: { pickingUpdate_ = updateNone; util::show(meshScale_, meshRes_); break; } } }); addProperty(meshType_); addProperty(position1_); addProperty(position2_); addProperty(normal_); addProperty(basis_); addProperty(torusRadius1_); addProperty(torusRadius2_); addProperty(color_); addProperty(meshScale_); addProperty(meshRes_); addProperty(enablePicking_); addProperty(camera_); camera_.setInvalidationLevel(InvalidationLevel::Valid); camera_.setCollapsed(true); } MeshCreator::~MeshCreator() {} std::shared_ptr<Mesh> MeshCreator::createMesh() { switch (meshType_.get()) { case MeshType::Sphere: return SimpleMeshCreator::sphere(0.5f * meshScale_.get(), meshRes_.get().y, meshRes_.get().x); case MeshType::ColorSphere: return BasicMesh::colorsphere(position1_, meshScale_.get()); case MeshType::CubeBasicMesh: { vec3 posLLF = position1_; vec3 posURB = position2_; mat4 m = glm::translate(mat4(1.0f), posLLF); m = glm::scale(m, posURB - posLLF); return BasicMesh::cube(m, color_.get()); } case MeshType::CubeSimpleMesh: { vec3 posLLF = position1_; vec3 posURB = position2_; return SimpleMeshCreator::rectangularPrism(posLLF, posURB, posLLF, posURB, vec4(posLLF, 1.f), vec4(posURB, 1.f)); } case MeshType::LineCube: return BasicMesh::boundingbox(basis_.getBasisAndOffset(), color_); case MeshType::LineCubeAdjacency: return BasicMesh::boundingBoxAdjacency(basis_.getBasisAndOffset(), color_); case MeshType::Plane: { return BasicMesh::square(position1_, normal_, vec2(1.0f, 1.0f) * meshScale_.get(), color_, meshRes_.get()); } case MeshType::Disk: return BasicMesh::disk(position1_, normal_, color_, meshScale_.get(), meshRes_.get().x); case MeshType::Cone: return BasicMesh::cone(position1_, position2_, color_, meshScale_.get(), meshRes_.get().x); case MeshType::Cylinder: return BasicMesh::cylinder(position1_, position2_, color_, meshScale_.get(), meshRes_.get().x); case MeshType::Arrow: return BasicMesh::arrow(position1_, position2_, color_, meshScale_.get(), 0.15f, meshScale_.get() * 2, meshRes_.get().x); case MeshType::CoordAxes: return BasicMesh::coordindicator(position1_, meshScale_.get()); case MeshType::Torus: return BasicMesh::torus(position1_, vec3(0, 0, 1), torusRadius1_, torusRadius2_, meshRes_, color_); case MeshType::SphereOpt: return BasicMesh::sphere(position1_, meshScale_, color_); default: return SimpleMeshCreator::sphere(0.1f, meshRes_.get().x, meshRes_.get().y); } } void MeshCreator::handlePicking(PickingEvent* p) { if (p->getState() == PickingState::Updated && p->getEvent()->hash() == MouseEvent::chash()) { auto me = p->getEventAs<MouseEvent>(); if ((me->buttonState() & MouseButton::Left) && me->state() == MouseState::Move) { pickingUpdate_(p); p->markAsUsed(); } } else if (p->getState() == PickingState::Updated && p->getEvent()->hash() == TouchEvent::chash()) { auto te = p->getEventAs<TouchEvent>(); if (!te->touchPoints().empty() && te->touchPoints()[0].state() == TouchState::Updated) { pickingUpdate_(p); p->markAsUsed(); } } } void MeshCreator::process() { auto mesh = createMesh(); if (enablePicking_) { // Add picking ids auto bufferRAM = std::make_shared<BufferRAMPrecision<uint32_t>>(mesh->getBuffer(0)->getSize()); auto pickBuffer = std::make_shared<Buffer<uint32_t>>(bufferRAM); auto& data = bufferRAM->getDataContainer(); std::fill(data.begin(), data.end(), static_cast<uint32_t>(picking_.getPickingId(0))); mesh->addBuffer(Mesh::BufferInfo(BufferType::NumberOfBufferTypes, 4), pickBuffer); } outport_.setData(mesh); } } // namespace
13,357
4,205
#include "LedManager.h" #include <stdlib.h> #include "Arduino.h" #include <EEPROM.h> // Configuration indicies #define EEPROM_HEADER 42 #define HEADER_ADDR 0 #define NUM_LEDS_ADDR 1 #define LED_SKIP_ADDR 3 #define LED_CHIP_TYPE_ADDR 4 #define LAST_PROGRAM_ADDR 5 #define EEPROM_LAST_INDEX 15 #define COMMAND_ARRAY_SIZE 40 #define COMMAND_MAX_SIZE COMMAND_ARRAY_SIZE - 1 LedManager::~LedManager() { delete controller; } void LedManager::setEepromOffset( uint16_t offset ) { eepromOffset = offset; } void LedManager::readEeprom() { if ( EEPROM.read( eepromOffset + HEADER_ADDR ) == EEPROM_HEADER ) { initialized = true; numLeds = ( EEPROM.read( eepromOffset + NUM_LEDS_ADDR ) << 8 ) + EEPROM.read( eepromOffset + NUM_LEDS_ADDR + 1 ); ledSkip = EEPROM.read( eepromOffset + LED_SKIP_ADDR ); ledChip = EEPROM.read( eepromOffset + LED_CHIP_TYPE_ADDR ); lastProgramIndex = EEPROM.read( eepromOffset + LAST_PROGRAM_ADDR ); } else { initialized = false; } } void LedManager::dumpConfig() { Serial.print( "Number of LEDs: " ); char ibuf[12]; Serial.println( itoa( numLeds, ibuf, 10 ) ); Serial.print( "Number of LEDs to skip: " ); Serial.println( itoa( ledSkip, ibuf, 10 ) ); Serial.print( "LED chipset: " ); if ( ledChip == 0 ) { Serial.println( "none" ); } else { Serial.println( LedController::getNameFromIndex( ledChip ) ); } Serial.print( "Display Program: " ); Serial.print( itoa( lastProgramIndex, ibuf, 10 ) ); Serial.print( ": " ); Serial.println( currentProgram->getName() ); } void LedManager::init() { cmd = new char[ COMMAND_ARRAY_SIZE ]; cmd[ 0 ] = 0; if ( EEPROM.read( eepromOffset + HEADER_ADDR ) != EEPROM_HEADER ) { EEPROM.write( eepromOffset + HEADER_ADDR, EEPROM_HEADER ); // reset all the bytes for ( int i = 1; i < EEPROM_LAST_INDEX; i++ ) { EEPROM.write( eepromOffset + i, 0 ); } } readEeprom(); // create the blank program currentProgram = Program::createProgram( Program::getProgramByIndex( lastProgramIndex ) ); initLEDs(); clearLEDs(); currentProgram->setController( controller ); currentProgram->init(); Serial.begin( 9600 ); // USB is always 12 Mbit/sec } void LedManager::initLEDs() { if ( controller != NULL ) { delete controller; controller = NULL; } // verify we have something to do if ( ledChip > 0 && numLeds > 0 ) { const char *chipset = LedController::getNameFromIndex( ledChip ); controller = LedController::create( chipset, numLeds ); } if ( controller == NULL ) { Serial.println( "LEDs not activited" ); controller = new LedController(); } currentProgram->setController( controller ); } void LedManager::clearLEDs() { for ( int i = 0; i < numLeds; i++ ) { controller->setPixel( i, 0, 0, 0 ); } controller->show(); } void LedManager::handleNumLeds( const char *str ) { clearLEDs(); char ibuf[12]; int num = atoi( str ); EEPROM.write( eepromOffset + NUM_LEDS_ADDR, num >> 8 ); EEPROM.write( eepromOffset + NUM_LEDS_ADDR + 1, num & 0xFF ); // reread from EEPROM readEeprom(); // update the controller controller->updateLength( numLeds ); clearLEDs(); Serial.print( "Saved number of LEDs: " ); Serial.println( itoa( numLeds, ibuf, 10 ) ); } void LedManager::handleLedSkip( const char *str ) { int num = atoi( str ); EEPROM.write( eepromOffset + LED_SKIP_ADDR, num ); readEeprom(); Serial.print( "Saved LED Skip: " ); char ibuf[12]; Serial.println( itoa( ledSkip, ibuf, 10 ) ); } void LedManager::handleLedType( const char *str ) { clearLEDs(); int type = LedController::getIndexFromName( str ); if ( type >= 0 ) { EEPROM.write( eepromOffset + LED_CHIP_TYPE_ADDR, type ); // reread from EEPROM readEeprom(); // reinitialize the controller initLEDs(); Serial.print( "Saved LED Type: " ); Serial.println( str ); } else { Serial.print( "Unknown LED type: " ); Serial.println( str ); } } void LedManager::handleStartProgram( const char *str ) { clearLEDs(); Serial.print( "Stopping program " ); Serial.print( currentProgram->getProgramIndex() ); Serial.print( ": " ); Serial.println( currentProgram->getName() ); delete currentProgram; currentProgram = Program::createProgram( str ); Serial.print( "Starting program " ); Serial.print( currentProgram->getProgramIndex() ); Serial.print( ": " ); Serial.println( currentProgram->getName() ); currentProgram->setController( controller ); currentProgram->init(); // wait for init to run before saving the program lastProgramIndex = currentProgram->getProgramIndex(); EEPROM.write( eepromOffset + LAST_PROGRAM_ADDR, lastProgramIndex ); } void LedManager::loop() { while ( Serial.available() > 0 ) { char c = Serial.read(); int currentCmdLength = strlen( cmd ); // we do detect the end of a command if ( c == '\n' || c == '\r' || currentCmdLength >= COMMAND_MAX_SIZE ) { // prevent buffer overflows cmd[ COMMAND_MAX_SIZE ] = 0; Serial.print( "> " ); Serial.println( cmd ); // check for the various commands if ( strncmp( "reboot", cmd, COMMAND_MAX_SIZE ) == 0 ) { Serial.println( "Rebooting to bootloader..." ); delay( 1000 ); // do not print too fast! _reboot_Teensyduino_(); } else if ( strncmp( "dumpConfig" ,cmd, COMMAND_MAX_SIZE ) == 0 ) { dumpConfig(); } else if ( strncmp( "help" ,cmd, COMMAND_MAX_SIZE ) == 0 ) { displayHelp(); } else if ( strncmp( "help ", cmd, 5 ) == 0 ) { handleHelp( cmd + 5 ); } else if ( strncmp( "setNumLeds ", cmd, 11 ) == 0 ) { handleNumLeds( cmd + 11 ); } else if ( strncmp( "setLedSkip ", cmd, 11 ) == 0 ) { handleLedSkip( cmd + 11 ); } else if ( strncmp( "setLedType ", cmd, 11 ) == 0 ) { handleLedType( cmd + 11 ); } else if ( strncmp( "startProgram ", cmd, 13 ) == 0 ) { handleStartProgram( cmd + 13 ); } else { Serial.print( "Unknown command: " ); Serial.println( cmd ); } // reset the command cmd[ 0 ] = 0; } else { // append the char to the command cmd[ currentCmdLength ] = c; cmd[ currentCmdLength + 1 ] = 0; } } currentProgram->loop(); currentProgram->incrementRuntime(); delay( 10 ); }
6,634
2,458
#include "precompiled.h" #include "cleanup_loop.h" #include "equality_context.h" #include "exceptions.h" #include "sbt-core.h" #include "stringification.h" #include "simple_face.h" namespace { typedef std::vector<point_3> loop; loop create_loop(const polyloop & p, equality_context * c) { std::vector<ipoint_3> pts; for (size_t i = 0; i < p.vertex_count; ++i) { pts.push_back(ipoint_3(p.vertices[i].x, p.vertices[i].y, p.vertices[i].z)); } loop res; if (geometry_common::cleanup_loop(&pts, c->height_epsilon())) { boost::transform(pts, std::back_inserter(res), [c](const ipoint_3 & p) { return c->request_point(p.x(), p.y(), p.z()); }); } return res; } } // namespace simple_face::simple_face( const face & f, bool force_planar, equality_context * c) { using boost::transform; using geometry_common::calculate_plane_and_average_point; using geometry_common::share_sense; auto raw_loop = create_loop(f.outer_boundary, c); if (raw_loop.size() < 3) { throw invalid_face_exception(); } plane_3 raw_pl; std::tie(raw_pl, m_average_point) = calculate_plane_and_average_point(raw_loop, *c); if (raw_pl.is_degenerate()) { throw invalid_face_exception(); } auto snapped_dir = c->snap(raw_pl.orthogonal_direction()); m_plane = plane_3(m_average_point, snapped_dir); auto project = [this](const point_3 & p) { return m_plane.projection(p); }; if (force_planar) { transform(raw_loop, std::back_inserter(m_outer), project); } else { m_outer = raw_loop; } for (size_t i = 0; i < f.void_count; ++i) { auto inner = create_loop(f.voids[i], c); auto inner_pl = std::get<0>(calculate_plane_and_average_point(inner, *c)); auto inner_dir = inner_pl.orthogonal_direction(); if (!share_sense(m_plane.orthogonal_direction(), inner_dir)) { boost::reverse(inner); } if (force_planar) { m_inners.push_back(loop()); transform(inner, std::back_inserter(m_inners.back()), project); } else { m_inners.push_back(inner); } } #ifndef NDEBUG direction_3 normal = m_plane.orthogonal_direction(); debug_dx = CGAL::to_double(normal.dx()); debug_dy = CGAL::to_double(normal.dy()); debug_dz = CGAL::to_double(normal.dz()); #endif } simple_face & simple_face::operator = (simple_face && src) { if (&src != this) { m_outer = std::move(src.m_outer); m_inners = std::move(src.m_inners); m_plane = std::move(src.m_plane); m_average_point = std::move(src.m_average_point); } return *this; } bool simple_face::is_planar() const { for (auto p = m_outer.begin(); p != m_outer.end(); ++p) { if (!m_plane.has_on(*p)) { return false; } } for (auto hole = m_inners.begin(); hole != m_inners.end(); ++hole) { for (auto p = hole->begin(); p != hole->end(); ++p) { if (!m_plane.has_on(*p)) { return false; } } } return true; } std::string simple_face::to_string() const { std::stringstream ss; ss << "Outer:\n"; for (auto p = m_outer.begin(); p != m_outer.end(); ++p) { ss << reporting::to_string(*p) << std::endl; } for (auto hole = m_inners.begin(); hole != m_inners.end(); ++hole) { ss << "Hole:\n"; for (auto p = hole->begin(); p != hole->end(); ++p) { ss << reporting::to_string(*p) << std::endl; } } return ss.str(); } simple_face simple_face::reversed() const { typedef std::vector<point_3> loop; std::vector<loop> inners; boost::transform( m_inners, std::back_inserter(inners), [](const loop & inner) { return loop(inner.rbegin(), inner.rend()); }); return simple_face( m_outer | boost::adaptors::reversed, inners, m_plane.opposite(), m_average_point); } std::vector<segment_3> simple_face::all_edges_voids_reversed() const { std::vector<segment_3> res; for (size_t i = 0; i < m_outer.size(); ++i) { res.push_back(segment_3(m_outer[i], m_outer[(i+1) % m_outer.size()])); } res.push_back(segment_3(m_outer.back(), m_outer.front())); boost::for_each(m_inners, [&res](const std::vector<point_3> & inner) { for (size_t i = 0; i < inner.size(); ++i) { res.push_back(segment_3(inner[(i+1) % inner.size()], inner[i])); } res.push_back(segment_3(inner.front(), inner.back())); }); return res; } simple_face simple_face::transformed(const transformation_3 & t) const { loop new_outer; boost::transform(m_outer, std::back_inserter(new_outer), t); std::vector<loop> new_inners; for (auto h = m_inners.begin(); h != m_inners.end(); ++h) { new_inners.push_back(loop()); boost::transform(*h, std::back_inserter(new_inners.back()), t); } return simple_face(new_outer, new_inners, t(m_plane), t(m_average_point)); }
4,543
1,889
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cmath> #include <iostream> #include <string> #include <folly/portability/GTest.h> #include <thrift/lib/cpp2/protocol/Serializer.h> #include <thrift/lib/cpp2/test/gen-cpp2/Paths_types.h> using namespace apache::thrift; using namespace apache::thrift::test; TEST(PathsDemo, example) { Path1 p1; // list of pairs, 5005 bytes Path2 p2; // pair of lists, 2009 bytes for (int i = 0; i < 1000; ++i) { int x = 60 * std::cos(i * 0.01); int y = 60 * std::sin(i * 0.01); Point p; p.x = x; p.y = y; p1.points.push_back(p); p2.xs.push_back(x); p2.ys.push_back(y); } auto s1 = CompactSerializer::serialize<std::string>(p1); auto s2 = CompactSerializer::serialize<std::string>(p2); EXPECT_EQ(5005, s1.size()); EXPECT_EQ(2009, s2.size()); }
1,408
531
// Copyright 2018-present MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <set> #include <bsoncxx/stdx/optional.hpp> #include <bsoncxx/string/to_string.hpp> #include <bsoncxx/test_util/catch.hh> #include <mongocxx/client.hpp> #include <mongocxx/exception/exception.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/test/spec/operation.hh> #include <mongocxx/test_util/client_helpers.hh> // Don't use SDAM Monitoring spec tests, we'd need libmongoc internals to send hello replies. namespace { using namespace mongocxx; using bsoncxx::oid; using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; using bsoncxx::string::to_string; void open_and_close_client(const uri& test_uri, const options::apm& apm_opts) { // Apply listeners and trigger connection. options::client client_opts; client_opts.apm_opts(apm_opts); client client{test_uri, test_util::add_test_server_api(client_opts)}; client["admin"].run_command(make_document(kvp("ping", 1))); } TEST_CASE("SDAM Monitoring", "[sdam_monitoring]") { instance::current(); std::string rs_name; uri test_uri; client discoverer{uri{}, test_util::add_test_server_api()}; auto topology_type = test_util::get_topology(discoverer); if (topology_type == "replicaset") { rs_name = test_util::replica_set_name(discoverer); test_uri = uri{"mongodb://localhost/?replicaSet=" + rs_name}; } options::apm apm_opts; stdx::optional<oid> topology_id; SECTION("Server Events") { int server_opening_events = 0; int server_changed_events = 0; /////////////////////////////////////////////////////////////////////// // Begin server description listener lambdas /////////////////////////////////////////////////////////////////////// // ServerOpeningEvent apm_opts.on_server_opening([&](const events::server_opening_event& event) { server_opening_events++; if (topology_id) { // A previous server was opened first. REQUIRE(topology_id.value() == event.topology_id()); } topology_id = event.topology_id(); }); // ServerDescriptionChanged apm_opts.on_server_changed([&](const events::server_changed_event& event) { server_changed_events++; // A server_opening_event should have set topology_id. REQUIRE(topology_id); REQUIRE(topology_id.value() == event.topology_id()); auto old_sd = event.previous_description(); auto new_sd = event.new_description(); auto new_type = to_string(new_sd.type()); REQUIRE(old_sd.hello().empty()); REQUIRE(to_string(old_sd.host()) == to_string(event.host())); REQUIRE(old_sd.port() == event.port()); REQUIRE(old_sd.round_trip_time() == -1); REQUIRE(to_string(old_sd.type()) == "Unknown"); REQUIRE(to_string(new_sd.host()) == to_string(event.host())); REQUIRE_FALSE(new_sd.hello().empty()); REQUIRE(new_sd.port() == event.port()); REQUIRE(new_sd.round_trip_time() >= 0); if (topology_type == "single") { REQUIRE(new_type == "Standalone"); } else if (topology_type == "replicaset") { // RSPrimary, RSSecondary, etc. REQUIRE(new_type.substr(0, 2) == "RS"); } else { REQUIRE(topology_type == "sharded"); REQUIRE(new_type == "Mongos"); } REQUIRE(old_sd.id() == new_sd.id()); }); // We don't expect a ServerClosedEvent unless a replica set member is removed. /////////////////////////////////////////////////////////////////////// // End server description listener lambdas /////////////////////////////////////////////////////////////////////// open_and_close_client(test_uri, apm_opts); REQUIRE(server_opening_events > 0); REQUIRE(server_changed_events > 0); } SECTION("Topology Events") { int topology_opening_events = 0; int topology_changed_events = 0; int topology_closed_events = 0; bool found_servers = false; /////////////////////////////////////////////////////////////////////// // Begin topology description listener lambdas /////////////////////////////////////////////////////////////////////// // TopologyOpeningEvent apm_opts.on_topology_opening([&](const events::topology_opening_event& event) { topology_opening_events++; if (topology_id) { // A previous server was opened first. REQUIRE(topology_id.value() == event.topology_id()); } topology_id = event.topology_id(); }); // TopologyDescriptionChanged apm_opts.on_topology_changed([&](const events::topology_changed_event& event) { topology_changed_events++; // A topology_opening_event should have set topology_id. REQUIRE(topology_id); REQUIRE(topology_id.value() == event.topology_id()); auto old_td = event.previous_description(); auto new_td = event.new_description(); auto new_type = to_string(new_td.type()); auto new_servers = new_td.servers(); if (topology_changed_events == 1) { // First event, nothing discovered yet. REQUIRE(old_td.servers().size() == 0); REQUIRE_FALSE(old_td.has_readable_server(read_preference{})); REQUIRE_FALSE(old_td.has_writable_server()); } if (topology_type == "replicaset") { if (new_td.has_writable_server()) { REQUIRE(new_type == "ReplicaSetWithPrimary"); } else { REQUIRE(new_type == "ReplicaSetNoPrimary"); } } else { REQUIRE(new_type == "Single"); } for (auto&& new_sd : new_servers) { found_servers = true; auto new_sd_type = to_string(new_sd.type()); REQUIRE(new_sd.host().length()); REQUIRE_FALSE(new_sd.hello().empty()); REQUIRE(new_sd.port() > 0); REQUIRE(new_sd.round_trip_time() >= 0); if (topology_type == "single") { REQUIRE(new_sd_type == "Standalone"); } else if (topology_type == "replicaset") { // RSPrimary, RSSecondary, etc. REQUIRE(new_sd_type.substr(0, 2) == "RS"); } else { REQUIRE(topology_type == "sharded"); REQUIRE(new_sd_type == "Mongos"); } } }); // TopologyClosedEvent apm_opts.on_topology_closed([&](const events::topology_closed_event& event) { topology_closed_events++; REQUIRE(topology_id.value() == event.topology_id()); }); /////////////////////////////////////////////////////////////////////// // End topology description listener lambdas /////////////////////////////////////////////////////////////////////// open_and_close_client(test_uri, apm_opts); REQUIRE(topology_opening_events > 0); REQUIRE(topology_changed_events > 0); REQUIRE(topology_closed_events > 0); REQUIRE(found_servers); } SECTION("Heartbeat Events") { int heartbeat_started_events = 0; int heartbeat_succeeded_events = 0; auto mock_started_awaited = libmongoc::apm_server_heartbeat_started_get_awaited.create_instance(); auto mock_succeeded_awaited = libmongoc::apm_server_heartbeat_succeeded_get_awaited.create_instance(); bool started_awaited_called = false; bool succeeded_awaited_called = false; mock_started_awaited->visit( [&](const mongoc_apm_server_heartbeat_started_t*) { started_awaited_called = true; }); mock_succeeded_awaited->visit([&](const mongoc_apm_server_heartbeat_succeeded_t*) { succeeded_awaited_called = true; }); /////////////////////////////////////////////////////////////////////// // Begin heartbeat listener lambdas /////////////////////////////////////////////////////////////////////// // ServerHeartbeatStartedEvent apm_opts.on_heartbeat_started([&](const events::heartbeat_started_event& event) { heartbeat_started_events++; REQUIRE_FALSE(event.host().empty()); REQUIRE(event.port() != 0); // Client is single-threaded, and will never perform an awaitable hello. REQUIRE(!event.awaited()); }); // ServerHeartbeatSucceededEvent apm_opts.on_heartbeat_succeeded([&](const events::heartbeat_succeeded_event& event) { heartbeat_succeeded_events++; REQUIRE_FALSE(event.host().empty()); REQUIRE(event.port() != 0); REQUIRE_FALSE(event.reply().empty()); // Client is single-threaded, and will never perform an awaitable hello. REQUIRE(!event.awaited()); }); // Don't expect a ServerHeartbeatFailedEvent here, see the test below. /////////////////////////////////////////////////////////////////////// // End heartbeat listener lambdas /////////////////////////////////////////////////////////////////////// open_and_close_client(test_uri, apm_opts); REQUIRE(heartbeat_started_events > 0); REQUIRE(heartbeat_succeeded_events > 0); REQUIRE(started_awaited_called); REQUIRE(succeeded_awaited_called); } } TEST_CASE("Heartbeat failed event", "[sdam_monitoring]") { instance::current(); options::apm apm_opts; bool failed_awaited_called = false; auto mock_failed_awaited = libmongoc::apm_server_heartbeat_failed_get_awaited.create_instance(); mock_failed_awaited->visit( [&](const mongoc_apm_server_heartbeat_failed_t*) { failed_awaited_called = true; }); int heartbeat_failed_events = 0; // ServerHeartbeatFailedEvent apm_opts.on_heartbeat_failed([&](const events::heartbeat_failed_event& event) { heartbeat_failed_events++; REQUIRE_FALSE(event.host().empty()); REQUIRE_FALSE(event.message().empty()); REQUIRE(event.port() != 0); REQUIRE(!event.awaited()); }); REQUIRE_THROWS_AS( open_and_close_client(uri{"mongodb://bad-host/?connectTimeoutMS=1"}, apm_opts), mongocxx::exception); REQUIRE(heartbeat_failed_events > 0); REQUIRE(failed_awaited_called); } } // namespace
11,425
3,479
#include "VideoDecoder.h" #include "Kernel/AssertionMemoryPanic.h" #include "Kernel/AssertionType.h" namespace Mengine { ////////////////////////////////////////////////////////////////////////// VideoDecoder::VideoDecoder() { } ////////////////////////////////////////////////////////////////////////// VideoDecoder::~VideoDecoder() { } ////////////////////////////////////////////////////////////////////////// void VideoDecoder::setCodecDataInfo( const CodecDataInfo * _dataInfo ) { MENGINE_ASSERTION_MEMORY_PANIC( _dataInfo ); MENGINE_ASSERTION_TYPE( _dataInfo, const VideoCodecDataInfo * ); m_dataInfo = *static_cast<const VideoCodecDataInfo *>(_dataInfo); } ////////////////////////////////////////////////////////////////////////// const VideoCodecDataInfo * VideoDecoder::getCodecDataInfo() const { return &m_dataInfo; } ////////////////////////////////////////////////////////////////////////// }
1,009
259
#include "weight.h" int main(void){ struct weight::hx711_args value; if(0 == weight::setup(&value)) weight::loop(&value); return 0; }
156
60
////////////////////////////////////////////////////////////////////// // 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: // Miguel A. Morales, moralessilva2@llnl.gov // Lawrence Livermore National Laboratory // // File created by: // Miguel A. Morales, moralessilva2@llnl.gov // Lawrence Livermore National Laboratory //////////////////////////////////////////////////////////////////////////////// #ifndef QMCPLUSPLUS_AFQMC_HAMILTONIANOPERATIONS_REAL3INDEXFACTORIZATION_HPP #define QMCPLUSPLUS_AFQMC_HAMILTONIANOPERATIONS_REAL3INDEXFACTORIZATION_HPP #include <vector> #include <type_traits> #include <random> #include "Configuration.h" #include "AFQMC/config.h" #include "mpi3/shared_communicator.hpp" #include "multi/array.hpp" #include "multi/array_ref.hpp" #include "AFQMC/Numerics/ma_operations.hpp" #include "AFQMC/Utilities/type_conversion.hpp" #include "AFQMC/Utilities/taskgroup.h" namespace qmcplusplus { namespace afqmc { // MAM: to make the working precision of this class a template parameter, // sed away SPComplexType by another type ( which is then defined through a template parameter) // This should be enough, since some parts are kept at ComplexType precision // defined through the cmake // Custom implementation for real build class Real3IndexFactorization { using sp_pointer = SPComplexType*; using const_sp_pointer = SPComplexType const*; using IVector = boost::multi::array<int,1>; using CVector = boost::multi::array<ComplexType,1>; using SpVector = boost::multi::array<SPComplexType,1>; using CMatrix = boost::multi::array<ComplexType,2>; using CMatrix_cref = boost::multi::array_cref<ComplexType,2>; using CMatrix_ref = boost::multi::array_ref<ComplexType,2>; using CVector_ref = boost::multi::array_ref<ComplexType,1>; using RMatrix = boost::multi::array<RealType,2>; using RMatrix_cref = boost::multi::array_cref<RealType,2>; using RMatrix_ref = boost::multi::array_ref<RealType,2>; using RVector_ref = boost::multi::array_ref<RealType,1>; using SpCMatrix = boost::multi::array<SPComplexType,2>; using SpCMatrix_cref = boost::multi::array_cref<SPComplexType,2>; using SpCVector_ref = boost::multi::array_ref<SPComplexType,1>; using SpCMatrix_ref = boost::multi::array_ref<SPComplexType,2>; using SpRMatrix = boost::multi::array<SPRealType,2>; using SpRMatrix_cref = boost::multi::array_cref<SPRealType,2>; using SpRVector_ref = boost::multi::array_ref<SPRealType,1>; using SpRMatrix_ref = boost::multi::array_ref<SPRealType,2>; using C3Tensor = boost::multi::array<ComplexType,3>; using SpC3Tensor = boost::multi::array<SPComplexType,3>; using SpC3Tensor_ref = boost::multi::array_ref<SPComplexType,3>; using SpC4Tensor_ref = boost::multi::array_ref<SPComplexType,4>; using shmCVector = boost::multi::array<ComplexType,1,shared_allocator<ComplexType>>; using shmRMatrix = boost::multi::array<RealType,2,shared_allocator<RealType>>; using shmCMatrix = boost::multi::array<ComplexType,2,shared_allocator<ComplexType>>; using shmC3Tensor = boost::multi::array<ComplexType,3,shared_allocator<ComplexType>>; using shmSpRVector = boost::multi::array<SPRealType,1,shared_allocator<SPRealType>>; using shmSpRMatrix = boost::multi::array<SPRealType,2,shared_allocator<SPRealType>>; using shmSpCMatrix = boost::multi::array<SPComplexType,2,shared_allocator<SPComplexType>>; using shmSpC3Tensor = boost::multi::array<SPComplexType,3,shared_allocator<SPComplexType>>; using this_t = Real3IndexFactorization; public: static const HamiltonianTypes HamOpType = RealDenseFactorized; HamiltonianTypes getHamType() const { return HamOpType; } Real3IndexFactorization(afqmc::TaskGroup_& tg_, WALKER_TYPES type, shmRMatrix&& hij_, shmCMatrix&& haj_, shmSpRMatrix&& vik, shmSpCMatrix&& vak, std::vector<shmSpC3Tensor>&& vank, shmCMatrix&& vn0_, ValueType e0_, int cv0, int gncv): TG(tg_), walker_type(type), global_origin(cv0), global_nCV(gncv), local_nCV(0), E0(e0_), hij(std::move(hij_)), haj(std::move(haj_)), Likn(std::move(vik)), Lank(std::move(vank)), Lakn(std::move(vak)), vn0(std::move(vn0_)), SM_TMats({1,1},shared_allocator<SPComplexType>{TG.TG_local()}) { local_nCV=Likn.size(1); TG.Node().barrier(); } ~Real3IndexFactorization() {} Real3IndexFactorization(const Real3IndexFactorization& other) = delete; Real3IndexFactorization& operator=(const Real3IndexFactorization& other) = delete; Real3IndexFactorization(Real3IndexFactorization&& other) = default; Real3IndexFactorization& operator=(Real3IndexFactorization&& other) = delete; CMatrix getOneBodyPropagatorMatrix(TaskGroup_& TG, boost::multi::array<ComplexType,1> const& vMF) { int NMO = hij.size(0); // in non-collinear case with SO, keep SO matrix here and add it // for now, stay collinear CMatrix H1({NMO,NMO}); // add sum_n vMF*Spvn, vMF has local contribution only! boost::multi::array_ref<ComplexType,1> H1D(H1.origin(),{NMO*NMO}); std::fill_n(H1D.origin(),H1D.num_elements(),ComplexType(0)); vHS(vMF, H1D); TG.TG().all_reduce_in_place_n(H1D.origin(),H1D.num_elements(),std::plus<>()); // add hij + vn0 and symmetrize using ma::conj; for(int i=0; i<NMO; i++) { H1[i][i] += hij[i][i] + vn0[i][i]; for(int j=i+1; j<NMO; j++) { H1[i][j] += hij[i][j] + vn0[i][j]; H1[j][i] += hij[j][i] + vn0[j][i]; // This is really cutoff dependent!!! if( std::abs( H1[i][j] - ma::conj(H1[j][i]) ) > 1e-6 ) { app_error()<<" WARNING in getOneBodyPropagatorMatrix. H1 is not hermitian. \n"; app_error()<<i <<" " <<j <<" " <<H1[i][j] <<" " <<H1[j][i] <<" " <<hij[i][j] <<" " <<hij[j][i] <<" " <<vn0[i][j] <<" " <<vn0[j][i] <<std::endl; //APP_ABORT("Error in getOneBodyPropagatorMatrix. H1 is not hermitian. \n"); } H1[i][j] = 0.5*(H1[i][j]+ma::conj(H1[j][i])); H1[j][i] = ma::conj(H1[i][j]); } } return H1; } template<class Mat, class MatB> void energy(Mat&& E, MatB const& G, int k, bool addH1=true, bool addEJ=true, bool addEXX=true) { MatB* Kr(nullptr); MatB* Kl(nullptr); energy(E,G,k,Kl,Kr,addH1,addEJ,addEXX); } // KEleft and KEright must be in shared memory for this to work correctly template<class Mat, class MatB, class MatC, class MatD> void energy(Mat&& E, MatB const& Gc, int nd, MatC* KEleft, MatD* KEright, bool addH1=true, bool addEJ=true, bool addEXX=true) { assert(E.size(1)>=3); assert(nd >= 0); assert(nd < haj.size()); if(walker_type==COLLINEAR) assert(2*nd+1 < Lank.size()); else assert(nd < Lank.size()); int nwalk = Gc.size(0); int nspin = (walker_type==COLLINEAR?2:1); int NMO = hij.size(0); int nel[2]; nel[0] = Lank[nspin*nd].size(0); nel[1] = ((nspin==2)?Lank[nspin*nd+1].size(0):0); assert(Lank[nspin*nd].size(1) == local_nCV); assert(Lank[nspin*nd].size(2) == NMO); if(nspin==2) { assert(Lank[nspin*nd+1].size(1) == local_nCV); assert(Lank[nspin*nd+1].size(2) == NMO); } assert(Gc.num_elements() == nwalk*(nel[0]+nel[1])*NMO); int getKr = KEright!=nullptr; int getKl = KEleft!=nullptr; if(E.size(0) != nwalk || E.size(1) < 3) APP_ABORT(" Error in AFQMC/HamiltonianOperations/Real3IndexFactorization::energy(...). Incorrect matrix dimensions \n"); // T[nwalk][nup][nup][local_nCV] + D[nwalk][nwalk][local_nCV] size_t mem_needs(0); size_t cnt(0); if(addEJ) { #if MIXED_PRECISION mem_needs += nwalk*local_nCV; #else if(not getKl) mem_needs += nwalk*local_nCV; #endif } if(addEXX) { mem_needs += nwalk*nel[0]*nel[0]*local_nCV; #if MIXED_PRECISION mem_needs += nwalk*nel[0]*NMO; #else if(nspin == 2) mem_needs += nwalk*nel[0]*NMO; #endif } set_shm_buffer(mem_needs); // messy SPComplexType *Klptr(nullptr); long Knr=0, Knc=0; if(addEJ) { Knr=nwalk; Knc=local_nCV; if(getKr) { assert(KEright->size(0) == nwalk && KEright->size(1) == local_nCV); assert(KEright->stride(0) == KEright->size(1)); } #if MIXED_PRECISION if(getKl) { assert(KEleft->size(0) == nwalk && KEleft->size(1) == local_nCV); assert(KEleft->stride(0) == KEleft->size(1)); } #else if(getKl) { assert(KEleft->size(0) == nwalk && KEleft->size(1) == local_nCV); assert(KEleft->stride(0) == KEleft->size(1)); Klptr = to_address(KEleft->origin()); } else #endif { Klptr = to_address(SM_TMats.origin())+cnt; cnt += Knr*Knc; } if(TG.TG_local().root()) std::fill_n(Klptr,Knr*Knc,SPComplexType(0.0)); } else if(getKr or getKl) { APP_ABORT(" Error: Kr and/or Kl can only be calculated with addEJ=true.\n"); } SpCMatrix_ref Kl(Klptr,{long(Knr),long(Knc)}); for(int n=0; n<nwalk; n++) std::fill_n(E[n].origin(),3,ComplexType(0.)); // one-body contribution // haj[ndet][nocc*nmo] // not parallelized for now, since it would require customization of Wfn if(addH1) { boost::multi::array_cref<ComplexType,1> haj_ref(to_address(haj[nd].origin()), iextensions<1u>{haj[nd].num_elements()}); ma::product(ComplexType(1.),Gc,haj_ref,ComplexType(1.),E(E.extension(0),0)); for(int i=0; i<nwalk; i++) E[i][0] += E0; } // move calculation of H1 here // NOTE: For CLOSED/NONCOLLINEAR, can do all walkers simultaneously to improve perf. of GEMM // Not sure how to do it for COLLINEAR. if(addEXX) { SPRealType scl = (walker_type==CLOSED?2.0:1.0); for(int ispin=0, is0=0; ispin<nspin; ispin++) { size_t cnt_(cnt); SPComplexType *ptr(nullptr); #if MIXED_PRECISION ptr = to_address(SM_TMats.origin())+cnt_; cnt_ += nwalk*nel[ispin]*NMO; for(int n=0; n<nwalk; ++n) { if( n%TG.TG_local().size() != TG.TG_local().rank() ) continue; copy_n_cast(to_address(Gc[n].origin())+is0,nel[ispin]*NMO,ptr+n*nel[ispin]*NMO); } TG.TG_local().barrier(); #else if(nspin==1) { ptr = to_address(Gc.origin()); } else { ptr = to_address(SM_TMats.origin())+cnt_; cnt_ += nwalk*nel[ispin]*NMO; for(int n=0; n<nwalk; ++n) { if( n%TG.TG_local().size() != TG.TG_local().rank() ) continue; std::copy_n(to_address(Gc[n].origin())+is0,nel[ispin]*NMO,ptr+n*nel[ispin]*NMO); } TG.TG_local().barrier(); } #endif SpCMatrix_ref GF(ptr,{nwalk*nel[ispin],NMO}); SpCMatrix_ref Lan(to_address(Lank[nd*nspin + ispin].origin()), {nel[ispin]*local_nCV,NMO}); SpCMatrix_ref Twban(to_address(SM_TMats.origin())+cnt_,{nwalk*nel[ispin],nel[ispin]*local_nCV}); SpC4Tensor_ref T4Dwban(Twban.origin(),{nwalk,nel[ispin],nel[ispin],local_nCV}); long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),long(nel[ispin]*local_nCV), long(TG.TG_local().size())); ma::product(GF,ma::T(Lan.sliced(i0,iN)),Twban(Twban.extension(0),{i0,iN})); TG.TG_local().barrier(); for(int n=0, an=0; n<nwalk; ++n) { ComplexType E_(0.0); for(int a=0; a<nel[ispin]; ++a, an++) { if( an%TG.TG_local().size() != TG.TG_local().rank() ) continue; for(int b=0; b<nel[ispin]; ++b) E_ += static_cast<ComplexType>(ma::dot(T4Dwban[n][a][b],T4Dwban[n][b][a])); } E[n][1] -= 0.5*scl*E_; } if(addEJ) { for(int n=0; n<nwalk; ++n) { if( n%TG.TG_local().size() != TG.TG_local().rank() ) continue; for(int a=0; a<nel[ispin]; ++a) ma::axpy(SPComplexType(1.0),T4Dwban[n][a][a],Kl[n]); } } is0 += nel[ispin]*NMO; } // if } TG.TG_local().barrier(); if(addEJ) { if(not addEXX) { // calculate Kr APP_ABORT(" Error: Finish addEJ and not addEXX"); } TG.TG_local().barrier(); SPRealType scl = (walker_type==CLOSED?2.0:1.0); for(int n=0; n<nwalk; ++n) { if(n%TG.TG_local().size() == TG.TG_local().rank()) E[n][2] += 0.5*static_cast<ComplexType>(scl*scl*ma::dot(Kl[n],Kl[n])); } #if MIXED_PRECISION if(getKl) { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),long(KEleft->num_elements()), long(TG.TG_local().size())); copy_n_cast(Klptr+i0,iN-i0,to_address(KEleft->origin())+i0); } #endif if(getKr) { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),long(KEright->num_elements()), long(TG.TG_local().size())); copy_n_cast(Klptr+i0,iN-i0,to_address(KEright->origin())+i0); } TG.TG_local().barrier(); } } template<class... Args> void fast_energy(Args&&... args) { APP_ABORT(" Error: fast_energy not implemented in Real3IndexFactorization. \n"); } template<class MatA, class MatB, typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==1)>, typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==1)>, typename = void > void vHS(MatA& X, MatB&& v, double a=1., double c=0.) { using BType = typename std::decay<MatB>::type::element ; using AType = typename std::decay<MatA>::type::element ; boost::multi::array_ref<BType,2> v_(to_address(v.origin()), {v.size(0),1}); boost::multi::array_ref<const AType,2> X_(to_address(X.origin()), {X.size(0),1}); return vHS(X_,v_,a,c); } template<class MatA, class MatB, typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==2)>, typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==2)> > void vHS(MatA& X, MatB&& v, double a=1., double c=0.) { using XType = typename std::decay_t<typename MatA::element>; using vType = typename std::decay<MatB>::type::element ; assert( Likn.size(1) == X.size(0) ); assert( Likn.size(0) == v.size(0) ); assert( X.size(1) == v.size(1) ); long ik0, ikN; std::tie(ik0,ikN) = FairDivideBoundary(long(TG.TG_local().rank()),long(Likn.size(0)),long(TG.TG_local().size())); // setup buffer space if changing precision in X or v size_t vmem(0),Xmem(0); if(not std::is_same<XType,SPComplexType>::value) Xmem = X.num_elements(); if(not std::is_same<vType,SPComplexType>::value) vmem = v.num_elements(); set_shm_buffer(vmem+Xmem); sp_pointer vptr(nullptr); const_sp_pointer Xptr(nullptr); // setup origin of Xsp and copy_n_cast if necessary if(std::is_same<XType,SPComplexType>::value) { Xptr = reinterpret_cast<const_sp_pointer>(to_address(X.origin())); } else { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()), long(X.num_elements()),long(TG.TG_local().size())); copy_n_cast(to_address(X.origin())+i0,iN-i0,to_address(SM_TMats.origin())+i0); Xptr = to_address(SM_TMats.origin()); } // setup origin of vsp and copy_n_cast if necessary if(std::is_same<vType,SPComplexType>::value) { vptr = reinterpret_cast<sp_pointer>(to_address(v.origin())); } else { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()), long(v.num_elements()),long(TG.TG_local().size())); vptr = to_address(SM_TMats.origin())+Xmem; if( std::abs(c) > 1e-12 ) copy_n_cast(to_address(v.origin())+i0,iN-i0,vptr+i0); } // setup array references boost::multi::array_cref<SPComplexType const,2> Xsp(Xptr, X.extensions()); boost::multi::array_ref<SPComplexType,2> vsp(vptr, v.extensions()); TG.TG_local().barrier(); ma::product(SPValueType(a),Likn.sliced(ik0,ikN),Xsp, SPValueType(c),vsp.sliced(ik0,ikN)); if(not std::is_same<vType,SPComplexType>::value) { copy_n_cast(to_address(vsp[ik0].origin()),vsp.size(1)*(ikN-ik0), to_address(v[ik0].origin())); } TG.TG_local().barrier(); } template<class MatA, class MatB, typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==1)>, typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==1)>, typename = void > void vbias(const MatA& G, MatB&& v, double a=1., double c=0., int k=0) { using BType = typename std::decay<MatB>::type::element ; using AType = typename std::decay<MatA>::type::element ; boost::multi::array_ref<BType,2> v_(to_address(v.origin()), {v.size(0),1}); if(haj.size(0) == 1) { boost::multi::array_cref<AType,2> G_(to_address(G.origin()), {1,G.size(0)}); return vbias(G_,v_,a,c,k); } else { boost::multi::array_cref<AType,2> G_(to_address(G.origin()), {G.size(0),1}); return vbias(G_,v_,a,c,k); } } // v(n,w) = sum_ak L(ak,n) G(w,ak) template<class MatA, class MatB, typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==2)>, typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==2)> > void vbias(const MatA& G, MatB&& v, double a=1., double c=0., int k=0) { using GType = typename std::decay_t<typename MatA::element>; using vType = typename std::decay<MatB>::type::element ; long ic0, icN; // setup buffer space if changing precision in G or v size_t vmem(0),Gmem(0); if(not std::is_same<GType,SPComplexType>::value) Gmem = G.num_elements(); if(not std::is_same<vType,SPComplexType>::value) vmem = v.num_elements(); set_shm_buffer(vmem+Gmem); const_sp_pointer Gptr(nullptr); sp_pointer vptr(nullptr); // setup origin of Gsp and copy_n_cast if necessary if(std::is_same<GType,SPComplexType>::value) { Gptr = reinterpret_cast<const_sp_pointer>(to_address(G.origin())); } else { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()), long(G.num_elements()),long(TG.TG_local().size())); copy_n_cast(to_address(G.origin())+i0,iN-i0,to_address(SM_TMats.origin())+i0); Gptr = to_address(SM_TMats.origin()); } // setup origin of vsp and copy_n_cast if necessary if(std::is_same<vType,SPComplexType>::value) { vptr = reinterpret_cast<sp_pointer>(to_address(v.origin())); } else { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()), long(v.num_elements()),long(TG.TG_local().size())); vptr = to_address(SM_TMats.origin())+Gmem; if( std::abs(c) > 1e-12 ) copy_n_cast(to_address(v.origin())+i0,iN-i0,vptr+i0); } // setup array references boost::multi::array_cref<SPComplexType const,2> Gsp(Gptr, G.extensions()); boost::multi::array_ref<SPComplexType,2> vsp(vptr, v.extensions()); TG.TG_local().barrier(); if(haj.size(0) == 1) { assert( Lakn.size(0) == G.size(1) ); assert( Lakn.size(1) == v.size(0) ); assert( G.size(0) == v.size(1) ); std::tie(ic0,icN) = FairDivideBoundary(long(TG.TG_local().rank()), long(Lakn.size(1)),long(TG.TG_local().size())); if(walker_type==CLOSED) a*=2.0; ma::product(SPValueType(a),ma::T(Lakn(Lakn.extension(0),{ic0,icN})),ma::T(Gsp), SPValueType(c),vsp.sliced(ic0,icN)); } else { // multideterminant is not half-rotated, so use Likn assert( Likn.size(0) == G.size(0) ); assert( Likn.size(1) == v.size(0) ); assert( G.size(1) == v.size(1) ); std::tie(ic0,icN) = FairDivideBoundary(long(TG.TG_local().rank()), long(Likn.size(1)),long(TG.TG_local().size())); if(walker_type==CLOSED) a*=2.0; ma::product(SPValueType(a),ma::T(Likn(Likn.extension(0),{ic0,icN})),Gsp, SPValueType(c),vsp.sliced(ic0,icN)); } // copy data back if changing precision if(not std::is_same<vType,SPComplexType>::value) { copy_n_cast(to_address(vsp[ic0].origin()),vsp.size(1)*(icN-ic0), to_address(v[ic0].origin())); } TG.TG_local().barrier(); } template<class Mat, class MatB> void generalizedFockMatrix(Mat&& G, MatB&& Fp, MatB&& Fm) { APP_ABORT(" Error: generalizedFockMatrix not implemented for this hamiltonian.\n"); } bool distribution_over_cholesky_vectors() const{ return true; } int number_of_ke_vectors() const{ return local_nCV; } int local_number_of_cholesky_vectors() const{ return local_nCV; } int global_number_of_cholesky_vectors() const{ return global_nCV; } int global_origin_cholesky_vector() const{ return global_origin; } // transpose=true means G[nwalk][ik], false means G[ik][nwalk] bool transposed_G_for_vbias() const{ return (haj.size(0) == 1); } bool transposed_G_for_E() const{return true;} // transpose=true means vHS[nwalk][ik], false means vHS[ik][nwalk] bool transposed_vHS() const{return false;} bool fast_ph_energy() const { return false; } boost::multi::array<ComplexType,2> getHSPotentials() { return boost::multi::array<ComplexType,2>{}; } private: afqmc::TaskGroup_& TG; WALKER_TYPES walker_type; int global_origin; int global_nCV; int local_nCV; ValueType E0; // bare one body hamiltonian shmRMatrix hij; // (potentially half rotated) one body hamiltonian shmCMatrix haj; //Cholesky Tensor Lik[i][k][n] shmSpRMatrix Likn; // permuted half-tranformed Cholesky tensor // Lank[ 2*idet + ispin ] std::vector<shmSpC3Tensor> Lank; // half-tranformed Cholesky tensor // only used in single determinant case, haj.size(0)==1. shmSpCMatrix Lakn; // one-body piece of Hamiltonian factorization shmCMatrix vn0; // shared buffer space // using matrix since there are issues with vectors shmSpCMatrix SM_TMats; myTimer Timer; void set_shm_buffer(size_t N) { if(SM_TMats.num_elements() < N) SM_TMats.reextent({N,1}); } }; } } #endif
23,974
9,024
#ifdef PEGASUS_OS_DARWIN #ifndef __UNIX_ABSTRACTINDICATIONSUBSCRIPTION_PRIVATE_H #define __UNIX_ABSTRACTINDICATIONSUBSCRIPTION_PRIVATE_H #endif #endif
157
75
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>>q; int i,j,k,l; TreeNode* z; TreeNode* x; queue<TreeNode* >a; if(root==NULL) return q; a.push(root); while(a.size()) { vector<int >w; k=a.size(); while(k--) { z=a.front(); if(z->left) a.push(z->left); if(z->right) a.push(z->right); w.push_back(z->val); a.pop(); } q.push_back(w); } for(i=1;i<q.size();i+=2) { reverse(q[i].begin(),q[i].end()); } return q; } };
1,032
338
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ #include "helpers/Loops.hpp" using namespace simdOps; namespace nd4j { ////////////////////////////////////////////////////////////////////////////// Loops::LoopKind Loops::deduceKindOfLoopXYZ(const Nd4jLong* tadShapeInfo, const Nd4jLong* yShapeInfo, const Nd4jLong* zShapeInfo) { const int xRank = shape::rank(tadShapeInfo); const Nd4jLong xEws = shape::elementWiseStride(tadShapeInfo); const Nd4jLong yEws = shape::elementWiseStride(yShapeInfo); const Nd4jLong zEws = shape::elementWiseStride(zShapeInfo); int temp; const bool xVector = shape::isCommonVector(tadShapeInfo, temp); const bool yVector = shape::isCommonVector(yShapeInfo, temp); const bool zVector = shape::isCommonVector(zShapeInfo, temp); const char xOrder = shape::order(tadShapeInfo); const char yOrder = shape::order(yShapeInfo); const char zOrder = shape::order(zShapeInfo); const bool shapesSame = shape::shapeEquals(tadShapeInfo, yShapeInfo) && shape::shapeEquals(tadShapeInfo, zShapeInfo); if (xEws == 1 && yEws == 1 && zEws == 1 && ((xOrder == yOrder && xOrder == zOrder) || ((xVector || xOrder == 'c') && (yVector || yOrder == 'c') && (zVector || zOrder == 'c')))) return EWS1; if(xEws > 0 && yEws > 0 && zEws > 0 && ((xOrder == yOrder && xOrder == zOrder) || ((xVector || xOrder == 'c') && (yVector || yOrder == 'c') && (zVector || zOrder == 'c')))) return EWSNONZERO; if(xRank == 1 && shapesSame) return RANK1; if(xRank == 2 && shapesSame) return RANK2; if(xRank == 3 && shapesSame) return RANK3; if(xRank == 4 && shapesSame) return RANK4; if(xRank == 5 && shapesSame) return RANK5; return COMMON; } ////////////////////////////////////////////////////////////////////////////// Loops::LoopKind Loops::deduceKindOfLoopXZ(const Nd4jLong* tadShapeInfo, const Nd4jLong* zShapeInfo) { const int xRank = shape::rank(tadShapeInfo); const Nd4jLong xEws = shape::elementWiseStride(tadShapeInfo); const Nd4jLong zEws = shape::elementWiseStride(zShapeInfo); const char xOrder = shape::order(tadShapeInfo); const char zOrder = shape::order(zShapeInfo); int temp; const bool xVector = shape::isCommonVector(tadShapeInfo, temp); const bool zVector = shape::isCommonVector(zShapeInfo, temp); const bool shapesSame = shape::shapeEquals(tadShapeInfo, zShapeInfo); if(xEws == 1 && zEws == 1 && ((xOrder == zOrder) || ((xVector || xOrder == 'c') && (zVector || zOrder == 'c')))) return EWS1; if(xEws > 0 && zEws > 0 && ((xOrder == zOrder) || ((xVector || xOrder == 'c') && (zVector || zOrder == 'c')))) return EWSNONZERO; if(xRank == 1 && shapesSame) return RANK1; if(xRank == 2 && shapesSame) return RANK2; if(xRank == 3 && shapesSame) return RANK3; if(xRank == 4 && shapesSame) return RANK4; if(xRank == 5 && shapesSame) return RANK5; if(xEws > 0 && (xOrder == 'c' || xVector) && zEws == 0) return X_EWSNONZERO; if(zEws > 0 && (zOrder == 'c' || zVector) && xEws == 0) return Z_EWSNONZERO; return COMMON; } ////////////////////////////////////////////////////////////////////////////// Loops::LoopKind Loops::deduceKindOfLoopTadXZ(const Nd4jLong* tadShapeInfo, const Nd4jLong* zShapeInfo) { const int xRank = shape::rank(tadShapeInfo); const Nd4jLong tadEws = shape::elementWiseStride(tadShapeInfo); const Nd4jLong zEws = shape::elementWiseStride(zShapeInfo); const char xOrder = shape::order(tadShapeInfo); const char zOrder = shape::order(zShapeInfo); int temp; const bool xVector = shape::isCommonVector(tadShapeInfo, temp); const bool zVector = shape::isCommonVector(zShapeInfo, temp); if(tadEws == 1 && zEws == 1 && ((xOrder == zOrder) || ((xVector || xOrder == 'c') && (zVector || zOrder == 'c')))) return EWS1; if(tadEws > 0 && zEws > 0 && ((xOrder == zOrder) || ((xVector || xOrder == 'c') && (zVector || zOrder == 'c')))) return EWSNONZERO; if(xRank == 1 && zEws == 1 && (zVector || zOrder == 'c')) return RANK1; if(xRank == 2 && zEws == 1 && (zVector || zOrder == 'c')) return RANK2; if(xRank == 3 && zEws == 1 && (zVector || zOrder == 'c')) return RANK3; if(xRank == 4 && zEws == 1 && (zVector || zOrder == 'c')) return RANK4; if(xRank == 5 && zEws == 1 && (zVector || zOrder == 'c')) return RANK5; if(tadEws > 0 && (xVector || xOrder == 'c') && zEws == 0) return X_EWSNONZERO; if(zEws > 0 && (zOrder == 'c' || zVector) && tadEws == 0) return Z_EWSNONZERO; return COMMON; } template <typename X> class IndexReduceWrapper { public: template <typename OpType> static void wrapper(const X *x, const Nd4jLong *tadShapeInfo, const Nd4jLong *tadOffset, Nd4jLong *z, const Nd4jLong *zShapeInfo, X *extras) { Loops::loopIndexTadXZ<X, OpType>(x, tadShapeInfo, tadOffset, z, zShapeInfo, extras); } static void wrap(const int opNum, const X *x, const Nd4jLong *tadShapeInfo, const Nd4jLong *tadOffset, Nd4jLong *z, const Nd4jLong *zShapeInfo, X *extras) { DISPATCH_BY_OPNUM_T(wrapper, PARAMS(x, tadShapeInfo, tadOffset, z, zShapeInfo, extras), INDEX_REDUCE_OPS); } }; BUILD_SINGLE_TEMPLATE(template class IndexReduceWrapper, , LIBND4J_TYPES); }
6,594
2,273
#include "Renderer.h" #include "post_processing/Bloom.h" #include "GlobalConstants.h" #include "../../MainWindow.h" #include "drawers/BatchedDrawer.h" #include "glad/glad.h" Renderer* Renderer::inst; Renderer::Renderer(GLFWwindow* window) { if (inst) { return; } inst = this; const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* vendor = glGetString(GL_VENDOR); const GLubyte* version = glGetString(GL_VERSION); const GLubyte* langVer = glGetString(GL_SHADING_LANGUAGE_VERSION); LOG4CXX_INFO(logger, "Renderer: " << (const char*)renderer); LOG4CXX_INFO(logger, "Vendor: " << (const char*)vendor); LOG4CXX_INFO(logger, "OpenGL Version: " << (const char*)version); LOG4CXX_INFO(logger, "GLSL Version: " << (const char*)langVer); viewportWidth = RENDERER_INITIAL_WIDTH; viewportHeight = RENDERER_INITIAL_HEIGHT; lastViewportWidth = viewportWidth; lastViewportHeight = viewportHeight; // Generate render texture glGenTextures(1, &renderTexture); glBindTexture(GL_TEXTURE_2D, renderTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, viewportWidth, viewportHeight, 0, GL_RGBA, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // Initialize framebuffer to copy from multisample framebuffer glGenFramebuffers(1, &finalFramebuffer); glBindFramebuffer(GL_FRAMEBUFFER, finalFramebuffer); // Attach generated resources to framebuffer glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderTexture, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Generate multisample color texture glGenTextures(1, &multisampleTexture); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, multisampleTexture); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, MSAA_SAMPLES, GL_RGBA16F, viewportWidth, viewportHeight, GL_TRUE); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); // Generate render texture glGenRenderbuffers(1, &depthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer); glRenderbufferStorageMultisample(GL_RENDERBUFFER, MSAA_SAMPLES, GL_DEPTH_COMPONENT, viewportWidth, viewportHeight); glBindRenderbuffer(GL_RENDERBUFFER, 0); // Initialize framebuffer to render into glGenFramebuffers(1, &multisampleFramebuffer); glBindFramebuffer(GL_FRAMEBUFFER, multisampleFramebuffer); // Attach generated resources to framebuffer glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, multisampleTexture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer); glBindFramebuffer(GL_FRAMEBUFFER, 0); mainWindow = window; camera = new Camera(); imGuiController = new ImGuiController(window, "Assets/Fonts/Inconsolata-Regular.ttf"); bloom = new Bloom(); // tonemapping = new Tonemapping(); } void Renderer::update() { imGuiController->update(); resizeViewport(); } void Renderer::resizeViewport() { if (viewportWidth != lastViewportWidth || viewportHeight != lastViewportHeight) { // Resize all framebuffer attachments glBindTexture(GL_TEXTURE_2D, renderTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, viewportWidth, viewportHeight, 0, GL_RGB, GL_FLOAT, nullptr); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, multisampleTexture); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, MSAA_SAMPLES, GL_RGBA16F, viewportWidth, viewportHeight, GL_TRUE); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer); glRenderbufferStorageMultisample(GL_RENDERBUFFER, MSAA_SAMPLES, GL_DEPTH_COMPONENT, viewportWidth, viewportHeight); glBindRenderbuffer(GL_RENDERBUFFER, 0); lastViewportWidth = viewportWidth; lastViewportHeight = viewportHeight; } } void Renderer::render() { renderViewport(); // Render ImGui last imGuiController->renderImGui(); } void Renderer::renderViewport() { float aspect = viewportWidth / (float)viewportHeight; glm::mat4 view, projection; camera->calculateViewProjection(aspect, &view, &projection); glm::mat4 viewProjection = projection * view; recursivelyRenderNodes(Scene::inst->rootNode, glm::mat4(1.0f)); prepareDrawers(); FramebufferStack::push(multisampleFramebuffer); glViewport(0, 0, viewportWidth, viewportHeight); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glDisable(GL_BLEND); // Opaque shits are drawn here for (Drawer* drawer : queuedOpaqueDrawers) { drawer->draw(viewProjection); delete drawer; } glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Transparent shits are drawn here for (Drawer* drawer : queuedTransparentDrawers) { drawer->draw(viewProjection); delete drawer; } glDepthMask(GL_TRUE); FramebufferStack::pop(); glBindFramebuffer(GL_READ_FRAMEBUFFER, multisampleFramebuffer); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, finalFramebuffer); glBlitFramebuffer(0, 0, viewportWidth, viewportHeight, 0, 0, viewportWidth, viewportHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_FRAMEBUFFER, 0); bloom->processImage(renderTexture, viewportWidth, viewportHeight); // tonemapping->processImage(renderTexture, viewportWidth, viewportHeight); // Clean up queuedOpaqueDrawers.clear(); queuedTransparentDrawers.clear(); BatchedDrawer::clearBatches(); glBindVertexArray(0); glUseProgram(0); } uint32_t Renderer::getRenderTexture() const { return renderTexture; } void Renderer::recursivelyRenderNodes(SceneNode* node, glm::mat4 parentTransform) { if (!node->getActive()) { return; } const glm::mat4 nodeTransform = node->transform.getLocalMatrix(); const glm::mat4 globalTransform = parentTransform * nodeTransform; if (node->renderer) { RenderCommand* cmd; if (node->renderer->tryRender(globalTransform, &cmd)) { if (cmd->drawDepth.has_value()) { queuedCommandTransparent.push_back(cmd); } else { queuedCommandOpaque.push_back(cmd); } } } for (SceneNode* child : node->activeChildren) { recursivelyRenderNodes(child, globalTransform); } } void Renderer::prepareDrawers() { // Sort draw commands // We sort opaque commands by type to maximize batching efficiency std::sort(queuedCommandOpaque.begin(), queuedCommandOpaque.end(), [](RenderCommand* a, RenderCommand* b) { return a->drawData->getType() < b->drawData->getType(); }); // For transparent commands, we sort by depth, then by type std::sort(queuedCommandTransparent.begin(), queuedCommandTransparent.end(), [](RenderCommand* a, RenderCommand* b) { assert(a->drawDepth.has_value()); assert(b->drawDepth.has_value()); const float depthA = a->drawDepth.value(); const float depthB = b->drawDepth.value(); if (depthA != depthB) { return depthA < depthB; } return a->drawData->getType() < b->drawData->getType(); }); // Batching and queuing other stuff // Batching opaque objects { BatchedDrawer* currentOpaqueDrawer = nullptr; for (RenderCommand* cmd : queuedCommandOpaque) { if (cmd->drawData->getType() == DrawDataType_Batched) { if (!currentOpaqueDrawer) { currentOpaqueDrawer = new BatchedDrawer(); } BatchedDrawData* drawData = (BatchedDrawData*)cmd->drawData; currentOpaqueDrawer->appendMesh(drawData->mesh, drawData->transform, drawData->color); } else { if (currentOpaqueDrawer) { queuedOpaqueDrawers.push_back(currentOpaqueDrawer); currentOpaqueDrawer = nullptr; } queuedOpaqueDrawers.push_back(cmd->drawData->getDrawer()); } delete cmd; } // We check if there is any unqueued opaque drawer at the end and if there is, queue it if (currentOpaqueDrawer) { queuedOpaqueDrawers.push_back(currentOpaqueDrawer); currentOpaqueDrawer = nullptr; } } // Batching transparent objects { BatchedDrawer* currentTransparentDrawer = nullptr; for (RenderCommand* cmd : queuedCommandTransparent) { if (cmd->drawData->getType() == DrawDataType_Batched) { if (!currentTransparentDrawer) { currentTransparentDrawer = new BatchedDrawer(); } BatchedDrawData* drawData = (BatchedDrawData*)cmd->drawData; currentTransparentDrawer->appendMesh(drawData->mesh, drawData->transform, drawData->color); } else { if (currentTransparentDrawer) { queuedTransparentDrawers.push_back(currentTransparentDrawer); currentTransparentDrawer = nullptr; } queuedTransparentDrawers.push_back(cmd->drawData->getDrawer()); } delete cmd; } // We check if there is any unqueued transparent drawer at the end and if there is, queue it if (currentTransparentDrawer) { queuedTransparentDrawers.push_back(currentTransparentDrawer); currentTransparentDrawer = nullptr; } } queuedCommandTransparent.clear(); queuedCommandOpaque.clear(); }
9,084
3,551
#include "UnrealEnginePythonPrivatePCH.h" int unreal_engine_py_init(ue_PyUObject *self, PyObject *args, PyObject *kwds) { // is it subclassing ? if (PyTuple_Size(args) == 3) { // TODO make it smarter on error checking UE_LOG(LogPython, Warning, TEXT("%s"), UTF8_TO_TCHAR(PyUnicode_AsUTF8(PyObject_Str(PyTuple_GetItem(args, 0))))); UE_LOG(LogPython, Warning, TEXT("%s"), UTF8_TO_TCHAR(PyUnicode_AsUTF8(PyObject_Str(PyTuple_GetItem(args, 1))))); UE_LOG(LogPython, Warning, TEXT("%s"), UTF8_TO_TCHAR(PyUnicode_AsUTF8(PyObject_Str(PyTuple_GetItem(args, 2))))); PyObject *parents = PyTuple_GetItem(args, 1); ue_PyUObject *parent = (ue_PyUObject *)PyTuple_GetItem(parents, 0); PyObject *class_attributes = PyTuple_GetItem(args, 2); PyObject *class_name = PyDict_GetItemString(class_attributes, (char *)"__qualname__"); char *name = PyUnicode_AsUTF8(class_name); // check if parent is a uclass UClass *new_class = unreal_engine_new_uclass(name, (UClass *)parent->ue_object); if (!new_class) return -1; // map the class to the python object self->ue_object = new_class; self->py_proxy = nullptr; self->auto_rooted = 0; self->py_dict = PyDict_New(); FUnrealEnginePythonHouseKeeper::Get()->RegisterPyUObject(new_class, self); PyObject *py_additional_properties = PyDict_New(); PyObject *class_attributes_keys = PyObject_GetIter(class_attributes); for (;;) { PyObject *key = PyIter_Next(class_attributes_keys); if (!key) { if (PyErr_Occurred()) return -1; break; } if (!PyUnicodeOrString_Check(key)) continue; char *class_key = PyUnicode_AsUTF8(key); PyObject *value = PyDict_GetItem(class_attributes, key); if (strlen(class_key) > 2 && class_key[0] == '_' && class_key[1] == '_') { continue; } bool prop_added = false; if (UProperty *u_property = new_class->FindPropertyByName(FName(UTF8_TO_TCHAR(class_key)))) { UE_LOG(LogPython, Warning, TEXT("Found UProperty %s"), UTF8_TO_TCHAR(class_key)); PyDict_SetItem(py_additional_properties, key, value); prop_added = true; } // add simple property else if (ue_is_pyuobject(value)) { ue_PyUObject *py_obj = (ue_PyUObject *)value; if (py_obj->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj->ue_object; if (p_class->IsChildOf<UProperty>()) { if (!py_ue_add_property(self, Py_BuildValue("(Os)", value, class_key))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } else { if (!py_ue_add_property(self, Py_BuildValue("(OsO)", (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()), class_key, value))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } else if (py_obj->ue_object->IsA<UScriptStruct>()) { if (!py_ue_add_property(self, Py_BuildValue("(OsO)", (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()), class_key, value))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } // add array property else if (PyList_Check(value)) { if (PyList_Size(value) == 1) { PyObject *first_item = PyList_GetItem(value, 0); if (ue_is_pyuobject(first_item)) { ue_PyUObject *py_obj = (ue_PyUObject *)first_item; if (py_obj->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj->ue_object; if (p_class->IsChildOf<UProperty>()) { if (!py_ue_add_property(self, Py_BuildValue("(Os)", value, class_key))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } else { if (!py_ue_add_property(self, Py_BuildValue("([O]sO)", (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()), class_key, first_item))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } else if (py_obj->ue_object->IsA<UScriptStruct>()) { if (!py_ue_add_property(self, Py_BuildValue("([O]sO)", (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()), class_key, first_item))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } } } #if ENGINE_MINOR_VERSION >= 15 else if (PyDict_Check(value)) { if (PyDict_Size(value) == 1) { PyObject *py_key = nullptr; PyObject *py_value = nullptr; Py_ssize_t pos = 0; PyDict_Next(value, &pos, &py_key, &py_value); if (ue_is_pyuobject(py_key) && ue_is_pyuobject(py_value)) { PyObject *first_item = nullptr; PyObject *second_item = nullptr; ue_PyUObject *py_obj = (ue_PyUObject *)py_key; if (py_obj->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj->ue_object; if (p_class->IsChildOf<UProperty>()) { first_item = py_key; } else { first_item = (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()); } } else if (py_obj->ue_object->IsA<UScriptStruct>()) { first_item = (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()); } ue_PyUObject *py_obj2 = (ue_PyUObject *)py_value; if (py_obj2->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj2->ue_object; if (p_class->IsChildOf<UProperty>()) { second_item = py_value; } else { second_item = (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()); } } else if (py_obj2->ue_object->IsA<UScriptStruct>()) { second_item = (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()); } if (!py_ue_add_property(self, Py_BuildValue("([OO]sOO)", first_item, second_item, class_key, py_key, py_value))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } } #endif // function ? else if (PyCallable_Check(value) && class_key[0] >= 'A' && class_key[0] <= 'Z') { uint32 func_flags = FUNC_Native | FUNC_BlueprintCallable | FUNC_Public; PyObject *is_event = PyObject_GetAttrString(value, (char *)"event"); if (is_event && PyObject_IsTrue(is_event)) { func_flags |= FUNC_Event | FUNC_BlueprintEvent; } else if (!is_event) PyErr_Clear(); PyObject *is_multicast = PyObject_GetAttrString(value, (char *)"multicast"); if (is_multicast && PyObject_IsTrue(is_multicast)) { func_flags |= FUNC_NetMulticast; } else if (!is_multicast) PyErr_Clear(); PyObject *is_server = PyObject_GetAttrString(value, (char *)"server"); if (is_server && PyObject_IsTrue(is_server)) { func_flags |= FUNC_NetServer; } else if (!is_server) PyErr_Clear(); PyObject *is_client = PyObject_GetAttrString(value, (char *)"client"); if (is_client && PyObject_IsTrue(is_client)) { func_flags |= FUNC_NetClient; } else if (!is_client) PyErr_Clear(); PyObject *is_reliable = PyObject_GetAttrString(value, (char *)"reliable"); if (is_reliable && PyObject_IsTrue(is_reliable)) { func_flags |= FUNC_NetReliable; } else if (!is_reliable) PyErr_Clear(); PyObject *is_pure = PyObject_GetAttrString(value, (char *)"pure"); if (is_pure && PyObject_IsTrue(is_pure)) { func_flags |= FUNC_BlueprintPure; } else if (!is_pure) PyErr_Clear(); PyObject *is_static = PyObject_GetAttrString(value, (char *)"static"); if (is_static && PyObject_IsTrue(is_static)) { func_flags |= FUNC_Static; } else if (!is_static) PyErr_Clear(); PyObject *override_name = PyObject_GetAttrString(value, (char *)"override"); if (override_name && PyUnicodeOrString_Check(override_name)) { class_key = PyUnicode_AsUTF8(override_name); } else if (override_name && PyUnicodeOrString_Check(override_name)) { class_key = PyUnicode_AsUTF8(override_name); } else if (!override_name) PyErr_Clear(); if (!unreal_engine_add_function(new_class, class_key, value, func_flags)) { UE_LOG(LogPython, Error, TEXT("unable to add function %s"), UTF8_TO_TCHAR(class_key)); return -1; } prop_added = true; } if (!prop_added) { UE_LOG(LogPython, Warning, TEXT("Adding %s as attr"), UTF8_TO_TCHAR(class_key)); PyObject_SetAttr((PyObject *)self, key, value); } } if (PyDict_Size(py_additional_properties) > 0) { PyObject_SetAttrString((PyObject *)self, (char*)"__additional_uproperties__", py_additional_properties); } UPythonClass *new_u_py_class = (UPythonClass *)new_class; // TODO: check if we can use this to decref the ue_PyUbject mapped to the class new_u_py_class->py_uobject = self; new_u_py_class->ClassConstructor = [](const FObjectInitializer &ObjectInitializer) { FScopePythonGIL gil; UClass *u_class = ue_py_class_constructor_placeholder ? ue_py_class_constructor_placeholder : ObjectInitializer.GetClass(); ue_py_class_constructor_placeholder = nullptr; UEPyClassConstructor(u_class->GetSuperClass(), ObjectInitializer); if (UPythonClass *u_py_class_casted = Cast<UPythonClass>(u_class)) { ue_PyUObject *new_self = ue_get_python_uobject(ObjectInitializer.GetObj()); if (!new_self) { unreal_engine_py_log_error(); return; } // fill __dict__ from class if (u_py_class_casted->py_uobject && u_py_class_casted->py_uobject->py_dict) { PyObject *found_additional_props = PyDict_GetItemString(u_py_class_casted->py_uobject->py_dict, (char *)"__additional_uproperties__"); // manage UProperties (and automatically maps multicast properties) if (found_additional_props) { PyObject *keys = PyDict_Keys(found_additional_props); Py_ssize_t items_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < items_len; i++) { PyObject *mc_key = PyList_GetItem(keys, i); PyObject *mc_value = PyDict_GetItem(found_additional_props, mc_key); char *mc_name = PyUnicode_AsUTF8(mc_key); UProperty *u_property = ObjectInitializer.GetObj()->GetClass()->FindPropertyByName(FName(UTF8_TO_TCHAR(mc_name))); if (u_property) { if (auto casted_prop = Cast<UMulticastDelegateProperty>(u_property)) { FMulticastScriptDelegate multiscript_delegate = casted_prop->GetPropertyValue_InContainer(ObjectInitializer.GetObj()); FScriptDelegate script_delegate; UPythonDelegate *py_delegate = FUnrealEnginePythonHouseKeeper::Get()->NewDelegate(ObjectInitializer.GetObj(), mc_value, casted_prop->SignatureFunction); // fake UFUNCTION for bypassing checks script_delegate.BindUFunction(py_delegate, FName("PyFakeCallable")); // add the new delegate multiscript_delegate.Add(script_delegate); // re-assign multicast delegate casted_prop->SetPropertyValue_InContainer(ObjectInitializer.GetObj(), multiscript_delegate); } else { PyObject_SetAttr((PyObject *)new_self, mc_key, mc_value); } } } Py_DECREF(keys); } else { PyErr_Clear(); } PyObject *keys = PyDict_Keys(u_py_class_casted->py_uobject->py_dict); Py_ssize_t keys_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < keys_len; i++) { PyObject *key = PyList_GetItem(keys, i); PyObject *value = PyDict_GetItem(u_py_class_casted->py_uobject->py_dict, key); if (PyUnicode_Check(key)) { char *key_name = PyUnicode_AsUTF8(key); if (!strcmp(key_name, (char *)"__additional_uproperties__")) continue; } // special case to bound function to method if (PyFunction_Check(value)) { PyObject *bound_function = PyObject_CallMethod(value, (char*)"__get__", (char*)"O", (PyObject *)new_self); if (bound_function) { PyObject_SetAttr((PyObject *)new_self, key, bound_function); Py_DECREF(bound_function); } else { unreal_engine_py_log_error(); } } else { PyObject_SetAttr((PyObject *)new_self, key, value); } } Py_DECREF(keys); } // call __init__ u_py_class_casted->CallPyConstructor(new_self); } }; if (self->py_dict) { ue_PyUObject *new_default_self = ue_get_python_uobject(new_u_py_class->ClassDefaultObject); if (!new_default_self) { unreal_engine_py_log_error(); UE_LOG(LogPython, Error, TEXT("unable to set dict on new ClassDefaultObject")); return -1; } PyObject *keys = PyDict_Keys(self->py_dict); Py_ssize_t keys_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < keys_len; i++) { PyObject *key = PyList_GetItem(keys, i); PyObject *value = PyDict_GetItem(self->py_dict, key); // special case to bound function to method if (PyFunction_Check(value)) { PyObject *bound_function = PyObject_CallMethod(value, (char*)"__get__", (char*)"O", (PyObject *)new_default_self); if (bound_function) { PyObject_SetAttr((PyObject *)new_default_self, key, bound_function); Py_DECREF(bound_function); } else { unreal_engine_py_log_error(); } } else { PyObject_SetAttr((PyObject *)new_default_self, key, value); } } Py_DECREF(keys); } // add default uproperties values if (py_additional_properties) { ue_PyUObject *new_default_self = ue_get_python_uobject(new_u_py_class->ClassDefaultObject); if (!new_default_self) { unreal_engine_py_log_error(); UE_LOG(LogPython, Error, TEXT("unable to set properties on new ClassDefaultObject")); return -1; } PyObject *keys = PyDict_Keys(py_additional_properties); Py_ssize_t keys_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < keys_len; i++) { PyObject *key = PyList_GetItem(keys, i); PyObject *value = PyDict_GetItem(py_additional_properties, key); PyObject_SetAttr((PyObject *)new_default_self, key, value); } Py_DECREF(keys); } // add custom constructor (__init__) PyObject *py_init = PyDict_GetItemString(class_attributes, (char *)"__init__"); if (py_init && PyCallable_Check(py_init)) { // fake initializer FObjectInitializer initializer(new_u_py_class->ClassDefaultObject, nullptr, false, true); new_u_py_class->SetPyConstructor(py_init); ue_PyUObject *new_default_self = ue_get_python_uobject(new_u_py_class->ClassDefaultObject); if (!new_default_self) { unreal_engine_py_log_error(); UE_LOG(LogPython, Error, TEXT("unable to call __init__ on new ClassDefaultObject")); return -1; } new_u_py_class->CallPyConstructor(new_default_self); } } return 0; }
14,996
7,076
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/Types/generated/Vector3.hpp> #include <RED4ext/Types/generated/anim/AnimNode_OnePoseInput.hpp> #include <RED4ext/Types/generated/anim/ConstraintWeightMode.hpp> #include <RED4ext/Types/generated/anim/NamedTrackIndex.hpp> #include <RED4ext/Types/generated/anim/TransformIndex.hpp> namespace RED4ext { namespace anim { struct AnimNode_AimConstraint_ObjectUp : anim::AnimNode_OnePoseInput { static constexpr const char* NAME = "animAnimNode_AimConstraint_ObjectUp"; static constexpr const char* ALIAS = NAME; anim::TransformIndex targetTransform; // 60 anim::TransformIndex upTransform; // 78 Vector3 forwardAxisLS; // 90 Vector3 upAxisLS; // 9C anim::TransformIndex transformIndex; // A8 anim::ConstraintWeightMode weightMode; // C0 float weight; // C4 anim::NamedTrackIndex weightFloatTrack; // C8 uint8_t unkE0[0x108 - 0xE0]; // E0 }; RED4EXT_ASSERT_SIZE(AnimNode_AimConstraint_ObjectUp, 0x108); } // namespace anim } // namespace RED4ext
1,156
393
#include "CppUTest/TestHarness.h" #include <string.h> #include <stdio.h> #define NO_OF_INPUT_REGS 10 #define INPUT_REG_START_ADDRESS 0 extern "C" { #include "mbap_conf.h" #include "mbap.h" } #define QUERY_SIZE_IN_BYTES (255u) #define RESPONSE_SIZE_IN_BYTES (255u) #define INPUT_REGISTER_START_ADDRESS (0u) #define MAX_INPUT_REGISTERS (15u) #define HOLDING_REGISTER_START_ADDRESS (0u) #define MAX_HOLDING_REGISTERS (15u) #define DISCRETE_INPUTS_START_ADDRESS (0u) #define MAX_DISCRETE_INPUTS (3u) #define COILS_START_ADDRESS (0u) #define MAX_COILS (3u) #define MBT_EXCEPTION_PACKET_LEN (9u) #define QUERY_LEN (12u) #define NO_OF_DATA_OFFSET (10u) #define DATA_START_ADDRESS_OFFSET (8u) #define REGISTER_VALUE_OFFSET (10u) //PDU Offset in response #define MBT_BYTE_COUNT_OFFSET (8u) #define MBT_DATA_VALUES_OFFSET (9u) #define MBAP_HEADER_LEN (7u) #define DISCRETE_INPUT_BUF_SIZE (MAX_DISCRETE_INPUTS / 8u + 1u) #define COILS_BUF_SIZE (MAX_COILS / 8u + 1u) int16_t g_sInputRegsBuf[MAX_INPUT_REGISTERS] = {1, 2, 3}; int16_t g_sHoldingRegsBuf[MAX_HOLDING_REGISTERS] = {5, 6, 7}; uint8_t g_ucDiscreteInputsBuf[DISCRETE_INPUT_BUF_SIZE] = {0xef}; uint8_t g_ucCoilsBuf[COILS_BUF_SIZE] = {5}; int16_t g_sHoldingRegsLowerLimitBuf[MAX_HOLDING_REGISTERS] = {0, 0, 0}; int16_t g_sHoldingRegsHigherLimitBuf[MAX_HOLDING_REGISTERS] = {200, 200, 200}; TEST_GROUP(Module) { uint8_t *pucQuery = NULL; uint8_t *pucResponse = NULL; int16_t *psInputRegisters = NULL; int16_t *psHoldingRegisters = NULL; ModbusData_t *pModbusData = NULL; void setup() { pucQuery = (uint8_t*)calloc(QUERY_SIZE_IN_BYTES, sizeof(uint8_t)); pucResponse = (uint8_t*)calloc(RESPONSE_SIZE_IN_BYTES, sizeof(uint8_t)); pModbusData = (ModbusData_t*)calloc(1, sizeof(ModbusData_t)); pModbusData->psInputRegisters = g_sInputRegsBuf; pModbusData->usInputRegisterStartAddress = INPUT_REGISTER_START_ADDRESS; pModbusData->usMaxInputRegisters = MAX_INPUT_REGISTERS; pModbusData->psHoldingRegisters = g_sHoldingRegsBuf; pModbusData->usHoldingRegisterStartAddress = HOLDING_REGISTER_START_ADDRESS; pModbusData->usMaxHoldingRegisters = MAX_HOLDING_REGISTERS; pModbusData->psHoldingRegisterLowerLimit = g_sHoldingRegsLowerLimitBuf; pModbusData->psHoldingRegisterHigherLimit = g_sHoldingRegsHigherLimitBuf; pModbusData->pucDiscreteInputs = g_ucDiscreteInputsBuf; pModbusData->usDiscreteInputStartAddress = DISCRETE_INPUTS_START_ADDRESS; pModbusData->usMaxDiscreteInputs = MAX_DISCRETE_INPUTS; pModbusData->pucCoils = g_ucCoilsBuf; pModbusData->usCoilsStartAddress = COILS_START_ADDRESS; pModbusData->usMaxCoils = MAX_COILS; mbap_DataInit(pModbusData); } void teardown() { free(pucQuery); free(pucResponse); free(pModbusData); } }; TEST(Module, read_input_registers) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 4, 0, 5, 0, 3}; uint8_t ucResponseLen = 0; uint8_t ucByteCount = 0; uint16_t usNumOfData = 0; uint16_t usStartAddress = 0; usStartAddress = (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET] << 8); usStartAddress |= (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET + 1]); usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8); usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]); ucResponseLen = MBAP_HEADER_LEN + (usNumOfData * 2) + 2; ucByteCount = usNumOfData * 2; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]); for (uint8_t ucCount = 0; ucCount < usNumOfData; ucCount++) { int16_t sReceivedValue = 0; sReceivedValue = (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2)] << 8); sReceivedValue |= (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2) + 1]); CHECK_EQUAL(g_sInputRegsBuf[ucCount + usStartAddress], sReceivedValue); } } TEST(Module, illegal_input_registers_address) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 4, 0, 0, 0, 16}; uint8_t ucResponseLen = 0; ucResponseLen = MBT_EXCEPTION_PACKET_LEN; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ILLEGAL_DATA_ADDRESS, pucResponse[MBT_BYTE_COUNT_OFFSET] ); } TEST(Module, read_holding_registers) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 3, 0, 5, 0, 3}; uint8_t ucResponseLen = 0; uint8_t ucByteCount = 0; uint16_t usNumOfData = 0; uint16_t usStartAddress = 0; usStartAddress = (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET] << 8); usStartAddress |= (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET + 1]); usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8); usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]); ucResponseLen = MBAP_HEADER_LEN + (usNumOfData * 2) + 2; ucByteCount = usNumOfData * 2; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]); for (uint8_t ucCount = 0; ucCount < usNumOfData; ucCount++) { int16_t sReceivedValue = 0; sReceivedValue = (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2)] << 8); sReceivedValue |= (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2) + 1]); CHECK_EQUAL(g_sHoldingRegsBuf[ucCount + usStartAddress], sReceivedValue); } } TEST(Module, illegal_holding_registers_address) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 3, 0, 0, 0, 16}; uint8_t ucResponseLen = 0; ucResponseLen = MBT_EXCEPTION_PACKET_LEN; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ILLEGAL_DATA_ADDRESS, pucResponse[MBT_BYTE_COUNT_OFFSET] ); } TEST(Module, illegal_function_code) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 10, 0, 0, 0, 11}; uint8_t ucResponseLen = 0; ucResponseLen = MBT_EXCEPTION_PACKET_LEN; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ILLEGAL_FUNCTION_CODE, pucResponse[MBT_BYTE_COUNT_OFFSET] ); } TEST(Module, write_single_holding_register) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 6, 0, 1, 0, 200}; uint8_t ucResponseLen = 0; int16_t sReceivedValue = 0; int16_t sSentValue = 0; ucResponseLen = MBAP_HEADER_LEN + 5; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); sReceivedValue = (int16_t)(pucResponse[REGISTER_VALUE_OFFSET] << 8); sReceivedValue |= (int16_t)(pucResponse[REGISTER_VALUE_OFFSET + 1]); sSentValue = (int16_t)(ucQueryBuf[REGISTER_VALUE_OFFSET] << 8); sSentValue |= (int16_t)(ucQueryBuf[REGISTER_VALUE_OFFSET + 1]); CHECK_EQUAL(sSentValue, sReceivedValue); } TEST(Module, illega_data_value) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 6, 0, 1, 0, 201}; uint8_t ucResponseLen = 0; ucResponseLen = MBT_EXCEPTION_PACKET_LEN; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ILLEGAL_DATA_VALUE, pucResponse[MBT_BYTE_COUNT_OFFSET] ); } TEST(Module, read_discrete_inputs) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 2, 0, 0, 0, 3}; uint8_t ucResponseLen = 0; uint8_t ucByteCount = 0; uint16_t usNumOfData = 0; usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8); usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]); ucResponseLen = MBAP_HEADER_LEN + (usNumOfData / 8) + 2; ucByteCount = usNumOfData / 8; if (0 != ucQueryBuf[11]) { ucResponseLen = ucResponseLen + 1; ucByteCount = ucByteCount + 1; } memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]); for (uint8_t ucCount = 0; ucCount < MAX_DISCRETE_INPUTS; ucCount++) { uint8_t ucReceivedValue = 0; uint16_t usByteOffset = 0; uint16_t usDiscreteBit = 0; usByteOffset = ucCount / 8 ; usDiscreteBit = ucCount - usByteOffset * 8; ucReceivedValue = (uint8_t)(pucResponse[MBT_DATA_VALUES_OFFSET + usByteOffset]); CHECK_EQUAL(g_ucDiscreteInputsBuf[usByteOffset] & (1 << usDiscreteBit) , ucReceivedValue & (1 << usDiscreteBit)); } } TEST(Module, read_coils) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 1, 0, 0, 0, 3}; uint8_t ucResponseLen = 0; uint8_t ucByteCount = 0; uint16_t usNumOfData = 0; usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8); usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]); ucResponseLen = MBAP_HEADER_LEN + (usNumOfData / 8) + 2; ucByteCount = usNumOfData / 8; if (0 != ucQueryBuf[11]) { ucResponseLen = ucResponseLen + 1; ucByteCount = ucByteCount + 1; } memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]); for (uint8_t ucCount = 0; ucCount < MAX_COILS; ucCount++) { uint8_t ucReceivedValue = 0; uint16_t usByteOffset = 0; uint16_t usCoilsBit = 0; usByteOffset = ucCount / 8 ; usCoilsBit = ucCount - usByteOffset * 8; ucReceivedValue = (uint8_t)(pucResponse[MBT_DATA_VALUES_OFFSET + usByteOffset]); CHECK_EQUAL(g_ucCoilsBuf[usByteOffset] & (1 << usCoilsBit) , ucReceivedValue & (1 << usCoilsBit)); } } TEST(Module, write_coil) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 1, 0, 0, 0, 3}; uint8_t ucResponseLen = 0; uint8_t ucByteCount = 0; uint16_t usNumOfData = 0; usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8); usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]); ucResponseLen = MBAP_HEADER_LEN + (usNumOfData / 8) + 2; ucByteCount = usNumOfData / 8; if (0 != ucQueryBuf[11]) { ucResponseLen = ucResponseLen + 1; ucByteCount = ucByteCount + 1; } memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]); for (uint8_t ucCount = 0; ucCount < MAX_COILS; ucCount++) { uint8_t ucReceivedValue = 0; uint16_t usByteOffset = 0; uint16_t usCoilsBit = 0; usByteOffset = ucCount / 8 ; usCoilsBit = ucCount - usByteOffset * 8; ucReceivedValue = (uint8_t)(pucResponse[MBT_DATA_VALUES_OFFSET + usByteOffset]); CHECK_EQUAL(g_ucCoilsBuf[usByteOffset] & (1 << usCoilsBit) , ucReceivedValue & (1 << usCoilsBit)); } }
11,677
5,438
#include <iostream> #include <cpptest.h> #include "MainTestHarness.h" #include "UnitTests/PacketQueueTests.h" #define RUN_MAIN_TEST_HARNESS // Comment this line if you want to run unit tests, otherwise this will trigger MainTestHarness to execute using namespace std; enum OutputType { Compiler, Html, TextTerse, TextVerbose }; static void usage() { cout << "usage: mytest [MODE]\n" << "where MODE may be one of:\n" << " --compiler\n" << " --html\n" << " --text-terse (default)\n" << " --text-verbose\n"; exit(0); } static auto_ptr<Test::Output> cmdline(int argc, char* argv[]) { if (argc > 2) usage(); // will not return Test::Output* output = 0; if (argc == 1) output = new Test::TextOutput(Test::TextOutput::Verbose); else { const char* arg = argv[1]; if (strcmp(arg, "--compiler") == 0) output = new Test::CompilerOutput; else if (strcmp(arg, "--html") == 0) output = new Test::HtmlOutput; else if (strcmp(arg, "--text-terse") == 0) output = new Test::TextOutput(Test::TextOutput::Terse); else if (strcmp(arg, "--text-verbose") == 0) output = new Test::TextOutput(Test::TextOutput::Verbose); else { cout << "invalid commandline argument: " << arg << endl; usage(); // will not return } } return auto_ptr<Test::Output>(output); } int run_tests(int argc, char* argv[]) { try { // Demonstrates the ability to use multiple test suites // Test::Suite ts; ts.add(auto_ptr<Test::Suite>(new PacketQueueTests)); // Run the tests // auto_ptr<Test::Output> output(cmdline(argc, argv)); ts.run(*output, true); Test::HtmlOutput* const html = dynamic_cast<Test::HtmlOutput*>(output.get()); if (html) html->generate(cout, true, "MyTest"); } catch (...) { cout << "unexpected exception encountered\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } // Main test program // int main(int argc, char* argv[]) { #ifdef RUN_MAIN_TEST_HARNESS MainTestHarness test; return test.Run(argc, argv); #else return run_tests(argc, argv); #endif }
2,034
818
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TGUI - Texus's Graphical User Interface // Copyright (C) 2012-2017 Bruno Van de Velde (vdv_b@tgui.eu) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "Tests.hpp" #include <TGUI/TGUI.hpp> TEST_CASE("[Widget]") { tgui::Widget::Ptr widget = std::make_shared<tgui::Button>(); SECTION("Visibile") { REQUIRE(widget->isVisible()); widget->hide(); REQUIRE(!widget->isVisible()); widget->show(); REQUIRE(widget->isVisible()); } SECTION("Enabled") { REQUIRE(widget->isEnabled()); widget->disable(); REQUIRE(!widget->isEnabled()); widget->enable(); REQUIRE(widget->isEnabled()); } SECTION("Parent") { tgui::Panel::Ptr panel1 = std::make_shared<tgui::Panel>(); tgui::Panel::Ptr panel2 = std::make_shared<tgui::Panel>(); tgui::Panel::Ptr panel3 = std::make_shared<tgui::Panel>(); REQUIRE(widget->getParent() == nullptr); panel1->add(widget); REQUIRE(widget->getParent() == panel1.get()); panel1->remove(widget); REQUIRE(widget->getParent() == nullptr); panel2->add(widget); REQUIRE(widget->getParent() == panel2.get()); widget->setParent(panel3.get()); REQUIRE(widget->getParent() == panel3.get()); widget->setParent(nullptr); REQUIRE(widget->getParent() == nullptr); } SECTION("Opacity") { REQUIRE(widget->getOpacity() == 1.f); widget->setOpacity(0.5f); REQUIRE(widget->getOpacity() == 0.5f); widget->setOpacity(2.f); REQUIRE(widget->getOpacity() == 1.f); widget->setOpacity(-2.f); REQUIRE(widget->getOpacity() == 0.f); } SECTION("Tooltip") { auto tooltip1 = std::make_shared<tgui::Label>(); tooltip1->setText("some text"); widget->setToolTip(tooltip1); REQUIRE(widget->getToolTip() == tooltip1); // ToolTip does not has to be a label auto tooltip2 = std::make_shared<tgui::Panel>(); widget->setToolTip(tooltip2); REQUIRE(widget->getToolTip() == tooltip2); // ToolTip can be removed widget->setToolTip(nullptr); REQUIRE(widget->getToolTip() == nullptr); } SECTION("Font") { widget = std::make_shared<tgui::Button>(); REQUIRE(widget->getFont() == nullptr); widget->setFont("resources/DroidSansArmenian.ttf"); REQUIRE(widget->getFont() != nullptr); widget->setFont(nullptr); REQUIRE(widget->getFont() == nullptr); tgui::Gui gui; gui.add(widget); REQUIRE(widget->getFont() != nullptr); } SECTION("Move to front/back") { auto container = std::make_shared<tgui::Panel>(); auto widget1 = std::make_shared<tgui::Button>(); auto widget2 = std::make_shared<tgui::Button>(); auto widget3 = std::make_shared<tgui::Button>(); container->add(widget1); container->add(widget2); container->add(widget3); REQUIRE(container->getWidgets().size() == 3); REQUIRE(container->getWidgets()[0] == widget1); REQUIRE(container->getWidgets()[1] == widget2); REQUIRE(container->getWidgets()[2] == widget3); widget1->moveToFront(); REQUIRE(container->getWidgets().size() == 3); REQUIRE(container->getWidgets()[0] == widget2); REQUIRE(container->getWidgets()[1] == widget3); REQUIRE(container->getWidgets()[2] == widget1); widget3->moveToFront(); REQUIRE(container->getWidgets().size() == 3); REQUIRE(container->getWidgets()[0] == widget2); REQUIRE(container->getWidgets()[1] == widget1); REQUIRE(container->getWidgets()[2] == widget3); widget1->moveToBack(); REQUIRE(container->getWidgets().size() == 3); REQUIRE(container->getWidgets()[0] == widget1); REQUIRE(container->getWidgets()[1] == widget2); REQUIRE(container->getWidgets()[2] == widget3); widget2->moveToBack(); REQUIRE(container->getWidgets().size() == 3); REQUIRE(container->getWidgets()[0] == widget2); REQUIRE(container->getWidgets()[1] == widget1); REQUIRE(container->getWidgets()[2] == widget3); } SECTION("Layouts") { auto container = std::make_shared<tgui::Panel>(); auto widget2 = std::make_shared<tgui::Button>(); container->add(widget); container->add(widget2, "w2"); widget2->setPosition(100, 50); widget2->setSize(600, 150); widget->setPosition(20, 10); widget->setSize(100, 30); SECTION("Position") { REQUIRE(widget->getPosition() == sf::Vector2f(20, 10)); widget->setPosition(tgui::bindLeft(widget2), {"w2.y"}); REQUIRE(widget->getPosition() == sf::Vector2f(100, 50)); widget2->setPosition(50, 30); REQUIRE(widget->getPosition() == sf::Vector2f(50, 30)); // String layout only works after adding widget to parent auto widget3 = widget->clone(); REQUIRE(widget3->getPosition() == sf::Vector2f(50, 0)); container->add(widget3); REQUIRE(widget3->getPosition() == sf::Vector2f(50, 30)); // Layout can only be copied when it is a string widget2->setPosition(20, 40); REQUIRE(widget3->getPosition() == sf::Vector2f(50, 40)); // String is re-evaluated and new widgets are bound after copying widget->setPosition({"{width, height}"}); REQUIRE(widget->getPosition() == sf::Vector2f(100, 30)); auto widget4 = widget->clone(); widget->setSize(40, 50); REQUIRE(widget4->getPosition() == sf::Vector2f(100, 30)); widget4->setSize(60, 70); REQUIRE(widget4->getPosition() == sf::Vector2f(60, 70)); } SECTION("Size") { REQUIRE(widget->getSize() == sf::Vector2f(100, 30)); widget->setSize({"w2.width"}, tgui::bindHeight(widget2)); REQUIRE(widget->getSize() == sf::Vector2f(600, 150)); widget2->setSize(50, 30); REQUIRE(widget->getSize() == sf::Vector2f(50, 30)); // String layout only works after adding widget to parent auto widget3 = widget->clone(); REQUIRE(widget3->getSize() == sf::Vector2f(0, 30)); container->add(widget3); REQUIRE(widget3->getSize() == sf::Vector2f(50, 30)); // Layout can only be copied when it is a string widget2->setSize(20, 40); REQUIRE(widget3->getSize() == sf::Vector2f(20, 30)); // String is re-evaluated and new widgets are bound after copying widget->setSize({"position"}); REQUIRE(widget->getSize() == sf::Vector2f(20, 10)); auto widget4 = widget->clone(); widget->setPosition(40, 50); REQUIRE(widget4->getSize() == sf::Vector2f(20, 10)); widget4->setPosition(60, 70); REQUIRE(widget4->getSize() == sf::Vector2f(60, 70)); } } SECTION("Saving and loading widget with layouts from file") { auto parent = std::make_shared<tgui::Panel>(); parent->add(widget, "Widget Name.With:Special{Chars}"); SECTION("Bind 2d non-string") { widget->setPosition(tgui::bindPosition(parent)); widget->setSize(tgui::bindSize(parent)); parent->setSize(400, 300); parent->setPosition(50, 50); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt")); parent->removeAllWidgets(); REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt")); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt")); REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt")); widget = parent->get("Widget Name.With:Special{Chars}"); // Non-string layouts cannot be saved yet! parent->setPosition(100, 100); parent->setSize(800, 600); REQUIRE(widget->getPosition() == sf::Vector2f(50, 50)); REQUIRE(widget->getSize() == sf::Vector2f(400, 300)); } SECTION("Bind 1d non-strings and string combination") { widget->setPosition(tgui::bindLeft(parent), {"parent.top"}); widget->setSize({"parent.width"}, tgui::bindHeight(parent)); parent->setSize(400, 300); parent->setPosition(50, 50); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt")); parent->removeAllWidgets(); REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt")); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt")); REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt")); widget = parent->get("Widget Name.With:Special{Chars}"); // Non-string layout cannot be saved yet, string layout will have been saved correctly! parent->setPosition(100, 100); parent->setSize(800, 600); REQUIRE(widget->getPosition() == sf::Vector2f(50, 100)); REQUIRE(widget->getSize() == sf::Vector2f(800, 300)); } SECTION("Bind 1d strings") { widget->setPosition({"&.x"}, {"&.y"}); widget->setSize({"&.w"}, {"&.h"}); parent->setSize(400, 300); parent->setPosition(50, 50); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt")); parent->removeAllWidgets(); REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt")); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt")); REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt")); widget = parent->get("Widget Name.With:Special{Chars}"); parent->setPosition(100, 100); parent->setSize(800, 600); REQUIRE(widget->getPosition() == sf::Vector2f(100, 100)); REQUIRE(widget->getSize() == sf::Vector2f(800, 600)); } SECTION("Bind 2d strings") { widget->setPosition({"{&.x, &.y}"}); widget->setSize({"parent.size"}); parent->setSize(400, 300); parent->setPosition(50, 50); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt")); parent->removeAllWidgets(); REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt")); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt")); REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt")); widget = parent->get("Widget Name.With:Special{Chars}"); parent->setPosition(100, 100); parent->setSize(800, 600); REQUIRE(widget->getPosition() == sf::Vector2f(100, 100)); REQUIRE(widget->getSize() == sf::Vector2f(800, 600)); } } SECTION("Bug Fixes") { SECTION("Disabled widgets should not be focusable (https://forum.tgui.eu/index.php?topic=384)") { tgui::Panel::Ptr panel = std::make_shared<tgui::Panel>(); tgui::EditBox::Ptr editBox = std::make_shared<tgui::EditBox>(); editBox->setFont("resources/DroidSansArmenian.ttf"); panel->add(editBox); editBox->focus(); REQUIRE(editBox->isFocused()); editBox->disable(); REQUIRE(!editBox->isFocused()); editBox->focus(); REQUIRE(!editBox->isFocused()); } } }
12,845
4,169
#include <torch/Node.h> #include <algorithm> #include <torch/Context.h> #include <torch/Link.h> #include <torch/Object.h> namespace torch { Node::Node(std::shared_ptr<Context> context) : Object(context) { } size_t Node::GetChildCount() const { return m_children.size(); } std::shared_ptr<Node> Node::GetChild(size_t index) const { return m_children[index]; } bool Node::HasChild(std::shared_ptr<const Node> child) const { auto iter = std::find(m_children.begin(), m_children.end(), child); return iter != m_children.end(); } void Node::AddChild(std::shared_ptr<Node> child) { if (CanAddChild(child)) { m_children.push_back(child); m_context->MarkDirty(); } } void Node::RemoveChild(std::shared_ptr<const Node> child) { auto iter = std::find(m_children.begin(), m_children.end(), child); if (iter != m_children.end()) { m_children.erase(iter); m_context->MarkDirty(); } } void Node::RemoveChildren() { if (!m_children.empty()) { m_children.clear(); m_context->MarkDirty(); } } void Node::PreBuildScene() { } void Node::BuildScene(Link& link) { BuildChildScene(link); } void Node::PostBuildScene() { } void Node::BuildScene(optix::Variable variable) { Link link(m_context); BuildScene(link); link.Write(variable); } BoundingBox Node::GetBounds(const Transform& transform) { return GetChildBounds(transform); } BoundingBox Node::GetChildBounds(const Transform& transform) { BoundingBox bounds; const Transform childTransform = transform * m_transform; for (std::shared_ptr<Node> child : m_children) { bounds.Union(child->GetBounds(childTransform)); } return bounds; } void Node::BuildChildScene(Link& link) { Link childLink = link.Branch(m_transform); for (std::shared_ptr<Node> child : m_children) { child->BuildScene(childLink); } } bool Node::CanAddChild(std::shared_ptr<const Node> child) const { return child && child.get() != this && !HasChild(child); } void Node::UpdateTransform() { m_context->MarkDirty(); } } // namespace torch
2,052
740
/*! * Copyright (c) 2020-2021 by Contributors * \file json_serializer.cc * \brief Reference serializer implementation, which serializes to JSON. This is useful for testing * correctness of the binary serializer * \author Hyunsu Cho */ #include <treelite/tree.h> #include <treelite/logging.h> #include <rapidjson/ostreamwrapper.h> #include <rapidjson/writer.h> #include <rapidjson/prettywriter.h> #include <ostream> #include <type_traits> #include <cstdint> #include <cstddef> namespace { template <typename WriterType, typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = true> void WriteElement(WriterType& writer, T e) { writer.Uint64(static_cast<uint64_t>(e)); } template <typename WriterType, typename T, typename std::enable_if<std::is_floating_point<T>::value, bool>::type = true> void WriteElement(WriterType& writer, T e) { writer.Double(static_cast<double>(e)); } template <typename WriterType> void WriteString(WriterType& writer, const std::string& str) { writer.String(str.data(), str.size()); } template <typename WriterType, typename ThresholdType, typename LeafOutputType> void WriteNode(WriterType& writer, const treelite::Tree<ThresholdType, LeafOutputType>& tree, int node_id) { writer.StartObject(); writer.Key("node_id"); writer.Int(node_id); if (tree.IsLeaf(node_id)) { writer.Key("leaf_value"); if (tree.HasLeafVector(node_id)) { writer.StartArray(); for (LeafOutputType e : tree.LeafVector(node_id)) { WriteElement(writer, e); } writer.EndArray(); } else { WriteElement(writer, tree.LeafValue(node_id)); } } else { writer.Key("split_feature_id"); writer.Uint(tree.SplitIndex(node_id)); writer.Key("default_left"); writer.Bool(tree.DefaultLeft(node_id)); writer.Key("split_type"); auto split_type = tree.SplitType(node_id); WriteString(writer, treelite::SplitFeatureTypeName(split_type)); if (split_type == treelite::SplitFeatureType::kNumerical) { writer.Key("comparison_op"); WriteString(writer, treelite::OpName(tree.ComparisonOp(node_id))); writer.Key("threshold"); writer.Double(tree.Threshold(node_id)); } else if (split_type == treelite::SplitFeatureType::kCategorical) { writer.Key("categories_list_right_child"); writer.Bool(tree.CategoriesListRightChild(node_id)); writer.Key("matching_categories"); writer.StartArray(); for (uint32_t e : tree.MatchingCategories(node_id)) { writer.Uint(e); } writer.EndArray(); } writer.Key("left_child"); writer.Int(tree.LeftChild(node_id)); writer.Key("right_child"); writer.Int(tree.RightChild(node_id)); } if (tree.HasDataCount(node_id)) { writer.Key("data_count"); writer.Uint64(tree.DataCount(node_id)); } if (tree.HasSumHess(node_id)) { writer.Key("sum_hess"); writer.Double(tree.SumHess(node_id)); } if (tree.HasGain(node_id)) { writer.Key("gain"); writer.Double(tree.Gain(node_id)); } writer.EndObject(); } template <typename WriterType> void SerializeTaskParamToJSON(WriterType& writer, treelite::TaskParam task_param) { writer.StartObject(); writer.Key("output_type"); WriteString(writer, treelite::OutputTypeToString(task_param.output_type)); writer.Key("grove_per_class"); writer.Bool(task_param.grove_per_class); writer.Key("num_class"); writer.Uint(task_param.num_class); writer.Key("leaf_vector_size"); writer.Uint(task_param.leaf_vector_size); writer.EndObject(); } template <typename WriterType> void SerializeModelParamToJSON(WriterType& writer, treelite::ModelParam model_param) { writer.StartObject(); writer.Key("pred_transform"); WriteString(writer, std::string(model_param.pred_transform)); writer.Key("sigmoid_alpha"); writer.Double(model_param.sigmoid_alpha); writer.Key("global_bias"); writer.Double(model_param.global_bias); writer.EndObject(); } } // anonymous namespace namespace treelite { template <typename WriterType, typename ThresholdType, typename LeafOutputType> void DumpTreeAsJSON(WriterType& writer, const Tree<ThresholdType, LeafOutputType>& tree) { writer.StartObject(); writer.Key("num_nodes"); writer.Int(tree.num_nodes); writer.Key("nodes"); writer.StartArray(); for (std::size_t i = 0; i < tree.nodes_.Size(); ++i) { WriteNode<WriterType, ThresholdType, LeafOutputType>(writer, tree, i); } writer.EndArray(); writer.EndObject(); // Basic checks TREELITE_CHECK_EQ(tree.nodes_.Size(), tree.num_nodes); TREELITE_CHECK_EQ(tree.nodes_.Size() + 1, tree.matching_categories_offset_.Size()); TREELITE_CHECK_EQ(tree.matching_categories_offset_.Back(), tree.matching_categories_.Size()); } template <typename WriterType, typename ThresholdType, typename LeafOutputType> void DumpModelAsJSON(WriterType& writer, const ModelImpl<ThresholdType, LeafOutputType>& model) { writer.StartObject(); writer.Key("num_feature"); writer.Int(model.num_feature); writer.Key("task_type"); WriteString(writer, TaskTypeToString(model.task_type)); writer.Key("average_tree_output"); writer.Bool(model.average_tree_output); writer.Key("task_param"); SerializeTaskParamToJSON(writer, model.task_param); writer.Key("model_param"); SerializeModelParamToJSON(writer, model.param); writer.Key("trees"); writer.StartArray(); for (const Tree<ThresholdType, LeafOutputType>& tree : model.trees) { DumpTreeAsJSON(writer, tree); } writer.EndArray(); writer.EndObject(); } template <typename ThresholdType, typename LeafOutputType> void ModelImpl<ThresholdType, LeafOutputType>::DumpAsJSON(std::ostream& fo, bool pretty_print) const { rapidjson::OStreamWrapper os(fo); if (pretty_print) { rapidjson::PrettyWriter<rapidjson::OStreamWrapper> writer(os); writer.SetFormatOptions(rapidjson::PrettyFormatOptions::kFormatSingleLineArray); DumpModelAsJSON(writer, *this); } else { rapidjson::Writer<rapidjson::OStreamWrapper> writer(os); DumpModelAsJSON(writer, *this); } } template void ModelImpl<float, uint32_t>::DumpAsJSON(std::ostream& fo, bool pretty_print) const; template void ModelImpl<float, float>::DumpAsJSON(std::ostream& fo, bool pretty_print) const; template void ModelImpl<double, uint32_t>::DumpAsJSON(std::ostream& fo, bool pretty_print) const; template void ModelImpl<double, double>::DumpAsJSON(std::ostream& fo, bool pretty_print) const; } // namespace treelite
6,545
2,208
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/experimental/micro/examples/micro_speech/command_responder.h" #include "LCD_DISCO_F746NG.h" LCD_DISCO_F746NG lcd; // When a command is detected, write it to the display and log it to the // serial port. void RespondToCommand(tflite::ErrorReporter *error_reporter, int32_t current_time, const char *found_command, uint8_t score, bool is_new_command) { if (is_new_command) { error_reporter->Report("Heard %s (%d) @%dms", found_command, score, current_time); if (*found_command == 'y') { lcd.Clear(0xFF0F9D58); lcd.DisplayStringAt(0, LINE(5), (uint8_t *)"Heard yes!", CENTER_MODE); } else if (*found_command == 'n') { lcd.Clear(0xFFDB4437); lcd.DisplayStringAt(0, LINE(5), (uint8_t *)"Heard no :(", CENTER_MODE); } else if (*found_command == 'u') { lcd.Clear(0xFFF4B400); lcd.DisplayStringAt(0, LINE(5), (uint8_t *)"Heard unknown", CENTER_MODE); } else { lcd.Clear(0xFF4285F4); lcd.DisplayStringAt(0, LINE(5), (uint8_t *)"Heard silence", CENTER_MODE); } } }
1,801
624
// TnzCore includes #include "tmeshimage.h" #include "tgl.h" #include "tundo.h" // TnzExt includes #include "ext/plasticdeformerstorage.h" // tcg includes #include "tcg/tcg_macros.h" #include "tcg/tcg_point_ops.h" #include <unordered_set> #include <unordered_map> using namespace tcg::bgl; #include <boost/graph/breadth_first_search.hpp> // STD includes #include <stack> #include "plastictool.h" using namespace PlasticToolLocals; //**************************************************************************************** // Local namespace stuff //**************************************************************************************** namespace { typedef PlasticTool::MeshIndex MeshIndex; typedef TTextureMesh::vertex_type vertex_type; typedef TTextureMesh::edge_type edge_type; typedef TTextureMesh::face_type face_type; //------------------------------------------------------------------------ bool borderEdge(const TTextureMesh &mesh, int e) { return (mesh.edge(e).facesCount() < 2); } bool borderVertex(const TTextureMesh &mesh, int v) { const TTextureVertex &vx = mesh.vertex(v); tcg::vertex_traits<TTextureVertex>::edges_const_iterator et, eEnd(vx.edgesEnd()); for (et = vx.edgesBegin(); et != eEnd; ++et) { if (borderEdge(mesh, *et)) return true; } return false; } //============================================================================ bool testSwapEdge(const TTextureMesh &mesh, int e) { return (mesh.edge(e).facesCount() == 2); } //------------------------------------------------------------------------ bool testCollapseEdge(const TTextureMesh &mesh, int e) { struct Locals { const TTextureMesh &m_mesh; int m_e; const TTextureMesh::edge_type &m_ed; bool testTrianglesCount() { // There must be at least one remanining triangle return (m_mesh.facesCount() > m_ed.facesCount()); } bool testBoundary() { // Must not join two non-adjacent boundary vertices return (!borderVertex(m_mesh, m_ed.vertex(0)) || !borderVertex(m_mesh, m_ed.vertex(1)) || borderEdge(m_mesh, m_e)); } bool testAdjacency() { // See TriMesh<>::collapseEdge() // Retrieve allowed adjacent vertices int f, fCount = m_ed.facesCount(); int allowedV[6], *avt, *avEnd = allowedV + 3 * fCount; for (f = 0, avt = allowedV; f != fCount; ++f, avt += 3) m_mesh.faceVertices(m_ed.face(f), avt[0], avt[1], avt[2]); // Test adjacent vertices int v0 = m_ed.vertex(0), v1 = m_ed.vertex(1); const vertex_type &vx0 = m_mesh.vertex(v0); tcg::vertex_traits<vertex_type>::edges_const_iterator et, eEnd = vx0.edgesEnd(); for (et = vx0.edgesBegin(); et != eEnd; ++et) { int otherV = m_mesh.edge(*et).otherVertex(v0); if (m_mesh.edgeInciding(v1, otherV) >= 0) { // Adjacent vertex - must be found in the allowed list if (std::find(allowedV, avEnd, otherV) == avEnd) return false; } } return true; } } locals = {mesh, e, mesh.edge(e)}; return (locals.testTrianglesCount() && locals.testBoundary() && locals.testAdjacency()); } } // namespace //**************************************************************************************** // PlasticToolLocals stuff //**************************************************************************************** namespace PlasticToolLocals { struct Closer { const TTextureMesh &m_mesh; TPointD m_pos; double dist2(const TTextureMesh::vertex_type &a) { return tcg::point_ops::dist2<TPointD>(a.P(), m_pos); } double dist2(const TTextureMesh::edge_type &a) { const TTextureMesh::vertex_type &avx0 = m_mesh.vertex(a.vertex(0)), &avx1 = m_mesh.vertex(a.vertex(1)); return sq(tcg::point_ops::segDist<TPointD>(avx0.P(), avx1.P(), m_pos)); } bool operator()(const TTextureMesh::vertex_type &a, const TTextureMesh::vertex_type &b) { return (dist2(a) < dist2(b)); } bool operator()(const TTextureMesh::edge_type &a, const TTextureMesh::edge_type &b) { return (dist2(a) < dist2(b)); } }; //============================================================================== static std::pair<double, int> closestVertex(const TTextureMesh &mesh, const TPointD &pos) { Closer closer = {mesh, pos}; int vIdx = int( std::min_element(mesh.vertices().begin(), mesh.vertices().end(), closer) .index()); return std::make_pair(closer.dist2(mesh.vertex(vIdx)), vIdx); } //------------------------------------------------------------------------ static std::pair<double, int> closestEdge(const TTextureMesh &mesh, const TPointD &pos) { Closer closer = {mesh, pos}; int eIdx = int(std::min_element(mesh.edges().begin(), mesh.edges().end(), closer) .index()); return std::make_pair(closer.dist2(mesh.edge(eIdx)), eIdx); } //------------------------------------------------------------------------ std::pair<double, MeshIndex> closestVertex(const TMeshImage &mi, const TPointD &pos) { std::pair<double, MeshIndex> closest((std::numeric_limits<double>::max)(), MeshIndex()); const TMeshImage::meshes_container &meshes = mi.meshes(); TMeshImage::meshes_container::const_iterator mt, mEnd = meshes.end(); for (mt = meshes.begin(); mt != mEnd; ++mt) { const std::pair<double, int> &candidateIdx = closestVertex(**mt, pos); std::pair<double, MeshIndex> candidate( candidateIdx.first, MeshIndex(mt - meshes.begin(), candidateIdx.second)); if (candidate < closest) closest = candidate; } return closest; } //------------------------------------------------------------------------ std::pair<double, MeshIndex> closestEdge(const TMeshImage &mi, const TPointD &pos) { std::pair<double, MeshIndex> closest((std::numeric_limits<double>::max)(), MeshIndex()); const TMeshImage::meshes_container &meshes = mi.meshes(); TMeshImage::meshes_container::const_iterator mt, mEnd = meshes.end(); for (mt = meshes.begin(); mt != mEnd; ++mt) { const std::pair<double, int> &candidateIdx = closestEdge(**mt, pos); std::pair<double, MeshIndex> candidate( candidateIdx.first, MeshIndex(mt - meshes.begin(), candidateIdx.second)); if (candidate < closest) closest = candidate; } return closest; } } // namespace //**************************************************************************************** // Cut Mesh operation //**************************************************************************************** namespace { struct EdgeCut { int m_vIdx; //!< Vertex index to cut from. int m_eIdx; //!< Edge index to cut. EdgeCut(int vIdx, int eIdx) : m_vIdx(vIdx), m_eIdx(eIdx) {} }; struct VertexOccurrence { int m_count; //!< Number of times a vertex occurs. int m_adjacentEdgeIdx[2]; //!< Edge indexes of which a vertex is endpoint. }; //============================================================================ bool buildEdgeCuts(const TMeshImage &mi, const PlasticTool::MeshSelection &edgesSelection, int &meshIdx, std::vector<EdgeCut> &edgeCuts) { typedef PlasticTool::MeshSelection::objects_container edges_container; typedef PlasticTool::MeshIndex MeshIndex; typedef std::unordered_map<int, VertexOccurrence> VertexOccurrencesMap; struct locals { static bool differentMesh(const MeshIndex &a, const MeshIndex &b) { return (a.m_meshIdx != b.m_meshIdx); } static int testSingleMesh(const edges_container &edges) { assert(!edges.empty()); return (std::find_if(edges.begin(), edges.end(), [&edges](const MeshIndex &x) { return differentMesh(x, edges.front()); }) == edges.end()) ? edges.front().m_meshIdx : -1; } static bool testNoBoundaryEdge(const TTextureMesh &mesh, const edges_container &edges) { edges_container::const_iterator et, eEnd = edges.end(); for (et = edges.begin(); et != eEnd; ++et) if (::borderEdge(mesh, et->m_idx)) return false; return true; } static bool buildVertexOccurrences( const TTextureMesh &mesh, const edges_container &edges, VertexOccurrencesMap &vertexOccurrences) { // Calculate vertex occurrences as edge endpoints edges_container::const_iterator et, eEnd = edges.end(); for (et = edges.begin(); et != eEnd; ++et) { const edge_type &ed = mesh.edge(et->m_idx); int v0 = ed.vertex(0), v1 = ed.vertex(1); VertexOccurrence &vo0 = vertexOccurrences[v0], &vo1 = vertexOccurrences[v1]; if (vo0.m_count > 1 || vo1.m_count > 1) return false; vo0.m_adjacentEdgeIdx[vo0.m_count++] = vo1.m_adjacentEdgeIdx[vo1.m_count++] = et->m_idx; } return true; } static bool buildEdgeCuts(const TTextureMesh &mesh, const edges_container &edges, std::vector<EdgeCut> &edgeCuts) { VertexOccurrencesMap vertexOccurrences; if (!buildVertexOccurrences(mesh, edges, vertexOccurrences)) return false; // Build endpoints (exactly 2) int endPoints[2]; int epCount = 0; VertexOccurrencesMap::iterator ot, oEnd = vertexOccurrences.end(); for (ot = vertexOccurrences.begin(); ot != oEnd; ++ot) { if (ot->second.m_count == 1) { if (epCount > 1) return false; endPoints[epCount++] = ot->first; } } if (epCount != 2) return false; // Pick the first endpoint on the boundary, if any (otherwise, just pick // one) int *ept, *epEnd = endPoints + 2; ept = std::find_if(endPoints, epEnd, [&mesh](int v) { return borderVertex(mesh, v); }); if (ept == epEnd) { // There is no boundary endpoint if (edges.size() < 2) // We should not cut the mesh on a return false; // single edge - no vertex to duplicate! ept = endPoints; } // Build the edge cuts list, expanding the edges selection from // the chosen endpoint edgeCuts.push_back(EdgeCut( // Build the first EdgeCut separately *ept, vertexOccurrences[*ept].m_adjacentEdgeIdx[0])); int e, eCount = int(edges.size()); // Build the remaining ones for (e = 1; e != eCount; ++e) { const EdgeCut &lastCut = edgeCuts.back(); int vIdx = mesh.edge(lastCut.m_eIdx).otherVertex(lastCut.m_vIdx); const int(&adjEdges)[2] = vertexOccurrences[vIdx].m_adjacentEdgeIdx; int eIdx = (adjEdges[0] == lastCut.m_eIdx) ? adjEdges[1] : adjEdges[0]; edgeCuts.push_back(EdgeCut(vIdx, eIdx)); } return true; } }; const edges_container &edges = edgesSelection.objects(); // Trivial early bailouts if (edges.empty()) return false; // Selected edges must lie on the same mesh meshIdx = locals::testSingleMesh(edges); if (meshIdx < 0) return false; const TTextureMesh &mesh = *mi.meshes()[meshIdx]; // No selected edge must be on the boundary return (locals::testNoBoundaryEdge(mesh, edges) && locals::buildEdgeCuts(mesh, edges, edgeCuts)); } //------------------------------------------------------------------------ inline bool testCutMesh(const TMeshImage &mi, const PlasticTool::MeshSelection &edgesSelection) { std::vector<EdgeCut> edgeCuts; int meshIdx; return buildEdgeCuts(mi, edgesSelection, meshIdx, edgeCuts); } //------------------------------------------------------------------------ void slitMesh(TTextureMesh &mesh, int e) //! Opens a slit along the specified edge index. { TTextureMesh::edge_type &ed = mesh.edge(e); assert(ed.facesCount() == 2); // Duplicate the edge and pass one face to the duplicate TTextureMesh::edge_type edDup(ed.vertex(0), ed.vertex(1)); int f = ed.face(1); edDup.addFace(f); ed.eraseFace(ed.facesBegin() + 1); int eDup = mesh.addEdge(edDup); // Alter the face to host the duplicate TTextureMesh::face_type &fc = mesh.face(f); (fc.edge(0) == e) ? fc.setEdge(0, eDup) : (fc.edge(1) == e) ? fc.setEdge(1, eDup) : fc.setEdge(2, eDup); } //------------------------------------------------------------------------ /*! \brief Duplicates a mesh edge-vertex pair (the 'cut') and separates their connections to adjacent mesh primitives. \remark The starting vertex is supposed to be on the mesh boundary. \remark Edges with a single neighbouring face can be duplicated, too. */ void cutEdge(TTextureMesh &mesh, const EdgeCut &edgeCut) { struct locals { static void transferEdge(TTextureMesh &mesh, int e, int vFrom, int vTo) { edge_type &ed = mesh.edge(e); vertex_type &vxFrom = mesh.vertex(vFrom), &vxTo = mesh.vertex(vTo); (ed.vertex(0) == vFrom) ? ed.setVertex(0, vTo) : ed.setVertex(1, vTo); vxTo.addEdge(e); vxFrom.eraseEdge( std::find(vxFrom.edges().begin(), vxFrom.edges().end(), e)); } static void transferFace(TTextureMesh &mesh, int eFrom, int eTo) { edge_type &edFrom = mesh.edge(eFrom), &edTo = mesh.edge(eTo); int f = mesh.edge(eFrom).face(1); { face_type &fc = mesh.face(f); (fc.edge(0) == eFrom) ? fc.setEdge(0, eTo) : (fc.edge(1) == eFrom) ? fc.setEdge(1, eTo) : fc.setEdge(2, eTo); edTo.addFace(f); edFrom.eraseFace(edFrom.facesBegin() + 1); } } }; // locals int vOrig = edgeCut.m_vIdx, eOrig = edgeCut.m_eIdx; // Create a new vertex at the same position of the original int vDup = mesh.addVertex(vertex_type(mesh.vertex(vOrig).P())); int e = eOrig; if (mesh.edge(e).facesCount() == 2) { // Duplicate the cut edge e = mesh.addEdge(edge_type(vDup, mesh.edge(eOrig).otherVertex(vOrig))); // Transfer one face from the original to the duplicate locals::transferFace(mesh, eOrig, e); } else { // Transfer the original edge to the duplicate vertex locals::transferEdge(mesh, eOrig, vOrig, vDup); } // Edges adjacent to the original vertex that are also adjacent // to the transferred face above must be transferred too int f = mesh.edge(e).face(0); while (f >= 0) { // Retrieve the next edge to transfer int otherE = mesh.otherFaceEdge(f, mesh.edge(e).otherVertex(vDup)); // NOTE: Not "mesh.edgeInciding(vOrig, mesh.otherFaceVertex(f, e))" in the // calculation // of otherE. This is required since by transferring each edge at a // time, // we're 'breaking' faces up - f is adjacent to both vOrig AND vDup! // // The chosen calculation, instead, just asks for the one edge which // does // not have a specific vertex in common to the 2 other edges in the // face. locals::transferEdge(mesh, otherE, vOrig, vDup); // Update e and f e = otherE; f = mesh.edge(otherE).otherFace(f); } } //------------------------------------------------------------------------ } namespace locals_ { // Need to use a named namespace due to // a known gcc 4.2 bug with compiler-generated struct VertexesRecorder // copy constructors. { std::unordered_set<int> &m_examinedVertexes; public: typedef boost::on_examine_vertex event_filter; public: VertexesRecorder(std::unordered_set<int> &examinedVertexes) : m_examinedVertexes(examinedVertexes) {} void operator()(int v, const TTextureMesh &) { m_examinedVertexes.insert(v); } }; } namespace { // void splitUnconnectedMesh(TMeshImage &mi, int meshIdx) { struct locals { static void buildConnectedComponent(const TTextureMesh &mesh, std::unordered_set<int> &vertexes) { // Prepare BFS algorithm std::unique_ptr<UCHAR[]> colorMapP(new UCHAR[mesh.vertices().nodesCount()]()); locals_::VertexesRecorder vertexesRecorder(vertexes); std::stack<int> verticesQueue; // Launch it boost::breadth_first_visit( mesh, int(mesh.vertices().begin().index()), verticesQueue, boost::make_bfs_visitor(vertexesRecorder), colorMapP.get()); } }; // locals // Retrieve the list of vertexes in the first connected component TTextureMesh &origMesh = *mi.meshes()[meshIdx]; std::unordered_set<int> firstComponent; locals::buildConnectedComponent(origMesh, firstComponent); if (firstComponent.size() == origMesh.verticesCount()) return; // There are (exactly) 2 connected components. Just duplicate the mesh // and keep/delete found vertexes. TTextureMeshP dupMeshPtr(new TTextureMesh(origMesh)); TTextureMesh &dupMesh = *dupMeshPtr; TTextureMesh::vertices_container &vertices = origMesh.vertices(); TTextureMesh::vertices_container::iterator vt, vEnd = vertices.end(); for (vt = vertices.begin(); vt != vEnd;) { int v = int(vt.index()); ++vt; if (firstComponent.count(v)) dupMesh.removeVertex(v); else origMesh.removeVertex(v); } dupMesh.squeeze(); origMesh.squeeze(); mi.meshes().push_back(dupMeshPtr); } //------------------------------------------------------------------------ void splitMesh(TMeshImage &mi, int meshIdx, int lastBoundaryVertex) { // Retrieve a cutting edge with a single adjacent face - cutting that // will just duplicate the vertex and separate the mesh in 2 connected // components TTextureMesh &mesh = *mi.meshes()[meshIdx]; int e; { const vertex_type &lbVx = mesh.vertex(lastBoundaryVertex); vertex_type::edges_const_iterator et = std::find_if(lbVx.edgesBegin(), lbVx.edgesEnd(), [&mesh](int e) { return borderEdge(mesh, e); }); assert(et != lbVx.edgesEnd()); e = *et; } cutEdge(mesh, EdgeCut(lastBoundaryVertex, e)); // At this point, separate the 2 resulting connected components // in 2 separate meshes (if necessary) splitUnconnectedMesh(mi, meshIdx); } //------------------------------------------------------------------------ bool cutMesh(TMeshImage &mi, const PlasticTool::MeshSelection &edgesSelection) { struct locals { static int lastVertex(const TTextureMesh &mesh, const std::vector<EdgeCut> &edgeCuts) { return mesh.edge(edgeCuts.back().m_eIdx) .otherVertex(edgeCuts.back().m_vIdx); } static int lastBoundaryVertex(const TTextureMesh &mesh, const std::vector<EdgeCut> &edgeCuts) { int v = lastVertex(mesh, edgeCuts); return ::borderVertex(mesh, v) ? v : -1; } }; // locals std::vector<EdgeCut> edgeCuts; int meshIdx; if (!::buildEdgeCuts(mi, edgesSelection, meshIdx, edgeCuts)) return false; TTextureMesh &mesh = *mi.meshes()[meshIdx]; int lastBoundaryVertex = locals::lastBoundaryVertex(mesh, edgeCuts); // Slit the mesh on the first edge, in case the cuts do not start // on the mesh boundary std::vector<EdgeCut>::iterator ecBegin = edgeCuts.begin(); if (!::borderVertex(mesh, ecBegin->m_vIdx)) { ::slitMesh(mesh, ecBegin->m_eIdx); ++ecBegin; } // Cut edges, in the order specified by edgeCuts std::for_each(ecBegin, edgeCuts.end(), [&mesh](const EdgeCut &edgeCut) { return cutEdge(mesh, edgeCut); }); // Finally, the mesh could have been split in 2 - we need to separate // the pieces if needed if (lastBoundaryVertex >= 0) splitMesh(mi, meshIdx, lastBoundaryVertex); return true; } } // namespace //**************************************************************************************** // Undo definitions //**************************************************************************************** namespace { class MoveVertexUndo_Mesh final : public TUndo { int m_row, m_col; //!< Xsheet coordinates std::vector<MeshIndex> m_vIdxs; //!< Moved vertices std::vector<TPointD> m_origVxsPos; //!< Original vertex positions TPointD m_posShift; //!< Vertex positions shift public: MoveVertexUndo_Mesh(const std::vector<MeshIndex> &vIdxs, const std::vector<TPointD> &origVxsPos, const TPointD &posShift) : m_row(::row()) , m_col(::column()) , m_vIdxs(vIdxs) , m_origVxsPos(origVxsPos) , m_posShift(posShift) { assert(m_vIdxs.size() == m_origVxsPos.size()); } int getSize() const override { return int(sizeof(*this) + m_vIdxs.size() * (sizeof(int) + 2 * sizeof(TPointD))); } void redo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); l_plasticTool.setMeshVertexesSelection(m_vIdxs); l_plasticTool.moveVertex_mesh(m_origVxsPos, m_posShift); l_plasticTool.invalidate(); l_plasticTool .notifyImageChanged(); // IMPORTANT: In particular, sets the level's } // dirty flag, so Toonz knows it has // to be saved! void undo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); l_plasticTool.setMeshVertexesSelection(m_vIdxs); l_plasticTool.moveVertex_mesh(m_origVxsPos, TPointD()); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } }; //============================================================================== class SwapEdgeUndo final : public TUndo { int m_row, m_col; //!< Xsheet coordinates mutable MeshIndex m_edgeIdx; //!< Edge index public: SwapEdgeUndo(const MeshIndex &edgeIdx) : m_row(::row()), m_col(::column()), m_edgeIdx(edgeIdx) {} int getSize() const override { return sizeof(*this); } void redo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); const TMeshImageP &mi = TMeshImageP(TTool::getImage(true)); assert(mi); // Perform swap TTextureMesh &mesh = *mi->meshes()[m_edgeIdx.m_meshIdx]; m_edgeIdx.m_idx = mesh.swapEdge(m_edgeIdx.m_idx); assert(m_edgeIdx.m_idx >= 0); // Invalidate any deformer associated with mi PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); // Update tool selection l_plasticTool.setMeshEdgesSelection(m_edgeIdx); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } void undo() const override { redo(); } // Operation is idempotent (indices // are perfectly restored, too) }; //============================================================================== class TTextureMeshUndo : public TUndo { protected: int m_row, m_col; //!< Xsheet coordinates int m_meshIdx; //!< Mesh index in the image at stored xsheet coords mutable TTextureMesh m_origMesh; //!< Copy of the original mesh public: TTextureMeshUndo(int meshIdx) : m_row(::row()), m_col(::column()), m_meshIdx(meshIdx) {} // Let's say 1MB each - storing the mesh is costly int getSize() const override { return 1 << 20; } TMeshImageP getMeshImage() const { const TMeshImageP &mi = TMeshImageP(TTool::getImage(true)); assert(mi); return mi; } }; //============================================================================== class CollapseEdgeUndo final : public TTextureMeshUndo { int m_eIdx; //!< Collapsed edge index public: CollapseEdgeUndo(const MeshIndex &edgeIdx) : TTextureMeshUndo(edgeIdx.m_meshIdx), m_eIdx(edgeIdx.m_idx) {} void redo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); const TMeshImageP &mi = getMeshImage(); // Store the original mesh TTextureMesh &mesh = *mi->meshes()[m_meshIdx]; m_origMesh = mesh; // Collapse mesh.collapseEdge(m_eIdx); mesh.squeeze(); // Invalidate any cached deformer associated with the modified mesh image PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); // Refresh the tool l_plasticTool.clearMeshSelections(); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } void undo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); const TMeshImageP &mi = getMeshImage(); // Restore the original mesh TTextureMesh &mesh = *mi->meshes()[m_meshIdx]; mesh = m_origMesh; PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); // Restore selection l_plasticTool.setMeshEdgesSelection(MeshIndex(m_meshIdx, m_eIdx)); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } }; //============================================================================== class SplitEdgeUndo final : public TTextureMeshUndo { int m_eIdx; //!< Split edge index public: SplitEdgeUndo(const MeshIndex &edgeIdx) : TTextureMeshUndo(edgeIdx.m_meshIdx), m_eIdx(edgeIdx.m_idx) {} void redo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); const TMeshImageP &mi = getMeshImage(); // Store the original mesh TTextureMesh &mesh = *mi->meshes()[m_meshIdx]; m_origMesh = mesh; // Split mesh.splitEdge(m_eIdx); // mesh.squeeze(); // // There should be no need to squeeze assert(mesh.vertices().size() == mesh.vertices().nodesCount()); // assert(mesh.edges().size() == mesh.edges().nodesCount()); // assert(mesh.faces().size() == mesh.faces().nodesCount()); // PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); l_plasticTool.clearMeshSelections(); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } void undo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); const TMeshImageP &mi = getMeshImage(); // Restore the original mesh TTextureMesh &mesh = *mi->meshes()[m_meshIdx]; mesh = m_origMesh; PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); // Restore selection l_plasticTool.setMeshEdgesSelection(MeshIndex(m_meshIdx, m_eIdx)); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } }; //============================================================================== class CutEdgesUndo final : public TUndo { int m_row, m_col; //!< Xsheet coordinates TMeshImageP m_origImage; //!< Clone of the original image PlasticTool::MeshSelection m_edgesSelection; //!< Selection to operate on public: CutEdgesUndo(const PlasticTool::MeshSelection &edgesSelection) : m_row(::row()) , m_col(::column()) , m_origImage(TTool::getImage(false)->cloneImage()) , m_edgesSelection(edgesSelection) {} int getSize() const override { return 1 << 20; } bool do_() const { TMeshImageP mi = TTool::getImage(true); if (::cutMesh(*mi, m_edgesSelection)) { PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); l_plasticTool.clearMeshSelections(); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); return true; } return false; } void redo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); bool ret = do_(); (void)ret; assert(ret); } void undo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); TMeshImageP mi = TTool::getImage(true); // Restore the original image *mi = *m_origImage; PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); // Restore selection l_plasticTool.setMeshEdgesSelection(m_edgesSelection); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } }; } // namespace //**************************************************************************************** // PlasticTool functions //**************************************************************************************** void PlasticTool::storeMeshImage() { TMeshImageP mi = getImage(false); if (mi != m_mi) { m_mi = mi; clearMeshSelections(); } } //------------------------------------------------------------------------ void PlasticTool::setMeshSelection(MeshSelection &target, const MeshSelection &newSel) { if (newSel.isEmpty()) { target.selectNone(); target.makeNotCurrent(); return; } target.setObjects(newSel.objects()); target.notifyView(); target.makeCurrent(); } //------------------------------------------------------------------------ void PlasticTool::toggleMeshSelection(MeshSelection &target, const MeshSelection &addition) { typedef MeshSelection::objects_container objects_container; const objects_container &storedIdxs = target.objects(); const objects_container &addedIdxs = addition.objects(); // Build new selection objects_container selectedIdxs; if (target.contains(addition)) { std::set_difference(storedIdxs.begin(), storedIdxs.end(), addedIdxs.begin(), addedIdxs.end(), std::back_inserter(selectedIdxs)); } else { std::set_union(storedIdxs.begin(), storedIdxs.end(), addedIdxs.begin(), addedIdxs.end(), std::back_inserter(selectedIdxs)); } setMeshSelection(target, selectedIdxs); } //------------------------------------------------------------------------ void PlasticTool::clearMeshSelections() { m_mvHigh = m_meHigh = MeshIndex(); m_mvSel.selectNone(); m_mvSel.makeNotCurrent(); m_meSel.selectNone(); m_meSel.makeNotCurrent(); } //------------------------------------------------------------------------ void PlasticTool::setMeshVertexesSelection(const MeshSelection &vSel) { setMeshSelection(m_meSel, MeshSelection()), setMeshSelection(m_mvSel, vSel); } //------------------------------------------------------------------------ void PlasticTool::toggleMeshVertexesSelection(const MeshSelection &vSel) { setMeshSelection(m_meSel, MeshSelection()), toggleMeshSelection(m_mvSel, vSel); } //------------------------------------------------------------------------ void PlasticTool::setMeshEdgesSelection(const MeshSelection &eSel) { setMeshSelection(m_meSel, eSel), setMeshSelection(m_mvSel, MeshSelection()); } //------------------------------------------------------------------------ void PlasticTool::toggleMeshEdgesSelection(const MeshSelection &eSel) { toggleMeshSelection(m_meSel, eSel), setMeshSelection(m_mvSel, MeshSelection()); } //------------------------------------------------------------------------ void PlasticTool::mouseMove_mesh(const TPointD &pos, const TMouseEvent &me) { // Track mouse position m_pos = pos; // Needs to be done now - ensures m_pos is valid m_mvHigh = MeshIndex(); // Reset highlighted primitives if (m_mi) { // Look for nearest primitive std::pair<double, MeshIndex> closestVertex = ::closestVertex(*m_mi, pos), closestEdge = ::closestEdge(*m_mi, pos); // Discriminate on fixed metric const double hDistSq = sq(getPixelSize() * MESH_HIGHLIGHT_DISTANCE); m_mvHigh = m_meHigh = MeshIndex(); if (closestEdge.first < hDistSq) m_meHigh = closestEdge.second; if (closestVertex.first < hDistSq) m_mvHigh = closestVertex.second, m_meHigh = MeshIndex(); } assert(!(m_mvHigh && m_meHigh)); // Vertex and edge highlights are mutually exclusive invalidate(); } //------------------------------------------------------------------------ void PlasticTool::leftButtonDown_mesh(const TPointD &pos, const TMouseEvent &me) { struct Locals { PlasticTool *m_this; void updateSelection(MeshSelection &sel, const MeshIndex &idx, const TMouseEvent &me) { if (idx) { MeshSelection newSel(idx); if (me.isCtrlPressed()) m_this->toggleMeshSelection(sel, newSel); else if (!sel.contains(newSel)) m_this->setMeshSelection(sel, newSel); } else m_this->setMeshSelection(sel, MeshSelection()); } } locals = {this}; // Track mouse position m_pressedPos = m_pos = pos; // Update selection locals.updateSelection(m_mvSel, m_mvHigh, me); locals.updateSelection(m_meSel, m_meHigh, me); // Store original vertex positions if (!m_mvSel.isEmpty()) { std::vector<TPointD> v; for (auto const &e : m_mvSel.objects()) { v.push_back(m_mi->meshes()[e.m_meshIdx]->vertex(e.m_idx).P()); } m_pressedVxsPos = std::move(v); } // Redraw selections invalidate(); } //------------------------------------------------------------------------ void PlasticTool::leftButtonDrag_mesh(const TPointD &pos, const TMouseEvent &me) { // Track mouse position m_pos = pos; if (!m_mvSel.isEmpty()) { moveVertex_mesh(m_pressedVxsPos, pos - m_pressedPos); invalidate(); } } //------------------------------------------------------------------------ void PlasticTool::leftButtonUp_mesh(const TPointD &pos, const TMouseEvent &me) { // Track mouse position m_pos = pos; if (m_dragged && !m_mvSel.isEmpty()) { TUndoManager::manager()->add(new MoveVertexUndo_Mesh( m_mvSel.objects(), m_pressedVxsPos, pos - m_pressedPos)); invalidate(); notifyImageChanged(); // Sets the level's dirty flag -.-' } } //------------------------------------------------------------------------ void PlasticTool::addContextMenuActions_mesh(QMenu *menu) { bool ret = true; if (!m_meSel.isEmpty()) { if (m_meSel.hasSingleObject()) { const MeshIndex &mIdx = m_meSel.objects().front(); const TTextureMesh &mesh = *m_mi->meshes()[mIdx.m_meshIdx]; if (::testSwapEdge(mesh, mIdx.m_idx)) { QAction *swapEdge = menu->addAction(tr("Swap Edge")); ret = ret && connect(swapEdge, SIGNAL(triggered()), &l_plasticTool, SLOT(swapEdge_mesh_undo())); } if (::testCollapseEdge(mesh, mIdx.m_idx)) { QAction *collapseEdge = menu->addAction(tr("Collapse Edge")); ret = ret && connect(collapseEdge, SIGNAL(triggered()), &l_plasticTool, SLOT(collapseEdge_mesh_undo())); } QAction *splitEdge = menu->addAction(tr("Split Edge")); ret = ret && connect(splitEdge, SIGNAL(triggered()), &l_plasticTool, SLOT(splitEdge_mesh_undo())); } if (::testCutMesh(*m_mi, m_meSel)) { QAction *cutEdges = menu->addAction(tr("Cut Mesh")); ret = ret && connect(cutEdges, SIGNAL(triggered()), &l_plasticTool, SLOT(cutEdges_mesh_undo())); } menu->addSeparator(); } assert(ret); } //------------------------------------------------------------------------ void PlasticTool::moveVertex_mesh(const std::vector<TPointD> &origVxsPos, const TPointD &posShift) { if (m_mvSel.isEmpty() || !m_mi) return; assert(origVxsPos.size() == m_mvSel.objects().size()); // Move selected vertices TMeshImageP mi = getImage(true); assert(m_mi == mi); int v, vCount = int(m_mvSel.objects().size()); for (v = 0; v != vCount; ++v) { const MeshIndex &meshIndex = m_mvSel.objects()[v]; TTextureMesh &mesh = *mi->meshes()[meshIndex.m_meshIdx]; mesh.vertex(meshIndex.m_idx).P() = origVxsPos[v] + posShift; } // Mesh must be recompiled PlasticDeformerStorage::instance()->invalidateMeshImage( mi.getPointer(), PlasticDeformerStorage::MESH); } //------------------------------------------------------------------------ void PlasticTool::swapEdge_mesh_undo() { if (!(m_mi && m_meSel.hasSingleObject())) return; // Test current edge swapability { const MeshIndex &eIdx = m_meSel.objects().front(); const TTextureMesh &mesh = *m_mi->meshes()[eIdx.m_meshIdx]; if (!::testSwapEdge(mesh, eIdx.m_idx)) return; } // Perform operation std::unique_ptr<TUndo> undo(new SwapEdgeUndo(m_meSel.objects().front())); undo->redo(); TUndoManager::manager()->add(undo.release()); } //------------------------------------------------------------------------ void PlasticTool::collapseEdge_mesh_undo() { if (!(m_mi && m_meSel.hasSingleObject())) return; // Test collapsibility of current edge { const MeshIndex &eIdx = m_meSel.objects().front(); const TTextureMesh &mesh = *m_mi->meshes()[eIdx.m_meshIdx]; if (!::testCollapseEdge(mesh, eIdx.m_idx)) return; } // Perform operation std::unique_ptr<TUndo> undo(new CollapseEdgeUndo(m_meSel.objects().front())); undo->redo(); TUndoManager::manager()->add(undo.release()); } //------------------------------------------------------------------------ void PlasticTool::splitEdge_mesh_undo() { if (!(m_mi && m_meSel.hasSingleObject())) return; std::unique_ptr<TUndo> undo(new SplitEdgeUndo(m_meSel.objects().front())); undo->redo(); TUndoManager::manager()->add(undo.release()); } //------------------------------------------------------------------------ void PlasticTool::cutEdges_mesh_undo() { if (!m_mi) return; std::unique_ptr<CutEdgesUndo> undo(new CutEdgesUndo(m_meSel.objects())); if (undo->do_()) TUndoManager::manager()->add(undo.release()); } //------------------------------------------------------------------------ void PlasticTool::draw_mesh() { struct Locals { PlasticTool *m_this; double m_pixelSize; void drawLine(const TPointD &a, const TPointD &b) { glVertex2d(a.x, a.y); glVertex2d(b.x, b.y); } void drawVertexSelections() { typedef MeshSelection::objects_container objects_container; const objects_container &objects = m_this->m_mvSel.objects(); glColor3ub(255, 0, 0); // Red glLineWidth(1.0f); const double hSize = MESH_SELECTED_HANDLE_SIZE * m_pixelSize; objects_container::const_iterator vt, vEnd = objects.end(); for (vt = objects.begin(); vt != vEnd; ++vt) { const TTextureVertex &vx = m_this->m_mi->meshes()[vt->m_meshIdx]->vertex(vt->m_idx); ::drawFullSquare(vx.P(), hSize); } } void drawEdgeSelections() { typedef MeshSelection::objects_container objects_container; const objects_container &objects = m_this->m_meSel.objects(); glColor3ub(0, 0, 255); // Blue glLineWidth(2.0f); glBegin(GL_LINES); objects_container::const_iterator et, eEnd = objects.end(); for (et = objects.begin(); et != eEnd; ++et) { const TTextureVertex &vx0 = m_this->m_mi->meshes()[et->m_meshIdx]->edgeVertex(et->m_idx, 0), &vx1 = m_this->m_mi->meshes()[et->m_meshIdx]->edgeVertex(et->m_idx, 1); drawLine(vx0.P(), vx1.P()); } glEnd(); } void drawVertexHighlights() { if (m_this->m_mvHigh) { const MeshIndex &vHigh = m_this->m_mvHigh; const TTextureMesh::vertex_type &vx = m_this->m_mi->meshes()[vHigh.m_meshIdx]->vertex(vHigh.m_idx); glColor3ub(255, 0, 0); // Red glLineWidth(1.0f); const double hSize = MESH_HIGHLIGHTED_HANDLE_SIZE * m_pixelSize; ::drawSquare(vx.P(), hSize); } } void drawEdgeHighlights() { if (m_this->m_meHigh) { const MeshIndex &eHigh = m_this->m_meHigh; const TTextureMesh::vertex_type &vx0 = m_this->m_mi->meshes()[eHigh.m_meshIdx]->edgeVertex( eHigh.m_idx, 0), &vx1 = m_this->m_mi->meshes()[eHigh.m_meshIdx]->edgeVertex( eHigh.m_idx, 1); { glPushAttrib(GL_LINE_BIT); glEnable(GL_LINE_STIPPLE); glLineStipple(1, 0xCCCC); glColor3ub(0, 0, 255); // Blue glLineWidth(1.0f); glBegin(GL_LINES); drawLine(vx0.P(), vx1.P()); glEnd(); glPopAttrib(); } } } } locals = {this, getPixelSize()}; // The selected mesh image is already drawn by the stage // Draw additional overlays if (m_mi) { locals.drawVertexSelections(); locals.drawEdgeSelections(); locals.drawVertexHighlights(); locals.drawEdgeHighlights(); } }
40,903
13,621
#include "fly/coders/base64/base64_coder.hpp" #include "test/util/path_util.hpp" #include "catch2/catch_test_macros.hpp" #include <cctype> #include <filesystem> namespace { // This must match the size of fly::coders::Base64Coder::m_encoded constexpr const std::size_t s_large_string_size = 256 << 10; } // namespace CATCH_TEST_CASE("Base64", "[coders]") { fly::coders::Base64Coder coder; CATCH_SECTION("Encode and decode empty stream") { const std::string raw; std::string enc, dec; CATCH_REQUIRE(coder.encode_string(raw, enc)); CATCH_REQUIRE(coder.decode_string(enc, dec)); CATCH_CHECK(enc.empty()); CATCH_CHECK(raw == dec); } CATCH_SECTION("Encode and decode a stream without padding") { const std::string raw = "Man"; std::string enc, dec; CATCH_REQUIRE(coder.encode_string(raw, enc)); CATCH_REQUIRE(coder.decode_string(enc, dec)); CATCH_CHECK(enc == "TWFu"); CATCH_CHECK(raw == dec); } CATCH_SECTION("Encode and decode a stream with one padding symbol") { const std::string raw = "Ma"; std::string enc, dec; CATCH_REQUIRE(coder.encode_string(raw, enc)); CATCH_REQUIRE(coder.decode_string(enc, dec)); CATCH_CHECK(enc == "TWE="); CATCH_CHECK(raw == dec); } CATCH_SECTION("Encode and decode a stream with two padding symbols") { const std::string raw = "M"; std::string enc, dec; CATCH_REQUIRE(coder.encode_string(raw, enc)); CATCH_REQUIRE(coder.decode_string(enc, dec)); CATCH_CHECK(enc == "TQ=="); CATCH_CHECK(raw == dec); } CATCH_SECTION("Cannot decode streams with invalid symbols") { std::string dec; for (char ch = 0x00; ch >= 0x00; ++ch) { if ((ch == '+') || (ch == '/') || (ch == '=') || std::isalnum(ch)) { continue; } const std::string test(1, ch); const std::string fill("a"); CATCH_CHECK_FALSE(coder.decode_string(test + test + test + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + test + test + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + test + fill + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + test + fill + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + fill + test + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + fill + test + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + fill + fill + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + fill + fill + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + test + test + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + test + test + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + test + fill + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + test + fill + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + fill + test + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + fill + test + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + fill + fill + test, dec)); } // Also ensure the failure is handled in a multi-chunk sized input stream. CATCH_CHECK_FALSE(coder.decode_string("abc^" + std::string(s_large_string_size, 'a'), dec)); } CATCH_SECTION("Cannot decode streams with invalid chunk sizes") { std::string dec; CATCH_CHECK_FALSE(coder.decode_string("a", dec)); CATCH_CHECK_FALSE(coder.decode_string("ab", dec)); CATCH_CHECK_FALSE(coder.decode_string("abc", dec)); CATCH_CHECK_FALSE(coder.decode_string("abcde", dec)); CATCH_CHECK_FALSE(coder.decode_string("abcdef", dec)); CATCH_CHECK_FALSE(coder.decode_string("abcdefg", dec)); // Also ensure the failure is handled in a multi-chunk sized input stream. CATCH_CHECK_FALSE(coder.decode_string("abc" + std::string(s_large_string_size, 'a'), dec)); } CATCH_SECTION("Cannot decode streams with padding in invalid position") { std::string dec; CATCH_CHECK_FALSE(coder.decode_string("=abc", dec)); CATCH_CHECK_FALSE(coder.decode_string("a=bc", dec)); CATCH_CHECK_FALSE(coder.decode_string("ab=c", dec)); // Also ensure the failure is handled in a multi-chunk sized input stream. CATCH_CHECK_FALSE(coder.decode_string("ab=c" + std::string(s_large_string_size, 'a'), dec)); } CATCH_SECTION("Example from Wikipedia: https://en.wikipedia.org/wiki/Base64#Examples") { const std::string raw = "Man is distinguished, not only by his reason, but by this singular passion from other " "animals, which is a lust of the mind, that by a perseverance of delight in the " "continued and indefatigable generation of knowledge, exceeds the short vehemence of " "any carnal pleasure."; std::string enc, dec; CATCH_REQUIRE(coder.encode_string(raw, enc)); CATCH_REQUIRE(coder.decode_string(enc, dec)); const std::string expected = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bG" "FyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQg" "YnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIG" "dlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5h" "bCBwbGVhc3VyZS4="; CATCH_CHECK(enc == expected); CATCH_CHECK(raw == dec); } CATCH_SECTION("File tests") { fly::test::PathUtil::ScopedTempDirectory path; std::filesystem::path encoded_file = path.file(); std::filesystem::path decoded_file = path.file(); CATCH_SECTION("Encode and decode a large file containing only ASCII symbols") { // Generated with: // tr -dc '[:graph:]' </dev/urandom | head -c 4194304 > test.txt const auto here = std::filesystem::path(__FILE__).parent_path(); const auto raw = here / "data" / "test.txt"; CATCH_REQUIRE(coder.encode_file(raw, encoded_file)); CATCH_REQUIRE(coder.decode_file(encoded_file, decoded_file)); // Generated with: // base64 -w0 test.txt > test.txt.base64 const auto expected = here / "data" / "test.txt.base64"; CATCH_CHECK(fly::test::PathUtil::compare_files(encoded_file, expected)); CATCH_CHECK(fly::test::PathUtil::compare_files(raw, decoded_file)); } CATCH_SECTION("Encode and decode a PNG image file") { const auto here = std::filesystem::path(__FILE__).parent_path(); const auto raw = here / "data" / "test.png"; CATCH_REQUIRE(coder.encode_file(raw, encoded_file)); CATCH_REQUIRE(coder.decode_file(encoded_file, decoded_file)); // Generated with: // base64 -w0 test.png > test.png.base64 const auto expected = here / "data" / "test.png.base64"; CATCH_CHECK(fly::test::PathUtil::compare_files(encoded_file, expected)); CATCH_CHECK(fly::test::PathUtil::compare_files(raw, decoded_file)); } CATCH_SECTION("Encode and decode a GIF image file") { const auto here = std::filesystem::path(__FILE__).parent_path(); const auto raw = here / "data" / "test.gif"; CATCH_REQUIRE(coder.encode_file(raw, encoded_file)); CATCH_REQUIRE(coder.decode_file(encoded_file, decoded_file)); // Generated with: // base64 -w0 test.gif > test.gif.base64 const auto expected = here / "data" / "test.gif.base64"; CATCH_CHECK(fly::test::PathUtil::compare_files(encoded_file, expected)); CATCH_CHECK(fly::test::PathUtil::compare_files(raw, decoded_file)); } } }
8,194
2,845
// Copyright 2021 The Cross-Media Measurement Authors // // 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 "wfa/virtual_people/common/field_filter/gt_filter.h" #include <memory> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "common_cpp/macros/macros.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "wfa/virtual_people/common/field_filter.pb.h" #include "wfa/virtual_people/common/field_filter/field_filter.h" #include "wfa/virtual_people/common/field_filter/utils/field_util.h" #include "wfa/virtual_people/common/field_filter/utils/integer_comparator.h" namespace wfa_virtual_people { absl::StatusOr<std::unique_ptr<GtFilter>> GtFilter::New( const google::protobuf::Descriptor* descriptor, const FieldFilterProto& config) { if (config.op() != FieldFilterProto::GT) { return absl::InvalidArgumentError(absl::StrCat( "Op must be GT. Input FieldFilterProto: ", config.DebugString())); } if (!config.has_name()) { return absl::InvalidArgumentError(absl::StrCat( "Name must be set. Input FieldFilterProto: ", config.DebugString())); } if (!config.has_value()) { return absl::InvalidArgumentError(absl::StrCat( "Value must be set. Input FieldFilterProto: ", config.DebugString())); } ASSIGN_OR_RETURN( std::vector<const google::protobuf::FieldDescriptor*> field_descriptors, GetFieldFromProto(descriptor, config.name())); ASSIGN_OR_RETURN( std::unique_ptr<IntegerComparator> comparator, IntegerComparator::New(std::move(field_descriptors), config.value())); return absl::make_unique<GtFilter>(std::move(comparator)); } bool GtFilter::IsMatch(const google::protobuf::Message& message) const { return comparator_->Compare(message) == IntegerCompareResult::GREATER_THAN; } } // namespace wfa_virtual_people
2,483
809
#include "numword.h" using namespace bw; // destructor numword::~numword() { clearbuf(); } // assignment operator numnum numword::operator = ( const numnum num ) { setnum(num); return getnum(); } const char * numword::words() { return words(_num); } // convert to words const char * numword::words( const numnum num ) { if (num > _maxnum) { return errnum; } initbuf(); numnum n = num; if (n == 0) { appendbuf(_singles[n]); return _buf; } // powers of 1000 if (n >= 1000) { for(int i = 5; i > 0; --i) { numnum power = (numnum) pow(1000.0, i); numnum _n = ( n - ( n % power ) ) / power; if (_n) { int index = i; numword _nw(_n); appendspace(); appendbuf(_nw.words()); appendspace(); appendbuf(_powers[index]); n -= _n * power; } } } // hundreds if (n >= 100 && n < 1000) { numnum _n = ( n - ( n % 100 ) ) / 100; numword _nw(_n); appendspace(); appendbuf(_nw.words()); appendspace(); appendbuf(_hundred); n -= _n * 100; } // tens if (n >= 20 && n < 100) { numnum _n = ( n - ( n % 10 ) ) / 10; appendspace(); appendbuf(_tens[_n]); n -= _n * 10; hyphen_flag = true; } // teens if (n >= 10 && n < 20) { appendspace(); appendbuf(_teens[n - 10]); n = 0; } // singles if (n > 0 && n < 10) { appendspace(); appendbuf(_singles[n]); } return _buf; } // -- private methods -- // reset the buffer void numword::clearbuf() { if (_buf != nullptr) { free(_buf); _buf = nullptr; } _buflen = 0; } // initialize the buffer void numword::initbuf() { clearbuf(); _buf = (char *) malloc(_maxstr); *_buf = 0; hyphen_flag = false; } // append space (or hyphen) void numword::appendspace() { if (_buflen) { appendbuf( hyphen_flag ? _hyphen : _space); hyphen_flag = false; } } // append text to the string buffer void numword::appendbuf(const char * s) { if(!s) return; size_t slen = strnlen(s, _maxstr); if (slen < 1) { return; } if ((slen + _buflen + 1) >= _maxstr) { return; } memcpy(_buf + _buflen, s, slen); _buflen += slen; _buf[_buflen] = 0; }
2,497
918
#include <QtGui> #include "rpc/local-repo.h" #include "repo-item.h" RepoItem::RepoItem(const LocalRepo& repo, QWidget *parent) : QWidget(parent), repo_(repo) { setupUi(this); refresh(); setFixedHeight(70); } void RepoItem::refresh() { mRepoName->setText(repo_.name); mRepoIcon->setPixmap(QPixmap(":/images/repo.png")); }
355
144
/**********************************************************\ This file is distributed under the MIT License. See https://github.com/morzhovets/momo/blob/master/LICENSE for details. tests/SimpleHashTesterOneI1.cpp \**********************************************************/ #include "pch.h" #include "TestSettings.h" #ifdef TEST_SIMPLE_HASH #ifdef TEST_OLD_HASH_BUCKETS #undef NDEBUG #include "SimpleHashTester.h" #include "../../momo/details/HashBucketOneI1.h" static int testSimpleHash = [] { SimpleHashTester::TestStrHash<momo::HashBucketOneI1>("momo::HashBucketOneI1"); SimpleHashTester::TestTemplHashSet<momo::HashBucketOneI1, 1, 1>("momo::HashBucketOneI1"); SimpleHashTester::TestTemplHashSet<momo::HashBucketOneI1, 4, 2>("momo::HashBucketOneI1"); return 0; }(); #endif // TEST_OLD_HASH_BUCKETS #endif // TEST_SIMPLE_HASH
886
357
#pragma once #include "../../../../common.hpp" #include "../../MSExcel.common.hpp" #include "../../IParsable.hpp" #include "Ptg.hpp" namespace oless { namespace excel { namespace structures { namespace formulas { // see: https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/f5ef334a-bc47-41ce-ba5d-096373423fab // ptg=0x11 // The PtgRange structure specifies the range operation, where the minimum bounding rectangle of the first expression and the second expression is generated. class PtgRange : public PtgBasic { private: public: PtgRange(unsigned char* buffer, size_t max, unsigned int offset):PtgBasic() { this->Parse(buffer, max, offset); } std::string to_string() const override { return "PtgRange"; } }; } } } }
819
325
/* * GeneticAlgoScene.cpp * * Created on: Nov 2, 2015 * Author: Karl Haubenwallner */ #include "GeneticAlgoScene.h" GeneticAlgoScene::GeneticAlgoScene(const std::string& filename): seed(217197128u), genetic_algo(PGA::ProceduralAlgorithm_impl::createFromConfig(filename)), _current_generation(0) { } double GeneticAlgoScene::recombine(bool restart) { //genetic_algo->reset(); //genetic_algo->doOneGeneration(); genetic_algo->run(); _current_generation ++; return 0.0f; } double GeneticAlgoScene::generate() { auto t0 = std::chrono::high_resolution_clock::now(); genetic_algo->generateGeometry(); auto t1 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0); return time_span.count(); } void GeneticAlgoScene::getVoxels(std::vector<math::float4>& centers) { genetic_algo->getVoxels(centers); } void GeneticAlgoScene::getGeometry(std::vector<PGA::GeneratedVertex>& geometry, std::vector<unsigned>& indices) { } PGA::GeometryBufferInstanced& GeneticAlgoScene::getGeometryBuffer() { return genetic_algo->getGeometryBufferInstanced(); }
1,173
452
/// shaft, connected to the bround by revolute joint at the point <100, 0, 0> /// initial linear speed is (0, 0, 300.); /// initial angular speed angularVelAbs = (0, 3., 0); #include <cmath> #include "chrono/physics/ChSystemNSC.h" #include "chrono/solver/ChIterativeSolverLS.h" #include "chrono/solver/ChDirectSolverLS.h" #include "chrono_irrlicht/ChIrrApp.h" using namespace chrono; using namespace chrono::irrlicht; using namespace irr; ChVector<> getLinearAccelAbs(std::shared_ptr<ChBody> body) { auto& bodyFrame = body->GetFrame_REF_to_abs(); ChVector<> linearAccAbs = body->GetFrame_REF_to_abs().GetPos_dtdt(); return linearAccAbs; } int main(int argc, char* argv[]) { ChSystemNSC m_System; m_System.Set_G_acc(ChVector<>(0, 0, 0)); // Create the ground (fixed) body // ------------------------------ auto ground = chrono_types::make_shared<ChBody>(); m_System.AddBody(ground); ground->SetIdentifier(-1); ground->SetBodyFixed(true); ground->SetCollide(false); auto m_Body = chrono_types::make_shared<ChBody>(); m_System.AddBody(m_Body); m_Body->SetIdentifier(1); m_Body->SetBodyFixed(false); m_Body->SetCollide(false); m_Body->SetMass(1); m_Body->SetInertiaXX(ChVector<>(1, 1, 1)); m_Body->SetPos(ChVector<>(0, 0, 0)); m_Body->SetRot(ChQuaternion<>(1, 0, 0, 0)); auto cyl = chrono_types::make_shared<ChCylinderShape>(); cyl->GetCylinderGeometry().p1 = ChVector<>(-100, 0, 0); cyl->GetCylinderGeometry().p2 = ChVector<>(100, 0, 0); cyl->GetCylinderGeometry().rad = 2; m_Body->AddAsset(cyl); auto col = chrono_types::make_shared<ChColorAsset>(0.6f, 0.0f, 0.0f); m_Body->AddAsset(col); ChVector<> linearVelAbs(0, 0, 300.); m_Body->SetPos_dt(linearVelAbs); ChVector<> angularVelAbs(0, 3, 0); //// RADU: changed this!!! m_Body->SetWvel_par(angularVelAbs); m_Body->SetPos_dt(linearVelAbs); ChVector<> translation(100, 0, 0); ChVector<> orientationRad = CH_C_DEG_TO_RAD * 90.; ChQuaternion<> quat; quat.Q_from_AngX(orientationRad[0]); Coordsys absCoor{translation, quat}; auto markerBodyLink = std::make_shared<ChMarker>("MarkerBodyLink", m_Body.get(), ChCoordsys<>(), ChCoordsys<>(), ChCoordsys<>()); m_Body->AddMarker(markerBodyLink); markerBodyLink->Impose_Abs_Coord(absCoor); auto markerGroundLink = std::make_shared<ChMarker>("MarkerGroundLink", ground.get(), ChCoordsys<>(), ChCoordsys<>(), ChCoordsys<>()); ground->AddMarker(markerGroundLink); markerGroundLink->Impose_Abs_Coord(absCoor); auto m_Link = std::shared_ptr<chrono::ChLinkMarkers>(new ChLinkLockRevolute()); m_Link->Initialize(markerGroundLink, markerBodyLink); m_System.AddLink(m_Link); auto solver = chrono_types::make_shared<ChSolverSparseQR>(); solver->SetVerbose(false); m_System.SetSolver(solver); m_System.SetSolverForceTolerance(1e-12); m_System.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT_PROJECTED); m_System.SetStep(1e-10); ChIrrApp application(&m_System, L"ChBodyAuxRef demo", core::dimension2d<u32>(800, 600), false, true); application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(0, 20, 150)); application.AssetBindAll(); application.AssetUpdateAll(); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); ////m_System.DoStepDynamics(1e-4); application.EndScene(); } m_System.DoFullAssembly(); auto linearAccelInit = getLinearAccelAbs(m_Body); }
3,691
1,427
// Copyright (c) 2020-2021 FRC Team 3512. All Rights Reserved. #include <frc/trajectory/constraint/MaxVelocityConstraint.h> #include <frc/trajectory/constraint/RectangularRegionConstraint.h> #include <wpi/numbers> #include "Robot.hpp" namespace frc3512 { void Robot::AutoRightSideShootSix() { // Initial Pose - Right in line with the three balls in the Trench Run const frc::Pose2d kInitialPose{12_m, 1.05_m, units::radian_t{wpi::numbers::pi}}; // Mid Pose - Drive forward slightly const frc::Pose2d kMidPose{12_m - 1.5 * Drivetrain::kLength, 1.05_m, units::radian_t{wpi::numbers::pi}}; // End Pose - Third/Farthest ball in the Trench Run const frc::Pose2d kEndPose{7.95_m, 1.05_m, units::radian_t{wpi::numbers::pi}}; drivetrain.Reset(kInitialPose); // Move back to shoot three comfortably drivetrain.AddTrajectory(kInitialPose, {}, kMidPose); intake.Deploy(); if (!m_autonChooser.Suspend([=] { return drivetrain.AtGoal(); })) { return; } if constexpr (IsSimulation()) { for (int i = 0; i < 3; ++i) { intakeSim.AddBall(); } } Shoot(3); if (!m_autonChooser.Suspend([=] { return !IsShooting(); })) { return; } // Add a constraint to slow down the drivetrain while it's // approaching the balls frc::RectangularRegionConstraint regionConstraint{ frc::Translation2d{kEndPose.X(), kEndPose.Y() - 0.5 * Drivetrain::kLength}, // X: First/Closest ball in the trench run frc::Translation2d{9.82_m + 0.5 * Drivetrain::kLength, kInitialPose.Y() + 0.5 * Drivetrain::kLength}, frc::MaxVelocityConstraint{1.6_mps}}; { auto config = Drivetrain::MakeTrajectoryConfig(); config.AddConstraint(regionConstraint); drivetrain.AddTrajectory(kMidPose, {}, kEndPose, config); } // Intake Balls x3 intake.Start(); if (!m_autonChooser.Suspend([=] { return drivetrain.AtGoal(); })) { return; } // Drive back { auto config = Drivetrain::MakeTrajectoryConfig(); config.SetReversed(true); drivetrain.AddTrajectory({kEndPose, kMidPose}, config); } if (!m_autonChooser.Suspend([=] { return drivetrain.AtGoal(); })) { return; } if constexpr (IsSimulation()) { for (int i = 0; i < 3; ++i) { intakeSim.AddBall(); } } Shoot(3); if (!m_autonChooser.Suspend([=] { return !IsShooting(); })) { return; } intake.Stop(); EXPECT_TRUE(turret.AtGoal()); } } // namespace frc3512
2,735
1,015
#ifndef RS_PHY_PATH_REG_HPP #define RS_PHY_PATH_REG_HPP #include "rodsConnect.h" #include "dataObjInpOut.h" int rsPhyPathReg( rsComm_t *rsComm, dataObjInp_t *phyPathRegInp ); #endif
185
90
#include <ATen/detail/ComplexHooksInterface.h> namespace at { namespace detail { const ComplexHooksInterface& getComplexHooks() { static std::unique_ptr<ComplexHooksInterface> complex_hooks; // NB: The once_flag here implies that if you try to call any Complex // functionality before you load the complex library, you're toast. // Same restriction as in getCUDAHooks() static std::once_flag once; std::call_once(once, [] { complex_hooks = ComplexHooksRegistry()->Create("ComplexHooks", ComplexHooksArgs{}); if (!complex_hooks) { complex_hooks = std::unique_ptr<ComplexHooksInterface>(new ComplexHooksInterface()); } }); return *complex_hooks; } } // namespace detail C10_DEFINE_REGISTRY( ComplexHooksRegistry, ComplexHooksInterface, ComplexHooksArgs) }
813
268
// menor custo para conseguir peso ate M usando N tipos diferentes de elementos, sendo que o i-esimo elemento pode ser usado b[i] vezes, tem peso w[i] e custo c[i] // O(N * M) int b[N], w[N], c[N]; MinQueue Q[M] int d[M] //d[i] = custo minimo para conseguir peso i for(int i = 0; i <= M; i++) d[i] = i ? oo : 0; for(int i = 0; i < N; i++){ for(int j = 0; j < w[i]; j++) Q[j].clear(); for(int j = 0; j <= M; j++){ q = Q[j % w[i]]; if(q.size() >= q) q.pop(); q.add(c[i]); q.push(d[j]); d[j] = q.getmin(); } }
524
265
//#pragma title("usercopy- copies user accounts") /* ================================================================================ (c) Copyright 1995-1998, Mission Critical Software, Inc., All Rights Reserved Proprietary and confidential to Mission Critical Software, Inc. Program - usercopy Class - LAN Manager Utilities Author - Tom Bernhardt Created - 05/08/91 Description- Merges the NetUser information from the specified source server with the target system (or the current system if no target is specified). Group information is also merged if the /g option is given. Existing entries on the target system are not overwritten unless the /r option is used. Syntax - USERCOPY source [target] [/u] [/l] [/g] [/r] where: source source server target destination server /g copies global group information /l copies local group information /u copies user information /r replaces existing target entries with source entries /AddTo:x Adds all newly created users (/u) to group "x" Updates - 91/06/17 TPB General code cleanup and change so that all stdout i/o lines up nicely on-screen for reporting. 93/06/12 TPB Port to Win32 96/06/21 TPB Support for local groups 97/09/20 CAB Added subset of accounts option for GUI 98/06 TPB/CAB Support for computer accounts 99/01 COM-ization of DCT. ================================================================================ */ #include "StdAfx.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <ntdsapi.h> #include <lm.h> #include <iads.h> #include "TxtSid.h" #define INCL_NETUSER #define INCL_NETGROUP #define INCL_NETERRORS #include <lm.h> #include "Common.hpp" #include "UString.hpp" #include "WorkObj.h" //#include "Usercopy.hpp" //#included by ARUtil.hpp below #include "ARUtil.hpp" #include "BkupRstr.hpp" #include "DCTStat.h" #include "ErrDct.hpp" #include "RegTrans.h" #include "TEvent.hpp" #include "LSAUtils.h" #include "GetDcName.h" #include <sddl.h> //#import "\bin\NetEnum.tlb" no_namespace //#import "\bin\DBManager.tlb" no_namespace, named_guids #import "NetEnum.tlb" no_namespace //#import "DBMgr.tlb" no_namespace, named_guids //already #imported via ARUtil.hpp #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern TErrorDct err; extern TErrorDct & errC; bool abortall; extern bool g_bAddSidWorks = false; // global counts of accounts processed AccountStats warnings = { 0,0,0,0 }; AccountStats errors = { 0,0,0,0 }; AccountStats created = { 0,0,0,0 }; AccountStats replaced = { 0,0,0,0 }; AccountStats processed = { 0,0,0,0 }; BOOL machineAcctsCreated = FALSE; BOOL otherAcctsCreated = FALSE; PSID srcSid = NULL; // SID for source domain typedef UINT (CALLBACK* DSBINDFUNC)(TCHAR*, TCHAR*, HANDLE*); typedef UINT (CALLBACK* DSADDSIDHISTORY)(HANDLE, DWORD, LPCTSTR, LPCTSTR, LPCTSTR, RPC_AUTH_IDENTITY_HANDLE,LPCTSTR,LPCTSTR); #ifndef IADsPtr _COM_SMARTPTR_TYPEDEF(IADs, IID_IADs); #endif int TNodeCompareSourceName(TNode const * t1,TNode const * t2) { TAcctReplNode const * n1 = (TAcctReplNode *)t1; TAcctReplNode const * n2 = (TAcctReplNode *)t2; return UStrICmp(n1->GetName(),n2->GetName()); } int TNodeCompareSourceNameValue(TNode const * t1, void const * v) { TAcctReplNode const * n1 = (TAcctReplNode *)t1; WCHAR const * name = (WCHAR const *)v; return UStrICmp(n1->GetName(),name); } bool BindToDS(Options* pOpt) { // Get the handle to the Directory service. DSBINDFUNC DsBind; HINSTANCE hInst = LoadLibrary(L"NTDSAPI.DLL"); if ( hInst ) { DsBind = (DSBINDFUNC) GetProcAddress(hInst, "DsBindW"); if (DsBind) { // // If source domain controllers are running W2K or later then specify // DNS name of target domain controller otherwise must specify flat // (NetBIOS) name of target domain controller. // // Note that this is a requirement of the DsAddSidHistory implementation // when the source domain is NT4 and explicit source domain credentials // are not supplied. As ADMT does not supply explicit credentials this // will always be the case when the source domain is NT4. // PWSTR strDestDC = (pOpt->srcDomainVer > 4) ? pOpt->tgtCompDns : pOpt->tgtCompFlat; DWORD rc = DsBind(strDestDC, NULL, &pOpt->dsBindHandle); if ( rc != 0 ) { err.SysMsgWrite( ErrE, rc, DCT_MSG_DSBIND_FAILED_S, strDestDC); Mark(L"errors", L"generic"); FreeLibrary(hInst); return false; } } else { err.SysMsgWrite(ErrE,GetLastError(),DCT_MSG_GET_PROC_ADDRESS_FAILED_SSD,L"NTDSAPI.DLL",L"DsBindW",GetLastError()); Mark(L"errors", L"generic"); FreeLibrary(hInst); return false; } } else { err.SysMsgWrite(ErrW,GetLastError(),DCT_MSG_LOAD_LIBRARY_FAILED_SD,L"NTDSAPI.DLL",GetLastError()); Mark(L"warnings", L"generic"); return false; } FreeLibrary(hInst); return true; } // The following function is used to get the actual account name from the source domain // instead of account that contains the SID in its SID history. DWORD GetName(PSID pObjectSID, WCHAR * sNameAccount, WCHAR * sDomain) { DWORD cb = 255; DWORD cbDomain = 255; DWORD tempVal; PDWORD psubAuth; PUCHAR pVal; SID_NAME_USE sid_Use; _bstr_t sDC; DWORD rc = 0; if ((pObjectSID == NULL) || !IsValidSid(pObjectSID)) { return ERROR_INVALID_PARAMETER; } // Copy the Sid to a temp SID DWORD sidLen = GetLengthSid(pObjectSID); PSID pObjectSID1 = new BYTE[sidLen]; if (!pObjectSID1) return ERROR_NOT_ENOUGH_MEMORY; if (!CopySid(sidLen, pObjectSID1, pObjectSID)) { delete pObjectSID1; return GetLastError(); } if (!IsValidSid(pObjectSID1)) { rc = GetLastError(); err.SysMsgWrite(ErrE, rc,DCT_MSG_DOMAIN_LOOKUP_FAILED_D,rc); try { Mark(L"errors", L"generic"); } catch (...) { } delete pObjectSID1; return rc; } // Get the RID out of the SID and get the domain SID pVal = GetSidSubAuthorityCount(pObjectSID1); (*pVal)--; psubAuth = GetSidSubAuthority(pObjectSID1, *pVal); tempVal = *psubAuth; *psubAuth = -1; //Lookup the domain from the SID if (!LookupAccountSid(NULL, pObjectSID1, sNameAccount, &cb, sDomain, &cbDomain, &sid_Use)) { rc = GetLastError(); err.SysMsgWrite(ErrE, rc,DCT_MSG_DOMAIN_LOOKUP_FAILED_D,rc); Mark(L"errors", L"generic"); delete pObjectSID1; return rc; } // Get a DC for the domain rc = GetAnyDcName4(sDomain, sDC); if ( rc ) { err.SysMsgWrite(ErrE,rc,DCT_MSG_GET_DCNAME_FAILED_SD,sDomain,rc); Mark(L"errors", L"generic"); delete pObjectSID1; return rc; } // Reset the sizes cb = 255; cbDomain = 255; // Lookup the account on the PDC that we found above. if ( LookupAccountSid(sDC, pObjectSID, sNameAccount, &cb, sDomain, &cbDomain, &sid_Use) == 0) { delete pObjectSID1; return GetLastError(); } delete pObjectSID1; return 0; } /* This is a list of specific error codes that can be returned by DsAddSidHistory. This was obtained from Microsoft via email > ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED > The operation requires that destination domain auditing be enabled for > Success and Failure auditing of account management operations. > > ERROR_DS_UNWILLING_TO_PERFORM > It may be that the user account is not one of UF_NORMAL_ACCOUNT, > UF_WORKSTATION_TRUST_ACCOUNT, or UF_SERVER_TRUST_ACCOUNT. > > It may be that the source principal is a built in account. > > It may be that the source principal is a well known RID being added > to a destination principal that is a different RID. In other words, > Administrators of the source domain can only be assigned to > Administrators of the destination domain. > > ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER > The source object must be a group or user. > > ERROR_DS_SRC_SID_EXISTS_IN_FOREST > The source object's SID already exists in destination forest. > > ERROR_DS_INTERNAL_FAILURE; > The directory service encountered an internal failure. Shouldn't > happen. > > ERROR_DS_MUST_BE_RUN_ON_DST_DC > For security reasons, the operation must be run on the destination DC. > Specifically, the connection between the client and server > (destination > DC) requires 128-bit encryption when credentials for the source domain > are supplied. > > ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION > The connection between client and server requires packet privacy or > better. > > ERROR_DS_SOURCE_DOMAIN_IN_FOREST > The source domain may not be in the same forest as destination. > > ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST > The destination domain must be in the forest. > > ERROR_DS_MASTERDSA_REQUIRED > The operation must be performed at a master DSA (writable DC). > > ERROR_DS_INSUFF_ACCESS_RIGHTS > Insufficient access rights to perform the operation. Most likely > the caller is not a member of domain admins for the dst domain. > > ERROR_DS_DST_DOMAIN_NOT_NATIVE > Destination domain must be in native mode. > > ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN > The operation couldn't locate a DC for the source domain. > > ERROR_DS_OBJ_NOT_FOUND > Directory object not found. Most likely the FQDN of the > destination principal could not be found in the destination > domain. > > ERROR_DS_NAME_ERROR_NOT_UNIQUE > Name translation: Input name mapped to more than one > output name. Most likely the destination principal mapped > to more than one FQDN in the destination domain. > > ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH > The source and destination object must be of the same type. > > ERROR_DS_OBJ_CLASS_VIOLATION > The requested operation did not satisfy one or more constraints > associated with the class of the object. Most likely because the > destination principal is not a user or group. > > ERROR_DS_UNAVAILABLE > The directory service is unavailable. Most likely the > ldap_initW() to the NT5 src DC failed. > > ERROR_DS_INAPPROPRIATE_AUTH > Inappropriate authentication. Most likely the ldap_bind_sW() to > the NT5 src dc failed. > > ERROR_DS_SOURCE_AUDITING_NOT_ENABLED > The operation requires that source domain auditing be enabled for > Success and Failure auditing of account management operations. > > ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER > For security reasons, the source DC must be Service Pack 4 or greater. > */ HRESULT CopySidHistoryProperty( Options * pOptions, TAcctReplNode * pNode, IStatusObj * pStatus ) { HRESULT hr = S_OK; IADs * pAds = NULL; _variant_t var; // long ub = 0, lb = 0; // fetch the SIDHistory property for the source account // for each entry in the source's SIDHistory, call DsAddSidHistory // Get the IADs pointer to the object and get the SIDHistory attribute. hr = ADsGetObject(const_cast<WCHAR*>(pNode->GetSourcePath()), IID_IADs, (void**)&pAds); if ( SUCCEEDED(hr) ) { hr = pAds->Get(L"sIDHistory", &var); } if ( SUCCEEDED(hr) ) { // This is a multivalued property so we need to get all the values // for each one get the name and the domain of the object and then call the // add sid history function to add the SID to the target objects SIDHistory. _variant_t var; DWORD rc = pAds->GetEx(L"sIDHistory", &var); if ( !rc ) { if ( V_VT(&var) == (VT_ARRAY | VT_VARIANT) ) { // This is the array type that we were looking for. void HUGEP *pArray; VARIANT var2; ULONG dwSLBound = -1; ULONG dwSUBound = -1; hr = SafeArrayGetLBound( V_ARRAY(&var), 1, (long FAR *) &dwSLBound ); hr = SafeArrayGetUBound( V_ARRAY(&var), 1, (long FAR *) &dwSUBound ); if (SUCCEEDED(hr)) { // Each element in this array is a SID in form of a VARIANT hr = SafeArrayAccessData( V_ARRAY(&var), &pArray ); for ( long x = (long)dwSLBound; x <= (long)dwSUBound; x++) { hr = SafeArrayGetElement(V_ARRAY(&var), &x, &var2); // Get the SID from the Variant in a ARRAY form hr = SafeArrayAccessData( V_ARRAY(&var2), &pArray ); PSID pObjectSID = (PSID)pArray; //Convert SID to string. if (pObjectSID) { WCHAR sNameAccount[255]; WCHAR sDomain[255]; WCHAR sNetBIOS[255]; DWORD rc = 0; rc = GetName(pObjectSID, sNameAccount, sDomain); if (!rc) { WCHAR sTemp[LEN_Path]; WCHAR sSourceDNS[LEN_Path]; // We are going to temporarily change the Domain DNS to the domain of the SID we are adding wcscpy(sTemp, pOptions->srcDomainDns); if ( GetDnsAndNetbiosFromName(sDomain, sNetBIOS, sSourceDNS) ) { wcscpy(pOptions->srcDomainDns, sSourceDNS); AddSidHistory(pOptions, sNameAccount, pNode->GetTargetSam(), NULL, FALSE); // Replace the original domain dns. wcscpy(pOptions->srcDomainDns, sTemp); } else { err.SysMsgWrite(ErrE, GetLastError(),DCT_MSG_DOMAIN_DNS_LOOKUP_FAILED_SD, sDomain,GetLastError()); Mark(L"errors", pNode->GetType()); } } else { // Get name failed we need to log a message. WCHAR sSid[LEN_Path]; DWORD len = LEN_Path; GetTextualSid(pObjectSID, sSid, &len); err.SysMsgWrite(ErrE,rc,DCT_MSG_ERROR_CONVERTING_SID_SSD, pNode->GetTargetName(), sSid, rc); Mark(L"errors", pNode->GetType()); } } SafeArrayUnaccessData(V_ARRAY(&var2)); } SafeArrayUnaccessData(V_ARRAY(&var)); } } } else { // No SID History to copy. } } return hr; } bool AddSidHistory( const Options * pOptions, const WCHAR * strSrcPrincipal, const WCHAR * strDestPrincipal, IStatusObj * pStatus, BOOL isFatal) { //Add the sid to the history // Authentication Structure SEC_WINNT_AUTH_IDENTITY auth; DWORD rc = 0; WCHAR szPassword[LEN_Password]; auth.Domain = const_cast<WCHAR*>(pOptions->authDomain); auth.DomainLength = wcslen(pOptions->authDomain); auth.User = const_cast<WCHAR*>(pOptions->authUser); auth.UserLength = wcslen(pOptions->authUser); // // If credentials were supplied then retrieve password. // if ((auth.DomainLength > 0) && (auth.UserLength > 0)) { DWORD dwError = RetrievePassword(pOptions->authPassword, szPassword, sizeof(szPassword) / sizeof(szPassword[0])); if (dwError == ERROR_SUCCESS) { auth.Password = szPassword; auth.PasswordLength = wcslen(szPassword); } else { err.SysMsgWrite(ErrE, dwError, DCT_MSG_UNABLE_TO_RETRIEVE_PASSWORD); g_bAddSidWorks = FALSE; // log a message indicating that SIDHistory will not be tried for the rest of the accounts err.MsgWrite(ErrW,DCT_MSG_SIDHISTORY_FATAL_ERROR); Mark(L"warnings", L"generic"); // we are going to set the status to abort so that we don't try to migrate anymore. if ( pStatus ) { pStatus->put_Status(DCT_STATUS_ABORTING); } return false; } } else { auth.Password = NULL; auth.PasswordLength = 0; } auth.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; // Auth Identity handle // if source domain credentials supplied use them // otherwise credentials of caller will be used RPC_AUTH_IDENTITY_HANDLE pHandle = ((auth.DomainLength > 0) && (auth.UserLength > 0)) ? &auth : NULL; DSADDSIDHISTORY DsAddSidHistory; HINSTANCE hInst = LoadLibrary(L"NTDSAPI.DLL"); if ( hInst ) { DsAddSidHistory = (DSADDSIDHISTORY) GetProcAddress(hInst, "DsAddSidHistoryW"); if (DsAddSidHistory) { if ( !pOptions->nochange ) { int loopCount = 0; rc = RPC_S_SERVER_UNAVAILABLE; // If we get the RPC server errors we need to retry 5 times. while ( (((rc == RPC_S_SERVER_UNAVAILABLE) || (rc == RPC_S_CALL_FAILED) || (rc == RPC_S_CALL_FAILED_DNE)) && loopCount < 5) || ( (rc == ERROR_INVALID_HANDLE) && loopCount < 3 ) ) // In case of invalid handle we try it 3 times now. { // Make the API call to add Sid to the history rc = DsAddSidHistory( pOptions->dsBindHandle, //DS Handle NULL, // flags pOptions->srcDomain, // Source domain strSrcPrincipal, // Source Account name NULL, // Source Domain Controller pHandle, // RPC_AUTH_IDENTITY_HANDLE pOptions->tgtDomainDns, // Target domain strDestPrincipal); // Target Account name if ( loopCount > 0 ) Sleep(500); loopCount++; } } SecureZeroMemory(szPassword, sizeof(szPassword)); if ( rc != 0 ) { switch ( rc ) { // these are the error codes caused by permissions or configuration problems case ERROR_NONE_MAPPED: err.MsgWrite(ErrE, DCT_MSG_ADDSIDHISTORY_FAIL_BUILTIN_SSD,strSrcPrincipal, strDestPrincipal, rc); break; case ERROR_DS_UNWILLING_TO_PERFORM: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_DS_UNWILLING_TO_PERFORM_SSSSD,strDestPrincipal,pOptions->srcDomain, strSrcPrincipal, pOptions->tgtDomain,rc); break; case ERROR_DS_INSUFF_ACCESS_RIGHTS: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_INSUFF_ACCESS_SD,strDestPrincipal,rc); g_bAddSidWorks = FALSE; break; case ERROR_INVALID_HANDLE: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_INVALID_HANDLE_SSD,pOptions->srcDomainDns,strDestPrincipal,rc); g_bAddSidWorks = FALSE; break; case ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_NOAUDIT_SSD,strDestPrincipal,pOptions->tgtDomainDns,rc); g_bAddSidWorks = FALSE; break; case ERROR_DS_MUST_BE_RUN_ON_DST_DC: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_DST_DC_SD,strDestPrincipal,rc); g_bAddSidWorks = FALSE; break; case ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_PKT_PRIVACY_SD,strDestPrincipal,rc); g_bAddSidWorks = FALSE; break; case ERROR_DS_SOURCE_DOMAIN_IN_FOREST: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_SOURCE_IN_FOREST_S,strDestPrincipal); g_bAddSidWorks = FALSE; break; case ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_DEST_WRONG_FOREST_S,strDestPrincipal); g_bAddSidWorks = FALSE; break; case ERROR_DS_MASTERDSA_REQUIRED: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_NO_MASTERDSA_S,strDestPrincipal); g_bAddSidWorks = FALSE; break; case ERROR_ACCESS_DENIED: g_bAddSidWorks = FALSE; if (pHandle) { err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_INSUFF2_SSS,strDestPrincipal,pOptions->authDomain,pOptions->authUser); } else { err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_INSUFF2_S,strDestPrincipal); } break; case ERROR_DS_DST_DOMAIN_NOT_NATIVE: g_bAddSidWorks = FALSE; err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_NOT_NATIVE_S,strDestPrincipal); break; case ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN: g_bAddSidWorks = FALSE; err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_NO_SOURCE_DC_S,strDestPrincipal); break; // case ERROR_DS_INAPPROPRIATE_AUTH: case ERROR_DS_UNAVAILABLE: g_bAddSidWorks = FALSE; err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_DS_UNAVAILABLE_S,strDestPrincipal); break; case ERROR_DS_SOURCE_AUDITING_NOT_ENABLED: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_NOAUDIT_SSD,strDestPrincipal,pOptions->srcDomain,rc); g_bAddSidWorks = FALSE; break; case ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_SOURCE_NOT_SP4_S,strDestPrincipal); g_bAddSidWorks = FALSE; break; case ERROR_SESSION_CREDENTIAL_CONFLICT: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_CREDENTIALS_CONFLICT_SSSS,strDestPrincipal,pOptions->srcDomain,pOptions->authDomain,pOptions->authUser); g_bAddSidWorks = FALSE; break; // these are error codes that only affect this particular account case ERROR_SUCCESS: g_bAddSidWorks = TRUE; // no error message needed for success case! break; case ERROR_DS_SRC_SID_EXISTS_IN_FOREST: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_IN_FOREST_SD,strDestPrincipal,rc); g_bAddSidWorks = TRUE; break; case ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_WRONGTYPE_SD,strDestPrincipal,rc); g_bAddSidWorks = TRUE; break; case ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH: err.MsgWrite(ErrE, DCT_MSG_SID_HISTORY_CLASS_MISMATCH_SSD, strDestPrincipal, strSrcPrincipal, rc); g_bAddSidWorks = TRUE; break; default: err.MsgWrite(ErrE,DCT_MSG_ADDSID_FAILED_SSD,strSrcPrincipal, strDestPrincipal,rc); g_bAddSidWorks = TRUE; break; } Mark(L"errors", L"generic"); // This may or may not be a fatal error depending on weather we are Adding // sid history or copying sid history g_bAddSidWorks |= !(isFatal); if (! g_bAddSidWorks ) { // log a message indicating that SIDHistory will not be tried for the rest of the accounts err.MsgWrite(ErrW,DCT_MSG_SIDHISTORY_FATAL_ERROR); Mark(L"warnings", L"generic"); // we are going to set the status to abort so that we don't try to migrate anymore. if ( pStatus ) { pStatus->put_Status(DCT_STATUS_ABORTING); } } FreeLibrary(hInst); return false; } else { err.MsgWrite(0, DCT_MSG_ADD_SID_SUCCESS_SSSS, pOptions->srcDomainFlat, strSrcPrincipal, pOptions->tgtDomainFlat, strDestPrincipal); FreeLibrary(hInst); return true; } } else { SecureZeroMemory(szPassword, sizeof(szPassword)); err.SysMsgWrite(ErrE,GetLastError(),DCT_MSG_NO_ADDSIDHISTORY_FUNCTION); Mark(L"errors", L"generic"); FreeLibrary(hInst); return false; } } else { SecureZeroMemory(szPassword, sizeof(szPassword)); err.SysMsgWrite(ErrE,GetLastError(),DCT_MSG_NO_NTDSAPI_DLL); Mark(L"errors", L"generic"); return false; } } //-------------------------------------------------------------------------- // FillupNamingContext : This function fills in the target Naming context // for NT5 domain. //-------------------------------------------------------------------------- void FillupNamingContext( Options * options //in,out- Options to fill up ) { WCHAR sPath[LEN_Path]; IADs * pAds; _variant_t var; HRESULT hr; wsprintf(sPath, L"LDAP://%s/rootDSE", options->tgtDomain); hr = ADsGetObject(sPath, IID_IADs, (void**)&pAds); if ( FAILED(hr) ) { wcscpy(options->tgtNamingContext, L""); return; } hr = pAds->Get(L"defaultNamingContext", &var); if ( FAILED(hr) ) { wcscpy(options->tgtNamingContext, L""); return; } pAds->Release(); wcscpy(options->tgtNamingContext, (WCHAR*) V_BSTR(&var)); } //-------------------------------------------------------------------------- // MakeFullyQualifiedAdsPath : Makes a LDAP sub path into a fully qualified // LDAP path name. //-------------------------------------------------------------------------- void MakeFullyQualifiedAdsPath( WCHAR * sPath, //out- Fully qulified LDAP path to the object DWORD nPathLen, //in - MAX size, in characters, of the sPath buffer WCHAR * sSubPath, //in- LDAP subpath of the object WCHAR * tgtDomain, //in- Domain name where object exists. WCHAR * sDN //in- Default naming context for the Domain ) { if ((!sPath) || (!sSubPath) || (!tgtDomain) || (!sDN)) return; _bstr_t sTempPath; if (wcsncmp(sSubPath, L"LDAP://", 7) == 0) { //it is already a fully qualified LDAP path so lets copy it and return it wcsncpy(sPath, sSubPath, nPathLen-1); sPath[nPathLen - 1] = L'\0'; return; } //We need to build this path so lets get to work if ( wcslen(sDN) ) { sTempPath = L"LDAP://"; sTempPath += tgtDomain; sTempPath += L"/"; sTempPath += sSubPath; sTempPath += L","; sTempPath += sDN; } else { sTempPath = L"LDAP://"; sTempPath += tgtDomain; sTempPath += L"/"; sTempPath += sSubPath; } if (sTempPath.length() > 0) { wcsncpy(sPath, sTempPath, nPathLen - 1); sPath[nPathLen - 1] = L'\0'; } else { *sPath = L'\0'; } } //-------------------------------------------------------------------------- // IsAccountMigrated : Function checks if the account has been migrated in // the past. If it has it returns true filling in the // name of the target object in case it was renamed. // Otherwise it returns FALSE and Empty string for the // target name. //-------------------------------------------------------------------------- bool IsAccountMigrated( TAcctReplNode * pNode, //in -Account node that contains the Account info Options * pOptions, //in -Options as specified by the user. IIManageDBPtr pDb, //in -Pointer to DB manager. We dont want to create this object for every account we process WCHAR * sTgtSam //in,out - Name of the target object that was copied if any. ) { IVarSetPtr pVs(__uuidof(VarSet)); IUnknown * pUnk; pVs->QueryInterface(IID_IUnknown, (void**) &pUnk); HRESULT hrFind = pDb->raw_GetAMigratedObject(const_cast<WCHAR*>(pNode->GetSourceSam()), pOptions->srcDomain, pOptions->tgtDomain, &pUnk); pUnk->Release(); if ( hrFind != S_OK ) { wcscpy(sTgtSam,L""); return false; } else { _bstr_t sText; sText = pVs->get(L"MigratedObjects.TargetSamName"); if (!(WCHAR*)sText) { wcscpy(sTgtSam,L""); return false; } wcscpy(sTgtSam, (WCHAR*) sText); return true; } } bool CheckifAccountExists( Options const * options, //in-Options as set by the user WCHAR * acctName //in-Name of the account to look for ) { USER_INFO_0 * buf; long rc = 0; if ( (rc = NetUserGetInfo(const_cast<WCHAR*>(options->tgtComp), acctName, 0, (LPBYTE *) &buf)) == NERR_Success ) { NetApiBufferFree(buf); return true; } if ( (rc = NetGroupGetInfo(const_cast<WCHAR*>(options->tgtComp), acctName, 0, (LPBYTE *) &buf)) == NERR_Success ) { NetApiBufferFree(buf); return true; } if ( (rc = NetLocalGroupGetInfo(const_cast<WCHAR*>(options->tgtComp), acctName, 0, (LPBYTE *) &buf)) == NERR_Success ) { NetApiBufferFree(buf); return true; } return false; } //-------------------------------------------------------------------------- // Mark : Increments appropriate counters depending on the arguments. //-------------------------------------------------------------------------- void Mark( _bstr_t sMark, //in- Represents the type of marking { processed, errors, replaced, created } _bstr_t sObj //in- Type of object being marked { user, group, computer } ) { if (!UStrICmp(sMark,L"processed")) { if ( !UStrICmp(sObj,L"user") || !UStrICmp(sObj,L"inetOrgPerson") ) processed.users++; else if ( !UStrICmp(sObj,L"group")) processed.globals++; else if ( !UStrICmp(sObj,L"computer")) processed.computers++; else if ( !UStrICmp(sObj,L"generic")) processed.generic++; } else if (!UStrICmp(sMark,L"errors")) { if ( !UStrICmp(sObj,L"user") || !UStrICmp(sObj,L"inetOrgPerson") ) errors.users++; else if ( !UStrICmp(sObj,L"group")) errors.globals++; else if ( !UStrICmp(sObj,L"computer")) errors.computers++; else if ( !UStrICmp(sObj,L"generic")) errors.generic++; } else if (!UStrICmp(sMark,L"warnings")) { if ( !UStrICmp(sObj,L"user") || !UStrICmp(sObj,L"inetOrgPerson") ) warnings.users++; else if ( !UStrICmp(sObj,L"group")) warnings.globals++; else if ( !UStrICmp(sObj,L"computer")) warnings.computers++; else if ( !UStrICmp(sObj,L"generic")) warnings.generic++; } else if (!UStrICmp(sMark,L"replaced")) { if ( !UStrICmp(sObj,L"user") || !UStrICmp(sObj,L"inetOrgPerson") ) replaced.users++; else if ( !UStrICmp(sObj,L"group")) replaced.globals++; else if ( !UStrICmp(sObj,L"computer")) replaced.computers++; else if ( !UStrICmp(sObj,L"generic")) replaced.generic++; } else if (!UStrICmp(sMark,L"created")) { if ( !UStrICmp(sObj,L"user") || !UStrICmp(sObj,L"inetOrgPerson") ) created.users++; else if ( !UStrICmp(sObj,L"group")) created.globals++; else if ( !UStrICmp(sObj,L"computer")) created.computers++; else if ( !UStrICmp(sObj,L"generic")) created.generic++; } } // // This function batch-marks one category of AccountStats based on an EAMAccountStatItem struct. // statItem: the EAMAccountStatItem struct // aStat: the AccountStats struct; should be one of errors, warnings, replaced, created, processed // static void BatchMarkCategory(const EAMAccountStatItem& statItem, AccountStats& aStat) { aStat.locals += statItem.locals; aStat.users += statItem.users; aStat.globals += statItem.globals; aStat.computers += statItem.computers; aStat.generic += statItem.generic; } // // This function batch-marks all categories of AccountStats based on an EAMAccountStats struct. // stats: the EAMAccountStats struct // void BatchMark(const EAMAccountStats& stats) { BatchMarkCategory(stats.errors, errors); BatchMarkCategory(stats.warnings, warnings); BatchMarkCategory(stats.replaced, replaced); BatchMarkCategory(stats.created, created); BatchMarkCategory(stats.processed, processed); } HRESULT __stdcall GetRidPoolAllocator(Options* pOptions) { WCHAR szADsPath[LEN_Path]; // // Bind to source Domain object and retrieve distinguished name of RID Manager object. // IADsPtr spDomain; _bstr_t strRIDManagerReference; szADsPath[countof(szADsPath) - 1] = L'\0'; int cch = _snwprintf( szADsPath, countof(szADsPath), L"LDAP://%s/%s", pOptions->srcComp + 2, pOptions->srcNamingContext ); if ((cch < 0) || (szADsPath[countof(szADsPath) - 1] != L'\0')) { return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } szADsPath[countof(szADsPath) - 1] = L'\0'; HRESULT hr = ADsGetObject(szADsPath, IID_IADs, (VOID**)&spDomain); if (FAILED(hr)) { return hr; } VARIANT varRIDManagerReference; VariantInit(&varRIDManagerReference); hr = spDomain->Get(L"rIDManagerReference", &varRIDManagerReference); if (FAILED(hr)) { return hr; } strRIDManagerReference = _variant_t(varRIDManagerReference, false); // // Bind to RID Manager object and retrieve distinguished name of the FSMO Role Owner. // IADsPtr spRIDManager; _bstr_t strFSMORoleOwner; szADsPath[countof(szADsPath) - 1] = L'\0'; cch = _snwprintf( szADsPath, countof(szADsPath), L"LDAP://%s/%s", pOptions->srcComp + 2, (PCWSTR)strRIDManagerReference ); if ((cch < 0) || (szADsPath[countof(szADsPath) - 1] != L'\0')) { return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } szADsPath[countof(szADsPath) - 1] = L'\0'; hr = ADsGetObject(szADsPath, IID_IADs, (VOID**)&spRIDManager); if (FAILED(hr)) { return hr; } VARIANT varFSMORoleOwner; VariantInit(&varFSMORoleOwner); hr = spRIDManager->Get(L"fSMORoleOwner", &varFSMORoleOwner); if (FAILED(hr)) { return hr; } strFSMORoleOwner = _variant_t(varFSMORoleOwner, false); // // Bind to NTDS-DSA object and retrieve ADsPath of parent Server object. // IADsPtr spNTDSDSA; _bstr_t strServer; szADsPath[countof(szADsPath) - 1] = L'\0'; cch = _snwprintf( szADsPath, countof(szADsPath), L"LDAP://%s/%s", pOptions->srcComp + 2, (PCWSTR)strFSMORoleOwner ); if ((cch < 0) || (szADsPath[countof(szADsPath) - 1] != L'\0')) { return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } szADsPath[countof(szADsPath) - 1] = L'\0'; hr = ADsGetObject(szADsPath, IID_IADs, (VOID**)&spNTDSDSA); if (FAILED(hr)) { return hr; } BSTR bstrServer; hr = spNTDSDSA->get_Parent(&bstrServer); if (FAILED(hr)) { return hr; } strServer = _bstr_t(bstrServer, false); // // Bind to Server object and retrieve distinguished name of Computer object. // IADsPtr spServer; _bstr_t strServerReference; hr = ADsGetObject(strServer, IID_IADs, (VOID**)&spServer); if (FAILED(hr)) { return hr; } VARIANT varServerReference; VariantInit(&varServerReference); hr = spServer->Get(L"serverReference", &varServerReference); if (FAILED(hr)) { return hr; } strServerReference = _variant_t(varServerReference, false); // // Bind to Computer object and retrieve DNS host name and SAM account name. // IADsPtr spComputer; _bstr_t strDNSHostName; _bstr_t strSAMAccountName; szADsPath[countof(szADsPath) - 1] = L'\0'; cch = _snwprintf( szADsPath, countof(szADsPath), L"LDAP://%s/%s", pOptions->srcComp + 2, (PCWSTR)strServerReference ); if ((cch < 0) || (szADsPath[countof(szADsPath) - 1] != L'\0')) { return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } szADsPath[countof(szADsPath) - 1] = L'\0'; hr = ADsGetObject(szADsPath, IID_IADs, (VOID**)&spComputer); if (FAILED(hr)) { return hr; } VARIANT varDNSHostName; VariantInit(&varDNSHostName); hr = spComputer->Get(L"dNSHostName", &varDNSHostName); if (FAILED(hr)) { return hr; } strDNSHostName = _variant_t(varDNSHostName, false); VARIANT varSAMAccountName; VariantInit(&varSAMAccountName); hr = spComputer->Get(L"SAMAccountName", &varSAMAccountName); if (FAILED(hr)) { return hr; } strSAMAccountName = _variant_t(varSAMAccountName, false); if ((strDNSHostName.length() == 0) || (strSAMAccountName.length() == 0)) { return E_OUTOFMEMORY; } // // Update source domain controller names. // if ((2 + strDNSHostName.length() >= countof(pOptions->srcComp)) || (2 + strDNSHostName.length() >= countof(pOptions->srcCompDns)) || (2 + strSAMAccountName.length() >= countof(pOptions->srcCompFlat))) { return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } wcscpy(pOptions->srcComp, L"\\\\"); wcscat(pOptions->srcComp, strDNSHostName); wcscpy(pOptions->srcCompDns, pOptions->srcComp); wcscpy(pOptions->srcCompFlat, L"\\\\"); wcscat(pOptions->srcCompFlat, strSAMAccountName); // Remove trailing $ character. pOptions->srcCompFlat[wcslen(pOptions->srcCompFlat) - 1] = L'\0'; return S_OK; }
41,303
14,031
#include "hydro_functions.H" #include "hydro_functions_F.H" #include "common_functions.H" #include "common_functions_F.H" #include "common_namespace.H" #include "gmres_functions.H" #include "gmres_functions_F.H" #include "gmres_namespace.H" #include <AMReX_ParallelDescriptor.H> #include <AMReX_MultiFabUtil.H> using namespace amrex; using namespace common; using namespace gmres; // argv contains the name of the inputs file entered at the command line void advance( std::array< MultiFab, AMREX_SPACEDIM >& umac, MultiFab& pres, const std::array< MultiFab, AMREX_SPACEDIM >& stochMfluxdiv, const std::array< MultiFab, AMREX_SPACEDIM >& sourceTerms, std::array< MultiFab, AMREX_SPACEDIM >& alpha_fc, MultiFab& beta, MultiFab& gamma, std::array< MultiFab, NUM_EDGE >& beta_ed, const Geometry geom, const Real& dt) { BL_PROFILE_VAR("advance()",advance); Real theta_alpha = 0.; Real norm_pre_rhs; const BoxArray& ba = beta.boxArray(); const DistributionMapping& dmap = beta.DistributionMap(); // rhs_p GMRES solve MultiFab gmres_rhs_p(ba, dmap, 1, 0); gmres_rhs_p.setVal(0.); // rhs_u GMRES solve std::array< MultiFab, AMREX_SPACEDIM > gmres_rhs_u; for (int d=0; d<AMREX_SPACEDIM; ++d) { gmres_rhs_u[d].define(convert(ba,nodal_flag_dir[d]), dmap, 1, 0); gmres_rhs_u[d].setVal(0.); } ////////////////////////////////////////////////// // ADVANCE velocity field ////////////////////////////////////////////////// // add stochastic forcing to gmres_rhs_u for (int d=0; d<AMREX_SPACEDIM; ++d) { MultiFab::Add(gmres_rhs_u[d], stochMfluxdiv[d], 0, 0, 1, 0); MultiFab::Add(gmres_rhs_u[d], sourceTerms[d], 0, 0, 1, 0); } // HERE is where you would add the particle forcing to gmres_rhs_u // // // // call GMRES GMRES(gmres_rhs_u,gmres_rhs_p,umac,pres,alpha_fc,beta,beta_ed,gamma,theta_alpha,geom,norm_pre_rhs); // fill periodic ghost cells for (int d=0; d<AMREX_SPACEDIM; ++d) { umac[d].FillBoundary(geom.periodicity()); } }
2,093
875
//-------------------------------------------------------------------------------------------------------------------------------- // Hassan Shahzad // 18i-0441 // OS-Project // FAST NUCES // main.cpp //-------------------------------------------------------------------------------------------------------------------------------- //================================================================================================================================ // 1: This file needs to be run inorder to ecexute the whole program successfully. //================================================================================================================================ #include <iostream> #include <vector> #include <unordered_set> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <unistd.h> #include <chrono> using namespace std::chrono; using namespace std; #include "board.cpp" State* start; State* goal; vector<State*> path; int numThreads = 0; int queuesPerThread = -1 ; #include "queues.cpp" #include "multithreading.cpp" int main(int argc, char *argv[]) { int size = 4; int moves = -1; int choice; string inputFile; cout<<"Do you want to test from file ?\n1: Yes\n2: No\nYour Choice = "; cin>>choice; if (choice == 1) { cout<<"Enter the name of the file = "; cin>>inputFile; } else { inputFile = ""; } cout<<"Enter the number of queues you want per thread = "; cin>> queuesPerThread; if (argc > 1) //Number of arguments must be greater than 1 numThreads = atoi(argv[1]); if (argc <=1 ) cout<<"Invalid number of threads"<<endl; cout << "Number of threads = " << numThreads << endl; cout << "Size = " << size << endl; cout << "Moves = " << moves << endl; if (inputFile.empty()) //If choice 2 is selected { if (moves >= 0) { start = (State*)(new Board(size, moves)); } else { start = (State*)(new Board(size)); } } else { start = (State*)(new Board(inputFile)); } cout << "Start board:" << endl; //Displaying the initial board cout << start->toString() << endl; if (numThreads != 0) { cout << "Running parallel version with " << numThreads << " threads..." << endl; //Displaying number of threads } if (queuesPerThread != -1) { int totalQueues = queuesPerThread * numThreads; //Storing the total number of queues cout << "Using " << totalQueues << " number of queues..." << endl; cout<<"Each thread will have "<<queuesPerThread << " queues to work with ...."<<endl; } goal = (State*)(new Board(size, 0)); auto start = high_resolution_clock::now(); //Calculating execution time if (numThreads == 0) { cout<<"Invalid number of threads entered.\nThe program will now exit........"<<endl; exit(0); } else { parallel(numThreads); } auto stop = high_resolution_clock::now(); auto duration = duration_cast<milliseconds>(stop - start); cout << "Optimal solution found!" << endl << endl; int length = path.size(); for (int i = 0; i < length; i++) //Dispalying steps { cout << "Step " << i << ":" << endl; cout << path[i]->toString() << endl; } cout << "Length of path: " << length-1 << endl; //Displaying total number of steps cout << "Total time: " << duration.count() << " ms" << endl; //Displaying execution time return 0; }
3,782
1,080
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/jit/vasm.h" #include "hphp/runtime/vm/jit/vasm-gen.h" #include "hphp/runtime/vm/jit/vasm-instr.h" #include "hphp/runtime/vm/jit/vasm-print.h" #include "hphp/runtime/vm/jit/vasm-reg.h" #include "hphp/runtime/vm/jit/vasm-unit.h" #include "hphp/runtime/vm/jit/vasm-util.h" #include "hphp/util/arch.h" #include "hphp/util/assertions.h" #include <folly/Optional.h> #include <cstdlib> TRACE_SET_MOD(vasm); namespace HPHP { namespace jit { namespace { // track ldimmq values struct ImmState { ImmState() {} ImmState(Immed64 a, Vreg b) : val{a}, base{b} {} void reset() { base = Vreg{}; } Immed64 val{0}; Vreg base; }; struct Env { Vunit& unit; std::vector<ImmState> immStateVec; }; bool isMultiword(int64_t imm) { switch (arch()) { case Arch::X64: case Arch::PPC64: break; case Arch::ARM: uint64_t val = std::abs(imm); if (val > (1 << 16)) return true; break; } return false; } // candidate around +/- uimm12 folly::Optional<int> reuseCandidate(Env& env, int64_t p, Vreg& reg) { for (auto const& elem : env.immStateVec) { if (!elem.base.isValid()) continue; int64_t q = elem.val.q(); if (((p >= q) && (p < (q + 4095))) || ((p < q) && (q < (p + 4095)))) { reg = elem.base; return folly::make_optional(safe_cast<int>(p - q)); } } return folly::none; } template <typename Inst> void reuseImmq(Env& env, const Inst& /*inst*/, Vlabel /*b*/, size_t i) { // leaky bucket env.immStateVec[i % RuntimeOption::EvalJitLdimmqSpan].reset(); } template<typename ReuseImm> void reuseimm_impl(Vunit& unit, Vlabel b, size_t i, ReuseImm reuse) { vmodify(unit, b, i, [&] (Vout& v) { reuse(v); return 1; }); } void reuseImmq(Env& env, const ldimmq& ld, Vlabel b, size_t i) { if (isMultiword(ld.s.q())) { Vreg base; auto const off = reuseCandidate(env, ld.s.q(), base); if (off.hasValue()) { reuseimm_impl(env.unit, b, i, [&] (Vout& v) { v << addqi{off.value(), base, ld.d, v.makeReg()}; }); return; } } env.immStateVec[i % RuntimeOption::EvalJitLdimmqSpan] = ImmState{ld.s, ld.d}; } void reuseImmq(Env& env, Vlabel b, size_t i) { assertx(i <= env.unit.blocks[b].code.size()); auto const& inst = env.unit.blocks[b].code[i]; if (isCall(inst)) { for (auto& elem : env.immStateVec) elem.reset(); return; } switch (inst.op) { #define O(name, ...) \ case Vinstr::name: \ reuseImmq(env, inst.name##_, b, i); \ break; VASM_OPCODES #undef O } } } // Opportunistically reuse immediate q values void reuseImmq(Vunit& unit) { assertx(check(unit)); auto& blocks = unit.blocks; if (RuntimeOption::EvalJitLdimmqSpan <= 0) return; Env env { unit }; env.immStateVec.resize(RuntimeOption::EvalJitLdimmqSpan); auto const labels = sortBlocks(unit); for (auto const b : labels) { for (auto& elem : env.immStateVec) elem.reset(); for (size_t i = 0; i < blocks[b].code.size(); ++i) { reuseImmq(env, b, i); } } printUnit(kVasmSimplifyLevel, "after vasm reuse immq", unit); } }}
4,130
1,539
// Copyright 2019 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <algorithm> #include <cmath> #include <functional> #include <random> #include <vector> #include <benchmark/benchmark.h> #include "bench/utils.h" #include <xnnpack/aligned-allocator.h> #include <xnnpack/common.h> #include <xnnpack/params.h> #include <xnnpack/raddexpminusmax.h> #include <xnnpack/rmax.h> static void f32_raddexpminusmax( benchmark::State& state, xnn_f32_rmax_ukernel_function rmax, xnn_f32_raddexpminusmax_ukernel_function raddexpminusmax, benchmark::utils::IsaCheckFunction isa_check = nullptr) { if (isa_check && !isa_check(state)) { return; } const size_t elements = state.range(0); const size_t cache_line_size_max = 128; const size_t packed_elements = benchmark::utils::RoundUp(elements, cache_line_size_max / sizeof(float)); std::random_device random_device; auto rng = std::mt19937(random_device()); auto f32rng = std::bind(std::uniform_real_distribution<float>(-1000.0f, 1000.0f), std::ref(rng)); const size_t num_buffers = 1 + benchmark::utils::DivideRoundUp<size_t>(benchmark::utils::GetMaxCacheSize(), packed_elements * sizeof(float)); std::vector<float, AlignedAllocator<float, 64>> x(elements); std::generate(x.begin(), x.end(), std::ref(f32rng)); benchmark::utils::DisableDenormals(); size_t buffer_index = 0; for (auto _ : state) { state.PauseTiming(); float x_max = nanf(""); rmax(elements * sizeof(float), x.data(), &x_max); if (++buffer_index == num_buffers) { buffer_index = 0; } state.ResumeTiming(); float y_sum = nanf(""); raddexpminusmax(elements * sizeof(float), x.data(), &y_sum, x_max); } const uint64_t cpu_frequency = benchmark::utils::GetCurrentCpuFrequency(); if (cpu_frequency != 0) { state.counters["cpufreq"] = cpu_frequency; } const size_t elements_per_iteration = elements; state.counters["elements"] = benchmark::Counter(uint64_t(state.iterations()) * elements_per_iteration, benchmark::Counter::kIsRate); const size_t bytes_per_iteration = 2 * elements * sizeof(float); state.counters["bytes"] = benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate); } static void CharacteristicArguments(benchmark::internal::Benchmark* b) { b->ArgName("N"); for (int32_t n = 10000; n <= 100000000; n *= 10) { b->Arg(n); } } #if XNN_ARCH_X86 || XNN_ARCH_X86_64 BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x64, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x64, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x64_acc2, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x64_acc2, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x64_acc4, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x64_acc4, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x72, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x72, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x72_acc3, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x72_acc3, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x80, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x80, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x80_acc2, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x80_acc2, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x80_acc5, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x80_acc5, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x96, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x96, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x96_acc2, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x96_acc2, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x96_acc3, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x96_acc3, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx2_p5_x96_acc6, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx2_p5_x96_acc6, benchmark::utils::CheckAVX2)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x128, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x128, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x128_acc2, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x128_acc2, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x128_acc4, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x128_acc4, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x144, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x144, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x144_acc3, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x144_acc3, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x160, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x160, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x160_acc2, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x160_acc2, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x160_acc5, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x160_acc5, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x192, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x192, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x192_acc2, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x192_acc2, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x192_acc3, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x192_acc3, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK_CAPTURE(f32_raddexpminusmax, avx512f_p5_scalef_x192_acc6, xnn_f32_rmax_ukernel__avx, xnn_f32_raddexpminusmax_ukernel__avx512f_p5_scalef_x192_acc6, benchmark::utils::CheckAVX512F)->Apply(CharacteristicArguments)->UseRealTime(); #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 #ifndef XNNPACK_BENCHMARK_NO_MAIN BENCHMARK_MAIN(); #endif
8,306
3,841
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h" #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/TestOutput.h" #include "CppUTest/JUnitTestOutput.h" #include "CppUTest/TeamCityTestOutput.h" #include "CppUTest/TestRegistry.h" int CommandLineTestRunner::RunAllTests(int ac, char** av) { return RunAllTests(ac, (const char**) av); } int CommandLineTestRunner::RunAllTests(int ac, const char** av) { int result = 0; ConsoleTestOutput backupOutput; MemoryLeakWarningPlugin memLeakWarn(DEF_PLUGIN_MEM_LEAK); memLeakWarn.destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(true); TestRegistry::getCurrentRegistry()->installPlugin(&memLeakWarn); { CommandLineTestRunner runner(ac, av, TestRegistry::getCurrentRegistry()); result = runner.runAllTestsMain(); } if (result == 0) { backupOutput << memLeakWarn.FinalReport(0); } TestRegistry::getCurrentRegistry()->removePluginByName(DEF_PLUGIN_MEM_LEAK); return result; } CommandLineTestRunner::CommandLineTestRunner(int ac, const char** av, TestRegistry* registry) : output_(NULL), arguments_(NULL), registry_(registry) { arguments_ = new CommandLineArguments(ac, av); } CommandLineTestRunner::~CommandLineTestRunner() { delete arguments_; delete output_; } int CommandLineTestRunner::runAllTestsMain() { int testResult = 0; SetPointerPlugin pPlugin(DEF_PLUGIN_SET_POINTER); registry_->installPlugin(&pPlugin); if (parseArguments(registry_->getFirstPlugin())) testResult = runAllTests(); registry_->removePluginByName(DEF_PLUGIN_SET_POINTER); return testResult; } void CommandLineTestRunner::initializeTestRun() { registry_->setGroupFilters(arguments_->getGroupFilters()); registry_->setNameFilters(arguments_->getNameFilters()); if (arguments_->isVerbose()) output_->verbose(); if (arguments_->isColor()) output_->color(); if (arguments_->runTestsInSeperateProcess()) registry_->setRunTestsInSeperateProcess(); if (arguments_->isRunIgnored()) registry_->setRunIgnored(); } int CommandLineTestRunner::runAllTests() { initializeTestRun(); int loopCount = 0; int failureCount = 0; int repeat_ = arguments_->getRepeatCount(); if (arguments_->isListingTestGroupNames()) { TestResult tr(*output_); registry_->listTestGroupNames(tr); return 0; } if (arguments_->isListingTestGroupAndCaseNames()) { TestResult tr(*output_); registry_->listTestGroupAndCaseNames(tr); return 0; } while (loopCount++ < repeat_) { output_->printTestRun(loopCount, repeat_); TestResult tr(*output_); registry_->runAllTests(tr); failureCount += tr.getFailureCount(); } return failureCount; } TestOutput* CommandLineTestRunner::createTeamCityOutput() { return new TeamCityTestOutput; } TestOutput* CommandLineTestRunner::createJUnitOutput(const SimpleString& packageName) { JUnitTestOutput* junitOutput = new JUnitTestOutput; if (junitOutput != NULL) { junitOutput->setPackageName(packageName); } return junitOutput; } TestOutput* CommandLineTestRunner::createConsoleOutput() { return new ConsoleTestOutput; } TestOutput* CommandLineTestRunner::createCompositeOutput(TestOutput* outputOne, TestOutput* outputTwo) { CompositeTestOutput* composite = new CompositeTestOutput; composite->setOutputOne(outputOne); composite->setOutputTwo(outputTwo); return composite; } bool CommandLineTestRunner::parseArguments(TestPlugin* plugin) { if (!arguments_->parse(plugin)) { output_ = createConsoleOutput(); output_->print(arguments_->usage()); return false; } if (arguments_->isJUnitOutput()) { output_= createJUnitOutput(arguments_->getPackageName()); if (arguments_->isVerbose()) output_ = createCompositeOutput(output_, createConsoleOutput()); } else if (arguments_->isTeamCityOutput()) { output_ = createTeamCityOutput(); } else output_ = createConsoleOutput(); return true; }
5,854
1,842
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Jayne Henry // ============================================================================= // // Simple powertrain model for the RCCar vehicle. // - based on torque-speed engine maps // - both power and torque limited // - no torque converter // - simple gear-shifting model (in automatic mode) // // ============================================================================= #include "chrono_models/vehicle/rccar/RCCar_SimpleMapPowertrain.h" using namespace chrono::vehicle; using namespace chrono; namespace chrono { namespace vehicle { namespace rccar { const double rpm2rads = CH_C_PI / 30; const double Kv_rating = 1300; const double supply_voltage = 8.0; const double max_rpm = Kv_rating * supply_voltage; const double stall_torque = 1.0; // TODO, currently a guess RCCar_SimpleMapPowertrain::RCCar_SimpleMapPowertrain(const std::string& name) : ChSimpleMapPowertrain(name) {} double RCCar_SimpleMapPowertrain::GetMaxEngineSpeed() { return max_rpm * rpm2rads; } void RCCar_SimpleMapPowertrain::SetEngineTorqueMaps(ChFunction_Recorder& map0, ChFunction_Recorder& mapF) { // since this is a model of motor and ESC combination, we assume a linear relationship. // while brushless motors dont follow linear torque-speed relationship, most hobby electronic // speed controllers control the motor such that it approximately follows a linear relationship mapF.AddPoint(0,stall_torque); //stall torque //TODO mapF.AddPoint(max_rpm * rpm2rads, 0); // no load speed // N-m and rad/s map0.AddPoint(0, 0); map0.AddPoint(.1 * max_rpm * rpm2rads, 0); map0.AddPoint(max_rpm * rpm2rads, -stall_torque); // TODO, currently a guess } void RCCar_SimpleMapPowertrain::SetGearRatios(std::vector<double>& fwd, double& rev) { rev = -1.0 / 3; fwd.push_back(1.0 / 3); } void RCCar_SimpleMapPowertrain::SetShiftPoints(std::vector<std::pair<double, double>>& shift_bands) { shift_bands.push_back(std::pair<double, double>(0, 10 * max_rpm * rpm2rads)); //never shifts } } // end namespace rccar } // namespace vehicle } // namespace chrono
2,592
846
/* * Mark Benjamin 6th March 2019 * Copyright (c) 2019 Mark Benjamin */ #ifndef FASTRL_SHELL_COMMAND_WORLD_ADD_STATE_OBJECT_SG_COMMAND_HPP #define FASTRL_SHELL_COMMAND_WORLD_ADD_STATE_OBJECT_SG_COMMAND_HPP class AddStateObjectSGCommand { }; #endif //FASTRL_SHELL_COMMAND_WORLD_ADD_STATE_OBJECT_SG_COMMAND_HPP
317
150
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "d3dx12affinity.h" #include "CD3DX12Utils.h" D3D12_DESCRIPTOR_HEAP_DESC STDMETHODCALLTYPE CD3DX12AffinityDescriptorHeap::GetDesc(UINT AffinityIndex) { return mDescriptorHeaps[AffinityIndex]->GetDesc(); } D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE CD3DX12AffinityDescriptorHeap::GetCPUDescriptorHandleForHeapStart(void) { if (GetNodeCount() == 1) { return mDescriptorHeaps[0]->GetCPUDescriptorHandleForHeapStart(); } D3D12_CPU_DESCRIPTOR_HANDLE handle; handle.ptr = (SIZE_T)mCPUHeapStart; return handle; } D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE CD3DX12AffinityDescriptorHeap::GetGPUDescriptorHandleForHeapStart(void) { if (GetNodeCount() == 1) { return mDescriptorHeaps[0]->GetGPUDescriptorHandleForHeapStart(); } D3D12_GPU_DESCRIPTOR_HANDLE handle; handle.ptr = (SIZE_T)mGPUHeapStart; return handle; } D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE CD3DX12AffinityDescriptorHeap::GetActiveCPUDescriptorHandleForHeapStart(UINT AffinityIndex) { return mDescriptorHeaps[AffinityIndex]->GetCPUDescriptorHandleForHeapStart(); } D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE CD3DX12AffinityDescriptorHeap::GetActiveGPUDescriptorHandleForHeapStart(UINT AffinityIndex) { return mDescriptorHeaps[AffinityIndex]->GetGPUDescriptorHandleForHeapStart(); } void CD3DX12AffinityDescriptorHeap::InitDescriptorHandles(D3D12_DESCRIPTOR_HEAP_TYPE type) { UINT const NodeCount = GetNodeCount(); UINT maxindex = 0; for (UINT i = 0; i < NodeCount; ++i) { D3D12_CPU_DESCRIPTOR_HANDLE const CPUBase = mDescriptorHeaps[i]->GetCPUDescriptorHandleForHeapStart(); D3D12_GPU_DESCRIPTOR_HANDLE const GPUBase = mDescriptorHeaps[i]->GetGPUDescriptorHandleForHeapStart(); UINT HandleIncrement = 0; if (GetParentDevice()->GetAffinityMode() == EAffinityMode::LDA) { HandleIncrement = GetParentDevice()->GetChildObject(0)->GetDescriptorHandleIncrementSize(type); } for (UINT j = 0; j < mNumDescriptors; ++j) { mCPUHeapStart[j * NodeCount + i] = CPUBase.ptr + HandleIncrement * j; mGPUHeapStart[j * NodeCount + i] = GPUBase.ptr + HandleIncrement * j; maxindex = max(maxindex, j * NodeCount + i); } } DebugLog("Used up to index %u in heap array\n", maxindex); DebugLog("Created a descriptor heap with CPU start at 0x%IX and GPU start a 0x%IX\n", mCPUHeapStart, mGPUHeapStart); for (UINT i = 0; i < NodeCount; ++i) { DebugLog(" Device %u CPU starts at 0x%IX and GPU starts at 0x%IX\n", i, mDescriptorHeaps[i]->GetCPUDescriptorHandleForHeapStart().ptr, mDescriptorHeaps[i]->GetGPUDescriptorHandleForHeapStart().ptr); } #ifdef D3DX_AFFINITY_ENABLE_HEAP_POINTER_VALIDATION // Validation { std::lock_guard<std::mutex> lock(GetParentDevice()->MutexPointerRanges); GetParentDevice()->CPUHeapPointerRanges.push_back(std::make_pair((SIZE_T)mCPUHeapStart, (SIZE_T)(mCPUHeapStart + mNumDescriptors * NodeCount))); GetParentDevice()->GPUHeapPointerRanges.push_back(std::make_pair((SIZE_T)mGPUHeapStart, (SIZE_T)(mGPUHeapStart + mNumDescriptors * NodeCount))); } #endif } CD3DX12AffinityDescriptorHeap::CD3DX12AffinityDescriptorHeap(CD3DX12AffinityDevice* device, ID3D12DescriptorHeap** descriptorHeaps, UINT Count) : CD3DX12AffinityPageable(device, reinterpret_cast<ID3D12Pageable**>(descriptorHeaps), Count) , mCPUHeapStart(nullptr) , mGPUHeapStart(nullptr) { for (UINT i = 0; i < D3DX12_MAX_ACTIVE_NODES; i++) { if (i < Count) { mDescriptorHeaps[i] = descriptorHeaps[i]; } else { mDescriptorHeaps[i] = nullptr; } } #ifdef DEBUG_OBJECT_NAME mObjectTypeName = L"DescriptorHeap"; #endif } CD3DX12AffinityDescriptorHeap::~CD3DX12AffinityDescriptorHeap() { if (mCPUHeapStart != nullptr) { delete[] mCPUHeapStart; } if (mGPUHeapStart != nullptr) { delete[] mGPUHeapStart; } } ID3D12DescriptorHeap* CD3DX12AffinityDescriptorHeap::GetChildObject(UINT AffinityIndex) { return mDescriptorHeaps[AffinityIndex]; }
4,661
1,743
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames // Copyright (C) 2015 Faust Logic, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// #include "arcaneFX.h" #include "T3D/aiPlayer.h" #include "T3D/tsStatic.h" #include "sim/netConnection.h" #include "ts/tsShapeInstance.h" #include "afxConstraint.h" #include "afxChoreographer.h" #include "afxEffectWrapper.h" //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxConstraintDef // static StringTableEntry afxConstraintDef::SCENE_CONS_KEY; StringTableEntry afxConstraintDef::EFFECT_CONS_KEY; StringTableEntry afxConstraintDef::GHOST_CONS_KEY; afxConstraintDef::afxConstraintDef() { if (SCENE_CONS_KEY == 0) { SCENE_CONS_KEY = StringTable->insert("#scene"); EFFECT_CONS_KEY = StringTable->insert("#effect"); GHOST_CONS_KEY = StringTable->insert("#ghost"); } reset(); } bool afxConstraintDef::isDefined() { return (def_type != CONS_UNDEFINED); } bool afxConstraintDef::isArbitraryObject() { return ((cons_src_name != ST_NULLSTRING) && (def_type == CONS_SCENE)); } void afxConstraintDef::reset() { cons_src_name = ST_NULLSTRING; cons_node_name = ST_NULLSTRING; def_type = CONS_UNDEFINED; history_time = 0; sample_rate = 30; runs_on_server = false; runs_on_client = false; pos_at_box_center = false; treat_as_camera = false; } bool afxConstraintDef::parseSpec(const char* spec, bool runs_on_server, bool runs_on_client) { reset(); if (spec == 0 || spec[0] == '\0') return false; history_time = 0.0f; sample_rate = 30; this->runs_on_server = runs_on_server; this->runs_on_client = runs_on_client; // spec should be in one of these forms: // CONSTRAINT_NAME (only) // CONSTRAINT_NAME.NODE (shapeBase objects only) // CONSTRAINT_NAME.#center // object.OBJECT_NAME // object.OBJECT_NAME.NODE (shapeBase objects only) // object.OBJECT_NAME.#center // effect.EFFECT_NAME // effect.EFFECT_NAME.NODE // effect.EFFECT_NAME.#center // #ghost.EFFECT_NAME // #ghost.EFFECT_NAME.NODE // #ghost.EFFECT_NAME.#center // // create scratch buffer by duplicating spec. char special = '\b'; char* buffer = dStrdup(spec); // substitute a dots not inside parens with special character S32 n_nested = 0; for (char* b = buffer; (*b) != '\0'; b++) { if ((*b) == '(') n_nested++; else if ((*b) == ')') n_nested--; else if ((*b) == '.' && n_nested == 0) (*b) = special; } // divide name into '.' separated tokens (up to 8) char* words[8] = {0, 0, 0, 0, 0, 0, 0, 0}; char* dot = buffer; int wdx = 0; while (wdx < 8) { words[wdx] = dot; dot = dStrchr(words[wdx++], special); if (!dot) break; *(dot++) = '\0'; if ((*dot) == '\0') break; } int n_words = wdx; // at this point the spec has been split into words. // n_words indicates how many words we have. // no words found (must have been all whitespace) if (n_words < 1) { dFree(buffer); return false; } char* hist_spec = 0; char* words2[8] = {0, 0, 0, 0, 0, 0, 0, 0}; int n_words2 = 0; // move words to words2 while extracting #center and #history for (S32 i = 0; i < n_words; i++) { if (dStrcmp(words[i], "#center") == 0) pos_at_box_center = true; else if (dStrncmp(words[i], "#history(", 9) == 0) hist_spec = words[i]; else words2[n_words2++] = words[i]; } // words2[] now contains just the constraint part // no words found (must have been all #center and #history) if (n_words2 < 1) { dFree(buffer); return false; } if (hist_spec) { char* open_paren = dStrchr(hist_spec, '('); if (open_paren) { hist_spec = open_paren+1; if ((*hist_spec) != '\0') { char* close_paren = dStrchr(hist_spec, ')'); if (close_paren) (*close_paren) = '\0'; char* slash = dStrchr(hist_spec, '/'); if (slash) (*slash) = ' '; F32 hist_age = 0.0; U32 hist_rate = 30; S32 args = dSscanf(hist_spec,"%g %d", &hist_age, &hist_rate); if (args > 0) history_time = hist_age; if (args > 1) sample_rate = hist_rate; } } } StringTableEntry cons_name_key = StringTable->insert(words2[0]); // must be in CONSTRAINT_NAME (only) form if (n_words2 == 1) { // arbitrary object/effect constraints must have a name if (cons_name_key == SCENE_CONS_KEY || cons_name_key == EFFECT_CONS_KEY) { dFree(buffer); return false; } cons_src_name = cons_name_key; def_type = CONS_PREDEFINED; dFree(buffer); return true; } // "#scene.NAME" or "#scene.NAME.NODE"" if (cons_name_key == SCENE_CONS_KEY) { cons_src_name = StringTable->insert(words2[1]); if (n_words2 > 2) cons_node_name = StringTable->insert(words2[2]); def_type = CONS_SCENE; dFree(buffer); return true; } // "#effect.NAME" or "#effect.NAME.NODE" if (cons_name_key == EFFECT_CONS_KEY) { cons_src_name = StringTable->insert(words2[1]); if (n_words2 > 2) cons_node_name = StringTable->insert(words2[2]); def_type = CONS_EFFECT; dFree(buffer); return true; } // "#ghost.NAME" or "#ghost.NAME.NODE" if (cons_name_key == GHOST_CONS_KEY) { if (runs_on_server) { dFree(buffer); return false; } cons_src_name = StringTable->insert(words2[1]); if (n_words2 > 2) cons_node_name = StringTable->insert(words2[2]); def_type = CONS_GHOST; dFree(buffer); return true; } // "CONSTRAINT_NAME.NODE" if (n_words2 == 2) { cons_src_name = cons_name_key; cons_node_name = StringTable->insert(words2[1]); def_type = CONS_PREDEFINED; dFree(buffer); return true; } // must be in unsupported form dFree(buffer); return false; } void afxConstraintDef::gather_cons_defs(Vector<afxConstraintDef>& defs, afxEffectList& fx) { for (S32 i = 0; i < fx.size(); i++) { if (fx[i]) fx[i]->gather_cons_defs(defs); } } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxConstraint afxConstraint::afxConstraint(afxConstraintMgr* mgr) { this->mgr = mgr; is_defined = false; is_valid = false; last_pos.zero(); last_xfm.identity(); history_time = 0.0f; is_alive = true; gone_missing = false; change_code = 0; } afxConstraint::~afxConstraint() { } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// inline afxPointConstraint* newPointCons(afxConstraintMgr* mgr, bool hist) { return (hist) ? new afxPointHistConstraint(mgr) : new afxPointConstraint(mgr); } inline afxTransformConstraint* newTransformCons(afxConstraintMgr* mgr, bool hist) { return (hist) ? new afxTransformHistConstraint(mgr) : new afxTransformConstraint(mgr); } inline afxShapeConstraint* newShapeCons(afxConstraintMgr* mgr, bool hist) { return (hist) ? new afxShapeHistConstraint(mgr) : new afxShapeConstraint(mgr); } inline afxShapeConstraint* newShapeCons(afxConstraintMgr* mgr, StringTableEntry name, bool hist) { return (hist) ? new afxShapeHistConstraint(mgr, name) : new afxShapeConstraint(mgr, name); } inline afxShapeNodeConstraint* newShapeNodeCons(afxConstraintMgr* mgr, StringTableEntry name, StringTableEntry node, bool hist) { return (hist) ? new afxShapeNodeHistConstraint(mgr, name, node) : new afxShapeNodeConstraint(mgr, name, node); } inline afxObjectConstraint* newObjectCons(afxConstraintMgr* mgr, bool hist) { return (hist) ? new afxObjectHistConstraint(mgr) : new afxObjectConstraint(mgr); } inline afxObjectConstraint* newObjectCons(afxConstraintMgr* mgr, StringTableEntry name, bool hist) { return (hist) ? new afxObjectHistConstraint(mgr, name) : new afxObjectConstraint(mgr, name); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxConstraintMgr #define CONS_BY_ID(id) ((*constraints_v[(id).index])[(id).sub_index]) #define CONS_BY_IJ(i,j) ((*constraints_v[(i)])[(j)]) afxConstraintMgr::afxConstraintMgr() { starttime = 0; on_server = false; initialized = false; scoping_dist_sq = 1000.0f*1000.0f; missing_objs = &missing_objs_a; missing_objs2 = &missing_objs_b; } afxConstraintMgr::~afxConstraintMgr() { for (S32 i = 0; i < constraints_v.size(); i++) { for (S32 j = 0; j < (*constraints_v[i]).size(); j++) delete CONS_BY_IJ(i,j); delete constraints_v[i]; } } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~// S32 afxConstraintMgr::find_cons_idx_from_name(StringTableEntry which) { for (S32 i = 0; i < constraints_v.size(); i++) { afxConstraint* cons = CONS_BY_IJ(i,0); if (cons && afxConstraintDef::CONS_EFFECT != cons->cons_def.def_type && which == cons->cons_def.cons_src_name) { return i; } } return -1; } S32 afxConstraintMgr::find_effect_cons_idx_from_name(StringTableEntry which) { for (S32 i = 0; i < constraints_v.size(); i++) { afxConstraint* cons = CONS_BY_IJ(i,0); if (cons && afxConstraintDef::CONS_EFFECT == cons->cons_def.def_type && which == cons->cons_def.cons_src_name) { return i; } } return -1; } // Defines a predefined constraint with given name and type void afxConstraintMgr::defineConstraint(U32 type, StringTableEntry name) { preDef predef = { name, type }; predefs.push_back(predef); } afxConstraintID afxConstraintMgr::setReferencePoint(StringTableEntry which, Point3F point, Point3F vector) { S32 idx = find_cons_idx_from_name(which); if (idx < 0) return afxConstraintID(); afxConstraintID id = afxConstraintID(idx); setReferencePoint(id, point, vector); return id; } afxConstraintID afxConstraintMgr::setReferenceTransform(StringTableEntry which, MatrixF& xfm) { S32 idx = find_cons_idx_from_name(which); if (idx < 0) return afxConstraintID(); afxConstraintID id = afxConstraintID(idx); setReferenceTransform(id, xfm); return id; } // Assigns an existing scene-object to the named constraint afxConstraintID afxConstraintMgr::setReferenceObject(StringTableEntry which, SceneObject* obj) { S32 idx = find_cons_idx_from_name(which); if (idx < 0) return afxConstraintID(); afxConstraintID id = afxConstraintID(idx); setReferenceObject(id, obj); return id; } // Assigns an un-scoped scene-object by scope_id to the named constraint afxConstraintID afxConstraintMgr::setReferenceObjectByScopeId(StringTableEntry which, U16 scope_id, bool is_shape) { S32 idx = find_cons_idx_from_name(which); if (idx < 0) return afxConstraintID(); afxConstraintID id = afxConstraintID(idx); setReferenceObjectByScopeId(id, scope_id, is_shape); return id; } afxConstraintID afxConstraintMgr::setReferenceEffect(StringTableEntry which, afxEffectWrapper* ew) { S32 idx = find_effect_cons_idx_from_name(which); if (idx < 0) return afxConstraintID(); afxConstraintID id = afxConstraintID(idx); setReferenceEffect(id, ew); return id; } afxConstraintID afxConstraintMgr::createReferenceEffect(StringTableEntry which, afxEffectWrapper* ew) { afxEffectConstraint* cons = new afxEffectConstraint(this, which); //cons->cons_def = def; cons->cons_def.def_type = afxConstraintDef::CONS_EFFECT; cons->cons_def.cons_src_name = which; afxConstraintList* list = new afxConstraintList(); list->push_back(cons); constraints_v.push_back(list); return setReferenceEffect(which, ew); } void afxConstraintMgr::setReferencePoint(afxConstraintID id, Point3F point, Point3F vector) { afxPointConstraint* pt_cons = dynamic_cast<afxPointConstraint*>(CONS_BY_ID(id)); // need to change type if (!pt_cons) { afxConstraint* cons = CONS_BY_ID(id); pt_cons = newPointCons(this, cons->cons_def.history_time > 0.0f); pt_cons->cons_def = cons->cons_def; CONS_BY_ID(id) = pt_cons; delete cons; } pt_cons->set(point, vector); // nullify all subnodes for (S32 j = 1; j < (*constraints_v[id.index]).size(); j++) { afxConstraint* cons = CONS_BY_IJ(id.index,j); if (cons) cons->unset(); } } void afxConstraintMgr::setReferenceTransform(afxConstraintID id, MatrixF& xfm) { afxTransformConstraint* xfm_cons = dynamic_cast<afxTransformConstraint*>(CONS_BY_ID(id)); // need to change type if (!xfm_cons) { afxConstraint* cons = CONS_BY_ID(id); xfm_cons = newTransformCons(this, cons->cons_def.history_time > 0.0f); xfm_cons->cons_def = cons->cons_def; CONS_BY_ID(id) = xfm_cons; delete cons; } xfm_cons->set(xfm); // nullify all subnodes for (S32 j = 1; j < (*constraints_v[id.index]).size(); j++) { afxConstraint* cons = CONS_BY_IJ(id.index,j); if (cons) cons->unset(); } } void afxConstraintMgr::set_ref_shape(afxConstraintID id, ShapeBase* shape) { id.sub_index = 0; afxShapeConstraint* shape_cons = dynamic_cast<afxShapeConstraint*>(CONS_BY_ID(id)); // need to change type if (!shape_cons) { afxConstraint* cons = CONS_BY_ID(id); shape_cons = newShapeCons(this, cons->cons_def.history_time > 0.0f); shape_cons->cons_def = cons->cons_def; CONS_BY_ID(id) = shape_cons; delete cons; } // set new shape on root shape_cons->set(shape); // update all subnodes for (S32 j = 1; j < (*constraints_v[id.index]).size(); j++) { afxConstraint* cons = CONS_BY_IJ(id.index,j); if (cons) { if (dynamic_cast<afxShapeNodeConstraint*>(cons)) ((afxShapeNodeConstraint*)cons)->set(shape); else if (dynamic_cast<afxShapeConstraint*>(cons)) ((afxShapeConstraint*)cons)->set(shape); else if (dynamic_cast<afxObjectConstraint*>(cons)) ((afxObjectConstraint*)cons)->set(shape); else cons->unset(); } } } void afxConstraintMgr::set_ref_shape(afxConstraintID id, U16 scope_id) { id.sub_index = 0; afxShapeConstraint* shape_cons = dynamic_cast<afxShapeConstraint*>(CONS_BY_ID(id)); // need to change type if (!shape_cons) { afxConstraint* cons = CONS_BY_ID(id); shape_cons = newShapeCons(this, cons->cons_def.history_time > 0.0f); shape_cons->cons_def = cons->cons_def; CONS_BY_ID(id) = shape_cons; delete cons; } // set new shape on root shape_cons->set_scope_id(scope_id); // update all subnodes for (S32 j = 1; j < (*constraints_v[id.index]).size(); j++) { afxConstraint* cons = CONS_BY_IJ(id.index,j); if (cons) cons->set_scope_id(scope_id); } } // Assigns an existing scene-object to the constraint matching the given constraint-id. void afxConstraintMgr::setReferenceObject(afxConstraintID id, SceneObject* obj) { if (!initialized) Con::errorf("afxConstraintMgr::setReferenceObject() -- constraint manager not initialized"); if (!CONS_BY_ID(id)->cons_def.treat_as_camera) { ShapeBase* shape = dynamic_cast<ShapeBase*>(obj); if (shape) { set_ref_shape(id, shape); return; } } afxObjectConstraint* obj_cons = dynamic_cast<afxObjectConstraint*>(CONS_BY_ID(id)); // need to change type if (!obj_cons) { afxConstraint* cons = CONS_BY_ID(id); obj_cons = newObjectCons(this, cons->cons_def.history_time > 0.0f); obj_cons->cons_def = cons->cons_def; CONS_BY_ID(id) = obj_cons; delete cons; } obj_cons->set(obj); // update all subnodes for (S32 j = 1; j < (*constraints_v[id.index]).size(); j++) { afxConstraint* cons = CONS_BY_IJ(id.index,j); if (cons) { if (dynamic_cast<afxObjectConstraint*>(cons)) ((afxObjectConstraint*)cons)->set(obj); else cons->unset(); } } } // Assigns an un-scoped scene-object by scope_id to the constraint matching the // given constraint-id. void afxConstraintMgr::setReferenceObjectByScopeId(afxConstraintID id, U16 scope_id, bool is_shape) { if (!initialized) Con::errorf("afxConstraintMgr::setReferenceObject() -- constraint manager not initialized"); if (is_shape) { set_ref_shape(id, scope_id); return; } afxObjectConstraint* obj_cons = dynamic_cast<afxObjectConstraint*>(CONS_BY_ID(id)); // need to change type if (!obj_cons) { afxConstraint* cons = CONS_BY_ID(id); obj_cons = newObjectCons(this, cons->cons_def.history_time > 0.0f); obj_cons->cons_def = cons->cons_def; CONS_BY_ID(id) = obj_cons; delete cons; } obj_cons->set_scope_id(scope_id); // update all subnodes for (S32 j = 1; j < (*constraints_v[id.index]).size(); j++) { afxConstraint* cons = CONS_BY_IJ(id.index,j); if (cons) cons->set_scope_id(scope_id); } } void afxConstraintMgr::setReferenceEffect(afxConstraintID id, afxEffectWrapper* ew) { afxEffectConstraint* eff_cons = dynamic_cast<afxEffectConstraint*>(CONS_BY_ID(id)); if (!eff_cons) return; eff_cons->set(ew); // update all subnodes for (S32 j = 1; j < (*constraints_v[id.index]).size(); j++) { afxConstraint* cons = CONS_BY_IJ(id.index,j); if (cons) { if (dynamic_cast<afxEffectNodeConstraint*>(cons)) ((afxEffectNodeConstraint*)cons)->set(ew); else if (dynamic_cast<afxEffectConstraint*>(cons)) ((afxEffectConstraint*)cons)->set(ew); else cons->unset(); } } } void afxConstraintMgr::invalidateReference(afxConstraintID id) { afxConstraint* cons = CONS_BY_ID(id); if (cons) cons->is_valid = false; } void afxConstraintMgr::create_constraint(const afxConstraintDef& def) { if (def.def_type == afxConstraintDef::CONS_UNDEFINED) return; //Con::printf("CON - %s [%s] [%s] h=%g", def.cons_type_name, def.cons_src_name, def.cons_node_name, def.history_time); bool want_history = (def.history_time > 0.0f); // constraint is an arbitrary named scene object // if (def.def_type == afxConstraintDef::CONS_SCENE) { if (def.cons_src_name == ST_NULLSTRING) return; // find the arbitrary object by name SceneObject* arb_obj; if (on_server) { arb_obj = dynamic_cast<SceneObject*>(Sim::findObject(def.cons_src_name)); if (!arb_obj) Con::errorf("afxConstraintMgr -- failed to find scene constraint source, \"%s\" on server.", def.cons_src_name); } else { arb_obj = find_object_from_name(def.cons_src_name); if (!arb_obj) Con::errorf("afxConstraintMgr -- failed to find scene constraint source, \"%s\" on client.", def.cons_src_name); } // if it's a shapeBase object, create a Shape or ShapeNode constraint if (dynamic_cast<ShapeBase*>(arb_obj)) { if (def.cons_node_name == ST_NULLSTRING && !def.pos_at_box_center) { afxShapeConstraint* cons = newShapeCons(this, def.cons_src_name, want_history); cons->cons_def = def; cons->set((ShapeBase*)arb_obj); afxConstraintList* list = new afxConstraintList(); list->push_back(cons); constraints_v.push_back(list); } else if (def.pos_at_box_center) { afxShapeConstraint* cons = newShapeCons(this, def.cons_src_name, want_history); cons->cons_def = def; cons->set((ShapeBase*)arb_obj); afxConstraintList* list = constraints_v[constraints_v.size()-1]; // SHAPE-NODE CONS-LIST (#scene)(#center) if (list && (*list)[0]) list->push_back(cons); } else { afxShapeNodeConstraint* sub = newShapeNodeCons(this, def.cons_src_name, def.cons_node_name, want_history); sub->cons_def = def; sub->set((ShapeBase*)arb_obj); afxConstraintList* list = constraints_v[constraints_v.size()-1]; if (list && (*list)[0]) list->push_back(sub); } } // if it's not a shapeBase object, create an Object constraint else if (arb_obj) { if (!def.pos_at_box_center) { afxObjectConstraint* cons = newObjectCons(this, def.cons_src_name, want_history); cons->cons_def = def; cons->set(arb_obj); afxConstraintList* list = new afxConstraintList(); // OBJECT CONS-LIST (#scene) list->push_back(cons); constraints_v.push_back(list); } else // if (def.pos_at_box_center) { afxObjectConstraint* cons = newObjectCons(this, def.cons_src_name, want_history); cons->cons_def = def; cons->set(arb_obj); afxConstraintList* list = constraints_v[constraints_v.size()-1]; // OBJECT CONS-LIST (#scene)(#center) if (list && (*list)[0]) list->push_back(cons); } } } // constraint is an arbitrary named effect // else if (def.def_type == afxConstraintDef::CONS_EFFECT) { if (def.cons_src_name == ST_NULLSTRING) return; // create an Effect constraint if (def.cons_node_name == ST_NULLSTRING && !def.pos_at_box_center) { afxEffectConstraint* cons = new afxEffectConstraint(this, def.cons_src_name); cons->cons_def = def; afxConstraintList* list = new afxConstraintList(); list->push_back(cons); constraints_v.push_back(list); } // create an Effect #center constraint else if (def.pos_at_box_center) { afxEffectConstraint* cons = new afxEffectConstraint(this, def.cons_src_name); cons->cons_def = def; afxConstraintList* list = constraints_v[constraints_v.size()-1]; // EFFECT-NODE CONS-LIST (#effect) if (list && (*list)[0]) list->push_back(cons); } // create an EffectNode constraint else { afxEffectNodeConstraint* sub = new afxEffectNodeConstraint(this, def.cons_src_name, def.cons_node_name); sub->cons_def = def; afxConstraintList* list = constraints_v[constraints_v.size()-1]; if (list && (*list)[0]) list->push_back(sub); } } // constraint is a predefined constraint // else { afxConstraint* cons = 0; afxConstraint* cons_ctr = 0; afxConstraint* sub = 0; if (def.def_type == afxConstraintDef::CONS_GHOST) { for (S32 i = 0; i < predefs.size(); i++) { if (predefs[i].name == def.cons_src_name) { if (def.cons_node_name == ST_NULLSTRING && !def.pos_at_box_center) { cons = newShapeCons(this, want_history); cons->cons_def = def; } else if (def.pos_at_box_center) { cons_ctr = newShapeCons(this, want_history); cons_ctr->cons_def = def; } else { sub = newShapeNodeCons(this, ST_NULLSTRING, def.cons_node_name, want_history); sub->cons_def = def; } break; } } } else { for (S32 i = 0; i < predefs.size(); i++) { if (predefs[i].name == def.cons_src_name) { switch (predefs[i].type) { case POINT_CONSTRAINT: cons = newPointCons(this, want_history); cons->cons_def = def; break; case TRANSFORM_CONSTRAINT: cons = newTransformCons(this, want_history); cons->cons_def = def; break; case OBJECT_CONSTRAINT: if (def.cons_node_name == ST_NULLSTRING && !def.pos_at_box_center) { cons = newShapeCons(this, want_history); cons->cons_def = def; } else if (def.pos_at_box_center) { cons_ctr = newShapeCons(this, want_history); cons_ctr->cons_def = def; } else { sub = newShapeNodeCons(this, ST_NULLSTRING, def.cons_node_name, want_history); sub->cons_def = def; } break; case CAMERA_CONSTRAINT: cons = newObjectCons(this, want_history); cons->cons_def = def; cons->cons_def.treat_as_camera = true; break; } break; } } } if (cons) { afxConstraintList* list = new afxConstraintList(); list->push_back(cons); constraints_v.push_back(list); } else if (cons_ctr && constraints_v.size() > 0) { afxConstraintList* list = constraints_v[constraints_v.size()-1]; // PREDEF-NODE CONS-LIST if (list && (*list)[0]) list->push_back(cons_ctr); } else if (sub && constraints_v.size() > 0) { afxConstraintList* list = constraints_v[constraints_v.size()-1]; if (list && (*list)[0]) list->push_back(sub); } else Con::printf("predef not found %s", def.cons_src_name); } } afxConstraintID afxConstraintMgr::getConstraintId(const afxConstraintDef& def) { if (def.def_type == afxConstraintDef::CONS_UNDEFINED) return afxConstraintID(); if (def.cons_src_name != ST_NULLSTRING) { for (S32 i = 0; i < constraints_v.size(); i++) { afxConstraintList* list = constraints_v[i]; afxConstraint* cons = (*list)[0]; if (def.cons_src_name == cons->cons_def.cons_src_name) { for (S32 j = 0; j < list->size(); j++) { afxConstraint* sub = (*list)[j]; if (def.cons_node_name == sub->cons_def.cons_node_name && def.pos_at_box_center == sub->cons_def.pos_at_box_center && def.cons_src_name == sub->cons_def.cons_src_name) { return afxConstraintID(i, j); } } // if we're here, it means the root object name matched but the node name // did not. if (def.def_type == afxConstraintDef::CONS_PREDEFINED && !def.pos_at_box_center) { afxShapeConstraint* shape_cons = dynamic_cast<afxShapeConstraint*>(cons); if (shape_cons) { //Con::errorf("Append a Node constraint [%s.%s] [%d,%d]", def.cons_src_name, def.cons_node_name, i, list->size()); bool want_history = (def.history_time > 0.0f); afxConstraint* sub = newShapeNodeCons(this, ST_NULLSTRING, def.cons_node_name, want_history); sub->cons_def = def; ((afxShapeConstraint*)sub)->set(shape_cons->shape); list->push_back(sub); return afxConstraintID(i, list->size()-1); } } break; } } } return afxConstraintID(); } afxConstraint* afxConstraintMgr::getConstraint(afxConstraintID id) { if (id.undefined()) return 0; afxConstraint* cons = CONS_BY_IJ(id.index,id.sub_index); if (cons && !cons->isDefined()) return NULL; return cons; } void afxConstraintMgr::sample(F32 dt, U32 now, const Point3F* cam_pos) { U32 elapsed = now - starttime; for (S32 i = 0; i < constraints_v.size(); i++) { afxConstraintList* list = constraints_v[i]; for (S32 j = 0; j < list->size(); j++) (*list)[j]->sample(dt, elapsed, cam_pos); } } S32 QSORT_CALLBACK cmp_cons_defs(const void* a, const void* b) { afxConstraintDef* def_a = (afxConstraintDef*) a; afxConstraintDef* def_b = (afxConstraintDef*) b; if (def_a->def_type == def_b->def_type) { if (def_a->cons_src_name == def_b->cons_src_name) { if (def_a->pos_at_box_center == def_b->pos_at_box_center) return (def_a->cons_node_name - def_b->cons_node_name); else return (def_a->pos_at_box_center) ? 1 : -1; } return (def_a->cons_src_name - def_b->cons_src_name); } return (def_a->def_type - def_b->def_type); } void afxConstraintMgr::initConstraintDefs(Vector<afxConstraintDef>& all_defs, bool on_server, F32 scoping_dist) { initialized = true; this->on_server = on_server; if (scoping_dist > 0.0) scoping_dist_sq = scoping_dist*scoping_dist; else { SceneManager* sg = (on_server) ? gServerSceneGraph : gClientSceneGraph; F32 vis_dist = (sg) ? sg->getVisibleDistance() : 1000.0f; scoping_dist_sq = vis_dist*vis_dist; } if (all_defs.size() < 1) return; // find effect ghost constraints if (!on_server) { Vector<afxConstraintDef> ghost_defs; for (S32 i = 0; i < all_defs.size(); i++) if (all_defs[i].def_type == afxConstraintDef::CONS_GHOST && all_defs[i].cons_src_name != ST_NULLSTRING) ghost_defs.push_back(all_defs[i]); if (ghost_defs.size() > 0) { // sort the defs if (ghost_defs.size() > 1) dQsort(ghost_defs.address(), ghost_defs.size(), sizeof(afxConstraintDef), cmp_cons_defs); S32 last = 0; defineConstraint(OBJECT_CONSTRAINT, ghost_defs[0].cons_src_name); for (S32 i = 1; i < ghost_defs.size(); i++) { if (ghost_defs[last].cons_src_name != ghost_defs[i].cons_src_name) { defineConstraint(OBJECT_CONSTRAINT, ghost_defs[i].cons_src_name); last++; } } } } Vector<afxConstraintDef> defs; // collect defs that run here (server or client) if (on_server) { for (S32 i = 0; i < all_defs.size(); i++) if (all_defs[i].runs_on_server) defs.push_back(all_defs[i]); } else { for (S32 i = 0; i < all_defs.size(); i++) if (all_defs[i].runs_on_client) defs.push_back(all_defs[i]); } // create unique set of constraints. // if (defs.size() > 0) { // sort the defs if (defs.size() > 1) dQsort(defs.address(), defs.size(), sizeof(afxConstraintDef), cmp_cons_defs); Vector<afxConstraintDef> unique_defs; S32 last = 0; // manufacture root-object def if absent if (defs[0].cons_node_name != ST_NULLSTRING) { afxConstraintDef root_def = defs[0]; root_def.cons_node_name = ST_NULLSTRING; unique_defs.push_back(root_def); last++; } else if (defs[0].pos_at_box_center) { afxConstraintDef root_def = defs[0]; root_def.pos_at_box_center = false; unique_defs.push_back(root_def); last++; } unique_defs.push_back(defs[0]); for (S32 i = 1; i < defs.size(); i++) { if (unique_defs[last].cons_node_name != defs[i].cons_node_name || unique_defs[last].cons_src_name != defs[i].cons_src_name || unique_defs[last].pos_at_box_center != defs[i].pos_at_box_center || unique_defs[last].def_type != defs[i].def_type) { // manufacture root-object def if absent if (defs[i].cons_src_name != ST_NULLSTRING && unique_defs[last].cons_src_name != defs[i].cons_src_name) { if (defs[i].cons_node_name != ST_NULLSTRING || defs[i].pos_at_box_center) { afxConstraintDef root_def = defs[i]; root_def.cons_node_name = ST_NULLSTRING; root_def.pos_at_box_center = false; unique_defs.push_back(root_def); last++; } } unique_defs.push_back(defs[i]); last++; } else { if (defs[i].history_time > unique_defs[last].history_time) unique_defs[last].history_time = defs[i].history_time; if (defs[i].sample_rate > unique_defs[last].sample_rate) unique_defs[last].sample_rate = defs[i].sample_rate; } } //Con::printf("\nConstraints on %s", (on_server) ? "server" : "client"); for (S32 i = 0; i < unique_defs.size(); i++) create_constraint(unique_defs[i]); } // collect the names of all the arbitrary object constraints // that run on clients and store in names_on_server array. // if (on_server) { names_on_server.clear(); defs.clear(); for (S32 i = 0; i < all_defs.size(); i++) if (all_defs[i].runs_on_client && all_defs[i].isArbitraryObject()) defs.push_back(all_defs[i]); if (defs.size() < 1) return; // sort the defs if (defs.size() > 1) dQsort(defs.address(), defs.size(), sizeof(afxConstraintDef), cmp_cons_defs); S32 last = 0; names_on_server.push_back(defs[0].cons_src_name); for (S32 i = 1; i < defs.size(); i++) { if (names_on_server[last] != defs[i].cons_src_name) { names_on_server.push_back(defs[i].cons_src_name); last++; } } } } void afxConstraintMgr::packConstraintNames(NetConnection* conn, BitStream* stream) { // pack any named constraint names and ghost indices if (stream->writeFlag(names_on_server.size() > 0)) //-- ANY NAMED CONS_BY_ID? { stream->write(names_on_server.size()); for (S32 i = 0; i < names_on_server.size(); i++) { stream->writeString(names_on_server[i]); NetObject* obj = dynamic_cast<NetObject*>(Sim::findObject(names_on_server[i])); if (!obj) { //Con::printf("CONSTRAINT-OBJECT %s does not exist.", names_on_server[i]); stream->write((S32)-1); } else { S32 ghost_id = conn->getGhostIndex(obj); /* if (ghost_id == -1) Con::printf("CONSTRAINT-OBJECT %s does not have a ghost.", names_on_server[i]); else Con::printf("CONSTRAINT-OBJECT %s name to server.", names_on_server[i]); */ stream->write(ghost_id); } } } } void afxConstraintMgr::unpackConstraintNames(BitStream* stream) { if (stream->readFlag()) //-- ANY NAMED CONS_BY_ID? { names_on_server.clear(); S32 sz; stream->read(&sz); for (S32 i = 0; i < sz; i++) { names_on_server.push_back(stream->readSTString()); S32 ghost_id; stream->read(&ghost_id); ghost_ids.push_back(ghost_id); } } } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~// SceneObject* afxConstraintMgr::find_object_from_name(StringTableEntry name) { if (names_on_server.size() > 0) { for (S32 i = 0; i < names_on_server.size(); i++) if (names_on_server[i] == name) { if (ghost_ids[i] == -1) return 0; NetConnection* conn = NetConnection::getConnectionToServer(); if (!conn) return 0; return dynamic_cast<SceneObject*>(conn->resolveGhost(ghost_ids[i])); } } return dynamic_cast<SceneObject*>(Sim::findObject(name)); } void afxConstraintMgr::addScopeableObject(SceneObject* object) { for (S32 i = 0; i < scopeable_objs.size(); i++) { if (scopeable_objs[i] == object) return; } object->addScopeRef(); scopeable_objs.push_back(object); } void afxConstraintMgr::removeScopeableObject(SceneObject* object) { for (S32 i = 0; i < scopeable_objs.size(); i++) if (scopeable_objs[i] == object) { object->removeScopeRef(); scopeable_objs.erase_fast(i); return; } } void afxConstraintMgr::clearAllScopeableObjs() { for (S32 i = 0; i < scopeable_objs.size(); i++) scopeable_objs[i]->removeScopeRef(); scopeable_objs.clear(); } void afxConstraintMgr::postMissingConstraintObject(afxConstraint* cons, bool is_deleting) { if (cons->gone_missing) return; if (!is_deleting) { SceneObject* obj = arcaneFX::findScopedObject(cons->getScopeId()); if (obj) { cons->restoreObject(obj); return; } } cons->gone_missing = true; missing_objs->push_back(cons); } void afxConstraintMgr::restoreScopedObject(SceneObject* obj, afxChoreographer* ch) { for (S32 i = 0; i < missing_objs->size(); i++) { if ((*missing_objs)[i]->getScopeId() == obj->getScopeId()) { (*missing_objs)[i]->gone_missing = false; (*missing_objs)[i]->restoreObject(obj); if (ch) ch->restoreObject(obj); } else missing_objs2->push_back((*missing_objs)[i]); } Vector<afxConstraint*>* tmp = missing_objs; missing_objs = missing_objs2; missing_objs2 = tmp; missing_objs2->clear(); } void afxConstraintMgr::adjustProcessOrdering(afxChoreographer* ch) { Vector<ProcessObject*> cons_sources; // add choreographer to the list cons_sources.push_back(ch); // collect all the ProcessObject related constraint sources for (S32 i = 0; i < constraints_v.size(); i++) { afxConstraintList* list = constraints_v[i]; afxConstraint* cons = (*list)[0]; if (cons) { ProcessObject* pobj = dynamic_cast<ProcessObject*>(cons->getSceneObject()); if (pobj) cons_sources.push_back(pobj); } } ProcessList* proc_list; if (ch->isServerObject()) proc_list = ServerProcessList::get(); else proc_list = ClientProcessList::get(); if (!proc_list) return; GameBase* nearest_to_end = dynamic_cast<GameBase*>(proc_list->findNearestToEnd(cons_sources)); GameBase* chor = (GameBase*) ch; // choreographer needs to be processed after the latest process object if (chor != nearest_to_end && nearest_to_end != 0) { //Con::printf("Choreographer processing BEFORE some of its constraints... fixing. [%s] -- %s", // (ch->isServerObject()) ? "S" : "C", nearest_to_end->getClassName()); if (chor->isProperlyAdded()) ch->processAfter(nearest_to_end); else ch->postProcessAfterObject(nearest_to_end); } else { //Con::printf("Choreographer processing AFTER its constraints... fine. [%s]", // (ch->isServerObject()) ? "S" : "C"); } } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxPointConstraint afxPointConstraint::afxPointConstraint(afxConstraintMgr* mgr) : afxConstraint(mgr) { point.zero(); vector.set(0,0,1); } afxPointConstraint::~afxPointConstraint() { } void afxPointConstraint::set(Point3F point, Point3F vector) { this->point = point; this->vector = vector; is_defined = true; is_valid = true; change_code++; sample(0.0f, 0, 0); } void afxPointConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos) { if (cam_pos) { Point3F dir = (*cam_pos) - point; F32 dist_sq = dir.lenSquared(); if (dist_sq > mgr->getScopingDistanceSquared()) { is_valid = false; return; } is_valid = true; } last_pos = point; last_xfm.identity(); last_xfm.setPosition(point); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxTransformConstraint afxTransformConstraint::afxTransformConstraint(afxConstraintMgr* mgr) : afxConstraint(mgr) { xfm.identity(); } afxTransformConstraint::~afxTransformConstraint() { } void afxTransformConstraint::set(const MatrixF& xfm) { this->xfm = xfm; is_defined = true; is_valid = true; change_code++; sample(0.0f, 0, 0); } void afxTransformConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos) { if (cam_pos) { Point3F dir = (*cam_pos) - xfm.getPosition(); F32 dist_sq = dir.lenSquared(); if (dist_sq > mgr->getScopingDistanceSquared()) { is_valid = false; return; } is_valid = true; } last_xfm = xfm; last_pos = xfm.getPosition(); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxShapeConstraint afxShapeConstraint::afxShapeConstraint(afxConstraintMgr* mgr) : afxConstraint(mgr) { arb_name = ST_NULLSTRING; shape = 0; scope_id = 0; clip_tag = 0; lock_tag = 0; } afxShapeConstraint::afxShapeConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name) : afxConstraint(mgr) { this->arb_name = arb_name; shape = 0; scope_id = 0; clip_tag = 0; lock_tag = 0; } afxShapeConstraint::~afxShapeConstraint() { if (shape) clearNotify(shape); } void afxShapeConstraint::set(ShapeBase* shape) { if (this->shape) { scope_id = 0; clearNotify(this->shape); if (clip_tag > 0) remapAnimation(clip_tag, shape); if (lock_tag > 0) unlockAnimation(lock_tag); } this->shape = shape; if (this->shape) { deleteNotify(this->shape); scope_id = this->shape->getScopeId(); } if (this->shape != NULL) { is_defined = true; is_valid = true; change_code++; sample(0.0f, 0, 0); } else is_valid = false; } void afxShapeConstraint::set_scope_id(U16 scope_id) { if (shape) clearNotify(shape); shape = 0; this->scope_id = scope_id; is_defined = (this->scope_id > 0); is_valid = false; mgr->postMissingConstraintObject(this); } void afxShapeConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos) { if (gone_missing) return; if (shape) { last_xfm = shape->getRenderTransform(); if (cons_def.pos_at_box_center) last_pos = shape->getBoxCenter(); else last_pos = shape->getRenderPosition(); } } void afxShapeConstraint::restoreObject(SceneObject* obj) { if (this->shape) { scope_id = 0; clearNotify(this->shape); } this->shape = (ShapeBase* )obj; if (this->shape) { deleteNotify(this->shape); scope_id = this->shape->getScopeId(); } is_valid = (this->shape != NULL); } void afxShapeConstraint::onDeleteNotify(SimObject* obj) { if (shape == dynamic_cast<ShapeBase*>(obj)) { shape = 0; is_valid = false; if (scope_id > 0) mgr->postMissingConstraintObject(this, true); } Parent::onDeleteNotify(obj); } U32 afxShapeConstraint::setAnimClip(const char* clip, F32 pos, F32 rate, F32 trans, bool is_death_anim) { if (!shape) return 0; if (shape->isServerObject()) { AIPlayer* ai_player = dynamic_cast<AIPlayer*>(shape); if (ai_player && !ai_player->isBlendAnimation(clip)) { ai_player->saveMoveState(); ai_player->stopMove(); } } clip_tag = shape->playAnimation(clip, pos, rate, trans, false/*hold*/, true/*wait*/, is_death_anim); return clip_tag; } void afxShapeConstraint::remapAnimation(U32 tag, ShapeBase* other_shape) { if (clip_tag == 0) return; if (!shape) return; if (!other_shape) { resetAnimation(tag); return; } Con::errorf("remapAnimation -- Clip name, %s.", shape->getLastClipName(tag)); if (shape->isClientObject()) { shape->restoreAnimation(tag); } else { AIPlayer* ai_player = dynamic_cast<AIPlayer*>(shape); if (ai_player) ai_player->restartMove(tag); else shape->restoreAnimation(tag); } clip_tag = 0; } void afxShapeConstraint::resetAnimation(U32 tag) { if (clip_tag == 0) return; if (!shape) return; if (shape->isClientObject()) { shape->restoreAnimation(tag); } else { AIPlayer* ai_player = dynamic_cast<AIPlayer*>(shape); if (ai_player) ai_player->restartMove(tag); else shape->restoreAnimation(tag); } if ((tag & 0x80000000) == 0 && tag == clip_tag) clip_tag = 0; } U32 afxShapeConstraint::lockAnimation() { if (!shape) return 0; lock_tag = shape->lockAnimation(); return lock_tag; } void afxShapeConstraint::unlockAnimation(U32 tag) { if (lock_tag == 0) return; if (!shape) return; shape->unlockAnimation(tag); lock_tag = 0; } F32 afxShapeConstraint::getAnimClipDuration(const char* clip) { return (shape) ? shape->getAnimationDuration(clip) : 0.0f; } S32 afxShapeConstraint::getDamageState() { return (shape) ? shape->getDamageState() : -1; } U32 afxShapeConstraint::getTriggers() { return (shape) ? shape->getShapeInstance()->getTriggerStateMask() : 0; } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxShapeNodeConstraint afxShapeNodeConstraint::afxShapeNodeConstraint(afxConstraintMgr* mgr) : afxShapeConstraint(mgr) { arb_node = ST_NULLSTRING; shape_node_ID = -1; } afxShapeNodeConstraint::afxShapeNodeConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name, StringTableEntry arb_node) : afxShapeConstraint(mgr, arb_name) { this->arb_node = arb_node; shape_node_ID = -1; } void afxShapeNodeConstraint::set(ShapeBase* shape) { if (shape) { shape_node_ID = shape->getShape()->findNode(arb_node); if (shape_node_ID == -1) Con::errorf("Failed to find node [%s]", arb_node); } else shape_node_ID = -1; Parent::set(shape); } void afxShapeNodeConstraint::set_scope_id(U16 scope_id) { shape_node_ID = -1; Parent::set_scope_id(scope_id); } void afxShapeNodeConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos) { if (shape && shape_node_ID != -1) { last_xfm = shape->getRenderTransform(); last_xfm.scale(shape->getScale()); last_xfm.mul(shape->getShapeInstance()->mNodeTransforms[shape_node_ID]); last_pos = last_xfm.getPosition(); } } void afxShapeNodeConstraint::restoreObject(SceneObject* obj) { ShapeBase* shape = dynamic_cast<ShapeBase*>(obj); if (shape) { shape_node_ID = shape->getShape()->findNode(arb_node); if (shape_node_ID == -1) Con::errorf("Failed to find node [%s]", arb_node); } else shape_node_ID = -1; Parent::restoreObject(obj); } void afxShapeNodeConstraint::onDeleteNotify(SimObject* obj) { Parent::onDeleteNotify(obj); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxObjectConstraint afxObjectConstraint::afxObjectConstraint(afxConstraintMgr* mgr) : afxConstraint(mgr) { arb_name = ST_NULLSTRING; obj = 0; scope_id = 0; is_camera = false; } afxObjectConstraint::afxObjectConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name) : afxConstraint(mgr) { this->arb_name = arb_name; obj = 0; scope_id = 0; is_camera = false; } afxObjectConstraint::~afxObjectConstraint() { if (obj) clearNotify(obj); } void afxObjectConstraint::set(SceneObject* obj) { if (this->obj) { scope_id = 0; clearNotify(this->obj); } this->obj = obj; if (this->obj) { deleteNotify(this->obj); scope_id = this->obj->getScopeId(); } if (this->obj != NULL) { is_camera = this->obj->isCamera(); is_defined = true; is_valid = true; change_code++; sample(0.0f, 0, 0); } else is_valid = false; } void afxObjectConstraint::set_scope_id(U16 scope_id) { if (obj) clearNotify(obj); obj = 0; this->scope_id = scope_id; is_defined = (scope_id > 0); is_valid = false; mgr->postMissingConstraintObject(this); } void afxObjectConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos) { if (gone_missing) return; if (obj) { if (!is_camera && cons_def.treat_as_camera && dynamic_cast<ShapeBase*>(obj)) { ShapeBase* cam_obj = (ShapeBase*) obj; F32 pov = 1.0f; cam_obj->getCameraTransform(&pov, &last_xfm); last_xfm.getColumn(3, &last_pos); } else { last_xfm = obj->getRenderTransform(); if (cons_def.pos_at_box_center) last_pos = obj->getBoxCenter(); else last_pos = obj->getRenderPosition(); } } } void afxObjectConstraint::restoreObject(SceneObject* obj) { if (this->obj) { scope_id = 0; clearNotify(this->obj); } this->obj = obj; if (this->obj) { deleteNotify(this->obj); scope_id = this->obj->getScopeId(); } is_valid = (this->obj != NULL); } void afxObjectConstraint::onDeleteNotify(SimObject* obj) { if (this->obj == dynamic_cast<SceneObject*>(obj)) { this->obj = 0; is_valid = false; if (scope_id > 0) mgr->postMissingConstraintObject(this, true); } Parent::onDeleteNotify(obj); } U32 afxObjectConstraint::getTriggers() { TSStatic* ts_static = dynamic_cast<TSStatic*>(obj); if (ts_static) { TSShapeInstance* obj_inst = ts_static->getShapeInstance(); return (obj_inst) ? obj_inst->getTriggerStateMask() : 0; } ShapeBase* shape_base = dynamic_cast<ShapeBase*>(obj); if (shape_base) { TSShapeInstance* obj_inst = shape_base->getShapeInstance(); return (obj_inst) ? obj_inst->getTriggerStateMask() : 0; } return 0; } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxEffectConstraint afxEffectConstraint::afxEffectConstraint(afxConstraintMgr* mgr) : afxConstraint(mgr) { effect_name = ST_NULLSTRING; effect = 0; } afxEffectConstraint::afxEffectConstraint(afxConstraintMgr* mgr, StringTableEntry effect_name) : afxConstraint(mgr) { this->effect_name = effect_name; effect = 0; } afxEffectConstraint::~afxEffectConstraint() { } bool afxEffectConstraint::getPosition(Point3F& pos, F32 hist) { if (!effect || !effect->inScope()) return false; if (cons_def.pos_at_box_center) effect->getUpdatedBoxCenter(pos); else effect->getUpdatedPosition(pos); return true; } bool afxEffectConstraint::getTransform(MatrixF& xfm, F32 hist) { if (!effect || !effect->inScope()) return false; effect->getUpdatedTransform(xfm); return true; } bool afxEffectConstraint::getAltitudes(F32& terrain_alt, F32& interior_alt) { if (!effect) return false; effect->getAltitudes(terrain_alt, interior_alt); return true; } void afxEffectConstraint::set(afxEffectWrapper* effect) { this->effect = effect; if (this->effect != NULL) { is_defined = true; is_valid = true; change_code++; } else is_valid = false; } U32 afxEffectConstraint::setAnimClip(const char* clip, F32 pos, F32 rate, F32 trans, bool is_death_anim) { return (effect) ? effect->setAnimClip(clip, pos, rate, trans) : 0; } void afxEffectConstraint::resetAnimation(U32 tag) { if (effect) effect->resetAnimation(tag); } F32 afxEffectConstraint::getAnimClipDuration(const char* clip) { return (effect) ? getAnimClipDuration(clip) : 0; } U32 afxEffectConstraint::getTriggers() { return (effect) ? effect->getTriggers() : 0; } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxEffectNodeConstraint afxEffectNodeConstraint::afxEffectNodeConstraint(afxConstraintMgr* mgr) : afxEffectConstraint(mgr) { effect_node = ST_NULLSTRING; effect_node_ID = -1; } afxEffectNodeConstraint::afxEffectNodeConstraint(afxConstraintMgr* mgr, StringTableEntry name, StringTableEntry node) : afxEffectConstraint(mgr, name) { this->effect_node = node; effect_node_ID = -1; } bool afxEffectNodeConstraint::getPosition(Point3F& pos, F32 hist) { if (!effect || !effect->inScope()) return false; TSShapeInstance* ts_shape_inst = effect->getTSShapeInstance(); if (!ts_shape_inst) return false; if (effect_node_ID == -1) { TSShape* ts_shape = effect->getTSShape(); effect_node_ID = (ts_shape) ? ts_shape->findNode(effect_node) : -1; } if (effect_node_ID == -1) return false; effect->getUpdatedTransform(last_xfm); Point3F scale; effect->getUpdatedScale(scale); MatrixF gag = ts_shape_inst->mNodeTransforms[effect_node_ID]; gag.setPosition( gag.getPosition()*scale ); MatrixF xfm; xfm.mul(last_xfm, gag); // pos = xfm.getPosition(); return true; } bool afxEffectNodeConstraint::getTransform(MatrixF& xfm, F32 hist) { if (!effect || !effect->inScope()) return false; TSShapeInstance* ts_shape_inst = effect->getTSShapeInstance(); if (!ts_shape_inst) return false; if (effect_node_ID == -1) { TSShape* ts_shape = effect->getTSShape(); effect_node_ID = (ts_shape) ? ts_shape->findNode(effect_node) : -1; } if (effect_node_ID == -1) return false; effect->getUpdatedTransform(last_xfm); Point3F scale; effect->getUpdatedScale(scale); MatrixF gag = ts_shape_inst->mNodeTransforms[effect_node_ID]; gag.setPosition( gag.getPosition()*scale ); xfm.mul(last_xfm, gag); return true; } void afxEffectNodeConstraint::set(afxEffectWrapper* effect) { if (effect) { TSShape* ts_shape = effect->getTSShape(); effect_node_ID = (ts_shape) ? ts_shape->findNode(effect_node) : -1; } else effect_node_ID = -1; Parent::set(effect); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxSampleBuffer afxSampleBuffer::afxSampleBuffer() { buffer_sz = 0; buffer_ms = 0; ms_per_sample = 33; elapsed_ms = 0; last_sample_ms = 0; next_sample_num = 0; n_samples = 0; } afxSampleBuffer::~afxSampleBuffer() { } void afxSampleBuffer::configHistory(F32 hist_len, U8 sample_rate) { buffer_sz = mCeil(hist_len*sample_rate) + 1; ms_per_sample = mCeil(1000.0f/sample_rate); buffer_ms = buffer_sz*ms_per_sample; } void afxSampleBuffer::recordSample(F32 dt, U32 elapsed_ms, void* data) { this->elapsed_ms = elapsed_ms; if (!data) return; U32 now_sample_num = elapsed_ms/ms_per_sample; if (next_sample_num <= now_sample_num) { last_sample_ms = elapsed_ms; while (next_sample_num <= now_sample_num) { recSample(next_sample_num % buffer_sz, data); next_sample_num++; n_samples++; } } } inline bool afxSampleBuffer::compute_idx_from_lag(F32 lag, U32& idx) { bool in_bounds = true; U32 lag_ms = lag*1000.0f; U32 rec_ms = (elapsed_ms < buffer_ms) ? elapsed_ms : buffer_ms; if (lag_ms > rec_ms) { // hasn't produced enough history lag_ms = rec_ms; in_bounds = false; } U32 latest_sample_num = last_sample_ms/ms_per_sample; U32 then_sample_num = (elapsed_ms - lag_ms)/ms_per_sample; if (then_sample_num > latest_sample_num) { // latest sample is older than lag then_sample_num = latest_sample_num; in_bounds = false; } idx = then_sample_num % buffer_sz; return in_bounds; } inline bool afxSampleBuffer::compute_idx_from_lag(F32 lag, U32& idx1, U32& idx2, F32& t) { bool in_bounds = true; F32 lag_ms = lag*1000.0f; F32 rec_ms = (elapsed_ms < buffer_ms) ? elapsed_ms : buffer_ms; if (lag_ms > rec_ms) { // hasn't produced enough history lag_ms = rec_ms; in_bounds = false; } F32 per_samp = ms_per_sample; F32 latest_sample_num = last_sample_ms/per_samp; F32 then_sample_num = (elapsed_ms - lag_ms)/per_samp; U32 latest_sample_num_i = latest_sample_num; U32 then_sample_num_i = then_sample_num; if (then_sample_num_i >= latest_sample_num_i) { if (latest_sample_num_i < then_sample_num_i) in_bounds = false; t = 0.0; idx1 = then_sample_num_i % buffer_sz; idx2 = idx1; } else { t = then_sample_num - then_sample_num_i; idx1 = then_sample_num_i % buffer_sz; idx2 = (then_sample_num_i+1) % buffer_sz; } return in_bounds; } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxSampleXfmBuffer afxSampleXfmBuffer::afxSampleXfmBuffer() { xfm_buffer = 0; } afxSampleXfmBuffer::~afxSampleXfmBuffer() { delete [] xfm_buffer; } void afxSampleXfmBuffer::configHistory(F32 hist_len, U8 sample_rate) { if (!xfm_buffer) { afxSampleBuffer::configHistory(hist_len, sample_rate); if (buffer_sz > 0) xfm_buffer = new MatrixF[buffer_sz]; } } void afxSampleXfmBuffer::recSample(U32 idx, void* data) { xfm_buffer[idx] = *((MatrixF*)data); } void afxSampleXfmBuffer::getSample(F32 lag, void* data, bool& in_bounds) { U32 idx1, idx2; F32 t; in_bounds = compute_idx_from_lag(lag, idx1, idx2, t); if (idx1 == idx2) { MatrixF* m1 = &xfm_buffer[idx1]; *((MatrixF*)data) = *m1; } else { MatrixF* m1 = &xfm_buffer[idx1]; MatrixF* m2 = &xfm_buffer[idx2]; Point3F p1 = m1->getPosition(); Point3F p2 = m2->getPosition(); Point3F p; p.interpolate(p1, p2, t); if (t < 0.5f) *((MatrixF*)data) = *m1; else *((MatrixF*)data) = *m2; ((MatrixF*)data)->setPosition(p); } } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxPointHistConstraint afxPointHistConstraint::afxPointHistConstraint(afxConstraintMgr* mgr) : afxPointConstraint(mgr) { samples = 0; } afxPointHistConstraint::~afxPointHistConstraint() { delete samples; } void afxPointHistConstraint::set(Point3F point, Point3F vector) { if (!samples) { samples = new afxSampleXfmBuffer; samples->configHistory(cons_def.history_time, cons_def.sample_rate); } Parent::set(point, vector); } void afxPointHistConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos) { Parent::sample(dt, elapsed_ms, cam_pos); if (isDefined()) { if (isValid()) samples->recordSample(dt, elapsed_ms, &last_xfm); else samples->recordSample(dt, elapsed_ms, 0); } } bool afxPointHistConstraint::getPosition(Point3F& pos, F32 hist) { bool in_bounds; MatrixF xfm; samples->getSample(hist, &xfm, in_bounds); pos = xfm.getPosition(); return in_bounds; } bool afxPointHistConstraint::getTransform(MatrixF& xfm, F32 hist) { bool in_bounds; samples->getSample(hist, &xfm, in_bounds); return in_bounds; } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxPointHistConstraint afxTransformHistConstraint::afxTransformHistConstraint(afxConstraintMgr* mgr) : afxTransformConstraint(mgr) { samples = 0; } afxTransformHistConstraint::~afxTransformHistConstraint() { delete samples; } void afxTransformHistConstraint::set(const MatrixF& xfm) { if (!samples) { samples = new afxSampleXfmBuffer; samples->configHistory(cons_def.history_time, cons_def.sample_rate); } Parent::set(xfm); } void afxTransformHistConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos) { Parent::sample(dt, elapsed_ms, cam_pos); if (isDefined()) { if (isValid()) samples->recordSample(dt, elapsed_ms, &last_xfm); else samples->recordSample(dt, elapsed_ms, 0); } } bool afxTransformHistConstraint::getPosition(Point3F& pos, F32 hist) { bool in_bounds; MatrixF xfm; samples->getSample(hist, &xfm, in_bounds); pos = xfm.getPosition(); return in_bounds; } bool afxTransformHistConstraint::getTransform(MatrixF& xfm, F32 hist) { bool in_bounds; samples->getSample(hist, &xfm, in_bounds); return in_bounds; } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxShapeHistConstraint afxShapeHistConstraint::afxShapeHistConstraint(afxConstraintMgr* mgr) : afxShapeConstraint(mgr) { samples = 0; } afxShapeHistConstraint::afxShapeHistConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name) : afxShapeConstraint(mgr, arb_name) { samples = 0; } afxShapeHistConstraint::~afxShapeHistConstraint() { delete samples; } void afxShapeHistConstraint::set(ShapeBase* shape) { if (shape && !samples) { samples = new afxSampleXfmBuffer; samples->configHistory(cons_def.history_time, cons_def.sample_rate); } Parent::set(shape); } void afxShapeHistConstraint::set_scope_id(U16 scope_id) { if (scope_id > 0 && !samples) { samples = new afxSampleXfmBuffer; samples->configHistory(cons_def.history_time, cons_def.sample_rate); } Parent::set_scope_id(scope_id); } void afxShapeHistConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos) { Parent::sample(dt, elapsed_ms, cam_pos); if (isDefined()) { if (isValid()) samples->recordSample(dt, elapsed_ms, &last_xfm); else samples->recordSample(dt, elapsed_ms, 0); } } bool afxShapeHistConstraint::getPosition(Point3F& pos, F32 hist) { bool in_bounds; MatrixF xfm; samples->getSample(hist, &xfm, in_bounds); pos = xfm.getPosition(); return in_bounds; } bool afxShapeHistConstraint::getTransform(MatrixF& xfm, F32 hist) { bool in_bounds; samples->getSample(hist, &xfm, in_bounds); return in_bounds; } void afxShapeHistConstraint::onDeleteNotify(SimObject* obj) { Parent::onDeleteNotify(obj); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxShapeNodeHistConstraint afxShapeNodeHistConstraint::afxShapeNodeHistConstraint(afxConstraintMgr* mgr) : afxShapeNodeConstraint(mgr) { samples = 0; } afxShapeNodeHistConstraint::afxShapeNodeHistConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name, StringTableEntry arb_node) : afxShapeNodeConstraint(mgr, arb_name, arb_node) { samples = 0; } afxShapeNodeHistConstraint::~afxShapeNodeHistConstraint() { delete samples; } void afxShapeNodeHistConstraint::set(ShapeBase* shape) { if (shape && !samples) { samples = new afxSampleXfmBuffer; samples->configHistory(cons_def.history_time, cons_def.sample_rate); } Parent::set(shape); } void afxShapeNodeHistConstraint::set_scope_id(U16 scope_id) { if (scope_id > 0 && !samples) { samples = new afxSampleXfmBuffer; samples->configHistory(cons_def.history_time, cons_def.sample_rate); } Parent::set_scope_id(scope_id); } void afxShapeNodeHistConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos) { Parent::sample(dt, elapsed_ms, cam_pos); if (isDefined()) { if (isValid()) samples->recordSample(dt, elapsed_ms, &last_xfm); else samples->recordSample(dt, elapsed_ms, 0); } } bool afxShapeNodeHistConstraint::getPosition(Point3F& pos, F32 hist) { bool in_bounds; MatrixF xfm; samples->getSample(hist, &xfm, in_bounds); pos = xfm.getPosition(); return in_bounds; } bool afxShapeNodeHistConstraint::getTransform(MatrixF& xfm, F32 hist) { bool in_bounds; samples->getSample(hist, &xfm, in_bounds); return in_bounds; } void afxShapeNodeHistConstraint::onDeleteNotify(SimObject* obj) { Parent::onDeleteNotify(obj); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxObjectHistConstraint afxObjectHistConstraint::afxObjectHistConstraint(afxConstraintMgr* mgr) : afxObjectConstraint(mgr) { samples = 0; } afxObjectHistConstraint::afxObjectHistConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name) : afxObjectConstraint(mgr, arb_name) { samples = 0; } afxObjectHistConstraint::~afxObjectHistConstraint() { delete samples; } void afxObjectHistConstraint::set(SceneObject* obj) { if (obj && !samples) { samples = new afxSampleXfmBuffer; samples->configHistory(cons_def.history_time, cons_def.sample_rate); } Parent::set(obj); } void afxObjectHistConstraint::set_scope_id(U16 scope_id) { if (scope_id > 0 && !samples) { samples = new afxSampleXfmBuffer; samples->configHistory(cons_def.history_time, cons_def.sample_rate); } Parent::set_scope_id(scope_id); } void afxObjectHistConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos) { Parent::sample(dt, elapsed_ms, cam_pos); if (isDefined()) { if (isValid()) samples->recordSample(dt, elapsed_ms, &last_xfm); else samples->recordSample(dt, elapsed_ms, 0); } } bool afxObjectHistConstraint::getPosition(Point3F& pos, F32 hist) { bool in_bounds; MatrixF xfm; samples->getSample(hist, &xfm, in_bounds); pos = xfm.getPosition(); return in_bounds; } bool afxObjectHistConstraint::getTransform(MatrixF& xfm, F32 hist) { bool in_bounds; samples->getSample(hist, &xfm, in_bounds); return in_bounds; } void afxObjectHistConstraint::onDeleteNotify(SimObject* obj) { Parent::onDeleteNotify(obj); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
64,498
24,097
// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NASA Vision Workbench is licensed under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ // TestCameraBBox.h #include <gtest/gtest_VW.h> #include <test/Helpers.h> #include <vw/Cartography/CameraBBox.h> #include <vw/Camera/PinholeModel.h> // Must have protobuf to be able to read camera #if defined(VW_HAVE_PKG_PROTOBUF) && VW_HAVE_PKG_PROTOBUF==1 && defined(VW_HAVE_PKG_CAMERA) && VW_HAVE_PKG_CAMERA using namespace vw; using namespace vw::cartography; using namespace vw::test; using namespace vw::camera; class CameraBBoxTest : public ::testing::Test { protected: virtual void SetUp() { apollo_camera = boost::shared_ptr<CameraModel>(new PinholeModel(TEST_SRCDIR"/apollo.pinhole")); moon_georef.set_well_known_geogcs("D_MOON"); DEM.set_size(20,20); // DEM covering lat {10,-10} long {80,100} for ( int32 i = 0; i < DEM.cols(); i++ ) for ( int32 j = 0; j <DEM.rows(); j++ ) DEM(i,j) = 1000 - 10*(pow(DEM.cols()/2.0-i,2.0)+pow(DEM.rows()/2.0-j,2.0)); } boost::shared_ptr<CameraModel> apollo_camera; GeoReference moon_georef; ImageView<float> DEM; }; TEST_F( CameraBBoxTest, GeospatialIntersectDatum ) { for ( unsigned i = 0; i < 10; i++ ) { Vector2 input_image( rand()%4096, rand()%4096 ); bool did_intersect; Vector2 lonlat = geospatial_intersect( moon_georef, apollo_camera->camera_center(input_image), apollo_camera->pixel_to_vector(input_image), did_intersect ); ASSERT_TRUE( did_intersect ); double radius = moon_georef.datum().radius( lonlat[0], lonlat[1] ); EXPECT_NEAR( radius, 1737400, 1e-3 ); Vector3 llr( lonlat[0], lonlat[1], 0 ); Vector3 ecef = moon_georef.datum().geodetic_to_cartesian(llr); Vector3 llr2 = moon_georef.datum().cartesian_to_geodetic(ecef); EXPECT_VECTOR_NEAR( llr2, llr, 1e-4 ); Vector2 retrn_image = apollo_camera->point_to_pixel( ecef ); EXPECT_VECTOR_NEAR( retrn_image, input_image, 1e-3 ); } } TEST_F( CameraBBoxTest, CameraBBoxDatum ) { float scale; // degrees per pixel BBox2 image_bbox = camera_bbox( moon_georef, apollo_camera, 4096, 4096, scale ); EXPECT_VECTOR_NEAR( image_bbox.min(), Vector2(86,-1), 2 ); EXPECT_VECTOR_NEAR( image_bbox.max(), Vector2(95,7), 2 ); EXPECT_NEAR( scale, (95-86.)/sqrt(4096*4096*2), 1e-3 ); // Cam is rotated } TEST_F( CameraBBoxTest, CameraBBoxDEM ) { Matrix<double> geotrans = vw::math::identity_matrix<3>(); geotrans(0,2) = 80; geotrans(1,1) = -1; geotrans(1,2) = 10; moon_georef.set_transform(geotrans); BBox2 image_bbox = camera_bbox( DEM, moon_georef, apollo_camera, 4096, 4096 ); EXPECT_VECTOR_NEAR( image_bbox.min(), Vector2(87,0), 2 ); EXPECT_VECTOR_NEAR( image_bbox.max(), Vector2(94,6), 2 ); } TEST_F( CameraBBoxTest, CameraPixelToXYZ) { Matrix<double> geotrans = vw::math::identity_matrix<3>(); geotrans(0,2) = 80; geotrans(1,1) = -1; geotrans(1,2) = 10; moon_georef.set_transform(geotrans); Vector2 input_pixel(50,10); bool treat_nodata_as_zero = false; bool has_intersection; Vector3 xyz = camera_pixel_to_dem_xyz(apollo_camera->camera_center(input_pixel), apollo_camera->pixel_to_vector(input_pixel), DEM, moon_georef, treat_nodata_as_zero, has_intersection ); // Verification Vector2 output_pixel = apollo_camera->point_to_pixel(xyz); EXPECT_EQ(has_intersection, 1); EXPECT_VECTOR_NEAR(input_pixel, output_pixel, 1e-8); } #endif
4,379
1,752
/* * Original work Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * Modified work Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/Box2D * * 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. */ #ifndef B2_BLOCK_ALLOCATOR_H #define B2_BLOCK_ALLOCATOR_H #include <Box2D/Common/Settings.hpp> namespace box2d { /// Block allocator. /// /// This is a small object allocator used for allocating small /// objects that persist for more than one time step. /// @note This data structure is 136-bytes large (on at least one 64-bit platform). /// @sa http://www.codeproject.com/useritems/Small_Block_Allocator.asp /// class BlockAllocator { public: using size_type = std::size_t; static constexpr auto ChunkSize = size_type{16 * 1024}; ///< Chunk size. static constexpr auto MaxBlockSize = size_type{640}; ///< Max block size (before using external allocator). static constexpr auto BlockSizes = size_type{14}; static constexpr auto ChunkArrayIncrement = size_type{128}; BlockAllocator(); ~BlockAllocator() noexcept; /// Allocates memory. /// @details Allocates uninitialized storage. /// Uses <code>Alloc</code> if the size is larger than <code>MaxBlockSize</code>. /// Otherwise looks for an appropriately sized block from the free list. /// Failing that, <code>Alloc</code> is used to grow the free list from which /// memory is returned. /// @sa Alloc. void* Allocate(size_type n); template <typename T> T* AllocateArray(size_type n) { return static_cast<T*>(Allocate(n * sizeof(T))); } /// Free memory. /// @details This will use free if the size is larger than <code>MaxBlockSize</code>. void Free(void* p, size_type n); /// Clears this allocator. /// @note This resets the chunk-count back to zero. void Clear(); auto GetChunkCount() const noexcept { return m_chunkCount; } private: struct Chunk; struct Block; size_type m_chunkCount = 0; size_type m_chunkSpace = ChunkArrayIncrement; Chunk* m_chunks; Block* m_freeLists[BlockSizes]; }; template <typename T> inline void Delete(const T* p, BlockAllocator& allocator) { p->~T(); allocator.Free(const_cast<T*>(p), sizeof(T)); } /// Blockl Deallocator. struct BlockDeallocator { using size_type = BlockAllocator::size_type; BlockDeallocator() = default; constexpr BlockDeallocator(BlockAllocator* a, size_type n) noexcept: allocator{a}, nelem{n} {} void operator()(void *p) noexcept { allocator->Free(p, nelem); } BlockAllocator* allocator; size_type nelem; }; inline bool operator==(const BlockAllocator& a, const BlockAllocator& b) { return &a == &b; } inline bool operator!=(const BlockAllocator& a, const BlockAllocator& b) { return &a != &b; } } // namespace box2d #endif
4,105
1,221
// rotating cube with texture object #include "Angel.h" const int NumTriangles = 12; // (6 faces)(2 triangles/face) const int NumVertices = 3 * NumTriangles; const int TextureSize = 64; typedef Angel::vec4 point4; typedef Angel::vec4 color4; // Texture objects and storage for texture image GLuint textures[2]; GLubyte image[TextureSize][TextureSize][3]; GLubyte image2[TextureSize][TextureSize][3]; // Vertex data arrays point4 points[NumVertices]; color4 quad_colors[NumVertices]; vec2 tex_coords[NumVertices]; // Array of rotation angles (in degrees) for each coordinate axis enum { Xaxis = 0, Yaxis = 1, Zaxis = 2, NumAxes = 3 }; int Axis = Xaxis; GLfloat Theta[NumAxes] = { 0.0, 0.0, 0.0 }; GLuint theta; //---------------------------------------------------------------------------- int Index = 0; void quad( int a, int b, int c, int d ) { point4 vertices[8] = { point4( -0.5, -0.5, 0.5, 1.0 ), point4( -0.5, 0.5, 0.5, 1.0 ), point4( 0.5, 0.5, 0.5, 1.0 ), point4( 0.5, -0.5, 0.5, 1.0 ), point4( -0.5, -0.5, -0.5, 1.0 ), point4( -0.5, 0.5, -0.5, 1.0 ), point4( 0.5, 0.5, -0.5, 1.0 ), point4( 0.5, -0.5, -0.5, 1.0 ) }; color4 colors[8] = { color4( 0.0, 0.0, 0.0, 1.0 ), // black color4( 1.0, 0.0, 0.0, 1.0 ), // red color4( 1.0, 1.0, 0.0, 1.0 ), // yellow color4( 0.0, 1.0, 0.0, 1.0 ), // green color4( 0.0, 0.0, 1.0, 1.0 ), // blue color4( 1.0, 0.0, 1.0, 1.0 ), // magenta color4( 1.0, 1.0, 1.0, 1.0 ), // white color4( 1.0, 1.0, 1.0, 1.0 ) // cyan }; quad_colors[Index] = colors[a]; points[Index] = vertices[a]; tex_coords[Index] = vec2( 0.0, 0.0 ); Index++; quad_colors[Index] = colors[a]; points[Index] = vertices[b]; tex_coords[Index] = vec2( 0.0, 1.0 ); Index++; quad_colors[Index] = colors[a]; points[Index] = vertices[c]; tex_coords[Index] = vec2( 1.0, 1.0 ); Index++; quad_colors[Index] = colors[a]; points[Index] = vertices[a]; tex_coords[Index] = vec2( 0.0, 0.0 ); Index++; quad_colors[Index] = colors[a]; points[Index] = vertices[c]; tex_coords[Index] = vec2( 1.0, 1.0 ); Index++; quad_colors[Index] = colors[a]; points[Index] = vertices[d]; tex_coords[Index] = vec2( 1.0, 0.0 ); Index++; } //---------------------------------------------------------------------------- void colorcube() { quad( 1, 0, 3, 2 ); quad( 2, 3, 7, 6 ); quad( 3, 0, 4, 7 ); quad( 6, 5, 1, 2 ); quad( 4, 5, 6, 7 ); quad( 5, 4, 0, 1 ); } //---------------------------------------------------------------------------- void init() { colorcube(); // Create a checkerboard pattern for ( int i = 0; i < 64; i++ ) { for ( int j = 0; j < 64; j++ ) { GLubyte c = (((i & 0x8) == 0) ^ ((j & 0x8) == 0)) * 255; image[i][j][0] = c; image[i][j][1] = c; image[i][j][2] = c; image2[i][j][0] = c; image2[i][j][1] = 0; image2[i][j][2] = c; } } // Initialize texture objects glGenTextures( 2, textures ); glBindTexture( GL_TEXTURE_2D, textures[0] ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, TextureSize, TextureSize, 0, GL_RGB, GL_UNSIGNED_BYTE, image ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glBindTexture( GL_TEXTURE_2D, textures[1] ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, TextureSize, TextureSize, 0, GL_RGB, GL_UNSIGNED_BYTE, image2 ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glActiveTexture( GL_TEXTURE0 ); glBindTexture( GL_TEXTURE_2D, textures[0] ); // Create a vertex array object GLuint vao; glGenVertexArraysAPPLE( 1, &vao ); glBindVertexArrayAPPLE( vao ); // Create and initialize a buffer object GLuint buffer; glGenBuffers( 1, &buffer ); glBindBuffer( GL_ARRAY_BUFFER, buffer ); glBufferData( GL_ARRAY_BUFFER, sizeof(points) + sizeof(quad_colors) + sizeof(tex_coords), NULL, GL_STATIC_DRAW ); // Specify an offset to keep track of where we're placing data in our // vertex array buffer. We'll use the same technique when we // associate the offsets with vertex attribute pointers. GLintptr offset = 0; glBufferSubData( GL_ARRAY_BUFFER, offset, sizeof(points), points ); offset += sizeof(points); glBufferSubData( GL_ARRAY_BUFFER, offset, sizeof(quad_colors), quad_colors ); offset += sizeof(quad_colors); glBufferSubData( GL_ARRAY_BUFFER, offset, sizeof(tex_coords), tex_coords ); // Load shaders and use the resulting shader program GLuint program = InitShader( "vshader_a8.glsl", "fshader_a8.glsl" ); glUseProgram( program ); // set up vertex arrays offset = 0; GLuint vPosition = glGetAttribLocation( program, "vPosition" ); glEnableVertexAttribArray( vPosition ); glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(offset) ); offset += sizeof(points); GLuint vColor = glGetAttribLocation( program, "vColor" ); glEnableVertexAttribArray( vColor ); glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(offset) ); offset += sizeof(quad_colors); GLuint vTexCoord = glGetAttribLocation( program, "vTexCoord" ); glEnableVertexAttribArray( vTexCoord ); glVertexAttribPointer( vTexCoord, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(offset) ); // Set the value of the fragment shader texture sampler variable // ("texture") to the the appropriate texture unit. In this case, // zero, for GL_TEXTURE0 which was previously set by calling // glActiveTexture(). glUniform1i( glGetUniformLocation(program, "texture"), 0 ); theta = glGetUniformLocation( program, "theta" ); glEnable( GL_DEPTH_TEST ); glClearColor( 1.0, 1.0, 1.0, 1.0 ); } void display( void ) { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glUniform3fv( theta, 1, Theta ); glDrawArrays( GL_TRIANGLES, 0, NumVertices ); glutSwapBuffers(); } //---------------------------------------------------------------------------- void mouse( int button, int state, int x, int y ) { if ( state == GLUT_DOWN ) { switch( button ) { case GLUT_LEFT_BUTTON: Axis = Xaxis; break; case GLUT_MIDDLE_BUTTON: Axis = Yaxis; break; case GLUT_RIGHT_BUTTON: Axis = Zaxis; break; } } } //---------------------------------------------------------------------------- void idle( void ) { Theta[Axis] += 0.01; if ( Theta[Axis] > 360.0 ) { Theta[Axis] -= 360.0; } glutPostRedisplay(); } //---------------------------------------------------------------------------- void keyboard( unsigned char key, int mousex, int mousey ) { switch( key ) { case 033: // Escape Key case 'q': case 'Q': exit( EXIT_SUCCESS ); break; case '1': glBindTexture( GL_TEXTURE_2D, textures[0] ); break; case '2': glBindTexture( GL_TEXTURE_2D, textures[1] ); break; } glutPostRedisplay(); } //---------------------------------------------------------------------------- int main( int argc, char **argv ) { glutInit( &argc, argv ); glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); glutInitWindowSize( 512, 512 ); glutCreateWindow( "Color Cube" ); init(); glutDisplayFunc( display ); glutKeyboardFunc( keyboard ); glutMouseFunc( mouse ); glutIdleFunc( idle ); glutMainLoop(); return 0; }
8,070
3,248
#include "memory.h" #include "regs.h" #include <cstdio> #include <cstring> // Parameters uint32_t DATA_SIZE = 0; uint32_t TEXT_SIZE = 0; uint32_t STACK_SIZE = 0; // TODO: move constants to header file // Memory Pointers uint8_t *DATA_POINTER; uint8_t *TEXT_POINTER; uint8_t *STACK_POINTER; uint32_t MAIN_START; // Heap Memory std::vector<uint8_t> Heap; // change program's break (sbrk) addr_t data_break(int32_t delta){ // calculate heap top addr_t heap_top = HEAP_START + Heap.size(); // convention: delta zero returns current heap_top if( delta == 0 ) return heap_top; auto old_top = heap_top; auto new_top = heap_top + delta; // check if new top is valid if( HEAP_START <= new_top and new_top <= R[REG_SP] ){ Heap.resize(new_top - HEAP_START); return old_top; } return -1; // this is standard (sbrk) } // resolve virtual address to "real" void* resolve_addr(addr_t addr){ // reserved space if( addr < TEXT_START or addr >= STACK_START ) return nullptr; // text segment if( addr < DATA_START ){ auto delta = addr - TEXT_START; return delta < TEXT_SIZE ? TEXT_POINTER + delta : nullptr; } // data segment if( addr < HEAP_START ){ auto delta = addr - DATA_START; return delta < DATA_SIZE ? DATA_POINTER + delta : nullptr; } // heap if( addr < HEAP_START + Heap.size() ) return Heap.data() + (addr - HEAP_START); // stack if( addr >= R[REG_SP] ) return STACK_POINTER + (STACK_SIZE - (STACK_START - addr)); // invalid return nullptr; } int ensure_stack_size(size_t cap){ // constraint already satisfied if( STACK_SIZE >= cap ) return 0; // calculate new stack size size_t new_size = 1; while( new_size < cap ) new_size <<= 1; auto delta = new_size - STACK_SIZE; // try to reallocate try{ auto *new_stack = new uint8_t[new_size]; memmove(new_stack + delta, STACK_POINTER, STACK_SIZE); delete[] STACK_POINTER; STACK_POINTER = new_stack; STACK_SIZE = new_size; }catch(...){ return -1; // TODO: standarize } return 0; }
2,207
812
#ifdef USE_CUDA #include <openpose/gpu/cuda.hpp> #include <openpose/gpu/cuda.hu> #endif #include <openpose/utilities/openCv.hpp> #include <openpose/core/opOutputToCvMat.hpp> namespace op { OpOutputToCvMat::OpOutputToCvMat(const bool gpuResize) : mGpuResize{gpuResize}, spOutputImageFloatCuda{std::make_shared<float*>()}, spOutputMaxSize{std::make_shared<unsigned long long>(0ull)}, spGpuMemoryAllocated{std::make_shared<bool>(false)}, pOutputImageUCharCuda{nullptr}, mOutputMaxSizeUChar{0ull} { try { #ifndef USE_CUDA if (mGpuResize) error("You need to compile OpenPose with CUDA support in order to use GPU resize.", __LINE__, __FUNCTION__, __FILE__); #endif } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } OpOutputToCvMat::~OpOutputToCvMat() { try { #ifdef USE_CUDA if (mGpuResize) { // Free temporary memory cudaFree(*spOutputImageFloatCuda); cudaFree(pOutputImageUCharCuda); } #endif } catch (const std::exception& e) { errorDestructor(e.what(), __LINE__, __FUNCTION__, __FILE__); } } void OpOutputToCvMat::setSharedParameters( const std::tuple<std::shared_ptr<float*>, std::shared_ptr<bool>, std::shared_ptr<unsigned long long>>& tuple) { try { spOutputImageFloatCuda = std::get<0>(tuple); spGpuMemoryAllocated = std::get<1>(tuple); spOutputMaxSize = std::get<2>(tuple); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } cv::Mat OpOutputToCvMat::formatToCvMat(const Array<float>& outputData) { try { // Sanity check if (outputData.empty()) error("Wrong input element (empty outputData).", __LINE__, __FUNCTION__, __FILE__); // Final result cv::Mat cvMat; // CPU version if (!mGpuResize) { // outputData to cvMat outputData.getConstCvMat().convertTo(cvMat, CV_8UC3); } // CUDA version else { #ifdef USE_CUDA // (Free and re-)Allocate temporary memory if (mOutputMaxSizeUChar < *spOutputMaxSize) { mOutputMaxSizeUChar = *spOutputMaxSize; cudaFree(pOutputImageUCharCuda); cudaMalloc((void**)&pOutputImageUCharCuda, sizeof(unsigned char) * mOutputMaxSizeUChar); } // Float ptr --> unsigned char ptr const auto volume = (int)outputData.getVolume(); uCharImageCast(pOutputImageUCharCuda, *spOutputImageFloatCuda, volume); // Allocate cvMat cvMat = cv::Mat(outputData.getSize(0), outputData.getSize(1), CV_8UC3); // CUDA --> CPU: Copy output image back to CPU cudaMemcpy( cvMat.data, pOutputImageUCharCuda, sizeof(unsigned char) * mOutputMaxSizeUChar, cudaMemcpyDeviceToHost); // Indicate memory was copied out *spGpuMemoryAllocated = false; #else error("You need to compile OpenPose with CUDA support in order to use GPU resize.", __LINE__, __FUNCTION__, __FILE__); #endif } // Return cvMat return cvMat; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return cv::Mat(); } } }
4,111
1,186
#include <cstring> #include <iostream> #include <string> #include <fcntl.h> #include <unistd.h> #define TEST_FILE "test.txt" using namespace std; #define checker(ret, key) \ do { \ if (!(ret)) { \ cout << "Failed to do " key ", err:" << errno << endl; \ exit(1); \ } \ } while (0); int main(int argc, char *argv[]) { ssize_t ret; string filename; char buf[32] = {'\0'}; string read_txt; string write_txt; int fd = -1; if (2 > argc || NULL == argv[1]) { cout << "Usage: fs-test <mount point>" << endl; exit(1); } filename = string(argv[1]) + "/" + TEST_FILE; checker(-1 != (fd = open(filename.c_str(), O_WRONLY | O_CREAT)), "open"); for (int i = 0; i < 8; ++i) { string tmp; for (int j = 0; j < 3000; ++j) tmp += to_string(i); tmp + ", "; checker(-1 != write(fd, tmp.c_str(), tmp.length()), "write"); write_txt += tmp; } checker(-1 != close(fd), "close"); checker(-1 != (fd = open(filename.c_str(), O_RDONLY)), "open"); while (0 < (ret = read(fd, buf, sizeof(buf) - 1))) { buf[ret] = '\0'; read_txt += string(buf); } checker(-1 != close(fd), "close"); if (read_txt != write_txt) { cout << "Failed to read buf " << read_txt << "." << endl; exit(1); } checker(-1 != unlink(filename.c_str()), "unlink"); return 0; }
1,705
578
/* * Copyright (c) 2021 Sebastian Kylander https://gaztin.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. */ #include "DiscordRPCSettingsModal.h" #include "Discord/DiscordRPC.h" ////////////////////////////////////////////////////////////////////////// std::string DiscordRPCSettingsModal::PopupID( void ) { return "EXT_DISCORD_RPC_MODAL"; } // PopupID ////////////////////////////////////////////////////////////////////////// std::string DiscordRPCSettingsModal::Title( void ) { return "Discord RPC Settings"; } // Title ////////////////////////////////////////////////////////////////////////// void DiscordRPCSettingsModal::UpdateDerived( void ) { ImGui::Text( "Show File Name" ); ImGui::SameLine(); ImGui::Checkbox( "##gd-ext-file", &DiscordRPC::Instance().m_Settings.ShowFilename ); ImGui::Text( "Show Workspace Name" ); ImGui::SameLine(); ImGui::Checkbox( "##gd-ext-wks", &DiscordRPC::Instance().m_Settings.ShowWrksName ); ImGui::Text( "Show Time" ); ImGui::SameLine(); ImGui::Checkbox( "##gd-ext-time", &DiscordRPC::Instance().m_Settings.ShowTime ); ImGui::Text( "Show" ); ImGui::SameLine(); ImGui::Checkbox( "##gd-ext-show", &DiscordRPC::Instance().m_Settings.Show ); if( ImGui::Button( "Close" ) ) Close(); } // UpdateDerived ////////////////////////////////////////////////////////////////////////// void DiscordRPCSettingsModal::Show( void ) { if( Open() ) ImGui::SetWindowSize( ImVec2( 365, 189 ) ); } // Show
2,296
678
//#include <iostream> //#include <sstream> //#include <vector> // //using namespace std; // //int main() { // // stringstream ss; // string tmp; // // cin >> tmp; // // ss.str(tmp); // // while (getline(ss, tmp, ',')) cout << tmp << " "; // // return 0; // //}
261
112
/* dvdisaster: Additional error correction for optical media. * Copyright (C) 2004-2007 Carsten Gnoerlich. * Project home page: http://www.dvdisaster.com * Email: carsten@dvdisaster.com -or- cgnoerlich@fsfe.org * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA, * or direct your browser at http://www.gnu.org. */ #include "dvdisaster.h" static GaloisTables *gt = NULL; /* for L-EC Reed-Solomon */ static ReedSolomonTables *rt = NULL; bool Init_LEC_Correct(void) { gt = CreateGaloisTables(0x11d); rt = CreateReedSolomonTables(gt, 0, 1, 10); return(1); } void Kill_LEC_Correct(void) { FreeGaloisTables(gt); FreeReedSolomonTables(rt); } /*** *** CD level CRC calculation ***/ /* * Test raw sector against its 32bit CRC. * Returns TRUE if frame is good. */ int CheckEDC(const unsigned char *cd_frame, bool xa_mode) { unsigned int expected_crc, real_crc; unsigned int crc_base = xa_mode ? 2072 : 2064; expected_crc = cd_frame[crc_base + 0] << 0; expected_crc |= cd_frame[crc_base + 1] << 8; expected_crc |= cd_frame[crc_base + 2] << 16; expected_crc |= cd_frame[crc_base + 3] << 24; if(xa_mode) real_crc = EDCCrc32(cd_frame+16, 2056); else real_crc = EDCCrc32(cd_frame, 2064); if(expected_crc == real_crc) return(1); else { //printf("Bad EDC CRC: Calculated: %08x, Recorded: %08x\n", real_crc, expected_crc); return(0); } } /*** *** A very simple L-EC error correction. *** * Perform just one pass over the Q and P vectors to see if everything * is okay respectively correct minor errors. This is pretty much the * same stuff the drive is supposed to do in the final L-EC stage. */ static int simple_lec(unsigned char *frame) { unsigned char byte_state[2352]; unsigned char p_vector[P_VECTOR_SIZE]; unsigned char q_vector[Q_VECTOR_SIZE]; unsigned char p_state[P_VECTOR_SIZE]; int erasures[Q_VECTOR_SIZE], erasure_count; int ignore[2]; int p_failures, q_failures; int p_corrected, q_corrected; int p,q; /* Setup */ memset(byte_state, 0, 2352); p_failures = q_failures = 0; p_corrected = q_corrected = 0; /* Perform Q-Parity error correction */ for(q=0; q<N_Q_VECTORS; q++) { int err; /* We have no erasure information for Q vectors */ GetQVector(frame, q_vector, q); err = DecodePQ(rt, q_vector, Q_PADDING, ignore, 0); /* See what we've got */ if(err < 0) /* Uncorrectable. Mark bytes are erasure. */ { q_failures++; FillQVector(byte_state, 1, q); } else /* Correctable */ { if(err == 1 || err == 2) /* Store back corrected vector */ { SetQVector(frame, q_vector, q); q_corrected++; } } } /* Perform P-Parity error correction */ for(p=0; p<N_P_VECTORS; p++) { int err,i; /* Try error correction without erasure information */ GetPVector(frame, p_vector, p); err = DecodePQ(rt, p_vector, P_PADDING, ignore, 0); /* If unsuccessful, try again using erasures. Erasure information is uncertain, so try this last. */ if(err < 0 || err > 2) { GetPVector(byte_state, p_state, p); erasure_count = 0; for(i=0; i<P_VECTOR_SIZE; i++) if(p_state[i]) erasures[erasure_count++] = i; if(erasure_count > 0 && erasure_count <= 2) { GetPVector(frame, p_vector, p); err = DecodePQ(rt, p_vector, P_PADDING, erasures, erasure_count); } } /* See what we've got */ if(err < 0) /* Uncorrectable. */ { p_failures++; } else /* Correctable. */ { if(err == 1 || err == 2) /* Store back corrected vector */ { SetPVector(frame, p_vector, p); p_corrected++; } } } /* Sum up */ if(q_failures || p_failures || q_corrected || p_corrected) { return 1; } return 0; } /*** *** Validate CD raw sector ***/ int ValidateRawSector(unsigned char *frame, bool xaMode) { int lec_did_sth = FALSE_0; /* Do simple L-EC. It seems that drives stop their internal L-EC as soon as the EDC is okay, so we may see uncorrected errors in the parity bytes. Since we are also interested in the user data only and doing the L-EC is expensive, we skip our L-EC as well when the EDC is fine. */ if(!CheckEDC(frame, xaMode)) { lec_did_sth = simple_lec(frame); } /* Test internal sector checksum again */ if(!CheckEDC(frame, xaMode)) { /* EDC failure in RAW sector */ return FALSE_0; } return TRUE_1; }
5,165
1,970
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "compiler/typecheck/capability_predicate.h" #include "compiler/printing.h" #include <fmt/ostream.h> namespace verona::compiler { PredicateSet::PredicateSet(CapabilityPredicate predicate) : values_(static_cast<underlying_type>(predicate)) {} PredicateSet::PredicateSet(underlying_type values) : values_(values) {} PredicateSet PredicateSet::empty() { return PredicateSet(0); } PredicateSet PredicateSet::all() { return CapabilityPredicate::Readable | CapabilityPredicate::Writable | CapabilityPredicate::NonWritable | CapabilityPredicate::NonLinear | CapabilityPredicate::Sendable; } bool PredicateSet::contains(CapabilityPredicate predicate) const { return (values_ & static_cast<underlying_type>(predicate)) != 0; } PredicateSet PredicateSet::operator|(PredicateSet other) const { return PredicateSet(values_ | other.values_); } PredicateSet PredicateSet::operator&(PredicateSet other) const { return PredicateSet(values_ & other.values_); } PredicateSet operator|(CapabilityPredicate lhs, CapabilityPredicate rhs) { return PredicateSet(lhs) | PredicateSet(rhs); } struct CapabilityPredicateVisitor : public TypeVisitor<PredicateSet> { PredicateSet visit_base_type(const TypePtr& type) final { return PredicateSet::empty(); } PredicateSet visit_capability(const CapabilityTypePtr& type) final { switch (type->kind) { case CapabilityKind::Isolated: if (std::holds_alternative<RegionNone>(type->region)) { return CapabilityPredicate::Readable | CapabilityPredicate::Writable | CapabilityPredicate::Sendable; } else { return CapabilityPredicate::Readable | CapabilityPredicate::Writable | CapabilityPredicate::NonLinear; } case CapabilityKind::Mutable: return CapabilityPredicate::Readable | CapabilityPredicate::Writable | CapabilityPredicate::NonLinear; case CapabilityKind::Subregion: return CapabilityPredicate::Readable | CapabilityPredicate::Writable | CapabilityPredicate::NonLinear; case CapabilityKind::Immutable: return CapabilityPredicate::Readable | CapabilityPredicate::NonWritable | CapabilityPredicate::Sendable | CapabilityPredicate::NonLinear; EXHAUSTIVE_SWITCH; } } /** * Visits each member of elements and merges the results using the given * BinaryOp. */ template<typename BinaryOp> PredicateSet combine_elements( const TypeSet& elements, PredicateSet initial, BinaryOp combine) { // std::transform_reduce isn't available yet in libstdc++7 :( PredicateSet result = initial; for (const auto& elem : elements) { result = combine(result, visit_type(elem)); } return result; } PredicateSet visit_static_type(const StaticTypePtr& type) final { return CapabilityPredicate::Sendable | CapabilityPredicate::NonLinear; } PredicateSet visit_string_type(const StringTypePtr& type) final { return CapabilityPredicate::Sendable | CapabilityPredicate::NonLinear; } PredicateSet visit_union(const UnionTypePtr& type) final { return combine_elements( type->elements, PredicateSet::all(), std::bit_and<PredicateSet>()); } PredicateSet visit_intersection(const IntersectionTypePtr& type) final { return combine_elements( type->elements, PredicateSet::empty(), std::bit_or<PredicateSet>()); } PredicateSet visit_variable_renaming_type(const VariableRenamingTypePtr& type) final { return visit_type(type->type); } PredicateSet visit_path_compression_type(const PathCompressionTypePtr& type) final { return visit_type(type->type); } PredicateSet visit_fixpoint_type(const FixpointTypePtr& type) final { return visit_type(type->inner); } PredicateSet visit_fixpoint_variable_type(const FixpointVariableTypePtr& type) final { return PredicateSet::all(); } }; PredicateSet predicates_for_type(TypePtr type) { // This is pretty cheap, but it's likely we'll be doing it a lot in the // future. We might want to cache results. return CapabilityPredicateVisitor().visit_type(type); } std::ostream& operator<<(std::ostream& out, CapabilityPredicate predicate) { switch (predicate) { case CapabilityPredicate::Readable: return out << "readable"; case CapabilityPredicate::Writable: return out << "writable"; case CapabilityPredicate::NonWritable: return out << "non-writable"; case CapabilityPredicate::Sendable: return out << "sendable"; case CapabilityPredicate::NonLinear: return out << "non-linear"; EXHAUSTIVE_SWITCH; } } }
5,082
1,486
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_OS_PERSISTENT_STATE_FACTORY_HPP #define IROHA_OS_PERSISTENT_STATE_FACTORY_HPP #include <memory> #include "ametsuchi/ordering_service_persistent_state.hpp" namespace iroha { namespace ametsuchi { class OsPersistentStateFactory { public: /** * @return ordering service persistent state */ virtual boost::optional<std::shared_ptr<OrderingServicePersistentState>> createOsPersistentState() const = 0; virtual ~OsPersistentStateFactory() = default; }; } // namespace ametsuchi } // namespace iroha #endif // IROHA_OS_PERSISTENT_STATE_FACTORY_HPP
719
250
//-------------------------------------------------------------------------- // // Environment: // This software is part of the EvtGen package developed jointly // for the BaBar and CLEO collaborations. If you use all or part // of it, please give an appropriate acknowledgement. // // Copyright Information: See EvtGen/COPYRIGHT // Copyright (C) 1998 Caltech, UCSB // // Module: EvtStringParticle.cc // // Description: Class to describe the partons that are produced in JetSet. // // Modification history: // // RYD Febuary 27,1998 Module created // //------------------------------------------------------------------------ // #include "EvtGenBase/EvtPatches.hh" #include <iostream> #include <math.h> #include <stdlib.h> #include "EvtGenBase/EvtStringParticle.hh" #include "EvtGenBase/EvtVector4R.hh" #include "EvtGenBase/EvtReport.hh" EvtStringParticle::~EvtStringParticle(){ if (_npartons!=0){ delete [] _p4partons; delete [] _idpartons; } } EvtStringParticle::EvtStringParticle(){ _p4partons=0; _idpartons=0; _npartons=0; return; } void EvtStringParticle::init(EvtId id, const EvtVector4R& p4){ _validP4=true; setp(p4); setpart_num(id); } void EvtStringParticle::initPartons(int npartons, EvtVector4R* p4partons,EvtId* idpartons){ _p4partons = new EvtVector4R[npartons]; _idpartons = new EvtId[npartons]; int i; _npartons=npartons; for(i=0;i<npartons;i++){ _p4partons[i]=p4partons[i]; _idpartons[i]=idpartons[i]; } } int EvtStringParticle::getNPartons(){ return _npartons; } EvtId EvtStringParticle::getIdParton(int i){ return _idpartons[i]; } EvtVector4R EvtStringParticle::getP4Parton(int i){ return _p4partons[i]; } EvtSpinDensity EvtStringParticle::rotateToHelicityBasis() const{ EvtGenReport(EVTGEN_ERROR,"EvtGen") << "rotateToHelicityBasis not implemented for strin particle."; EvtGenReport(EVTGEN_ERROR,"EvtGen") << "Will terminate execution."; ::abort(); EvtSpinDensity rho; return rho; } EvtSpinDensity EvtStringParticle::rotateToHelicityBasis(double, double, double) const{ EvtGenReport(EVTGEN_ERROR,"EvtGen") << "rotateToHelicityBasis(alpha,beta,gamma) not implemented for string particle."; EvtGenReport(EVTGEN_ERROR,"EvtGen") << "Will terminate execution."; ::abort(); EvtSpinDensity rho; return rho; }
2,418
938
#include <_character_disconnect_result_wrac.hpp> START_ATF_NAMESPACE int _character_disconnect_result_wrac::size() { using org_ptr = int (WINAPIV*)(struct _character_disconnect_result_wrac*); return (org_ptr(0x1401d24e0L))(this); }; END_ATF_NAMESPACE
281
111
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <fcntl.h> #include <errno.h> #include <linux/hidraw.h> #include <stdint.h> #include <string> #include <linux/version.h> #include "UVCLinuxControl.h" #include "UVCLinux.h" typedef int BOOLEAN; typedef int BOOL; typedef int INT; typedef unsigned int UINT; typedef long long REFERENCE_TIME; typedef double DOUBLE; typedef uint8_t BYTE; typedef char CHAR, *PCHAR; typedef unsigned char UCHAR, *PUCHAR; typedef short SHORT, *PSHORT; typedef unsigned short USHORT, *PUSHORT; typedef unsigned short WORD, *PWORD; typedef long LONG, *PLONG; typedef unsigned long ULONG, *PULONG; typedef unsigned long DWORD, *PDWORD, *LPDWORD; typedef unsigned int UINT; typedef long long LONGLONG; typedef unsigned long long ULONGLONG; typedef wchar_t WCHAR, *PWCHAR, *WSTRING; typedef void *PVOID; typedef PVOID HWND; typedef PVOID HANDLE; #if LINUX_VERSION_CODE <= KERNEL_VERSION(3, 1, 0) /* The first uint8_t of SFEATURE and GFEATURE is the report number */ #define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE | _IOC_READ, 'H', 0x06, len) #define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE | _IOC_READ, 'H', 0x07, len) #endif #define _W64 __attribute__((mode(__pointer__))) typedef _W64 uintptr_t ULONG_PTR, DWORD_PTR; #define LOBYTE(w) ((uint8_t)(((DWORD_PTR)(w)) & 0xff)) struct PD570_HID_ID { static const int I2C_READ_SET_ID = 9; static const int I2C_READ_GET_ID = 10; static const int I2C_WRITE_ID = 11; static const int RESET_ID = 18; static const int GET_RES_ID = 19; }; struct PD570_HID_CONSTS { static const int MAX_COMM_READ_BUFFER_SIZE = 32; }; int hid_send_feature_report(int fd, const unsigned char *data, size_t length) { return ioctl(fd, HIDIOCSFEATURE(length), data); } int hid_get_feature_report(int fd, unsigned char *data, size_t length) { return ioctl(fd, HIDIOCGFEATURE(length), data); } int hid_report_read(int fd, void *p_buffer, size_t i_size) { return hid_get_feature_report(fd, (unsigned char *)p_buffer, i_size); } int hid_report_write(int fd, void *p_buffer, size_t i_size) { return hid_send_feature_report(fd, (const unsigned char *)p_buffer, i_size); } bool find_hid_dev_path(int devNum, ULONG pszDeviceID, char *outPath) { int err = 0; for (int i = 0;; ++i) { char pszDeviceName[128]; sprintf(pszDeviceName, "hidraw%d", i); std::string strDeviceName = pszDeviceName; std::string strDevicePath = "/dev/" + strDeviceName; struct stat status; if (-1 == stat(strDevicePath.c_str(), &status)) { break; } if (false == S_ISCHR(status.st_mode)) { break; } int fd = open(strDevicePath.c_str(), O_RDWR, 0); // printf("[find_hid_dev_path] OPENING %s -> %d\n", strDevicePath.c_str(), fd); if (fd == -1) { err = errno; printf("%s(%d): open(\"%s\") failed, err=%d\n", __FUNCTION__, __LINE__, strDevicePath.c_str(), err); break; } int _vid = -1, _pid = -1; do { hidraw_devinfo devinfo; err = ioctl(fd, HIDIOCGRAWINFO, &devinfo); if (err < 0) { err = errno; printf("%s(%d): ioctl(HIDIOCGRAWINFO) failed, err=%d\n", __FUNCTION__, __LINE__, err); break; } _vid = devinfo.vendor & 0xFFFF; _pid = devinfo.product & 0xFFFF; } while (false); // printf("[find_hid_dev_path] CLOSING %d\n", fd); close(fd); // LOGI("!!!!!!!!!!!!!!!!!! %04X %04X ?= %04X:%04X", _vid, _pid, vid, pid); int vid = -1, pid = -1; bool found = false; for (int c = 0;; ++c) { if (pszDeviceID == 0) break; vid = (pszDeviceID & 0xFFFF0000) >> 16; pid = (pszDeviceID & 0x0000FFFF); if (_vid == vid && _pid == pid) { found = true; break; } } if (devNum >= 0 && found) { if (devNum == 0) { strcpy(outPath, strDevicePath.c_str()); return true; } --devNum; } } return false; } int read_i2c_data(int fd, uint32_t nDeviceAddress, uint32_t nRegisterAddress, uint8_t *pData, uint32_t nLength) { uint8_t buffer[5 + PD570_HID_CONSTS::MAX_COMM_READ_BUFFER_SIZE] = { PD570_HID_ID::I2C_READ_SET_ID, nDeviceAddress, LOBYTE(nRegisterAddress), nLength, }; int err = hid_report_write(fd, buffer, 4); if (err < 0) { err = errno; printf("%s(%d): hid_report_write(I2C_READ_SET_ID) failed, err=%d\n", __FUNCTION__, __LINE__); return err; } buffer[0] = PD570_HID_ID::I2C_READ_GET_ID; err = hid_report_read(fd, buffer, 4 + PD570_HID_CONSTS::MAX_COMM_READ_BUFFER_SIZE); if (err < 0) { err = errno; printf("%s(%d): hid_report_read(I2C_READ_GET_ID) failed, err=%d\n", __FUNCTION__, __LINE__); return err; } memcpy(pData, buffer, nLength); return 0; } int write_i2c_data(int fd, uint32_t nDeviceAddress, uint32_t nRegisterAddress, uint8_t *pData, uint32_t nLength) { uint8_t buffer[4 + PD570_HID_CONSTS::MAX_COMM_READ_BUFFER_SIZE] = { PD570_HID_ID::I2C_WRITE_ID, nDeviceAddress, LOBYTE(nRegisterAddress), nLength, }; memcpy(&buffer[4], pData, nLength); memset(&buffer[4 + nLength], 0, sizeof(buffer) - 4 - nLength); #if 0 for(int i = 0;i < 8;++i) { LOGD("!!!! write_i2c_data %d 0x%X", i, (int)buffer[i]); } #endif int err = hid_report_write(fd, buffer, 4 + PD570_HID_CONSTS::MAX_COMM_READ_BUFFER_SIZE); if (err < 0) { err = errno; printf("%s(%d): hid_report_write(I2C_WRITE_ID) failed, err=%d\n", __FUNCTION__, __LINE__); return err; } } void UVCLinuxControl::Init() { g_bIsValid = true; // g_fd = -1; } void UVCLinuxControl::Destroy() { // printf("[Destroy] CLOSING %d", g_fd); close(g_fd); g_bIsValid = false; g_fd = -1; } UVCLinuxControl::UVCLinuxControl() { g_bIsValid = false; g_fd = -1; } UVCLinuxControl::~UVCLinuxControl() { } /* int UVCLinuxControl::OpenDeviceEx(char* pszDeviceID) { int nDeviceID = strtol(pszDeviceID, NULL, 16); char strDevicePath[256] = ""; find_hid_dev_path(0, nDeviceID, &strDevicePath[0]); int fd = open(strDevicePath, O_RDWR, 0); printf("[OpenDeviceEx] OPENING %s -> %d\n", strDevicePath, fd); if(fd < 0){ return 4; } g_fd = fd; return 0; }*/ int UVCLinuxControl::OpenDeviceEx(char *strDevicePath) { struct stat status; if (-1 == stat(strDevicePath, &status) || false == S_ISCHR(status.st_mode)) { return UVC_RS_DEVICE_CREATE_FAILED; } // TODO: More checks int fd = open(strDevicePath, O_RDWR, 0); // printf("[OpenDeviceEx] OPENING %s -> %d\n", strDevicePath, fd); if (fd < 0) { return UVC_RS_DEVICE_CREATE_FAILED; } g_fd = fd; return 0; } int UVCLinuxControl::GetVideoFormatPollingRead(unsigned long *pWidth, unsigned long *pHeight, unsigned long *pFPS, int *pIs_1000_1001, int *pIsInterleaced, int *pIsSignalLocked, int *pIsHDCP, int *pIsHDMI) { unsigned char pDevice_format[32] = ""; unsigned long deivce_input_width, deivce_input_height, deivce_input_fps; BYTE detail_format = 0x00; int deivce_input_interleaved, deivce_input_is_1000_1001, deivce_input_lock, deivce_input_hdcp, deivce_input_hdmi; // printf("DEBUG: g_fd: %d\n", g_fd); int err = read_i2c_data(g_fd, 0x55, 0x00, (BYTE *)pDevice_format, 7); if (err != 0) { return err; } deivce_input_width = (pDevice_format[1] & 0xff) | ((pDevice_format[2] & 0xff) << 8); deivce_input_height = (pDevice_format[3] & 0xff) | ((pDevice_format[4] & 0xff) << 8); deivce_input_fps = pDevice_format[5]; detail_format = pDevice_format[6]; if ((detail_format & 0x01) == 0x01) deivce_input_interleaved = 1; else deivce_input_interleaved = 0; if ((detail_format & 0x02) == 0x02) deivce_input_is_1000_1001 = 1; else deivce_input_is_1000_1001 = 0; if ((detail_format & 0x04) == 0x04) deivce_input_lock = 1; else deivce_input_lock = 0; if ((detail_format & 0x08) == 0x08) deivce_input_hdcp = 1; else deivce_input_hdcp = 0; if ((detail_format & 0x10) == 0x10) deivce_input_hdmi = 1; else deivce_input_hdmi = 0; // printf("GetVideoFormatPollingRead: %dx%d %dfps, interleaved:%d 1000_1001:%d lock:%d HDCP:%d HDMI:%d\n", deivce_input_width, deivce_input_height, deivce_input_fps, deivce_input_interleaved, deivce_input_is_1000_1001, deivce_input_lock, deivce_input_hdcp, deivce_input_hdmi); *pWidth = deivce_input_width; *pHeight = deivce_input_height; *pFPS = deivce_input_fps; *pIsInterleaced = deivce_input_interleaved; *pIs_1000_1001 = deivce_input_is_1000_1001; *pIsSignalLocked = deivce_input_lock; *pIsHDCP = deivce_input_hdcp; *pIsHDMI = deivce_input_hdmi; return 0; } int UVCLinuxControl::WriteI2CData(unsigned long nVideoInput) { int set_input_type = 0x00; if (nVideoInput == 0) { set_input_type = 0x00; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 1) { set_input_type = 0x01; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 2) { set_input_type = 0x02; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 3) { set_input_type = 0x03; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 4) { set_input_type = 0x10; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 5) { set_input_type = 0x11; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 6) { set_input_type = 0x20; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 7) { set_input_type = 0x21; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 8) { set_input_type = 0x30; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 9) { set_input_type = 0x31; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 10) { set_input_type = 0x40; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 11) { set_input_type = 0x41; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 12) { set_input_type = 0x50; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 13) { set_input_type = 0x51; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 14) { set_input_type = 0x60; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 15) { set_input_type = 0x61; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } if (nVideoInput == 16) { set_input_type = 0x70; uint8_t bdata[] = {set_input_type}; write_i2c_data(g_fd, 0x55, 0x09, bdata, sizeof(bdata)); } return 0; }
11,116
5,631
/** Copyright 2009-2018 National Technology and Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA-0003525, the U.S. Government retains certain rights in this software. Sandia National Laboratories is a multimission laboratory managed and operated by National Technology and Engineering Solutions of Sandia, LLC., a wholly owned subsidiary of Honeywell International, Inc., for the U.S. Department of Energy's National Nuclear Security Administration under contract DE-NA0003525. Copyright (c) 2009-2018, NTESS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. Questions? Contact sst-macro-help@sandia.gov */ #include <dumpi/bin/metadata.h> #include <dumpi/bin/trace.h> #include <dumpi/bin/dumpistats-timebin.h> #include <dumpi/bin/dumpistats-gatherbin.h> #include <dumpi/bin/dumpistats-handlers.h> #include <dumpi/bin/dumpistats-callbacks.h> #include <sstream> #include <getopt.h> #include <stdio.h> #include <string.h> #include <errno.h> using namespace dumpi; static const struct option longopts[] = { {"help", no_argument, NULL, 'h'}, {"verbose", no_argument, NULL, 'v'}, {"bin", required_argument, NULL, 'b'}, {"mark", required_argument, NULL, 'm'}, {"gather", required_argument, NULL, 'g'}, {"count", required_argument, NULL, 'c'}, {"time", required_argument, NULL, 't'}, {"sent", required_argument, NULL, 's'}, {"recvd", required_argument, NULL, 'r'}, {"exchange", required_argument, NULL, 'x'}, {"lump", required_argument, NULL, 'l'}, {"perfctr", required_argument, NULL, 'p'}, {"in", required_argument, NULL, 'i'}, {"out", required_argument, NULL, 'o'}, {NULL, 0, NULL, 0} }; void print_help(const std::string &name) { std::cerr << name << ": Extract statistics from DUMPI trace files\n" << "Options:\n" << " (-h|--help) Print help screen and exit\n" << " (-v|--verbose) Verbose status output\n" << " (-b|--bin) timerange Define a collection time range\n" << " (-m|--mark) /crt/end/ Create/end a bin at annotations\n" << " (-g|--gather) /crt/end/ Accumulate to an annotated bin\n" << " (-c|--count) funcname Count entries into a function\n" << " (-t|--time) funcname Accumulate time in a function\n" << " (-s|--sent) funcname Count bytes sent by a function\n" << " (-r|--recvd) funcname Count bytes recvd by function\n" << " (-x|--exchange) funcname Full send/recv exchange info\n" << " (-l|--lump) funcname Lump (bin) messages by size\n" << " (-p|--perfctr) funcname PAPI perfcounter info\n" << " (-i|--in) metafile DUMPI metafile (required)\n" << " (-o|--out) fileroot Output file root (required)\n" << "\n" << "The timerange has the form:\n" << " (all | mpi | BOUND to BOUND) [by TIME]\n" << " where BOUND the form:\n" << " (IDENTITY | TIME) [(+|-) TIME]\n" << " and IDENTITY is:\n" << " start | end | init | finalize | TIME\n" << " and TIME is:\n" << " (hh:)?(mm:)?[0-9]0-9+(.[0-9]*)?\n" << "\n" << "The funcname has the form:\n" << " all | mpi | non-mpi | sends | recvs | coll | wait | io | RE\n" << " where RE is a case-insensitive regular expression\n" << " (e.g. \"MPI_Wait.*\" or \"mpio?_(wait.*|test.*))\"\n" << " All regular expressions are implicitly flanked by ^ and $,\n" << " so \"mpi_.?send\" does not match MPI_Sendrecv\n" << "\n" << "The annotated bins (-m and -g) use regular expressions\n" << "with a format similar to sed basic regular expressions, so:" << " -m '/begin bin/end bin/'\n" << " -m '!begin bin!end bin!i'\n" << " -g '| +start loop [0-9]+ *$|end loop [0-9]+$|'\n" << "are all valid annotations (note that backreferences are \n" << "not allowed). Escaped characters other than the delimiter\n" << "are passed directly to the regular expression parser.\n" << "\n" << "Example 1:\n" << " " << name << " --bin=all --time=mpi --time=other \\\n" << " -i dumpi.meta -o stats\n" << " Writes a file called stats-0.dat with three columns:\n" << " 1: The rank of each MPI node\n" << " 2: Aggregate time spent in MPI calls\n" << " 3: Aggregate time spent outside MPI calls\n" << "\n" << "Example 2\n" << " " << name << " --bin='init to finalize by 1:00' \\ \n" << " --count=mpi_.*send -i dumpi.meta -o stats\n" << " Writes files with send counts binned into 1 minute\n" << " intervals.\n" << "\n" << "Example 3\n" << " " << name << " --bin='begin+10 to end-10' -s all -r all \\\n" << " -i dumpi.meta -o stats \\\n" << " Writes a new file containing bytes sent and received\n" << " starting 10 seconds after first and ending 10 seconds\n" << " before last simulation timestamp\n"; } struct options { bool verbose; std::string infile, outroot; std::vector<binbase*> bin; std::vector<handlerbase*> handlers; options() : verbose(false) {} }; int main(int argc, char **argv) { std::string shortopts; for(int optid = 0; longopts[optid].name != NULL; ++optid) { if(longopts[optid].val) { shortopts += char(longopts[optid].val); if(longopts[optid].has_arg != no_argument) shortopts += ":"; } } options opt; int ch; /* {"help", no_argument, NULL, 'h'}, {"verbose", no_argument, NULL, 'v'}, {"bin", required_argument, NULL, 'b'}, {"count", required_argument, NULL, 'c'}, {"time", required_argument, NULL, 't'}, {"sent", required_argument, NULL, 's'}, {"recvd", required_argument, NULL, 'r'}, {"exchange", required_argument, NULL, 'x'}, {"in", required_argument, NULL, 'i'}, {"out", required_argument, NULL, 'o'}, */ while((ch=getopt_long(argc, argv, shortopts.c_str(), longopts, NULL)) != -1) { switch(ch) { case 'h': print_help(argv[0]); return 1; case 'v': opt.verbose = true; break; case 'b': opt.bin.push_back(new timebin(optarg)); break; case 'm': opt.bin.push_back(new gatherbin(optarg, false)); break; case 'g': opt.bin.push_back(new gatherbin(optarg, true)); break; case 'c': opt.handlers.push_back(new counter(optarg)); break; case 't': opt.handlers.push_back(new timer(optarg)); break; case 's': opt.handlers.push_back(new sender(optarg)); break; case 'r': opt.handlers.push_back(new recver(optarg)); break; case 'x': opt.handlers.push_back(new exchanger(optarg)); break; case 'l': opt.handlers.push_back(new lumper(optarg)); break; case 'p': opt.handlers.push_back(new perfcounter(optarg)); break; case 'i': opt.infile = optarg; break; case 'o': opt.outroot = optarg; break; default: std::cerr << "Invalid argument: " << char(ch) << "\n"; return 2; } } if(opt.infile == "" || opt.outroot == "") { std::cerr << "Usage: " << argv[0] << " [options] -i infile -o outroot\n"; return 3; } FILE *ff = fopen(opt.infile.c_str(), "r"); if(! ff) { std::cerr << opt.infile << ": " << strerror(errno) << "\n"; return 4; } try { // Provide some sensible defaults (time in MPI and non-MPI functions). if(opt.bin.empty()) opt.bin.push_back(new timebin("all")); if(opt.handlers.empty()) { opt.handlers.push_back(new timer("mpi")); } // Preparse the streams to get data types etc. correct. if(opt.verbose) std::cerr << "Parsing metafile\n"; metadata meta(opt.infile); // Open traces. if(opt.verbose) std::cout << "Pre-parsing traces.\n"; sharedstate shared(meta.numTraces()); std::vector<trace> traces; preparse_traces(meta, &shared, traces); // Tell the handlers about world size. if(opt.verbose) std::cerr << "Setting up handlers\n"; for(size_t i = 0; i < opt.handlers.size(); ++i) opt.handlers.at(i)->set_world_size(meta.numTraces()); // Set up. Each bin gets a copy of all the handlers. for(size_t i = 0; i < opt.bin.size(); ++i) { std::stringstream ss; ss << opt.outroot << "-bin" << i; std::string name = ss.str(); opt.bin.at(i)->init(name, &traces, opt.handlers); } callbacks cb; if(opt.verbose) std::cerr << "Re-parsing files and building tables\n"; cb.go(meta, traces, opt.bin); // Clean up. for(size_t i = 0; i < opt.bin.size(); ++i) delete opt.bin.at(i); } catch(const char *desc) { std::cerr << "Error exit: " << desc << "\n"; return 10; } }
10,666
3,678
#ifndef PATH_H #define PATH_H #include <vector> #include <map> #include "coordinate.hpp" class Path { private: std::vector<Coordinate> coords; public: Path(std::vector<Coordinate> coords); Path(int, int); void add_coords(int x, int y); void add_coords(Coordinate coord); size_t size(); bool in(int x, int y); bool in(Coordinate coord); Coordinate get_coordinate(int index); }; #include "path_creator.cpp" #endif
464
168
/*-------------------------------------------------------------------------- Copyright (c) 2009, Code Aurora Forum. 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 Code Aurora 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, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT 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. --------------------------------------------------------------------------*/ /*======================================================================== O p e n M M V i d e o U t i l i t i e s *//** @file H264_Utils.cpp This module contains utilities and helper routines. @par EXTERNALIZED FUNCTIONS @par INITIALIZATION AND SEQUENCING REQUIREMENTS (none) *//*====================================================================== */ /* ======================================================================= INCLUDE FILES FOR MODULE ========================================================================== */ #include "H264_Utils.h" #include "omx_vdec.h" #include <string.h> #include <stdlib.h> #ifdef _ANDROID_ #include "cutils/properties.h" #endif #include "qtv_msg.h" /* ======================================================================= DEFINITIONS AND DECLARATIONS FOR MODULE This section contains definitions for constants, macros, types, variables and other items needed by this module. ========================================================================== */ #define SIZE_NAL_FIELD_MAX 4 #define BASELINE_PROFILE 66 #define MAIN_PROFILE 77 #define HIGH_PROFILE 100 #define MAX_SUPPORTED_LEVEL 32 RbspParser::RbspParser(const uint8 * _begin, const uint8 * _end) :begin(_begin), end(_end), pos(-1), bit(0), cursor(0xFFFFFF), advanceNeeded(true) { } // Destructor /*lint -e{1540} Pointer member neither freed nor zeroed by destructor * No problem */ RbspParser::~RbspParser() { } // Return next RBSP byte as a word uint32 RbspParser::next() { if (advanceNeeded) advance(); //return static_cast<uint32> (*pos); return static_cast < uint32 > (begin[pos]); } // Advance RBSP decoder to next byte void RbspParser::advance() { ++pos; //if (pos >= stop) if (begin + pos == end) { /*lint -e{730} Boolean argument to function * I don't see a problem here */ //throw false; QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->NEED TO THROW THE EXCEPTION...\n"); } cursor <<= 8; //cursor |= static_cast<uint32> (*pos); cursor |= static_cast < uint32 > (begin[pos]); if ((cursor & 0xFFFFFF) == 0x000003) { advance(); } advanceNeeded = false; } // Decode unsigned integer uint32 RbspParser::u(uint32 n) { uint32 i, s, x = 0; for (i = 0; i < n; i += s) { s = static_cast < uint32 > STD_MIN(static_cast < int >(8 - bit), static_cast < int >(n - i)); x <<= s; x |= ((next() >> ((8 - static_cast < uint32 > (bit)) - s)) & ((1 << s) - 1)); bit = (bit + s) % 8; if (!bit) { advanceNeeded = true; } } return x; } // Decode unsigned integer Exp-Golomb-coded syntax element uint32 RbspParser::ue() { int leadingZeroBits = -1; for (uint32 b = 0; !b; ++leadingZeroBits) { b = u(1); } return ((1 << leadingZeroBits) - 1) + u(static_cast < uint32 > (leadingZeroBits)); } // Decode signed integer Exp-Golomb-coded syntax element int32 RbspParser::se() { const uint32 x = ue(); if (!x) return 0; else if (x & 1) return static_cast < int32 > ((x >> 1) + 1); else return -static_cast < int32 > (x >> 1); } void H264_Utils::allocate_rbsp_buffer(uint32 inputBufferSize) { m_rbspBytes = (byte *) malloc(inputBufferSize); m_prv_nalu.nal_ref_idc = 0; m_prv_nalu.nalu_type = NALU_TYPE_UNSPECIFIED; } H264_Utils::H264_Utils():m_height(0), m_width(0), m_rbspBytes(NULL), m_default_profile_chk(true), m_default_level_chk(true) { #ifdef _ANDROID_ char property_value[PROPERTY_VALUE_MAX] = {0}; if(0 != property_get("persist.omxvideo.profilecheck", property_value, NULL)) { if(!strcmp(property_value, "false")) { m_default_profile_chk = false; } } else { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264_Utils:: Constr failed in \ getting value for the Android property [persist.omxvideo.profilecheck]"); } if(0 != property_get("persist.omxvideo.levelcheck", property_value, NULL)) { if(!strcmp(property_value, "false")) { m_default_level_chk = false; } } else { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264_Utils:: Constr failed in \ getting value for the Android property [persist.omxvideo.levelcheck]"); } #endif initialize_frame_checking_environment(); } H264_Utils::~H264_Utils() { /* if(m_pbits) { delete(m_pbits); m_pbits = NULL; } */ if (m_rbspBytes) { free(m_rbspBytes); m_rbspBytes = NULL; } } /***********************************************************************/ /* FUNCTION: H264_Utils::initialize_frame_checking_environment DESCRIPTION: Extract RBSP data from a NAL INPUT/OUTPUT PARAMETERS: None RETURN VALUE: boolean SIDE EFFECTS: None. */ /***********************************************************************/ void H264_Utils::initialize_frame_checking_environment() { m_forceToStichNextNAL = false; } /***********************************************************************/ /* FUNCTION: H264_Utils::extract_rbsp DESCRIPTION: Extract RBSP data from a NAL INPUT/OUTPUT PARAMETERS: <In> buffer : buffer containing start code or nal length + NAL units buffer_length : the length of the NAL buffer start_code : If true, start code is detected, otherwise size nal length is detected size_of_nal_length_field: size of nal length field <Out> rbsp_bistream : extracted RBSP bistream rbsp_length : the length of the RBSP bitstream nal_unit : decoded NAL header information RETURN VALUE: boolean SIDE EFFECTS: None. */ /***********************************************************************/ boolean H264_Utils::extract_rbsp(OMX_IN OMX_U8 * buffer, OMX_IN OMX_U32 buffer_length, OMX_IN OMX_U32 size_of_nal_length_field, OMX_OUT OMX_U8 * rbsp_bistream, OMX_OUT OMX_U32 * rbsp_length, OMX_OUT NALU * nal_unit) { byte coef1, coef2, coef3; uint32 pos = 0; uint32 nal_len = buffer_length; uint32 sizeofNalLengthField = 0; uint32 zero_count; boolean eRet = true; boolean start_code = (size_of_nal_length_field == 0) ? true : false; QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "extract_rbsp\n"); if (start_code) { // Search start_code_prefix_one_3bytes (0x000001) coef2 = buffer[pos++]; coef3 = buffer[pos++]; do { if (pos >= buffer_length) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_HIGH, "Error at extract rbsp line %d", __LINE__); return false; } coef1 = coef2; coef2 = coef3; coef3 = buffer[pos++]; } while (coef1 || coef2 || coef3 != 1); } else if (size_of_nal_length_field) { /* This is the case to play multiple NAL units inside each access unit */ /* Extract the NAL length depending on sizeOfNALength field */ sizeofNalLengthField = size_of_nal_length_field; nal_len = 0; while (size_of_nal_length_field--) { nal_len |= buffer[pos++] << (size_of_nal_length_field << 3); } if (nal_len >= buffer_length) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "Error at extract rbsp line %d", __LINE__); return false; } } if (nal_len > buffer_length) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "Error at extract rbsp line %d", __LINE__); return false; } if (pos + 1 > (nal_len + sizeofNalLengthField)) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "Error at extract rbsp line %d", __LINE__); return false; } if (nal_unit->forbidden_zero_bit = (buffer[pos] & 0x80)) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "Error at extract rbsp line %d", __LINE__); } nal_unit->nal_ref_idc = (buffer[pos] & 0x60) >> 5; nal_unit->nalu_type = buffer[pos++] & 0x1f; *rbsp_length = 0; if (nal_unit->nalu_type == NALU_TYPE_EOSEQ || nal_unit->nalu_type == NALU_TYPE_EOSTREAM) return eRet; zero_count = 0; while (pos < (nal_len + sizeofNalLengthField)) //similar to for in p-42 { if (zero_count == 2) { if (buffer[pos] == 0x03) { pos++; zero_count = 0; continue; } if (buffer[pos] <= 0x01) { if (start_code) { *rbsp_length -= 2; pos -= 2; break; } } zero_count = 0; } zero_count++; if (buffer[pos] != 0) zero_count = 0; rbsp_bistream[(*rbsp_length)++] = buffer[pos++]; } return eRet; } /*=========================================================================== FUNCTION: H264_Utils::iSNewFrame DESCRIPTION: Returns true if NAL parsing successfull otherwise false. INPUT/OUTPUT PARAMETERS: <In> buffer : buffer containing start code or nal length + NAL units buffer_length : the length of the NAL buffer start_code : If true, start code is detected, otherwise size nal length is detected size_of_nal_length_field: size of nal length field <out> isNewFrame: true if the NAL belongs to a differenet frame false if the NAL belongs to a current frame RETURN VALUE: boolean true, if nal parsing is successful false, if the nal parsing has errors SIDE EFFECTS: None. ===========================================================================*/ bool H264_Utils::isNewFrame(OMX_IN OMX_U8 * buffer, OMX_IN OMX_U32 buffer_length, OMX_IN OMX_U32 size_of_nal_length_field, OMX_OUT OMX_BOOL & isNewFrame, bool & isUpdateTimestamp) { NALU nal_unit; uint16 first_mb_in_slice = 0; uint32 numBytesInRBSP = 0; bool eRet = true; isUpdateTimestamp = false; QTV_MSG_PRIO3(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "get_h264_nal_type %p nal_length %d nal_length_field %d\n", buffer, buffer_length, size_of_nal_length_field); if (false == extract_rbsp(buffer, buffer_length, size_of_nal_length_field, m_rbspBytes, &numBytesInRBSP, &nal_unit)) { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "get_h264_nal_type - ERROR at extract_rbsp\n"); isNewFrame = OMX_FALSE; eRet = false; } else { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "Nalu type: %d",nal_unit.nalu_type); switch (nal_unit.nalu_type) { case NALU_TYPE_IDR: case NALU_TYPE_NON_IDR: { RbspParser rbsp_parser(m_rbspBytes, (m_rbspBytes + numBytesInRBSP)); first_mb_in_slice = rbsp_parser.ue(); if (m_forceToStichNextNAL) { isNewFrame = OMX_FALSE; if(!first_mb_in_slice){ isUpdateTimestamp = true; } } else { if ((!first_mb_in_slice) || /*(slice.prv_frame_num != slice.frame_num ) || */ ((m_prv_nalu.nal_ref_idc != nal_unit.nal_ref_idc) && (nal_unit.nal_ref_idc * m_prv_nalu.nal_ref_idc == 0)) || /*( ((m_prv_nalu.nalu_type == NALU_TYPE_IDR) && (nal_unit.nalu_type == NALU_TYPE_IDR)) && (slice.idr_pic_id != slice.prv_idr_pic_id) ) || */ ((m_prv_nalu.nalu_type != nal_unit.nalu_type) && ((m_prv_nalu.nalu_type == NALU_TYPE_IDR) || (nal_unit.nalu_type == NALU_TYPE_IDR)))) { isNewFrame = OMX_TRUE; } else { isNewFrame = OMX_FALSE; } } m_forceToStichNextNAL = false; break; } default: { isNewFrame = (m_forceToStichNextNAL ? OMX_FALSE : OMX_TRUE); m_forceToStichNextNAL = true; break; } } // end of switch } // end of if m_prv_nalu = nal_unit; QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "get_h264_nal_type - newFrame value %d\n", isNewFrame); return eRet; } /************************************************************************** ** This function parses an H.264 Annex B formatted bitstream, returning the ** next frame in the format required by MP4 (specified in ISO/IEC 14496-15, ** section 5.2.3, "AVC Sample Structure Definition"), and recovering any ** header (sequence and picture parameter set NALUs) information, formatting ** it as a header block suitable for writing to video format services. ** ** IN const uint8 *encodedBytes ** This points to the H.264 Annex B formatted video bitstream, starting ** with the next frame for which to locate frame boundaries. ** ** IN uint32 totalBytes ** This is the total number of bytes left in the H.264 video bitstream, ** from the given starting position. ** ** INOUT H264StreamInfo &streamInfo ** This structure contains state information about the stream as it has ** been so far parsed. ** ** OUT vector<uint8> &frame ** The properly MP4 formatted H.264 frame will be stored here. ** ** OUT uint32 &bytesConsumed ** This is set to the total number of bytes parsed from the bitstream. ** ** OUT uint32 &nalSize ** The true size of the NAL (without padding zeroes) ** ** OUT bool &keyFrame ** Indicator whether this is an I-frame ** ** IN bool stripSeiAud ** If set, any SEI or AU delimiter NALUs are stripped out. *************************************************************************/ bool H264_Utils::parseHeader(uint8 * encodedBytes, uint32 totalBytes, uint32 sizeOfNALLengthField, unsigned &height, unsigned &width, bool & bInterlace, unsigned &cropx, unsigned &cropy, unsigned &cropdx, unsigned &cropdy) { bool keyFrame = FALSE; bool stripSeiAud = FALSE; bool nalSize = FALSE; uint64 bytesConsumed = 0; uint8 frame[64]; struct H264ParamNalu temp = { 0 }; // Scan NALUs until a frame boundary is detected. If this is the first // frame, scan a second time to find the end of the frame. Otherwise, the // first boundary found is the end of the current frame. While scanning, // collect any sequence/parameter set NALUs for use in constructing the // stream header. bool inFrame = true; bool inNalu = false; bool vclNaluFound = false; uint8 naluType = 0; uint32 naluStart = 0, naluSize = 0; uint32 prevVclFrameNum = 0, vclFrameNum = 0; bool prevVclFieldPicFlag = false, vclFieldPicFlag = false; bool prevVclBottomFieldFlag = false, vclBottomFieldFlag = false; uint8 prevVclNalRefIdc = 0, vclNalRefIdc = 0; uint32 prevVclPicOrderCntLsb = 0, vclPicOrderCntLsb = 0; int32 prevVclDeltaPicOrderCntBottom = 0, vclDeltaPicOrderCntBottom = 0; int32 prevVclDeltaPicOrderCnt0 = 0, vclDeltaPicOrderCnt0 = 0; int32 prevVclDeltaPicOrderCnt1 = 0, vclDeltaPicOrderCnt1 = 0; uint8 vclNaluType = 0; uint32 vclPicOrderCntType = 0; uint64 pos; uint64 posNalDetected = 0xFFFFFFFF; uint32 cursor = 0xFFFFFFFF; unsigned int profile_id = 0, level_id = 0; H264ParamNalu *seq = NULL, *pic = NULL; // used to determin possible infinite loop condition int loopCnt = 0; for (pos = 0;; ++pos) { // return early, found possible infinite loop if (loopCnt > 100000) return 0; // Scan ahead next byte. cursor <<= 8; cursor |= static_cast < uint32 > (encodedBytes[pos]); if (sizeOfNALLengthField != 0) { inNalu = true; naluStart = sizeOfNALLengthField; } // If in NALU, scan forward until an end of NALU condition is // detected. if (inNalu) { if (sizeOfNALLengthField == 0) { // Detect end of NALU condition. if (((cursor & 0xFFFFFF) == 0x000000) || ((cursor & 0xFFFFFF) == 0x000001) || (pos >= totalBytes)) { inNalu = false; if (pos < totalBytes) { pos -= 3; } naluSize = static_cast < uint32 > ((static_cast < uint32 > (pos) - naluStart) + 1); QTV_MSG_PRIO3(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->1.nalusize=%x pos=%x naluStart=%x\n", naluSize, pos, naluStart); } else { ++loopCnt; continue; } } // Determine NALU type. naluType = (encodedBytes[naluStart] & 0x1F); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->2.naluType=%x....\n", naluType); if (naluType == 5) keyFrame = true; // For NALUs in the frame having a slice header, parse additional // fields. bool isVclNalu = false; if ((naluType == 1) || (naluType == 2) || (naluType == 5)) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->3.naluType=%x....\n", naluType); // Parse additional fields. RbspParser rbsp(&encodedBytes[naluStart + 1], &encodedBytes[naluStart + naluSize]); vclNaluType = naluType; vclNalRefIdc = ((encodedBytes[naluStart] >> 5) & 0x03); (void)rbsp.ue(); (void)rbsp.ue(); const uint32 picSetID = rbsp.ue(); pic = this->pic.find(picSetID); QTV_MSG_PRIO2(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->4.sizeof %x %x\n", this->pic.size(), this->seq.size()); if (!pic) { if (this->pic.empty()) { // Found VCL NALU before needed picture parameter set // -- assume that we started parsing mid-frame, and // discard the rest of the frame we're in. inFrame = false; //frame.clear (); QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->5.pic empty........\n"); } else { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->6.FAILURE to parse..break frm here"); break; } } if (pic) { QTV_MSG_PRIO2(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->7.sizeof %x %x\n", this->pic.size(), this->seq.size()); seq = this->seq.find(pic->seqSetID); if (!seq) { if (this->seq.empty()) { QTV_MSG_PRIO (QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->8.seq empty........\n"); // Found VCL NALU before needed sequence parameter // set -- assume that we started parsing // mid-frame, and discard the rest of the frame // we're in. inFrame = false; //frame.clear (); } else { QTV_MSG_PRIO (QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->9.FAILURE to parse...break"); break; } } } QTV_MSG_PRIO2(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->10.sizeof %x %x\n", this->pic.size(), this->seq.size()); if (pic && seq) { QTV_MSG_PRIO2(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->11.pic and seq[%x][%x]........\n", pic, seq); isVclNalu = true; vclFrameNum = rbsp.u(seq->log2MaxFrameNumMinus4 + 4); if (!seq->frameMbsOnlyFlag) { vclFieldPicFlag = (rbsp.u(1) == 1); if (vclFieldPicFlag) { vclBottomFieldFlag = (rbsp.u(1) == 1); } } else { vclFieldPicFlag = false; vclBottomFieldFlag = false; } if (vclNaluType == 5) { (void)rbsp.ue(); } vclPicOrderCntType = seq->picOrderCntType; if (seq->picOrderCntType == 0) { vclPicOrderCntLsb = rbsp.u (seq-> log2MaxPicOrderCntLsbMinus4 + 4); if (pic->picOrderPresentFlag && !vclFieldPicFlag) { vclDeltaPicOrderCntBottom = rbsp.se(); } else { vclDeltaPicOrderCntBottom = 0; } } else { vclPicOrderCntLsb = 0; vclDeltaPicOrderCntBottom = 0; } if ((seq->picOrderCntType == 1) && !seq-> deltaPicOrderAlwaysZeroFlag) { vclDeltaPicOrderCnt0 = rbsp.se(); if (pic->picOrderPresentFlag && !vclFieldPicFlag) { vclDeltaPicOrderCnt1 = rbsp.se(); } else { vclDeltaPicOrderCnt1 = 0; } } else { vclDeltaPicOrderCnt0 = 0; vclDeltaPicOrderCnt1 = 0; } } } ////////////////////////////////////////////////////////////////// // Perform frame boundary detection. ////////////////////////////////////////////////////////////////// // The end of the bitstream is always a boundary. bool boundary = (pos >= totalBytes); // The first of these NALU types always mark a boundary, but skip // any that occur before the first VCL NALU in a new frame. QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->12.naluType[%x].....\n", naluType); if ((((naluType >= 6) && (naluType <= 9)) || ((naluType >= 13) && (naluType <= 18))) && (vclNaluFound || !inFrame)) { boundary = true; } // If a VCL NALU is found, compare with the last VCL NALU to // determine if they belong to different frames. else if (vclNaluFound && isVclNalu) { // Clause 7.4.1.2.4 -- detect first VCL NALU through // parsing of portions of the NALU header and slice // header. /*lint -e{731} Boolean argument to equal/not equal * It's ok */ if ((prevVclFrameNum != vclFrameNum) || (prevVclFieldPicFlag != vclFieldPicFlag) || (prevVclBottomFieldFlag != vclBottomFieldFlag) || ((prevVclNalRefIdc != vclNalRefIdc) && ((prevVclNalRefIdc == 0) || (vclNalRefIdc == 0))) || ((vclPicOrderCntType == 0) && ((prevVclPicOrderCntLsb != vclPicOrderCntLsb) || (prevVclDeltaPicOrderCntBottom != vclDeltaPicOrderCntBottom))) || ((vclPicOrderCntType == 1) && ((prevVclDeltaPicOrderCnt0 != vclDeltaPicOrderCnt0) || (prevVclDeltaPicOrderCnt1 != vclDeltaPicOrderCnt1)))) { boundary = true; } } // If a frame boundary is reached and we were in the frame in // which at least one VCL NALU was found, we are done processing // this frame. Remember to back up to NALU start code to make // sure it is available for when the next frame is parsed. if (boundary && inFrame && vclNaluFound) { pos = static_cast < uint64 > (naluStart - 3); QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->13.Break \n"); break; } inFrame = (inFrame || boundary); // Process sequence and parameter set NALUs specially. if ((naluType == 7) || (naluType == 8)) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->14.naluType[%x].....\n", naluType); QTV_MSG_PRIO2(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->15.sizeof %x %x\n", this->pic.size(), this->seq.size()); H264ParamNaluSet & naluSet = ((naluType == 7) ? this->seq : this->pic); // Parse parameter set ID and other stream information. H264ParamNalu newParam; RbspParser rbsp(&encodedBytes[naluStart + 1], &encodedBytes[naluStart + naluSize]); uint32 id; if (naluType == 7) { unsigned int tmp; QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->16.naluType[%x].....\n", naluType); profile_id = rbsp.u(8); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->33.prfoile[%d].....\n", profile_id); tmp = rbsp.u(8); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->33.prfoilebytes[%x].....\n", tmp); level_id = rbsp.u(8); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->33.level[%d].....\n", level_id); id = newParam.seqSetID = rbsp.ue(); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->33.seqID[%d].....\n", id); if (profile_id == 100) { //Chroma_format_idc tmp = rbsp.ue(); if (tmp == 3) { //residual_colour_transform_flag (void)rbsp.u(1); } //bit_depth_luma_minus8 (void)rbsp.ue(); //bit_depth_chroma_minus8 (void)rbsp.ue(); //qpprime_y_zero_transform_bypass_flag (void)rbsp.u(1); // seq_scaling_matrix_present_flag tmp = rbsp.u(1); if (tmp) { unsigned int tmp1, t; //seq_scaling_list_present_flag for (t = 0; t < 6; t++) { tmp1 = rbsp.u(1); if (tmp1) { unsigned int last_scale = 8, next_scale = 8, delta_scale; for (int j = 0; j < 16; j++) { if (next_scale) { delta_scale = rbsp. se (); next_scale = (last_scale + delta_scale + 256) % 256; } last_scale = next_scale ? next_scale : last_scale; } } } for (t = 0; t < 2; t++) { tmp1 = rbsp.u(1); if (tmp1) { unsigned int last_scale = 8, next_scale = 8, delta_scale; for (int j = 0; j < 64; j++) { if (next_scale) { delta_scale = rbsp. se (); next_scale = (last_scale + delta_scale + 256) % 256; } last_scale = next_scale ? next_scale : last_scale; } } } } } newParam.log2MaxFrameNumMinus4 = rbsp.ue(); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->33.log2MaxFrameNumMinu[%d].....\n", newParam. log2MaxFrameNumMinus4); newParam.picOrderCntType = rbsp.ue(); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->33.picOrderCntType[%d].....\n", newParam.picOrderCntType); if (newParam.picOrderCntType == 0) { newParam. log2MaxPicOrderCntLsbMinus4 = rbsp.ue(); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->33.log2MaxPicOrderCntLsbMinus4 [%d].....\n", newParam. log2MaxPicOrderCntLsbMinus4); } else if (newParam.picOrderCntType == 1) { newParam. deltaPicOrderAlwaysZeroFlag = (rbsp.u(1) == 1); (void)rbsp.se(); (void)rbsp.se(); const uint32 numRefFramesInPicOrderCntCycle = rbsp.ue(); for (uint32 i = 0; i < numRefFramesInPicOrderCntCycle; ++i) { (void)rbsp.se(); } } tmp = rbsp.ue(); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->33.numrefFrames[%d].....\n", tmp); tmp = rbsp.u(1); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->33.gapsflag[%x].....\n", tmp); newParam.picWidthInMbsMinus1 = rbsp.ue(); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->33.picWidthInMbsMinus1[%d].....\n", newParam. picWidthInMbsMinus1); newParam.picHeightInMapUnitsMinus1 = rbsp.ue(); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->33.gapsflag[%d].....\n", newParam. picHeightInMapUnitsMinus1); newParam.frameMbsOnlyFlag = (rbsp.u(1) == 1); if (!newParam.frameMbsOnlyFlag) (void)rbsp.u(1); (void)rbsp.u(1); tmp = rbsp.u(1); newParam.crop_left = 0; newParam.crop_right = 0; newParam.crop_top = 0; newParam.crop_bot = 0; if (tmp) { newParam.crop_left = rbsp.ue(); newParam.crop_right = rbsp.ue(); newParam.crop_top = rbsp.ue(); newParam.crop_bot = rbsp.ue(); } QTV_MSG_PRIO4(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser--->34 crop left %d, right %d, top %d, bot %d\n", newParam.crop_left, newParam.crop_right, newParam.crop_top, newParam.crop_bot); } else { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->17.naluType[%x].....\n", naluType); id = newParam.picSetID = rbsp.ue(); newParam.seqSetID = rbsp.ue(); (void)rbsp.u(1); newParam.picOrderPresentFlag = (rbsp.u(1) == 1); } // We currently don't support updating existing parameter // sets. //const H264ParamNaluSet::const_iterator it = naluSet.find (id); H264ParamNalu *it = naluSet.find(id); if (it) { const uint32 tempSize = static_cast < uint32 > (it->nalu); // ??? if ((naluSize != tempSize) || (0 != memcmp(&encodedBytes[naluStart], &it->nalu, static_cast < int >(naluSize)))) { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->18.H264 stream contains two or \ more parameter set NALUs having the \ same ID -- this requires either a \ separate parameter set ES or \ multiple sample description atoms, \ neither of which is currently \ supported!"); break; } } // Otherwise, add NALU to appropriate NALU set. else { H264ParamNalu *newParamInSet = naluSet.find(id); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->19.newParamInset[%x]\n", newParamInSet); if (!newParamInSet) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->20.newParamInset[%x]\n", newParamInSet); newParamInSet = &temp; memcpy(newParamInSet, &newParam, sizeof(struct H264ParamNalu)); } QTV_MSG_PRIO4(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->21.encodebytes=%x naluStart=%x\n", encodedBytes, naluStart, naluSize, newParamInSet); QTV_MSG_PRIO2(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->22.naluSize=%x newparaminset=%p\n", naluSize, newParamInSet); QTV_MSG_PRIO4(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->23.-->0x%x 0x%x 0x%x 0x%x\n", (encodedBytes + naluStart), (encodedBytes + naluStart + 1), (encodedBytes + naluStart + 2), (encodedBytes + naluStart + 3)); memcpy(&newParamInSet->nalu, (encodedBytes + naluStart), sizeof(newParamInSet->nalu)); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->24.nalu=0x%x \n", newParamInSet->nalu); naluSet.insert(id, newParamInSet); } } // Otherwise, if we are inside the frame, convert the NALU // and append it to the frame output, if its type is acceptable. else if (inFrame && (naluType != 0) && (naluType < 12) && (!stripSeiAud || (naluType != 9) && (naluType != 6))) { uint8 sizeBuffer[4]; sizeBuffer[0] = static_cast < uint8 > (naluSize >> 24); sizeBuffer[1] = static_cast < uint8 > ((naluSize >> 16) & 0xFF); sizeBuffer[2] = static_cast < uint8 > ((naluSize >> 8) & 0xFF); sizeBuffer[3] = static_cast < uint8 > (naluSize & 0xFF); /*lint -e{1025, 1703, 119, 64, 534} * These are known lint issues */ //frame.insert (frame.end (), sizeBuffer, // sizeBuffer + sizeof (sizeBuffer)); /*lint -e{1025, 1703, 119, 64, 534, 632} * These are known lint issues */ //frame.insert (frame.end (), encodedBytes + naluStart, // encodedBytes + naluStart + naluSize); } // If NALU was a VCL, save VCL NALU parameters // for use in frame boundary detection. if (isVclNalu) { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->25.isvclnalu check passed\n"); vclNaluFound = true; prevVclFrameNum = vclFrameNum; prevVclFieldPicFlag = vclFieldPicFlag; prevVclNalRefIdc = vclNalRefIdc; prevVclBottomFieldFlag = vclBottomFieldFlag; prevVclPicOrderCntLsb = vclPicOrderCntLsb; prevVclDeltaPicOrderCntBottom = vclDeltaPicOrderCntBottom; prevVclDeltaPicOrderCnt0 = vclDeltaPicOrderCnt0; prevVclDeltaPicOrderCnt1 = vclDeltaPicOrderCnt1; } } // If not currently in a NALU, detect next NALU start code. if ((cursor & 0xFFFFFF) == 0x000001) { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->26..here\n"); inNalu = true; naluStart = static_cast < uint32 > (pos + 1); if (0xFFFFFFFF == posNalDetected) posNalDetected = pos - 2; } else if (pos >= totalBytes) { QTV_MSG_PRIO2(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->27.pos[%x] totalBytes[%x]\n", pos, totalBytes); break; } } uint64 tmpPos = 0; // find the first non-zero byte if (pos > 0) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->28.last loop[%x]\n", pos); tmpPos = pos - 1; while (tmpPos != 0 && encodedBytes[tmpPos] == 0) --tmpPos; // add 1 to get the beginning of the start code ++tmpPos; } QTV_MSG_PRIO3(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->29.tmppos=%ld bytesConsumed=%x %x\n", tmpPos, bytesConsumed, posNalDetected); bytesConsumed = tmpPos; nalSize = static_cast < uint32 > (bytesConsumed - posNalDetected); // Fill in the height and width QTV_MSG_PRIO2(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->30.seq[%x] pic[%x]\n", this->seq.size(), this->pic.size()); if (this->seq.size()) { m_height = (unsigned)(16 * (2 - (this->seq.begin()->frameMbsOnlyFlag)) * (this->seq.begin()->picHeightInMapUnitsMinus1 + 1)); m_width = (unsigned)(16 * (this->seq.begin()->picWidthInMbsMinus1 + 1)); if ((m_height % 16) != 0) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "\n Height %d is not a multiple of 16", m_height); m_height = (m_height / 16 + 1) * 16; QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "\n Height adjusted to %d \n", m_height); } if ((m_width % 16) != 0) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "\n Width %d is not a multiple of 16", m_width); m_width = (m_width / 16 + 1) * 16; QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "\n Width adjusted to %d \n", m_width); } height = m_height; width = m_width; bInterlace = (!this->seq.begin()->frameMbsOnlyFlag); cropx = this->seq.begin()->crop_left << 1; cropy = this->seq.begin()->crop_top << 1; cropdx = width - ((this->seq.begin()->crop_left + this->seq.begin()->crop_right) << 1); cropdy = height - ((this->seq.begin()->crop_top + this->seq.begin()->crop_bot) << 1); QTV_MSG_PRIO2(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->31.cropdy [%x] cropdx[%x]\n", cropdy, cropdx); QTV_MSG_PRIO2(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264Parser-->31.Height [%x] Width[%x]\n", height, width); } this->seq.eraseall(); this->pic.eraseall(); return validate_profile_and_level(profile_id, level_id);; } /* ====================================================================== FUNCTION H264_Utils::parse_first_h264_input_buffer DESCRIPTION parse first h264 input buffer PARAMETERS OMX_IN OMX_BUFFERHEADERTYPE* buffer. RETURN VALUE true if success false otherwise ========================================================================== */ OMX_U32 H264_Utils::parse_first_h264_input_buffer(OMX_IN OMX_BUFFERHEADERTYPE * buffer, OMX_U32 size_of_nal_length_field) { OMX_U32 c1, c2, c3, curr_ptr = 0; OMX_U32 i, j, aSize[4], size = 0; OMX_U32 header_len = 0; QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264 clip, NAL length field %d\n", size_of_nal_length_field); if (buffer == NULL) { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "Error - buffer is NULL\n"); } if (size_of_nal_length_field == 0) { /* Start code with a lot of 0x00 before 0x00 0x00 0x01 Need to move pBuffer to the first 0x00 0x00 0x00 0x01 */ c1 = 1; c2 = buffer->pBuffer[curr_ptr++]; c3 = buffer->pBuffer[curr_ptr++]; do { if (curr_ptr >= buffer->nFilledLen) { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "ERROR: parse_first_h264_input_buffer - Couldn't find the first 2 NAL (SPS and PPS)\n"); return 0; } c1 = c2; c2 = c3; c3 = buffer->pBuffer[curr_ptr++]; } while (c1 || c2 || c3 == 0); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "curr_ptr = %d\n", curr_ptr); if (curr_ptr > 4) { // There are unnecessary 0x00 QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "Remove unnecessary 0x00 at SPS\n"); memmove(buffer->pBuffer, &buffer->pBuffer[curr_ptr - 4], buffer->nFilledLen - curr_ptr - 4); } QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "dat clip, NAL length field %d\n", size_of_nal_length_field); QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "Start code SPS 0x00 00 00 01\n"); curr_ptr = 4; /* Start code 00 00 01 */ for (OMX_U8 i = 0; i < 2; i++) { c1 = 1; c2 = buffer->pBuffer[curr_ptr++]; c3 = buffer->pBuffer[curr_ptr++]; do { if (curr_ptr >= buffer->nFilledLen) { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "ERROR: parse_first_h264_input_buffer - Couldn't find the first 2 NAL (SPS and PPS)\n"); break; } c1 = c2; c2 = c3; c3 = buffer->pBuffer[curr_ptr++]; } while (c1 || c2 || c3 != 1); } header_len = curr_ptr - 4; } else { /* NAL length clip */ QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "NAL length clip, NAL length field %d\n", size_of_nal_length_field); /* SPS size */ for (i = 0; i < SIZE_NAL_FIELD_MAX - size_of_nal_length_field; i++) { aSize[SIZE_NAL_FIELD_MAX - 1 - i] = 0; } for (j = 0; i < SIZE_NAL_FIELD_MAX; i++, j++) { aSize[SIZE_NAL_FIELD_MAX - 1 - i] = buffer->pBuffer[j]; } size = (uint32) (*((uint32 *) (aSize))); header_len = size + size_of_nal_length_field; QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "OMX - SPS length %d\n", header_len); /* PPS size */ for (i = 0; i < SIZE_NAL_FIELD_MAX - size_of_nal_length_field; i++) { aSize[SIZE_NAL_FIELD_MAX - 1 - i] = 0; } for (j = header_len; i < SIZE_NAL_FIELD_MAX; i++, j++) { aSize[SIZE_NAL_FIELD_MAX - 1 - i] = buffer->pBuffer[j]; } size = (uint32) (*((uint32 *) (aSize))); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "OMX - PPS size %d\n", size); header_len += size + size_of_nal_length_field; } return header_len; } OMX_U32 H264_Utils::check_header(OMX_IN OMX_BUFFERHEADERTYPE * buffer, OMX_U32 sizeofNAL, bool & isPartial, OMX_U32 headerState) { byte coef1, coef2, coef3; uint32 pos = 0; uint32 nal_len = 0, nal_len2 = 0; uint32 sizeofNalLengthField = 0; uint32 zero_count; OMX_U32 eRet = -1; OMX_U8 *nal1_ptr = NULL, *nal2_ptr = NULL; isPartial = true; QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_LOW, "H264_Utils::check_header "); if (!sizeofNAL) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_HIGH, "check_header: start code %d", buffer->nFilledLen); // Search start_code_prefix_one_3bytes (0x000001) coef2 = buffer->pBuffer[pos++]; coef3 = buffer->pBuffer[pos++]; do { if (pos >= buffer->nFilledLen) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "Error at extract rbsp line %d", __LINE__); return eRet; } coef1 = coef2; coef2 = coef3; coef3 = buffer->pBuffer[pos++]; } while (coef1 || coef2 || coef3 != 1); QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_HIGH, "check_header: start code got fisrt NAL %d", pos); nal1_ptr = (OMX_U8 *) & buffer->pBuffer[pos]; // Search start_code_prefix_one_3bytes (0x000001) if (pos + 2 < buffer->nFilledLen) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_HIGH, "check_header: start code looking for second NAL %d", pos); isPartial = false; coef2 = buffer->pBuffer[pos++]; coef3 = buffer->pBuffer[pos++]; do { if (pos >= buffer->nFilledLen) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_HIGH, "Error at extract rbsp line %d", __LINE__); isPartial = true; break; } coef1 = coef2; coef2 = coef3; coef3 = buffer->pBuffer[pos++]; } while (coef1 || coef2 || coef3 != 1); } if (!isPartial) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "check_header: start code two nals in one buffer %d", pos); nal2_ptr = (OMX_U8 *) & buffer->pBuffer[pos]; if (((nal1_ptr[0] & 0x1f) == NALU_TYPE_SPS) && ((nal2_ptr[0] & 0x1f) == NALU_TYPE_PPS)) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "check_header: start code two nals in one buffer SPS+PPS %d", pos); eRet = 0; } else if (((nal1_ptr[0] & 0x1f) == NALU_TYPE_SPS) && (buffer->nFilledLen < 512)) { eRet = 0; } } else { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_HIGH, "check_header: start code partial nal in one buffer %d", pos); if (headerState == 0 && ((nal1_ptr[0] & 0x1f) == NALU_TYPE_SPS)) { eRet = 0; } else if (((nal1_ptr[0] & 0x1f) == NALU_TYPE_PPS)) { eRet = 0; } else eRet = -1; } } else { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "check_header: size nal %d", sizeofNAL); /* This is the case to play multiple NAL units inside each access unit */ /* Extract the NAL length depending on sizeOfNALength field */ sizeofNalLengthField = sizeofNAL; nal_len = 0; while (sizeofNAL--) { nal_len |= buffer->pBuffer[pos++] << (sizeofNAL << 3); } if (nal_len >= buffer->nFilledLen) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "Error at extract rbsp line %d", __LINE__); return eRet; } QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "check_header: size nal got fist NAL %d", nal_len); nal1_ptr = (OMX_U8 *) & buffer->pBuffer[pos]; if ((nal_len + sizeofNalLengthField) < buffer->nFilledLen) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "check_header: getting second NAL %d", buffer->nFilledLen); isPartial = false; pos += nal_len; QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "check_header: getting second NAL position %d", pos); sizeofNAL = sizeofNalLengthField; nal_len2 = 0; while (sizeofNAL--) { nal_len2 |= buffer->pBuffer[pos++] << (sizeofNAL << 3); } QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "check_header: getting second NAL %d", nal_len2); if (nal_len + nal_len2 + 2 * sizeofNalLengthField > buffer->nFilledLen) { QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "Error at extract rbsp line %d", __LINE__); return eRet; } QTV_MSG_PRIO1(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "check_header: size nal got second NAL %d", nal_len); nal2_ptr = (OMX_U8 *) & buffer->pBuffer[pos]; } if (!isPartial) { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "check_header: size nal partial nal "); if (((nal1_ptr[0] & 0x1f) == NALU_TYPE_SPS) && ((nal2_ptr[0] & 0x1f) == NALU_TYPE_PPS)) { eRet = 0; } } else { QTV_MSG_PRIO(QTVDIAG_GENERAL, QTVDIAG_PRIO_ERROR, "check_header: size nal full header"); if (headerState == 0 && ((nal1_ptr[0] & 0x1f) == NALU_TYPE_SPS)) { eRet = 0; } else if (((nal1_ptr[0] & 0x1f) == NALU_TYPE_PPS)) { eRet = 0; } else eRet = -1; } } return eRet; } /*=========================================================================== FUNCTION: validate_profile_and_level DESCRIPTION: This function validate the profile and level that is supported. INPUT/OUTPUT PARAMETERS: uint32 profile uint32 level RETURN VALUE: false it it's not supported true otherwise SIDE EFFECTS: None. ===========================================================================*/ bool H264_Utils::validate_profile_and_level(uint32 profile, uint32 level) { QTV_MSG_PRIO2(QTVDIAG_GENERAL, QTVDIAG_PRIO_MED, "H264 profile %d, level %d\n", profile, level); if ((m_default_profile_chk && profile != BASELINE_PROFILE && profile != MAIN_PROFILE && profile != HIGH_PROFILE) || (m_default_level_chk && level > MAX_SUPPORTED_LEVEL) ) { return false; } return true; }
57,177
18,960
/* * Interactive disassembler (IDA). * Copyright (c) 1990-2015 Hex-Rays * ALL RIGHTS RESERVED. * */ #ifndef _INTS_HPP #define _INTS_HPP #pragma pack(push, 1) // IDA uses 1 byte alignments! /*! \file ints.hpp \brief Functions that deal with the predefined comments */ class insn_t; class WorkReg; //-------------------------------------------------------------------- // P R E D E F I N E D C O M M E N T S //-------------------------------------------------------------------- /// Get predefined comment. /// \param cmd current instruction information /// \param buf buffer for the comment /// \param bufsize size of the output buffer /// \return size of comment or -1 idaman ssize_t ida_export get_predef_insn_cmt( const insn_t &cmd, char *buf, size_t bufsize); /// Get predefined comment. /// \param info text string with description of operand and register values. /// This string consists of equations: /// - reg=value ... /// where reg may be any word register name, /// or Op1,Op2 - for first or second operands /// \param wrktyp icode of instruction to get comment about /// \param buf buffer for the comment /// \param bufsize size of the output buffer /// \return size of comment or -1 idaman ssize_t ida_export get_predef_cmt( const char *info, int wrktyp, char *buf, size_t bufsize); /// Get predefined VxD function name. /// \param vxdnum number of VxD /// \param funcnum number of function in the VxD /// \param buf buffer for the comment /// \param bufsize size of the output buffer /// \return comment or NULL #ifdef _IDP_HPP inline char *idaapi get_vxd_func_name( int vxdnum, int funcnum, char *buf, size_t bufsize) { buf[0] = '\0'; ph.notify(ph.get_vxd_name, vxdnum, funcnum, buf, bufsize); return buf[0] ? buf : NULL; } #endif //-------------------------------------------------------------------- // Private definitions //------------------------------------------------------------------- #pragma pack(pop) #endif // _INTS_HPP
2,196
662
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * Modifications Copyright (c) 2018 LG Electronics, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "gflags/gflags.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/log.h" #include "ros/include/ros/ros.h" #include "std_msgs/String.h" #include "modules/canbus/common/canbus_gflags.h" #include "modules/common/util/file.h" #include "modules/control/proto/control_cmd.pb.h" int main(int32_t argc, char **argv) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); FLAGS_alsologtostderr = true; ros::init(argc, argv, "canbus_tester"); ros::NodeHandle nh; ros::Publisher pub = nh.advertise<std_msgs::String>(FLAGS_control_command_topic, 100); apollo::control::ControlCommand control_cmd; if (!apollo::common::util::GetProtoFromFile(FLAGS_canbus_test_file, &control_cmd)) { AERROR << "failed to load file: " << FLAGS_canbus_test_file; return -1; } std_msgs::String msg; control_cmd.SerializeToString(&msg.data); ros::Rate loop_rate(1); // frequency while (ros::ok()) { pub.publish(msg); ros::spinOnce(); // yield loop_rate.sleep(); } return 0; }
1,978
647
#include <iostream> #include <viface/viface.hpp> #include <viface/utils.hpp> using namespace std; class MyDispatcher { private: int count = 0; public: bool handler(string const& name, uint id, vector<uint8_t>& packet) { cout << "+++ Received packet " << dec << count; cout << " from interface " << name; cout << " (" << id << ") of size " << packet.size(); cout << " and CRC of 0x" << hex << viface::utils::crc32(packet); cout << endl; cout << viface::utils::hexdump(packet) << endl; this->count++; return true; } }; /** * This example shows how to setup a dispatcher for a set of virtual interfaces. * This uses a class method for the callback in order to show this kind of * usage, but any function using the same signature as dispatcher_cb type * can be used. * * To help with the example you can send a few packets to the created virtual * interfaces using scapy, wireshark, libtins or any other. */ int main(int argc, const char* argv[]) { cout << "Starting dispatch example ..." << endl; try { viface::VIface iface1("viface%d"); iface1.up(); cout << "Interface " << iface1.getName() << " up!" << endl; viface::VIface iface2("viface%d"); iface2.up(); cout << "Interface " << iface2.getName() << " up!" << endl; // Call dispatch set<viface::VIface*> myifaces = {&iface1, &iface2}; MyDispatcher printer; viface::dispatcher_cb mycb = bind( &MyDispatcher::handler, &printer, placeholders::_1, placeholders::_2, placeholders::_3 ); cout << "Calling dispath ..." << endl; viface::dispatch(myifaces, mycb); } catch(exception const & ex) { cerr << ex.what() << endl; return -1; } return 0; }
1,940
603
// Config Scroller class // Copyright (C) 1996 Michael D. Lore All Rights Reserved #include <stdio.h> #include <io.h> #include "cfgscr.h" #include "registry.h" #include "console/colors.h" #include "cfgdlg.h" #include "console/inputdlg.h" #include "ptr.h" #define COMMAND_SIZE 1024 ConfigScroller::ConfigScroller (Screen& screen, int x, int y, int w, int h) : Scroller (screen, x, y, w, h, 0), mExitKey (KB_ESC), mDialog (0), mDllHist ("RegSvr History"), mRegHist ("Cmd Export History") { setScrollable (&mScrollCfg); } ConfigScroller::~ConfigScroller () { } int ConfigScroller::processEvent (const Event& event) { int key; int table; switch (event.key) { case KB_ESC: mExitKey = KB_ESC; postEvent (Event (EV_QUIT)); break; case KB_ENTER: // Launch command edit window myScreen.sendEvent (Event(EV_STATUS_MSG, (DWORD) "")); key = mScrollCfg.getCursor (); switch (key) { case 0: // "Select Color Scheme" table = getColorTable (); selectColorTable (++table); myScreen.sendEvent (Event (EV_COLOR_CHANGE)); if (mDialog != NULL) mDialog->draw (); draw (); break; case 1: // "Export Custom Commands" exportReg (); break; case 2: // "Import Custom Commands" importReg (); break; case 3: // "Register DLL Server" registerServer (); break; case 4: // "Unregister DLL Server" unregisterServer (); break; default: break; } // drawLine (mCursor); break; default: return Scroller::processEvent (event); } return 1; } void ConfigScroller::exportReg () { int exitCode = KB_ESC; char path[512]; *path = 0; { InputDialog dlg (myScreen, "Export Custom Commands", "Enter the pathname:", path, 511, &mRegHist); dlg.run (); exitCode = dlg.getExitCode (); } if (exitCode != KB_ESC) { if (_access (path, 0) == 0) if (myScreen.ask ("Confirm File Replace", "Overwrite the existing file?") == 0) return; FILE *file = fopen (path, "w"); if (file == NULL) { myScreen.sendEvent (Event(EV_STATUS_MSG, (DWORD) "Could not create file.")); return; } for (int i = 0; i < 2; i++) { int st, fn; if (i == 0) { st = 'A'; fn = 'Z'; } else if (i == 1) { st = '0'; fn = '9'; } for (char c = st; c <= fn; c++) { try { // Open registry key RegistryKey k (HKEY_CURRENT_USER, HKCU_SUBKEY_HERMIT "\\Commands", KEY_READ); char valname[2]; valname[0] = c; valname[1] = '\0'; // try to read the current value char *value = 0; DWORD type; try { value = k.queryValue (valname, type); if (type == REG_SZ && value != 0 && value[0] != '\0') { fprintf (file, "%c,%s\n", c, value); } delete [] value; } catch (const std::exception&) { } } catch (const std::exception&) { } } } fclose (file); myScreen.sendEvent (Event(EV_STATUS_MSG, (DWORD) "Commands exported.")); } } void ConfigScroller::importReg () { int exitCode = KB_ESC; char path[512]; *path = 0; { InputDialog dlg (myScreen, "Import Custom Commands", "Enter the pathname:", path, 511, &mRegHist); dlg.run (); exitCode = dlg.getExitCode (); } if (exitCode != KB_ESC) { myScreen.sendEvent (Event(EV_STATUS_MSG, (DWORD) importCommands (path))); } } const char *ConfigScroller::importCommands (const char *path) { FILE *file = fopen (path, "r"); if (file == NULL) return "Could not open file"; ArrayPtr<char> str = new char [COMMAND_SIZE + 3]; if (str == 0) throw AppException (WHERE, ERR_OUT_OF_MEMORY); char *status = 0; while (fgets (str, COMMAND_SIZE + 3, file) != NULL) { // Remove trailing whitespace int n = (int) strlen (str); while (n > 0 && (str[n - 1] == '\n' || str[n - 1] == '\t' || str[n - 1] == ' ')) { str[n - 1] = '\0'; n--; } // If string is empty, just ignore it if (str[0] == '\0') continue; // Uppercase the first letter str[0] = toupper (str[0]); // Make sure the command format is [A-Z,0-9], if ((!(str[0] >= 'A' && str[0] <= 'Z') && !(str[0] >= '0' && str[0] <= '9')) || str[1] != ',') { status = "A read error occurred."; break; } // Create the value name string char valname[2]; valname[0] = str[0]; valname[1] = '\0'; // Save to registry try { // Open registry key RegistryKey k (HKEY_CURRENT_USER, HKCU_SUBKEY_HERMIT "\\Commands", KEY_READ | KEY_WRITE); k.setValue (valname, &str[2]); } catch (const std::exception&) { status = "Error saving key to registry"; break; } } if (ferror (file) != 0) status = "A read error occurred."; if (status == 0) { // Set initialized state (actually no reason...we use Commands key) #if 0 try { RegistryKey k (HKEY_CURRENT_USER, HKCU_SUBKEY_HERMIT "\\Initialized", KEY_READ | KEY_WRITE); } catch (const std::exception&) { } #endif // Set message status = "Commands imported."; } fclose (file); return status; } void ConfigScroller::registerServer () { int exitCode = KB_ESC; char dllpath[512]; *dllpath = 0; { InputDialog dlg (myScreen, "Register DLL Server", "Enter the DLL pathname:", dllpath, 511, &mDllHist); dlg.run (); exitCode = dlg.getExitCode (); } if (exitCode != KB_ESC) { HINSTANCE hInst = LoadLibrary (dllpath); if (hInst == NULL) { myScreen.sendWinErrStatusMsg ("Cannot load DLL"); return; } FARPROC dllEntryPoint; dllEntryPoint = GetProcAddress (hInst, "DllRegisterServer"); if (dllEntryPoint == NULL) { myScreen.sendWinErrStatusMsg ("Cannot load DllRegisterServer"); FreeLibrary (hInst); return; } if (FAILED ((*dllEntryPoint) ())) myScreen.sendEvent (Event(EV_STATUS_MSG, (DWORD) "The registration function failed.")); else myScreen.sendEvent (Event(EV_STATUS_MSG, (DWORD) "Server registered!")); FreeLibrary (hInst); } } void ConfigScroller::unregisterServer () { int exitCode = KB_ESC; char dllpath[512]; *dllpath = 0; { InputDialog dlg (myScreen, "Unregister DLL Server", "Enter the DLL pathname:", dllpath, 511, &mDllHist); dlg.run (); exitCode = dlg.getExitCode (); } if (exitCode != KB_ESC) { HINSTANCE hInst = LoadLibrary (dllpath); if (hInst == NULL) { myScreen.sendWinErrStatusMsg ("Cannot load DLL"); return; } FARPROC dllEntryPoint; dllEntryPoint = GetProcAddress (hInst, "DllUnregisterServer"); if (dllEntryPoint == NULL) { myScreen.sendWinErrStatusMsg ("Cannot load DllUnregisterServer"); FreeLibrary (hInst); return; } if (FAILED ((*dllEntryPoint) ())) myScreen.sendEvent (Event(EV_STATUS_MSG, (DWORD) "The unregistration function failed.")); else myScreen.sendEvent (Event(EV_STATUS_MSG, (DWORD) "Server unregistered!")); FreeLibrary (hInst); } } // End
7,218
2,878
/*** * Copyright 2019 The Katla Authors * * 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 "uv-signal-handler.h" #include "uv-event-loop.h" #include "katla/core/core-errors.h" #include <signal.h> namespace katla { UvSignalHandler::UvSignalHandler(UvEventLoop& eventLoop) : m_eventLoop(eventLoop) { } UvSignalHandler::~UvSignalHandler() { assert(!m_handle); // should be destroyed before destruction because it needs event-loop } outcome::result<void, Error> UvSignalHandler::init() { if (m_handle) { return Error(katla::make_error_code(katla::CoreErrorCode::AlreadyInitialized)); } m_handle = new uv_signal_t(); m_handle->data = this; auto uvEventLoop = m_eventLoop.handle(); auto result = uv_signal_init(uvEventLoop, m_handle); if (result != 0) { return Error(katla::make_error_code(katla::CoreErrorCode::InitFailed), uv_strerror(result), uv_err_name(result)); } return outcome::success(); } outcome::result<void, Error> UvSignalHandler::close() { if (!m_handle) { return outcome::success(); } if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(m_handle))) { uv_close(reinterpret_cast<uv_handle_t*>(m_handle), uv_close_callback); } return outcome::success(); } outcome::result<void, Error> UvSignalHandler::start(Signal signal, std::function<void()> function) { if (!m_handle) { return Error(katla::make_error_code(katla::CoreErrorCode::NotInitialized)); } m_function = function; if (signal == Signal::Unknown) { return Error(katla::make_error_code(katla::CoreErrorCode::InvalidSignal)); } int uvSignal = -1; switch (signal) { case Signal::Unknown: assert(false); case Signal::Interrupt: uvSignal = SIGINT; break; case Signal::Hangup: uvSignal = SIGHUP; break; case Signal::Kill: uvSignal = SIGKILL; break; case Signal::Stop: uvSignal = SIGSTOP; break; case Signal::Terminate: uvSignal = SIGTERM; break; } auto result = uv_signal_start(m_handle, &uv_signal_handler_callback, uvSignal); if (result != 0) { return Error(katla::make_error_code(katla::CoreErrorCode::OperationFailed), uv_strerror(result), uv_err_name(result)); } return outcome::success(); } outcome::result<void, Error> UvSignalHandler::stop() { if (!m_handle) { return outcome::success(); } if (uv_is_active(reinterpret_cast<uv_handle_t*>(m_handle))) { auto result = uv_signal_stop(m_handle); if (result != 0) { return Error(katla::make_error_code(katla::CoreErrorCode::OperationFailed), uv_strerror(result), uv_err_name(result)); } } return outcome::success(); } void UvSignalHandler::callback(int signum) { if (m_function) { m_function(); } } void UvSignalHandler::uv_signal_handler_callback(uv_signal_t* handle, int signum) { if (handle->data) { static_cast<UvSignalHandler*>(handle->data)->callback(signum); } } void UvSignalHandler::uv_close_callback(uv_handle_t* handle) { assert(handle); assert(handle->data); // event-loop should close handle before destruction if (handle->data) { static_cast<UvSignalHandler*>(handle->data)->deleteHandle(); } } void UvSignalHandler::deleteHandle() { if (m_handle) { delete m_handle; m_handle = nullptr; } } }
3,901
1,358
#include <iostream> int main(){ long n, k; std::cin >> n >> k; std::string s; std::cin >> s; if(k == 0){std::cout << s << std::endl;} else if(s.size() == 1){std::cout << "0" << std::endl;} else{ if(s[0] != '1'){s[0] = '1'; --k;} for(long p = 1; p < s.size() && k > 0; p++){ if(s[p] == '0'){continue;} s[p] = '0'; --k; } std::cout << s << std::endl; } return 0; }
456
195
#include <hxcpp.h> #ifndef INCLUDED_DefaultAssetLibrary #include <DefaultAssetLibrary.h> #endif #ifndef INCLUDED_IMap #include <IMap.h> #endif #ifndef INCLUDED_Type #include <Type.h> #endif #ifndef INCLUDED_flash_display_BitmapData #include <flash/display/BitmapData.h> #endif #ifndef INCLUDED_flash_display_DisplayObject #include <flash/display/DisplayObject.h> #endif #ifndef INCLUDED_flash_display_DisplayObjectContainer #include <flash/display/DisplayObjectContainer.h> #endif #ifndef INCLUDED_flash_display_IBitmapDrawable #include <flash/display/IBitmapDrawable.h> #endif #ifndef INCLUDED_flash_display_InteractiveObject #include <flash/display/InteractiveObject.h> #endif #ifndef INCLUDED_flash_display_MovieClip #include <flash/display/MovieClip.h> #endif #ifndef INCLUDED_flash_display_Sprite #include <flash/display/Sprite.h> #endif #ifndef INCLUDED_flash_events_EventDispatcher #include <flash/events/EventDispatcher.h> #endif #ifndef INCLUDED_flash_events_IEventDispatcher #include <flash/events/IEventDispatcher.h> #endif #ifndef INCLUDED_flash_media_Sound #include <flash/media/Sound.h> #endif #ifndef INCLUDED_flash_text_Font #include <flash/text/Font.h> #endif #ifndef INCLUDED_flash_utils_ByteArray #include <flash/utils/ByteArray.h> #endif #ifndef INCLUDED_flash_utils_IDataInput #include <flash/utils/IDataInput.h> #endif #ifndef INCLUDED_flash_utils_IDataOutput #include <flash/utils/IDataOutput.h> #endif #ifndef INCLUDED_haxe_Log #include <haxe/Log.h> #endif #ifndef INCLUDED_haxe_Unserializer #include <haxe/Unserializer.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_openfl_AssetCache #include <openfl/AssetCache.h> #endif #ifndef INCLUDED_openfl_AssetLibrary #include <openfl/AssetLibrary.h> #endif #ifndef INCLUDED_openfl_AssetType #include <openfl/AssetType.h> #endif #ifndef INCLUDED_openfl_Assets #include <openfl/Assets.h> #endif #ifndef INCLUDED_openfl_utils_IMemoryRange #include <openfl/utils/IMemoryRange.h> #endif namespace openfl{ Void Assets_obj::__construct() { return null(); } Assets_obj::~Assets_obj() { } Dynamic Assets_obj::__CreateEmpty() { return new Assets_obj; } hx::ObjectPtr< Assets_obj > Assets_obj::__new() { hx::ObjectPtr< Assets_obj > result = new Assets_obj(); result->__construct(); return result;} Dynamic Assets_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Assets_obj > result = new Assets_obj(); result->__construct(); return result;} ::openfl::AssetCache Assets_obj::cache; ::haxe::ds::StringMap Assets_obj::libraries; bool Assets_obj::initialized; bool Assets_obj::exists( ::String id,::openfl::AssetType type){ HX_STACK_PUSH("Assets::exists","openfl/Assets.hx",40); HX_STACK_ARG(id,"id"); HX_STACK_ARG(type,"type"); HX_STACK_LINE(42) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(46) if (((type == null()))){ HX_STACK_LINE(46) type = ::openfl::AssetType_obj::BINARY; } HX_STACK_LINE(52) ::String libraryName = id.substring((int)0,id.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(53) ::String symbolName = id.substr((id.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(54) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(56) if (((library != null()))){ HX_STACK_LINE(56) return library->exists(symbolName,type); } HX_STACK_LINE(64) return false; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,exists,return ) ::flash::display::BitmapData Assets_obj::getBitmapData( ::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACK_PUSH("Assets::getBitmapData","openfl/Assets.hx",76); HX_STACK_ARG(id,"id"); HX_STACK_ARG(useCache,"useCache"); { HX_STACK_LINE(78) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(82) if (((bool((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled))) && bool(::openfl::Assets_obj::cache->bitmapData->exists(id))))){ HX_STACK_LINE(84) ::flash::display::BitmapData bitmapData = ::openfl::Assets_obj::cache->bitmapData->get(id); HX_STACK_VAR(bitmapData,"bitmapData"); HX_STACK_LINE(86) if ((::openfl::Assets_obj::isValidBitmapData(bitmapData))){ HX_STACK_LINE(86) return bitmapData; } } HX_STACK_LINE(94) ::String libraryName = id.substring((int)0,id.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(95) ::String symbolName = id.substr((id.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(96) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(98) if (((library != null()))){ HX_STACK_LINE(98) if ((library->exists(symbolName,::openfl::AssetType_obj::IMAGE))){ HX_STACK_LINE(100) if ((library->isLocal(symbolName,::openfl::AssetType_obj::IMAGE))){ HX_STACK_LINE(104) ::flash::display::BitmapData bitmapData = library->getBitmapData(symbolName); HX_STACK_VAR(bitmapData,"bitmapData"); HX_STACK_LINE(106) if (((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled)))){ HX_STACK_LINE(106) ::openfl::Assets_obj::cache->bitmapData->set(id,bitmapData); } HX_STACK_LINE(112) return bitmapData; } else{ HX_STACK_LINE(114) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] BitmapData asset \"") + id) + HX_CSTRING("\" exists, but only asynchronously")),hx::SourceInfo(HX_CSTRING("Assets.hx"),116,HX_CSTRING("openfl.Assets"),HX_CSTRING("getBitmapData"))); } } else{ HX_STACK_LINE(120) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no BitmapData asset with an ID of \"") + id) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),122,HX_CSTRING("openfl.Assets"),HX_CSTRING("getBitmapData"))); } } else{ HX_STACK_LINE(126) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),128,HX_CSTRING("openfl.Assets"),HX_CSTRING("getBitmapData"))); } HX_STACK_LINE(134) return null(); } } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,getBitmapData,return ) ::flash::utils::ByteArray Assets_obj::getBytes( ::String id){ HX_STACK_PUSH("Assets::getBytes","openfl/Assets.hx",145); HX_STACK_ARG(id,"id"); HX_STACK_LINE(147) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(151) ::String libraryName = id.substring((int)0,id.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(152) ::String symbolName = id.substr((id.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(153) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(155) if (((library != null()))){ HX_STACK_LINE(155) if ((library->exists(symbolName,::openfl::AssetType_obj::BINARY))){ HX_STACK_LINE(157) if ((library->isLocal(symbolName,::openfl::AssetType_obj::BINARY))){ HX_STACK_LINE(159) return library->getBytes(symbolName); } else{ HX_STACK_LINE(163) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] String or ByteArray asset \"") + id) + HX_CSTRING("\" exists, but only asynchronously")),hx::SourceInfo(HX_CSTRING("Assets.hx"),165,HX_CSTRING("openfl.Assets"),HX_CSTRING("getBytes"))); } } else{ HX_STACK_LINE(169) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no String or ByteArray asset with an ID of \"") + id) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),171,HX_CSTRING("openfl.Assets"),HX_CSTRING("getBytes"))); } } else{ HX_STACK_LINE(175) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),177,HX_CSTRING("openfl.Assets"),HX_CSTRING("getBytes"))); } HX_STACK_LINE(183) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getBytes,return ) ::flash::text::Font Assets_obj::getFont( ::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACK_PUSH("Assets::getFont","openfl/Assets.hx",194); HX_STACK_ARG(id,"id"); HX_STACK_ARG(useCache,"useCache"); { HX_STACK_LINE(196) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(200) if (((bool((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled))) && bool(::openfl::Assets_obj::cache->font->exists(id))))){ HX_STACK_LINE(200) return ::openfl::Assets_obj::cache->font->get(id); } HX_STACK_LINE(206) ::String libraryName = id.substring((int)0,id.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(207) ::String symbolName = id.substr((id.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(208) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(210) if (((library != null()))){ HX_STACK_LINE(210) if ((library->exists(symbolName,::openfl::AssetType_obj::FONT))){ HX_STACK_LINE(212) if ((library->isLocal(symbolName,::openfl::AssetType_obj::FONT))){ HX_STACK_LINE(216) ::flash::text::Font font = library->getFont(symbolName); HX_STACK_VAR(font,"font"); HX_STACK_LINE(218) if (((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled)))){ HX_STACK_LINE(218) ::openfl::Assets_obj::cache->font->set(id,font); } HX_STACK_LINE(224) return font; } else{ HX_STACK_LINE(226) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] Font asset \"") + id) + HX_CSTRING("\" exists, but only asynchronously")),hx::SourceInfo(HX_CSTRING("Assets.hx"),228,HX_CSTRING("openfl.Assets"),HX_CSTRING("getFont"))); } } else{ HX_STACK_LINE(232) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no Font asset with an ID of \"") + id) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),234,HX_CSTRING("openfl.Assets"),HX_CSTRING("getFont"))); } } else{ HX_STACK_LINE(238) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),240,HX_CSTRING("openfl.Assets"),HX_CSTRING("getFont"))); } HX_STACK_LINE(246) return null(); } } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,getFont,return ) ::openfl::AssetLibrary Assets_obj::getLibrary( ::String name){ HX_STACK_PUSH("Assets::getLibrary","openfl/Assets.hx",251); HX_STACK_ARG(name,"name"); HX_STACK_LINE(253) if (((bool((name == null())) || bool((name == HX_CSTRING("")))))){ HX_STACK_LINE(253) name = HX_CSTRING("default"); } HX_STACK_LINE(259) return ::openfl::Assets_obj::libraries->get(name); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getLibrary,return ) ::flash::display::MovieClip Assets_obj::getMovieClip( ::String id){ HX_STACK_PUSH("Assets::getMovieClip","openfl/Assets.hx",270); HX_STACK_ARG(id,"id"); HX_STACK_LINE(272) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(276) ::String libraryName = id.substring((int)0,id.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(277) ::String symbolName = id.substr((id.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(278) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(280) if (((library != null()))){ HX_STACK_LINE(280) if ((library->exists(symbolName,::openfl::AssetType_obj::MOVIE_CLIP))){ HX_STACK_LINE(282) if ((library->isLocal(symbolName,::openfl::AssetType_obj::MOVIE_CLIP))){ HX_STACK_LINE(284) return library->getMovieClip(symbolName); } else{ HX_STACK_LINE(288) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] MovieClip asset \"") + id) + HX_CSTRING("\" exists, but only asynchronously")),hx::SourceInfo(HX_CSTRING("Assets.hx"),290,HX_CSTRING("openfl.Assets"),HX_CSTRING("getMovieClip"))); } } else{ HX_STACK_LINE(294) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no MovieClip asset with an ID of \"") + id) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),296,HX_CSTRING("openfl.Assets"),HX_CSTRING("getMovieClip"))); } } else{ HX_STACK_LINE(300) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),302,HX_CSTRING("openfl.Assets"),HX_CSTRING("getMovieClip"))); } HX_STACK_LINE(308) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getMovieClip,return ) ::flash::media::Sound Assets_obj::getMusic( ::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACK_PUSH("Assets::getMusic","openfl/Assets.hx",319); HX_STACK_ARG(id,"id"); HX_STACK_ARG(useCache,"useCache"); { HX_STACK_LINE(321) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(325) if (((bool((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled))) && bool(::openfl::Assets_obj::cache->sound->exists(id))))){ HX_STACK_LINE(327) ::flash::media::Sound sound = ::openfl::Assets_obj::cache->sound->get(id); HX_STACK_VAR(sound,"sound"); HX_STACK_LINE(329) if ((::openfl::Assets_obj::isValidSound(sound))){ HX_STACK_LINE(329) return sound; } } HX_STACK_LINE(337) ::String libraryName = id.substring((int)0,id.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(338) ::String symbolName = id.substr((id.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(339) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(341) if (((library != null()))){ HX_STACK_LINE(341) if ((library->exists(symbolName,::openfl::AssetType_obj::MUSIC))){ HX_STACK_LINE(343) if ((library->isLocal(symbolName,::openfl::AssetType_obj::MUSIC))){ HX_STACK_LINE(347) ::flash::media::Sound sound = library->getMusic(symbolName); HX_STACK_VAR(sound,"sound"); HX_STACK_LINE(349) if (((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled)))){ HX_STACK_LINE(349) ::openfl::Assets_obj::cache->sound->set(id,sound); } HX_STACK_LINE(355) return sound; } else{ HX_STACK_LINE(357) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] Sound asset \"") + id) + HX_CSTRING("\" exists, but only asynchronously")),hx::SourceInfo(HX_CSTRING("Assets.hx"),359,HX_CSTRING("openfl.Assets"),HX_CSTRING("getMusic"))); } } else{ HX_STACK_LINE(363) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no Sound asset with an ID of \"") + id) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),365,HX_CSTRING("openfl.Assets"),HX_CSTRING("getMusic"))); } } else{ HX_STACK_LINE(369) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),371,HX_CSTRING("openfl.Assets"),HX_CSTRING("getMusic"))); } HX_STACK_LINE(377) return null(); } } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,getMusic,return ) ::String Assets_obj::getPath( ::String id){ HX_STACK_PUSH("Assets::getPath","openfl/Assets.hx",388); HX_STACK_ARG(id,"id"); HX_STACK_LINE(390) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(394) ::String libraryName = id.substring((int)0,id.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(395) ::String symbolName = id.substr((id.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(396) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(398) if (((library != null()))){ HX_STACK_LINE(398) if ((library->exists(symbolName,null()))){ HX_STACK_LINE(400) return library->getPath(symbolName); } else{ HX_STACK_LINE(404) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset with an ID of \"") + id) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),406,HX_CSTRING("openfl.Assets"),HX_CSTRING("getPath"))); } } else{ HX_STACK_LINE(410) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),412,HX_CSTRING("openfl.Assets"),HX_CSTRING("getPath"))); } HX_STACK_LINE(418) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getPath,return ) ::flash::media::Sound Assets_obj::getSound( ::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACK_PUSH("Assets::getSound","openfl/Assets.hx",429); HX_STACK_ARG(id,"id"); HX_STACK_ARG(useCache,"useCache"); { HX_STACK_LINE(431) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(435) if (((bool((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled))) && bool(::openfl::Assets_obj::cache->sound->exists(id))))){ HX_STACK_LINE(437) ::flash::media::Sound sound = ::openfl::Assets_obj::cache->sound->get(id); HX_STACK_VAR(sound,"sound"); HX_STACK_LINE(439) if ((::openfl::Assets_obj::isValidSound(sound))){ HX_STACK_LINE(439) return sound; } } HX_STACK_LINE(447) ::String libraryName = id.substring((int)0,id.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(448) ::String symbolName = id.substr((id.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(449) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(451) if (((library != null()))){ HX_STACK_LINE(451) if ((library->exists(symbolName,::openfl::AssetType_obj::SOUND))){ HX_STACK_LINE(453) if ((library->isLocal(symbolName,::openfl::AssetType_obj::SOUND))){ HX_STACK_LINE(457) ::flash::media::Sound sound = library->getSound(symbolName); HX_STACK_VAR(sound,"sound"); HX_STACK_LINE(459) if (((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled)))){ HX_STACK_LINE(459) ::openfl::Assets_obj::cache->sound->set(id,sound); } HX_STACK_LINE(465) return sound; } else{ HX_STACK_LINE(467) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] Sound asset \"") + id) + HX_CSTRING("\" exists, but only asynchronously")),hx::SourceInfo(HX_CSTRING("Assets.hx"),469,HX_CSTRING("openfl.Assets"),HX_CSTRING("getSound"))); } } else{ HX_STACK_LINE(473) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no Sound asset with an ID of \"") + id) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),475,HX_CSTRING("openfl.Assets"),HX_CSTRING("getSound"))); } } else{ HX_STACK_LINE(479) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),481,HX_CSTRING("openfl.Assets"),HX_CSTRING("getSound"))); } HX_STACK_LINE(487) return null(); } } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,getSound,return ) ::String Assets_obj::getText( ::String id){ HX_STACK_PUSH("Assets::getText","openfl/Assets.hx",498); HX_STACK_ARG(id,"id"); HX_STACK_LINE(500) ::flash::utils::ByteArray bytes = ::openfl::Assets_obj::getBytes(id); HX_STACK_VAR(bytes,"bytes"); HX_STACK_LINE(502) if (((bytes == null()))){ HX_STACK_LINE(502) return null(); } else{ HX_STACK_LINE(506) return bytes->readUTFBytes(bytes->length); } HX_STACK_LINE(502) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getText,return ) Void Assets_obj::initialize( ){ { HX_STACK_PUSH("Assets::initialize","openfl/Assets.hx",515); HX_STACK_LINE(515) if ((!(::openfl::Assets_obj::initialized))){ HX_STACK_LINE(521) ::openfl::Assets_obj::registerLibrary(HX_CSTRING("default"),::DefaultAssetLibrary_obj::__new()); HX_STACK_LINE(525) ::openfl::Assets_obj::initialized = true; } } return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC0(Assets_obj,initialize,(void)) bool Assets_obj::isLocal( ::String id,::openfl::AssetType type,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACK_PUSH("Assets::isLocal","openfl/Assets.hx",532); HX_STACK_ARG(id,"id"); HX_STACK_ARG(type,"type"); HX_STACK_ARG(useCache,"useCache"); { HX_STACK_LINE(534) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(538) if (((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled)))){ HX_STACK_LINE(540) if (((bool((type == ::openfl::AssetType_obj::IMAGE)) || bool((type == null()))))){ HX_STACK_LINE(540) if ((::openfl::Assets_obj::cache->bitmapData->exists(id))){ HX_STACK_LINE(542) return true; } } HX_STACK_LINE(546) if (((bool((type == ::openfl::AssetType_obj::FONT)) || bool((type == null()))))){ HX_STACK_LINE(546) if ((::openfl::Assets_obj::cache->font->exists(id))){ HX_STACK_LINE(548) return true; } } HX_STACK_LINE(552) if (((bool((bool((type == ::openfl::AssetType_obj::SOUND)) || bool((type == ::openfl::AssetType_obj::MUSIC)))) || bool((type == null()))))){ HX_STACK_LINE(552) if ((::openfl::Assets_obj::cache->sound->exists(id))){ HX_STACK_LINE(554) return true; } } } HX_STACK_LINE(560) ::String libraryName = id.substring((int)0,id.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(561) ::String symbolName = id.substr((id.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(562) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(564) if (((library != null()))){ HX_STACK_LINE(564) return library->isLocal(symbolName,type); } HX_STACK_LINE(572) return false; } } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Assets_obj,isLocal,return ) bool Assets_obj::isValidBitmapData( ::flash::display::BitmapData bitmapData){ HX_STACK_PUSH("Assets::isValidBitmapData","openfl/Assets.hx",577); HX_STACK_ARG(bitmapData,"bitmapData"); HX_STACK_LINE(581) return (bitmapData->__handle != null()); HX_STACK_LINE(597) return true; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,isValidBitmapData,return ) bool Assets_obj::isValidSound( ::flash::media::Sound sound){ HX_STACK_PUSH("Assets::isValidSound","openfl/Assets.hx",602); HX_STACK_ARG(sound,"sound"); HX_STACK_LINE(602) return (bool((sound->__handle != null())) && bool((sound->__handle != (int)0))); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,isValidSound,return ) Void Assets_obj::loadBitmapData( ::String id,Dynamic handler,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACK_PUSH("Assets::loadBitmapData","openfl/Assets.hx",617); HX_STACK_ARG(id,"id"); HX_STACK_ARG(handler,"handler"); HX_STACK_ARG(useCache,"useCache"); { HX_STACK_LINE(617) Dynamic handler1 = Dynamic( Array_obj<Dynamic>::__new().Add(handler)); HX_STACK_VAR(handler1,"handler1"); HX_STACK_LINE(617) Array< ::String > id1 = Array_obj< ::String >::__new().Add(id); HX_STACK_VAR(id1,"id1"); HX_STACK_LINE(619) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(623) if (((bool((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled))) && bool(::openfl::Assets_obj::cache->bitmapData->exists(id1->__get((int)0)))))){ HX_STACK_LINE(625) ::flash::display::BitmapData bitmapData = ::openfl::Assets_obj::cache->bitmapData->get(id1->__get((int)0)); HX_STACK_VAR(bitmapData,"bitmapData"); HX_STACK_LINE(627) if ((::openfl::Assets_obj::isValidBitmapData(bitmapData))){ HX_STACK_LINE(629) handler1->__GetItem((int)0)(bitmapData).Cast< Void >(); HX_STACK_LINE(630) return null(); } } HX_STACK_LINE(636) ::String libraryName = id1->__get((int)0).substring((int)0,id1->__get((int)0).indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(637) ::String symbolName = id1->__get((int)0).substr((id1->__get((int)0).indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(638) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(640) if (((library != null()))){ HX_STACK_LINE(640) if ((library->exists(symbolName,::openfl::AssetType_obj::IMAGE))){ HX_STACK_LINE(644) if (((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled)))){ HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_Function_4_1,Array< ::String >,id1,Dynamic,handler1) Void run(::flash::display::BitmapData bitmapData){ HX_STACK_PUSH("*::_Function_4_1","openfl/Assets.hx",646); HX_STACK_ARG(bitmapData,"bitmapData"); { HX_STACK_LINE(648) ::openfl::Assets_obj::cache->bitmapData->set(id1->__get((int)0),bitmapData); HX_STACK_LINE(649) handler1->__GetItem((int)0)(bitmapData).Cast< Void >(); } return null(); } HX_END_LOCAL_FUNC1((void)) HX_STACK_LINE(644) library->loadBitmapData(symbolName, Dynamic(new _Function_4_1(id1,handler1))); } else{ HX_STACK_LINE(653) library->loadBitmapData(symbolName,handler1->__GetItem((int)0)); } HX_STACK_LINE(659) return null(); } else{ HX_STACK_LINE(661) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no BitmapData asset with an ID of \"") + id1->__get((int)0)) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),663,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadBitmapData"))); } } else{ HX_STACK_LINE(667) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),669,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadBitmapData"))); } HX_STACK_LINE(675) handler1->__GetItem((int)0)(null()).Cast< Void >(); } return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Assets_obj,loadBitmapData,(void)) Void Assets_obj::loadBytes( ::String id,Dynamic handler){ { HX_STACK_PUSH("Assets::loadBytes","openfl/Assets.hx",680); HX_STACK_ARG(id,"id"); HX_STACK_ARG(handler,"handler"); HX_STACK_LINE(682) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(686) ::String libraryName = id.substring((int)0,id.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(687) ::String symbolName = id.substr((id.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(688) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(690) if (((library != null()))){ HX_STACK_LINE(690) if ((library->exists(symbolName,::openfl::AssetType_obj::BINARY))){ HX_STACK_LINE(694) library->loadBytes(symbolName,handler); HX_STACK_LINE(695) return null(); } else{ HX_STACK_LINE(697) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no String or ByteArray asset with an ID of \"") + id) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),699,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadBytes"))); } } else{ HX_STACK_LINE(703) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),705,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadBytes"))); } HX_STACK_LINE(711) handler(null()).Cast< Void >(); } return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,loadBytes,(void)) Void Assets_obj::loadFont( ::String id,Dynamic handler,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACK_PUSH("Assets::loadFont","openfl/Assets.hx",716); HX_STACK_ARG(id,"id"); HX_STACK_ARG(handler,"handler"); HX_STACK_ARG(useCache,"useCache"); { HX_STACK_LINE(716) Dynamic handler1 = Dynamic( Array_obj<Dynamic>::__new().Add(handler)); HX_STACK_VAR(handler1,"handler1"); HX_STACK_LINE(716) Array< ::String > id1 = Array_obj< ::String >::__new().Add(id); HX_STACK_VAR(id1,"id1"); HX_STACK_LINE(718) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(722) if (((bool((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled))) && bool(::openfl::Assets_obj::cache->font->exists(id1->__get((int)0)))))){ HX_STACK_LINE(724) handler1->__GetItem((int)0)(::openfl::Assets_obj::cache->font->get(id1->__get((int)0))).Cast< Void >(); HX_STACK_LINE(725) return null(); } HX_STACK_LINE(729) ::String libraryName = id1->__get((int)0).substring((int)0,id1->__get((int)0).indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(730) ::String symbolName = id1->__get((int)0).substr((id1->__get((int)0).indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(731) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(733) if (((library != null()))){ HX_STACK_LINE(733) if ((library->exists(symbolName,::openfl::AssetType_obj::FONT))){ HX_STACK_LINE(737) if (((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled)))){ HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_Function_4_1,Array< ::String >,id1,Dynamic,handler1) Void run(::flash::text::Font font){ HX_STACK_PUSH("*::_Function_4_1","openfl/Assets.hx",739); HX_STACK_ARG(font,"font"); { HX_STACK_LINE(741) ::openfl::Assets_obj::cache->font->set(id1->__get((int)0),font); HX_STACK_LINE(742) handler1->__GetItem((int)0)(font).Cast< Void >(); } return null(); } HX_END_LOCAL_FUNC1((void)) HX_STACK_LINE(737) library->loadFont(symbolName, Dynamic(new _Function_4_1(id1,handler1))); } else{ HX_STACK_LINE(746) library->loadFont(symbolName,handler1->__GetItem((int)0)); } HX_STACK_LINE(752) return null(); } else{ HX_STACK_LINE(754) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no Font asset with an ID of \"") + id1->__get((int)0)) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),756,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadFont"))); } } else{ HX_STACK_LINE(760) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),762,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadFont"))); } HX_STACK_LINE(768) handler1->__GetItem((int)0)(null()).Cast< Void >(); } return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Assets_obj,loadFont,(void)) Void Assets_obj::loadLibrary( ::String name,Dynamic handler){ { HX_STACK_PUSH("Assets::loadLibrary","openfl/Assets.hx",773); HX_STACK_ARG(name,"name"); HX_STACK_ARG(handler,"handler"); HX_STACK_LINE(775) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(779) ::String data = ::openfl::Assets_obj::getText(((HX_CSTRING("libraries/") + name) + HX_CSTRING(".dat"))); HX_STACK_VAR(data,"data"); HX_STACK_LINE(781) if (((bool((data != null())) && bool((data != HX_CSTRING("")))))){ HX_STACK_LINE(783) ::haxe::Unserializer unserializer = ::haxe::Unserializer_obj::__new(data); HX_STACK_VAR(unserializer,"unserializer"); struct _Function_2_1{ inline static Dynamic Block( ){ HX_STACK_PUSH("*::closure","openfl/Assets.hx",784); { hx::Anon __result = hx::Anon_obj::Create(); __result->Add(HX_CSTRING("resolveEnum") , ::openfl::Assets_obj::resolveEnum_dyn(),false); __result->Add(HX_CSTRING("resolveClass") , ::openfl::Assets_obj::resolveClass_dyn(),false); return __result; } return null(); } }; HX_STACK_LINE(784) unserializer->setResolver(_Function_2_1::Block()); HX_STACK_LINE(786) ::openfl::AssetLibrary library = unserializer->unserialize(); HX_STACK_VAR(library,"library"); HX_STACK_LINE(787) ::openfl::Assets_obj::libraries->set(name,library); HX_STACK_LINE(788) library->load(handler); } else{ HX_STACK_LINE(790) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + name) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),792,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadLibrary"))); } } return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,loadLibrary,(void)) Void Assets_obj::loadMusic( ::String id,Dynamic handler,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACK_PUSH("Assets::loadMusic","openfl/Assets.hx",801); HX_STACK_ARG(id,"id"); HX_STACK_ARG(handler,"handler"); HX_STACK_ARG(useCache,"useCache"); { HX_STACK_LINE(801) Dynamic handler1 = Dynamic( Array_obj<Dynamic>::__new().Add(handler)); HX_STACK_VAR(handler1,"handler1"); HX_STACK_LINE(801) Array< ::String > id1 = Array_obj< ::String >::__new().Add(id); HX_STACK_VAR(id1,"id1"); HX_STACK_LINE(803) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(807) if (((bool((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled))) && bool(::openfl::Assets_obj::cache->sound->exists(id1->__get((int)0)))))){ HX_STACK_LINE(809) ::flash::media::Sound sound = ::openfl::Assets_obj::cache->sound->get(id1->__get((int)0)); HX_STACK_VAR(sound,"sound"); HX_STACK_LINE(811) if ((::openfl::Assets_obj::isValidSound(sound))){ HX_STACK_LINE(813) handler1->__GetItem((int)0)(sound).Cast< Void >(); HX_STACK_LINE(814) return null(); } } HX_STACK_LINE(820) ::String libraryName = id1->__get((int)0).substring((int)0,id1->__get((int)0).indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(821) ::String symbolName = id1->__get((int)0).substr((id1->__get((int)0).indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(822) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(824) if (((library != null()))){ HX_STACK_LINE(824) if ((library->exists(symbolName,::openfl::AssetType_obj::MUSIC))){ HX_STACK_LINE(828) if (((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled)))){ HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_Function_4_1,Array< ::String >,id1,Dynamic,handler1) Void run(::flash::media::Sound sound){ HX_STACK_PUSH("*::_Function_4_1","openfl/Assets.hx",830); HX_STACK_ARG(sound,"sound"); { HX_STACK_LINE(832) ::openfl::Assets_obj::cache->sound->set(id1->__get((int)0),sound); HX_STACK_LINE(833) handler1->__GetItem((int)0)(sound).Cast< Void >(); } return null(); } HX_END_LOCAL_FUNC1((void)) HX_STACK_LINE(828) library->loadMusic(symbolName, Dynamic(new _Function_4_1(id1,handler1))); } else{ HX_STACK_LINE(837) library->loadMusic(symbolName,handler1->__GetItem((int)0)); } HX_STACK_LINE(843) return null(); } else{ HX_STACK_LINE(845) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no Sound asset with an ID of \"") + id1->__get((int)0)) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),847,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadMusic"))); } } else{ HX_STACK_LINE(851) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),853,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadMusic"))); } HX_STACK_LINE(859) handler1->__GetItem((int)0)(null()).Cast< Void >(); } return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Assets_obj,loadMusic,(void)) Void Assets_obj::loadMovieClip( ::String id,Dynamic handler){ { HX_STACK_PUSH("Assets::loadMovieClip","openfl/Assets.hx",864); HX_STACK_ARG(id,"id"); HX_STACK_ARG(handler,"handler"); HX_STACK_LINE(866) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(870) ::String libraryName = id.substring((int)0,id.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(871) ::String symbolName = id.substr((id.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(872) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(874) if (((library != null()))){ HX_STACK_LINE(874) if ((library->exists(symbolName,::openfl::AssetType_obj::MOVIE_CLIP))){ HX_STACK_LINE(878) library->loadMovieClip(symbolName,handler); HX_STACK_LINE(879) return null(); } else{ HX_STACK_LINE(881) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no MovieClip asset with an ID of \"") + id) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),883,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadMovieClip"))); } } else{ HX_STACK_LINE(887) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),889,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadMovieClip"))); } HX_STACK_LINE(895) handler(null()).Cast< Void >(); } return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,loadMovieClip,(void)) Void Assets_obj::loadSound( ::String id,Dynamic handler,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACK_PUSH("Assets::loadSound","openfl/Assets.hx",900); HX_STACK_ARG(id,"id"); HX_STACK_ARG(handler,"handler"); HX_STACK_ARG(useCache,"useCache"); { HX_STACK_LINE(900) Dynamic handler1 = Dynamic( Array_obj<Dynamic>::__new().Add(handler)); HX_STACK_VAR(handler1,"handler1"); HX_STACK_LINE(900) Array< ::String > id1 = Array_obj< ::String >::__new().Add(id); HX_STACK_VAR(id1,"id1"); HX_STACK_LINE(902) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(906) if (((bool((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled))) && bool(::openfl::Assets_obj::cache->sound->exists(id1->__get((int)0)))))){ HX_STACK_LINE(908) ::flash::media::Sound sound = ::openfl::Assets_obj::cache->sound->get(id1->__get((int)0)); HX_STACK_VAR(sound,"sound"); HX_STACK_LINE(910) if ((::openfl::Assets_obj::isValidSound(sound))){ HX_STACK_LINE(912) handler1->__GetItem((int)0)(sound).Cast< Void >(); HX_STACK_LINE(913) return null(); } } HX_STACK_LINE(919) ::String libraryName = id1->__get((int)0).substring((int)0,id1->__get((int)0).indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(920) ::String symbolName = id1->__get((int)0).substr((id1->__get((int)0).indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(921) ::openfl::AssetLibrary library = ::openfl::Assets_obj::getLibrary(libraryName); HX_STACK_VAR(library,"library"); HX_STACK_LINE(923) if (((library != null()))){ HX_STACK_LINE(923) if ((library->exists(symbolName,::openfl::AssetType_obj::SOUND))){ HX_STACK_LINE(927) if (((bool(useCache) && bool(::openfl::Assets_obj::cache->enabled)))){ HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_Function_4_1,Array< ::String >,id1,Dynamic,handler1) Void run(::flash::media::Sound sound){ HX_STACK_PUSH("*::_Function_4_1","openfl/Assets.hx",929); HX_STACK_ARG(sound,"sound"); { HX_STACK_LINE(931) ::openfl::Assets_obj::cache->sound->set(id1->__get((int)0),sound); HX_STACK_LINE(932) handler1->__GetItem((int)0)(sound).Cast< Void >(); } return null(); } HX_END_LOCAL_FUNC1((void)) HX_STACK_LINE(927) library->loadSound(symbolName, Dynamic(new _Function_4_1(id1,handler1))); } else{ HX_STACK_LINE(936) library->loadSound(symbolName,handler1->__GetItem((int)0)); } HX_STACK_LINE(942) return null(); } else{ HX_STACK_LINE(944) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no Sound asset with an ID of \"") + id1->__get((int)0)) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),946,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadSound"))); } } else{ HX_STACK_LINE(950) ::haxe::Log_obj::trace(((HX_CSTRING("[openfl.Assets] There is no asset library named \"") + libraryName) + HX_CSTRING("\"")),hx::SourceInfo(HX_CSTRING("Assets.hx"),952,HX_CSTRING("openfl.Assets"),HX_CSTRING("loadSound"))); } HX_STACK_LINE(958) handler1->__GetItem((int)0)(null()).Cast< Void >(); } return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Assets_obj,loadSound,(void)) Void Assets_obj::loadText( ::String id,Dynamic handler){ { HX_STACK_PUSH("Assets::loadText","openfl/Assets.hx",963); HX_STACK_ARG(id,"id"); HX_STACK_ARG(handler,"handler"); HX_STACK_LINE(963) Dynamic handler1 = Dynamic( Array_obj<Dynamic>::__new().Add(handler)); HX_STACK_VAR(handler1,"handler1"); HX_STACK_LINE(965) ::openfl::Assets_obj::initialize(); HX_BEGIN_LOCAL_FUNC_S1(hx::LocalFunc,_Function_1_1,Dynamic,handler1) Void run(::flash::utils::ByteArray bytes){ HX_STACK_PUSH("*::_Function_1_1","openfl/Assets.hx",969); HX_STACK_ARG(bytes,"bytes"); { HX_STACK_LINE(969) if (((bytes == null()))){ HX_STACK_LINE(971) handler1->__GetItem((int)0)(null()).Cast< Void >(); } else{ HX_STACK_LINE(975) handler1->__GetItem((int)0)(bytes->readUTFBytes(bytes->length)).Cast< Void >(); } } return null(); } HX_END_LOCAL_FUNC1((void)) HX_STACK_LINE(969) Dynamic callback = Dynamic(new _Function_1_1(handler1)); HX_STACK_VAR(callback,"callback"); HX_STACK_LINE(983) ::openfl::Assets_obj::loadBytes(id,callback); } return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,loadText,(void)) Void Assets_obj::registerLibrary( ::String name,::openfl::AssetLibrary library){ { HX_STACK_PUSH("Assets::registerLibrary","openfl/Assets.hx",994); HX_STACK_ARG(name,"name"); HX_STACK_ARG(library,"library"); HX_STACK_LINE(996) if ((::openfl::Assets_obj::libraries->exists(name))){ HX_STACK_LINE(996) ::openfl::Assets_obj::unloadLibrary(name); } HX_STACK_LINE(1002) ::openfl::Assets_obj::libraries->set(name,library); } return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,registerLibrary,(void)) ::Class Assets_obj::resolveClass( ::String name){ HX_STACK_PUSH("Assets::resolveClass","openfl/Assets.hx",1007); HX_STACK_ARG(name,"name"); HX_STACK_LINE(1007) return ::Type_obj::resolveClass(name); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,resolveClass,return ) ::Enum Assets_obj::resolveEnum( ::String name){ HX_STACK_PUSH("Assets::resolveEnum","openfl/Assets.hx",1014); HX_STACK_ARG(name,"name"); HX_STACK_LINE(1016) ::Enum value = ::Type_obj::resolveEnum(name); HX_STACK_VAR(value,"value"); HX_STACK_LINE(1028) return value; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,resolveEnum,return ) Void Assets_obj::unloadLibrary( ::String name){ { HX_STACK_PUSH("Assets::unloadLibrary","openfl/Assets.hx",1033); HX_STACK_ARG(name,"name"); HX_STACK_LINE(1035) ::openfl::Assets_obj::initialize(); HX_STACK_LINE(1039) Dynamic keys = ::openfl::Assets_obj::cache->bitmapData->keys(); HX_STACK_VAR(keys,"keys"); HX_STACK_LINE(1041) for(::cpp::FastIterator_obj< ::String > *__it = ::cpp::CreateFastIterator< ::String >(keys); __it->hasNext(); ){ ::String key = __it->next(); { HX_STACK_LINE(1043) ::String libraryName = key.substring((int)0,key.indexOf(HX_CSTRING(":"),null())); HX_STACK_VAR(libraryName,"libraryName"); HX_STACK_LINE(1044) ::String symbolName = key.substr((key.indexOf(HX_CSTRING(":"),null()) + (int)1),null()); HX_STACK_VAR(symbolName,"symbolName"); HX_STACK_LINE(1046) if (((libraryName == name))){ HX_STACK_LINE(1046) ::openfl::Assets_obj::cache->bitmapData->remove(key); } } ; } HX_STACK_LINE(1054) ::openfl::Assets_obj::libraries->remove(name); } return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,unloadLibrary,(void)) Assets_obj::Assets_obj() { } void Assets_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Assets); HX_MARK_END_CLASS(); } void Assets_obj::__Visit(HX_VISIT_PARAMS) { } Dynamic Assets_obj::__Field(const ::String &inName,bool inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"cache") ) { return cache; } break; case 6: if (HX_FIELD_EQ(inName,"exists") ) { return exists_dyn(); } break; case 7: if (HX_FIELD_EQ(inName,"getFont") ) { return getFont_dyn(); } if (HX_FIELD_EQ(inName,"getPath") ) { return getPath_dyn(); } if (HX_FIELD_EQ(inName,"getText") ) { return getText_dyn(); } if (HX_FIELD_EQ(inName,"isLocal") ) { return isLocal_dyn(); } break; case 8: if (HX_FIELD_EQ(inName,"getBytes") ) { return getBytes_dyn(); } if (HX_FIELD_EQ(inName,"getMusic") ) { return getMusic_dyn(); } if (HX_FIELD_EQ(inName,"getSound") ) { return getSound_dyn(); } if (HX_FIELD_EQ(inName,"loadFont") ) { return loadFont_dyn(); } if (HX_FIELD_EQ(inName,"loadText") ) { return loadText_dyn(); } break; case 9: if (HX_FIELD_EQ(inName,"libraries") ) { return libraries; } if (HX_FIELD_EQ(inName,"loadBytes") ) { return loadBytes_dyn(); } if (HX_FIELD_EQ(inName,"loadMusic") ) { return loadMusic_dyn(); } if (HX_FIELD_EQ(inName,"loadSound") ) { return loadSound_dyn(); } break; case 10: if (HX_FIELD_EQ(inName,"getLibrary") ) { return getLibrary_dyn(); } if (HX_FIELD_EQ(inName,"initialize") ) { return initialize_dyn(); } break; case 11: if (HX_FIELD_EQ(inName,"initialized") ) { return initialized; } if (HX_FIELD_EQ(inName,"loadLibrary") ) { return loadLibrary_dyn(); } if (HX_FIELD_EQ(inName,"resolveEnum") ) { return resolveEnum_dyn(); } break; case 12: if (HX_FIELD_EQ(inName,"getMovieClip") ) { return getMovieClip_dyn(); } if (HX_FIELD_EQ(inName,"isValidSound") ) { return isValidSound_dyn(); } if (HX_FIELD_EQ(inName,"resolveClass") ) { return resolveClass_dyn(); } break; case 13: if (HX_FIELD_EQ(inName,"getBitmapData") ) { return getBitmapData_dyn(); } if (HX_FIELD_EQ(inName,"loadMovieClip") ) { return loadMovieClip_dyn(); } if (HX_FIELD_EQ(inName,"unloadLibrary") ) { return unloadLibrary_dyn(); } break; case 14: if (HX_FIELD_EQ(inName,"loadBitmapData") ) { return loadBitmapData_dyn(); } break; case 15: if (HX_FIELD_EQ(inName,"registerLibrary") ) { return registerLibrary_dyn(); } break; case 17: if (HX_FIELD_EQ(inName,"isValidBitmapData") ) { return isValidBitmapData_dyn(); } } return super::__Field(inName,inCallProp); } Dynamic Assets_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"cache") ) { cache=inValue.Cast< ::openfl::AssetCache >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"libraries") ) { libraries=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"initialized") ) { initialized=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void Assets_obj::__GetFields(Array< ::String> &outFields) { super::__GetFields(outFields); }; static ::String sStaticFields[] = { HX_CSTRING("cache"), HX_CSTRING("libraries"), HX_CSTRING("initialized"), HX_CSTRING("exists"), HX_CSTRING("getBitmapData"), HX_CSTRING("getBytes"), HX_CSTRING("getFont"), HX_CSTRING("getLibrary"), HX_CSTRING("getMovieClip"), HX_CSTRING("getMusic"), HX_CSTRING("getPath"), HX_CSTRING("getSound"), HX_CSTRING("getText"), HX_CSTRING("initialize"), HX_CSTRING("isLocal"), HX_CSTRING("isValidBitmapData"), HX_CSTRING("isValidSound"), HX_CSTRING("loadBitmapData"), HX_CSTRING("loadBytes"), HX_CSTRING("loadFont"), HX_CSTRING("loadLibrary"), HX_CSTRING("loadMusic"), HX_CSTRING("loadMovieClip"), HX_CSTRING("loadSound"), HX_CSTRING("loadText"), HX_CSTRING("registerLibrary"), HX_CSTRING("resolveClass"), HX_CSTRING("resolveEnum"), HX_CSTRING("unloadLibrary"), String(null()) }; static ::String sMemberFields[] = { String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Assets_obj::__mClass,"__mClass"); HX_MARK_MEMBER_NAME(Assets_obj::cache,"cache"); HX_MARK_MEMBER_NAME(Assets_obj::libraries,"libraries"); HX_MARK_MEMBER_NAME(Assets_obj::initialized,"initialized"); }; static void sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Assets_obj::__mClass,"__mClass"); HX_VISIT_MEMBER_NAME(Assets_obj::cache,"cache"); HX_VISIT_MEMBER_NAME(Assets_obj::libraries,"libraries"); HX_VISIT_MEMBER_NAME(Assets_obj::initialized,"initialized"); }; Class Assets_obj::__mClass; void Assets_obj::__register() { hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("openfl.Assets"), hx::TCanCast< Assets_obj> ,sStaticFields,sMemberFields, &__CreateEmpty, &__Create, &super::__SGetClass(), 0, sMarkStatics, sVisitStatics); } void Assets_obj::__boot() { cache= ::openfl::AssetCache_obj::__new(); libraries= ::haxe::ds::StringMap_obj::__new(); initialized= false; } } // end namespace openfl
49,898
23,261
/*******************************************************************\ Module: Show program locations Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ #include <iostream> #include <util/xml.h> #include <util/i2string.h> #include <util/xml_irep.h> #include <langapi/language_util.h> #include "show_locations.h" /*******************************************************************\ Function: show_locations Inputs: Outputs: Purpose: \*******************************************************************/ void show_locations( ui_message_handlert::uit ui, const irep_idt function_id, const goto_programt &goto_program) { for(goto_programt::instructionst::const_iterator it=goto_program.instructions.begin(); it!=goto_program.instructions.end(); it++) { const source_locationt &source_location=it->source_location; switch(ui) { case ui_message_handlert::XML_UI: { xmlt xml("program_location"); xml.new_element("function").data=id2string(function_id); xml.new_element("id").data=i2string(it->location_number); xmlt &l=xml.new_element(); l.name="location"; l.new_element("line").data=id2string(source_location.get_line()); l.new_element("file").data=id2string(source_location.get_file()); l.new_element("function").data=id2string(source_location.get_function()); std::cout << xml << std::endl; } break; case ui_message_handlert::PLAIN: std::cout << function_id << " " << it->location_number << " " << it->source_location << std::endl; break; default: assert(false); } } } /*******************************************************************\ Function: show_locations Inputs: Outputs: Purpose: \*******************************************************************/ void show_locations( ui_message_handlert::uit ui, const goto_functionst &goto_functions) { for(goto_functionst::function_mapt::const_iterator it=goto_functions.function_map.begin(); it!=goto_functions.function_map.end(); it++) show_locations(ui, it->first, it->second.body); }
2,296
694
#include "windows/material_properties.hpp" #include "editor_tools.hpp" #include "windows/materials.hpp" #include "erhe/primitive/material.hpp" #include <imgui.h> #include <imgui/misc/cpp/imgui_stdlib.h> namespace editor { Material_properties::Material_properties() : erhe::components::Component{c_name} , Imgui_window {c_title} { } Material_properties::~Material_properties() = default; void Material_properties::connect() { m_materials = get<Materials>(); } void Material_properties::initialize_component() { get<Editor_tools>()->register_imgui_window(this); } void Material_properties::imgui() { if (m_materials == nullptr) { return; } { const auto selected_material = m_materials->selected_material(); if (selected_material) { ImGui::InputText("Name", &selected_material->name); ImGui::SliderFloat("Metallic", &selected_material->metallic, 0.0f, 1.0f); ImGui::SliderFloat("Anisotropy", &selected_material->anisotropy, -1.0f, 1.0f); ImGui::SliderFloat("Roughness", &selected_material->roughness, 0.0f, 1.0f); ImGui::ColorEdit4 ("Base Color", &selected_material->base_color.x, ImGuiColorEditFlags_Float); } } } }
1,283
429
// Copyright 2021 The Autoware Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "vehicle_constants_manager/vehicle_constants_manager.hpp" #include <rclcpp/rclcpp.hpp> #include <map> #include <stdexcept> #include <string> #include <utility> namespace autoware { namespace common { namespace vehicle_constants_manager { using float64_t = VehicleConstants::float64_t; VehicleConstants::VehicleConstants( float64_t wheel_radius, float64_t wheel_width, float64_t wheel_base, float64_t wheel_tread, float64_t overhang_front, float64_t overhang_rear, float64_t overhang_left, float64_t overhang_right, float64_t vehicle_height, float64_t cg_to_rear, float64_t tire_cornering_stiffness_front, float64_t tire_cornering_stiffness_rear, float64_t mass_vehicle, float64_t inertia_yaw_kg_m_2) : wheel_radius(wheel_radius), wheel_width(wheel_width), wheel_base(wheel_base), wheel_tread(wheel_tread), overhang_front(overhang_front), overhang_rear(overhang_rear), overhang_left(overhang_left), overhang_right(overhang_right), vehicle_height(vehicle_height), cg_to_rear(cg_to_rear), tire_cornering_stiffness_front(tire_cornering_stiffness_front), tire_cornering_stiffness_rear(tire_cornering_stiffness_rear), mass_vehicle(mass_vehicle), inertia_yaw_kg_m2(inertia_yaw_kg_m_2), cg_to_front(wheel_base - cg_to_rear), vehicle_length(overhang_front + wheel_base + overhang_rear), vehicle_width(overhang_left + wheel_tread + overhang_right), offset_longitudinal_min(-overhang_rear), offset_longitudinal_max(wheel_base + overhang_front), offset_lateral_min(-(wheel_tread / 2.0 + overhang_right)), offset_lateral_max(wheel_tread / 2.0 + overhang_left), offset_height_min(-wheel_radius), offset_height_max(vehicle_height - wheel_radius) { // Sanity Checks // Center of gravity must be between front and rear axles if (wheel_base < cg_to_rear) { throw std::runtime_error("wheel_base must be larger than cg_to_rear"); } // These values must be positive auto throw_if_negative = [](float64_t number, const std::string & name) { if (number < 0.0) { throw std::runtime_error( name + " = " + std::to_string(number) + " shouldn't be negative."); } }; throw_if_negative(wheel_radius, "wheel_radius"); throw_if_negative(wheel_width, "wheel_width"); throw_if_negative(wheel_base, "wheel_base"); throw_if_negative(wheel_tread, "wheel_tread"); throw_if_negative(overhang_front, "overhang_front"); throw_if_negative(overhang_rear, "overhang_rear"); throw_if_negative(overhang_left, "overhang_left"); throw_if_negative(overhang_right, "overhang_right"); throw_if_negative(vehicle_height, "vehicle_height"); throw_if_negative(cg_to_rear, "cg_to_rear"); throw_if_negative(tire_cornering_stiffness_front, "tire_cornering_stiffness_front"); throw_if_negative(tire_cornering_stiffness_rear, "tire_cornering_stiffness_rear"); throw_if_negative(mass_vehicle, "mass_vehicle"); throw_if_negative(inertia_yaw_kg_m_2, "inertia_yaw_kg_m_2"); } std::string VehicleConstants::str_pretty() const { return std::string{ "wheel_radius: " + std::to_string(wheel_radius) + "\n" "wheel_width: " + std::to_string(wheel_width) + "\n" "wheel_base: " + std::to_string(wheel_base) + "\n" "wheel_tread: " + std::to_string(wheel_tread) + "\n" "overhang_front: " + std::to_string(overhang_front) + "\n" "overhang_rear: " + std::to_string(overhang_rear) + "\n" "overhang_left: " + std::to_string(overhang_left) + "\n" "overhang_right: " + std::to_string(overhang_right) + "\n" "vehicle_height: " + std::to_string(vehicle_height) + "\n" "cg_to_rear: " + std::to_string(cg_to_rear) + "\n" "tire_cornering_stiffness_front: " + std::to_string(tire_cornering_stiffness_front) + "\n" "tire_cornering_stiffness_rear: " + std::to_string(tire_cornering_stiffness_rear) + "\n" "mass_vehicle: " + std::to_string(mass_vehicle) + "\n" "inertia_yaw_kg_m2: " + std::to_string(inertia_yaw_kg_m2) + "\n" "cg_to_front: " + std::to_string(cg_to_front) + "\n" "vehicle_length: " + std::to_string(vehicle_length) + "\n" "vehicle_width: " + std::to_string(vehicle_width) + "\n" "offset_longitudinal_min: " + std::to_string(offset_longitudinal_min) + "\n" "offset_longitudinal_max: " + std::to_string(offset_longitudinal_max) + "\n" "offset_lateral_min: " + std::to_string(offset_lateral_min) + "\n" "offset_lateral_max: " + std::to_string(offset_lateral_max) + "\n" "offset_height_min: " + std::to_string(offset_height_min) + "\n" "offset_height_max: " + std::to_string(offset_height_max) + "\n" }; } VehicleConstants declare_and_get_vehicle_constants(rclcpp::Node & node) { // Initialize the parameters const std::string ns = "vehicle."; std::map<std::string, float64_t> params{ std::make_pair(ns + "wheel_radius", -1.0), std::make_pair(ns + "wheel_width", -1.0), std::make_pair(ns + "wheel_base", -1.0), std::make_pair(ns + "wheel_tread", -1.0), std::make_pair(ns + "overhang_front", -1.0), std::make_pair(ns + "overhang_rear", -1.0), std::make_pair(ns + "overhang_left", -1.0), std::make_pair(ns + "overhang_right", -1.0), std::make_pair(ns + "vehicle_height", -1.0), std::make_pair(ns + "cg_to_rear", -1.0), std::make_pair(ns + "tire_cornering_stiffness_front", -1.0), std::make_pair(ns + "tire_cornering_stiffness_rear", -1.0), std::make_pair(ns + "mass_vehicle", -1.0), std::make_pair(ns + "inertia_yaw_kg_m2", -1.0) }; // Try to get parameter values from parameter_overrides set either from .yaml // or with args. for (auto & pair : params) { // If it is already declared if (node.has_parameter(pair.first)) { pair.second = node.get_parameter(pair.first).get_value<float64_t>(); continue; } pair.second = node.declare_parameter(pair.first).get<float64_t>(); } return VehicleConstants( params.at(ns + "wheel_radius"), params.at(ns + "wheel_width"), params.at(ns + "wheel_base"), params.at(ns + "wheel_tread"), params.at(ns + "overhang_front"), params.at(ns + "overhang_rear"), params.at(ns + "overhang_left"), params.at(ns + "overhang_right"), params.at(ns + "vehicle_height"), params.at(ns + "cg_to_rear"), params.at(ns + "tire_cornering_stiffness_front"), params.at(ns + "tire_cornering_stiffness_rear"), params.at(ns + "mass_vehicle"), params.at(ns + "inertia_yaw_kg_m2") ); } } // namespace vehicle_constants_manager } // namespace common } // namespace autoware
7,153
2,871
#pragma once #include "engine/graphics/interface/framebuffer.hpp" #include "engine/graphics/opengl/gl_texture.hpp" #include "engine/internal_libs.hpp" namespace oe::graphics { class GLFrameBuffer : public IFrameBuffer { private: // uint32_t m_rbo; uint32_t m_id; Texture m_texture; public: static uint32_t bound_fbo_id; static glm::ivec4 current_viewport; static glm::ivec2 gl_max_fb_size; static void bind_fb(uint32_t fb_id, const glm::ivec4& viewport); public: GLFrameBuffer(const FrameBufferInfo& framebuffer_info); ~GLFrameBuffer() override; void bind() override; void clear(const oe::color& c = oe::colors::clear_color) override; static std::unique_ptr<state> save_state(); static void load_state(const std::unique_ptr<state>&); inline Texture& getTexture() override { return m_texture; } }; }
884
349
#include "PhysicsSystem.h" namespace { const unsigned long COMPONENTS_MASK { ECSComponent::COMPONENT_POSITION | ECSComponent::COMPONENT_VELOCITY }; } PhysicsSystem::PhysicsSystem(EntityManager &manager, std::vector<ECSComponent::Position> &positions, std::vector<ECSComponent::Velocity> &velocities) : ECSSystem(manager, COMPONENTS_MASK), m_positions(positions), m_velocities(velocities) { } void PhysicsSystem::updateEntity(int entityId, float deltaTime) { m_positions[entityId].xyz += m_velocities[entityId].xyz * deltaTime; }
547
207
#include "GameConfig.h" #include "../Utils/Strings.h" void GameConfig::loadGameConfig(const char* filename) { XMLDocument doc; doc.LoadFile(filename); XMLElement* objElement = doc.FirstChildElement("Game"); for (XMLElement* child = objElement->FirstChildElement(); child != NULL; child = child->NextSiblingElement()) { const char* ename = child->Name(); if (strcmp(ename,"Resolution") == 0) { const char* cWidth = child->Attribute("x"); const char* cHeight = child->Attribute("y"); windowWidth = (int)atoi(cWidth); windowHeight = (int)atoi(cHeight); } else if (strcmp(ename,"Map") == 0) { mapFile = std::string(child->Attribute("name")); } else if (strcmp(ename,"Bus") == 0) { busModel = std::string(child->Attribute("model")); } else if (strcmp(ename,"Configuration") == 0) { for (XMLElement* configElement = child->FirstChildElement(); configElement != NULL; configElement = configElement->NextSiblingElement()) { const char* ename = configElement->Name(); if (strcmp(ename,"Fullscreen") == 0) { isFullscreen = toBool(configElement->GetText()); } if (strcmp(ename, "VerticalSync") == 0) { verticalSync = toBool(configElement->GetText()); } else if (strcmp(ename, "HdrQuality") == 0) { hdrQuality = toInt(configElement->GetText()); } else if (strcmp(ename,"MsaaAntialiasing") == 0) { msaaAntialiasing = toBool(configElement->GetText()); } else if (strcmp(ename,"MsaaAntialiasingLevel") == 0) { msaaAntialiasingLevel = toInt(configElement->GetText()); } else if (strcmp(ename,"Shadowmapping") == 0) { isShadowmappingEnable = toBool(configElement->GetText()); } else if (strcmp(ename,"ShadowmapSize") == 0) { shadowmapSize = toInt(configElement->GetText()); } else if (strcmp(ename, "StaticShadowmapSize") == 0) { staticShadowmapSize = toInt(configElement->GetText()); } else if (strcmp(ename,"Bloom") == 0) { isBloomEnabled = toBool(configElement->GetText()); } else if (strcmp(ename,"Grass") == 0) { isGrassEnable = toBool(configElement->GetText()); } else if (strcmp(ename, "GrassRenderingDistance") == 0) { grassRenderingDistance = toFloat(configElement->GetText()); } else if (strcmp(ename, "Mirrors") == 0) { isMirrorsEnabled = toBool(configElement->GetText()); } else if (strcmp(ename, "MirrorRenderingDistance") == 0) { mirrorRenderingDistance = toFloat(configElement->GetText()); } else if (strcmp(ename, "TextureCompression") == 0) { textureCompression = toBool(configElement->GetText()); } else if (strcmp(ename, "AnisotropicFiltering") == 0) { anisotropicFiltering = toBool(configElement->GetText()); } else if (strcmp(ename, "AnisotropySamples") == 0) { anisotropySamples = toFloat(configElement->GetText()); } else if (strcmp(ename, "PbrSupport") == 0) { pbrSupport = toBool(configElement->GetText()); } } } } } void GameConfig::loadDevelopmentConfig(const char* filename) { XMLDocument doc; doc.LoadFile(filename); XMLElement* objElement = doc.FirstChildElement("DevSettings"); for (XMLElement* child = objElement->FirstChildElement(); child != NULL; child = child->NextSiblingElement()) { const char* ename = child->Name(); if (strcmp(ename, "alternativeResourcesPath") == 0) { alternativeResourcesPath = std::string(child->GetText()); } else if (strcmp(ename, "developmentMode") == 0) { developmentMode = toBool(child->GetText()); } } } GameConfig* GameConfig::instance = NULL;
4,257
1,434
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // /////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <cstdint> #include "cldnn.hpp" #include "compounds.h" #include "primitive.hpp" #include <vector> #include <memory> namespace cldnn { /// @addtogroup cpp_api C++ API /// @{ /// @defgroup cpp_topology Network Topology /// @{ struct topology_impl; /// @brief Network topology to be defined by user. struct topology { /// @brief Constructs empty network topology. topology(); /// @brief Constructs topology containing primitives provided in argument(s). template <class... Args> explicit topology(const Args&... args) : topology() { add<Args...>(args...); } /// @brief Copy construction. topology(const topology& other) : _impl(other._impl) { retain(); } /// @brief Copy assignment. topology& operator=(const topology& other) { if (_impl == other._impl) return *this; release(); _impl = other._impl; retain(); return *this; } /// Construct C++ topology based on C API @p cldnn_topology explicit topology(topology_impl* other) : _impl(other) { if (_impl == nullptr) throw std::invalid_argument("implementation pointer should not be null"); } /// @brief Releases wrapped C API @ref cldnn_topology. ~topology() { release(); } friend bool operator==(const topology& lhs, const topology& rhs) { return lhs._impl == rhs._impl; } friend bool operator!=(const topology& lhs, const topology& rhs) { return !(lhs == rhs); } void add_primitive(std::shared_ptr<primitive> desc); /// @brief Adds a primitive to topology. template <class PType> void add(PType const& desc) { add_primitive(std::static_pointer_cast<primitive>(std::make_shared<PType>(desc))); } /// @brief Adds primitives to topology. template <class PType, class... Args> void add(PType const& desc, Args const&... args) { add(desc); add<Args...>(args...); } /// @brief Returns wrapped implementation pointer. topology_impl* get() const { return _impl; } const std::vector<primitive_id> get_primitive_ids() const; void change_input_layout(primitive_id id, const layout& new_layout); const std::shared_ptr<primitive>& at(const primitive_id& id) const; private: friend struct engine; friend struct network; topology_impl* _impl; void retain(); void release(); }; CLDNN_API_CLASS(topology) /// @} /// @} } // namespace cldnn
2,654
813
#include <capi/config.h> #include <iomanip> #include <memory> #include <algorithm> #include <log.hxx> #include <ut/string_view.hxx> #include <global_state.hxx> namespace internal { template< typename T > T retrieve_config_value(ut::string_view p_path) { const auto t_val = global_state<configuration>().get<T>({p_path.to_string()}); if(!t_val) { LOG_F_TAG("libascii") << "Requested configuration entry does not exist or type mismatch: \"" << (p_path) << "\""; throw new ::std::runtime_error("requested configuration entry does not exist or type mismatch"); } return *t_val; } } extern "C" { float configuration_get_float(const char* p_path) { return internal::retrieve_config_value<float>({p_path}); } double configuration_get_double(const char* p_path) { return internal::retrieve_config_value<double>({p_path}); } int configuration_get_int(const char* p_path) { return internal::retrieve_config_value<int>({p_path}); } unsigned configuration_get_uint(const char* p_path) { return internal::retrieve_config_value<unsigned>({p_path}); } const char* configuration_get_string(const char* p_path) { const auto t_str = internal::retrieve_config_value<::std::string>({p_path}); ::std::unique_ptr<char[]> t_buf{ new char[t_str.length() + 1] }; ::std::copy(t_str.cbegin(), t_str.end(), t_buf.get()); t_buf[t_str.length()] = '\0'; return t_buf.release(); } bool_t configuration_get_boolean(const char* p_path) { return static_cast<bool_t>(internal::retrieve_config_value<bool>({p_path})); } }
1,572
627
/* Copyright (c) 2016, Dan Eicher All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "jit-module.h" #include <jit/jit-dynamic.h> typedef struct { PyObject_HEAD jit_dynlib_handle_t obj; } PyJit_dynlib_handle; extern PyTypeObject PyJit_dynlib_handle_Type; static PyObject * PyJit_dynamic_set_debug(PyObject * UNUSED(dummy), PyObject *args, PyObject *kwargs) { PyObject *py_flag; const char *keywords[] = {"flag", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "O:set_debug", (char **) keywords, &py_flag)) { return NULL; } jit_dynlib_set_debug(PyObject_IsTrue(py_flag)); Py_RETURN_NONE; } static PyObject * PyJit_dynamic_get_suffix() { return Py_BuildValue((char *) "s", jit_dynlib_get_suffix()); } static PyMethodDef jit_dynamic_functions[] = { {(char *) "set_debug", (PyCFunction) PyJit_dynamic_set_debug, METH_KEYWORDS|METH_VARARGS, NULL }, {(char *) "get_suffix", (PyCFunction) PyJit_dynamic_get_suffix, METH_NOARGS, NULL }, {NULL, NULL, 0, NULL} }; static PyObject * PyJit__dynamic_get_symbol(PyJit_dynlib_handle *self, PyObject *args, PyObject *kwargs) { char const *name; const char *keywords[] = {"name", NULL}; void *symbol; if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "s:get_symbol", (char **) keywords, &name)) { return NULL; } if ((symbol = jit_dynlib_get_symbol(self->obj, name)) == NULL) { PyErr_Format(PyExc_ValueError, "symbol '%s' not found", name); return NULL; } return PyLong_FromVoidPtr(symbol); } static PyMethodDef PyJit_dynlib_handle_methods[] = { {(char *) "get_symbol", (PyCFunction) PyJit__dynamic_get_symbol, METH_KEYWORDS|METH_VARARGS, NULL }, {NULL, NULL, 0, NULL} }; static int PyJit_dynlib_handle__tp_init(PyJit_dynlib_handle *self, PyObject *args, PyObject *kwargs) { char const *name; const char *keywords[] = {"name", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "s", (char **) keywords, &name)) { return -1; } self->obj = jit_dynlib_open(name); if (self->obj == NULL) { PyErr_Format(PyExc_ValueError, "unable to open library '%s'", name); return -1; } return 0; } static void PyJit_dynlib_handle__tp_dealloc(PyJit_dynlib_handle *self) { jit_dynlib_handle_t tmp = self->obj; self->obj = NULL; if (tmp) { jit_dynlib_close(tmp); } Py_TYPE(self)->tp_free((PyObject*)self); } PyTypeObject PyJit_dynlib_handle_Type = { PyVarObject_HEAD_INIT(NULL, 0) (char *) "jit.dynamic.Library", /* tp_name */ sizeof(PyJit_dynlib_handle), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)PyJit_dynlib_handle__tp_dealloc, /* tp_dealloc */ (printfunc)0, /* tp_print */ (getattrfunc)NULL, /* tp_getattr */ (setattrfunc)NULL, /* tp_setattr */ (cmpfunc)NULL, /* tp_compare */ (reprfunc)NULL, /* tp_repr */ (PyNumberMethods*)NULL, /* tp_as_number */ (PySequenceMethods*)NULL, /* tp_as_sequence */ (PyMappingMethods*)NULL, /* tp_as_mapping */ (hashfunc)NULL, /* tp_hash */ (ternaryfunc)NULL, /* tp_call */ (reprfunc)NULL, /* tp_str */ (getattrofunc)NULL, /* tp_getattro */ (setattrofunc)NULL, /* tp_setattro */ (PyBufferProcs*)NULL, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ NULL, /* Documentation string */ (traverseproc)NULL, /* tp_traverse */ (inquiry)NULL, /* tp_clear */ (richcmpfunc)NULL, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)NULL, /* tp_iter */ (iternextfunc)NULL, /* tp_iternext */ (struct PyMethodDef*)PyJit_dynlib_handle_methods, /* tp_methods */ (struct PyMemberDef*)0, /* tp_members */ 0, /* tp_getset */ NULL, /* tp_base */ NULL, /* tp_dict */ (descrgetfunc)NULL, /* tp_descr_get */ (descrsetfunc)NULL, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)PyJit_dynlib_handle__tp_init, /* tp_init */ (allocfunc)PyType_GenericAlloc, /* tp_alloc */ (newfunc)PyType_GenericNew, /* tp_new */ (freefunc)0, /* tp_free */ (inquiry)NULL, /* tp_is_gc */ NULL, /* tp_bases */ NULL, /* tp_mro */ NULL, /* tp_cache */ NULL, /* tp_subclasses */ NULL, /* tp_weaklist */ (destructor) NULL /* tp_del */ }; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef jit_dynamic_moduledef = { PyModuleDef_HEAD_INIT, "jit.dynamic", NULL, -1, jit_dynamic_functions, }; #endif PyObject * initjit_dynamic(void) { PyObject *m; #if PY_VERSION_HEX >= 0x03000000 m = PyModule_Create(&jit_dynamic_moduledef); #else m = Py_InitModule3((char *) "jit.dynamic", jit_dynamic_functions, NULL); #endif if (m == NULL) { return NULL; } /* Register the 'jit_dynlib_handle_t' class */ if (PyType_Ready(&PyJit_dynlib_handle_Type)) { return NULL; } PyModule_AddObject(m, (char *) "Library", (PyObject *) &PyJit_dynlib_handle_Type); return m; }
8,256
2,592
/** * spaint: PerLabelVoxelSampler_CPU.cpp * Copyright (c) Torr Vision Group, University of Oxford, 2015. All rights reserved. */ #include "sampling/cpu/PerLabelVoxelSampler_CPU.h" #include "sampling/shared/PerLabelVoxelSampler_Shared.h" namespace spaint { //#################### CONSTRUCTORS #################### PerLabelVoxelSampler_CPU::PerLabelVoxelSampler_CPU(size_t maxLabelCount, size_t maxVoxelsPerLabel, int raycastResultSize, unsigned int seed) : PerLabelVoxelSampler(maxLabelCount, maxVoxelsPerLabel, raycastResultSize, seed) {} //#################### PRIVATE MEMBER FUNCTIONS #################### void PerLabelVoxelSampler_CPU::calculate_voxel_mask_prefix_sums(const ORUtils::MemoryBlock<bool>& labelMaskMB) const { const bool *labelMask = labelMaskMB.GetData(MEMORYDEVICE_CPU); const unsigned char *voxelMasks = m_voxelMasksMB->GetData(MEMORYDEVICE_CPU); unsigned int *voxelMaskPrefixSums = m_voxelMaskPrefixSumsMB->GetData(MEMORYDEVICE_CPU); // For each possible label: const int stride = m_raycastResultSize + 1; for(size_t k = 0; k < m_maxLabelCount; ++k) { // If the label is not currently in use, continue. if(!labelMask[k]) continue; // Calculate the prefix sum of the voxel mask. const size_t offset = k * stride; voxelMaskPrefixSums[offset] = 0; for(int i = 1; i < stride; ++i) { voxelMaskPrefixSums[offset + i] = voxelMaskPrefixSums[offset + (i - 1)] + voxelMasks[offset + (i - 1)]; } } } void PerLabelVoxelSampler_CPU::calculate_voxel_masks(const ITMFloat4Image *raycastResult, const SpaintVoxel *voxelData, const ITMVoxelIndex::IndexData *indexData) const { const Vector4f *raycastResultData = raycastResult->GetData(MEMORYDEVICE_CPU); unsigned char *voxelMasks = m_voxelMasksMB->GetData(MEMORYDEVICE_CPU); #ifdef WITH_OPENMP #pragma omp parallel for #endif for(int voxelIndex = 0; voxelIndex < m_raycastResultSize; ++voxelIndex) { // Update the voxel masks based on the contents of the voxel. update_masks_for_voxel( voxelIndex, raycastResultData, m_raycastResultSize, voxelData, indexData, m_maxLabelCount, voxelMasks ); } } void PerLabelVoxelSampler_CPU::write_candidate_voxel_counts(const ORUtils::MemoryBlock<bool>& labelMaskMB, ORUtils::MemoryBlock<unsigned int>& voxelCountsForLabelsMB) const { const bool *labelMask = labelMaskMB.GetData(MEMORYDEVICE_CPU); const unsigned int *voxelMaskPrefixSums = m_voxelMaskPrefixSumsMB->GetData(MEMORYDEVICE_CPU); unsigned int *voxelCountsForLabels = voxelCountsForLabelsMB.GetData(MEMORYDEVICE_CPU); #ifdef WITH_OPENMP #pragma omp parallel for #endif for(int k = 0; k < static_cast<int>(m_maxLabelCount); ++k) { write_candidate_voxel_count(k, m_raycastResultSize, labelMask, voxelMaskPrefixSums, voxelCountsForLabels); } } void PerLabelVoxelSampler_CPU::write_candidate_voxel_locations(const ITMFloat4Image *raycastResult) const { const Vector4f *raycastResultData = raycastResult->GetData(MEMORYDEVICE_CPU); const unsigned char *voxelMasks = m_voxelMasksMB->GetData(MEMORYDEVICE_CPU); const unsigned int *voxelMaskPrefixSums = m_voxelMaskPrefixSumsMB->GetData(MEMORYDEVICE_CPU); Vector3s *candidateVoxelLocations = m_candidateVoxelLocationsMB->GetData(MEMORYDEVICE_CPU); #ifdef WITH_OPENMP #pragma omp parallel for #endif for(int voxelIndex = 0; voxelIndex < m_raycastResultSize; ++voxelIndex) { write_candidate_voxel_location( voxelIndex, raycastResultData, m_raycastResultSize, voxelMasks, voxelMaskPrefixSums, m_maxLabelCount, candidateVoxelLocations ); } } void PerLabelVoxelSampler_CPU::write_sampled_voxel_locations(const ORUtils::MemoryBlock<bool>& labelMaskMB, ORUtils::MemoryBlock<Vector3s>& sampledVoxelLocationsMB) const { const Vector3s *candidateVoxelLocations = m_candidateVoxelLocationsMB->GetData(MEMORYDEVICE_CPU); const int *candidateVoxelIndices = m_candidateVoxelIndicesMB->GetData(MEMORYDEVICE_CPU); const bool *labelMask = labelMaskMB.GetData(MEMORYDEVICE_CPU); Vector3s *sampledVoxelLocations = sampledVoxelLocationsMB.GetData(MEMORYDEVICE_CPU); #ifdef WITH_OPENMP #pragma omp parallel for #endif for(int voxelIndex = 0; voxelIndex < static_cast<int>(m_maxVoxelsPerLabel); ++voxelIndex) { copy_sampled_voxel_locations( voxelIndex, labelMask, m_maxLabelCount, m_maxVoxelsPerLabel, m_raycastResultSize, candidateVoxelLocations, candidateVoxelIndices, sampledVoxelLocations ); } } }
4,798
1,759
#ifndef FBi_XMLRPC_UTILITY_HPP #define FBi_XMLRPC_UTILITY_HPP #include <xmlrpc_server/libxmlrpc_server_config.h> namespace FBi { /// The utility class for XMLRPC. class LIBXMLRPCSERVER_DECL XMLRPC_Utility { public: /** * @brief Function to get the default error string of XMLRPC. * * @param[in] error_code The default error code of XMLRPC. * @return The default error string correspond with the input error code. */ static std::string GetXMLRPCErrorString(int error_code) { switch(error_code) { case -32700: return "Parse error. not well formed. "; case -32701: return "Parse error. unsupported encoding. "; case -32702: return "Parse error. invalid character for encoding. "; case -32600: return "Server error. invalid xml-rpc. not conforming to spec. "; case -32601: return "Server error. requested method not found. "; case -32602: return "Server error. invalid method parameters. "; case -32603: return "Server error. internal xml-rpc error. "; case -32500: return "Application error. "; case -32400: return "System error. "; case -32300: return "Transport error. "; default: return ""; } } }; } #endif
1,189
474
#include "position.hpp" #include <iostream> #include <regex> uint32_t Position::parse(const std::string &str) { const std::regex re("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$"); std::smatch match; if (!std::regex_match(str, match, re)) { throw std::runtime_error("Could not parse string"); } const uint32_t bar = atoi(match.str(1).c_str()); const uint8_t beat = atoi(match.str(2).c_str()); const uint8_t sixteenths = atoi(match.str(3).c_str()); const uint8_t ticks = atoi(match.str(4).c_str()); return ticksFromPosition(bar, beat, sixteenths, ticks); } std::string Position::toString() const { std::ostringstream oss; oss << "Position(" << (uint32_t)bar << "." << (uint32_t)beat << "." << (uint32_t)sixteenths << "." << (uint32_t)ticks << ")"; return oss.str(); } std::ostream & operator<<(std::ostream &out, const Position &position) { return out << position.toString(); } void Position::update(const float &bpm, const float &sampleRate) { const double ticksPerSecond = (bpm * 4.0 * 240.0) / 60.0; recalculate(_totalTicks + ticksPerSecond / sampleRate); } void Position::recalculate(double newTicks) { uint32_t previousTicks = _totalTicks; _totalTicks = newTicks; uint32_t tmp = newTicks; ticks = tmp % 240; tmp /= 240; sixteenths = tmp % 4; tmp /= 4; beat = tmp % 4; bar = tmp / 4; _ticksChanged = static_cast<uint32_t>(_totalTicks) != previousTicks; }
1,401
592
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include "Core/Shader.h" #include "Camera/CenteredCamera.h" #include "Model.h" #include "Light.h" #include "Models/Lamp.h" #include "Models/Cube.h" #include "Models/Tetrahedron.h" #include "Models/Piramid.h" #include "Models/Sphere.h" #include "Models/ModelImporter.h" void global_config(); void framebuffer_size_callback(GLFWwindow* glfWwindow, int width, int height); void mouse_callback(GLFWwindow* glfWwindow, double xpos, double ypos); void scroll_callback(GLFWwindow* glfWwindow, double xoffset, double yoffset); void processInput(); void renderModel(); const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; GLFWwindow* window; float lastX = SCR_WIDTH / 2.0f; float lastY = SCR_HEIGHT / 2.0f; bool firstMouse = true; //Camera CenteredCamera camera(glm::vec3(0.0f, 0.0f, 0.0f)); //lighting Light *currLightN, *currLightM; glm::vec3 lightPos1(0.00001f, -4.0f, 0.0f); glm::vec3 lightPos2(0.00001f, 0.0f, -4.0f); Light l1s[4], l2s[4]; //lights and camera movement parameters float deltaTime = 0.0f; // Time between current frame and last frame float lastFrame = 0.0f; // Time of last frame //state machine bool firstChangeModel = true; bool firstChangeShader = true; bool firstChangeLightN = true; bool firstChangeLightM = true; int modelRendered = 0; int shaderRendered = 0; int lightRenderedN = 0; int lightRenderedM = 0; //models Sphere sphere; Cube cube; Piramid piramid; Tetrahedron tet; ModelImporter sword; //Shaders Shader* currShader; Shader phongShader; Shader normalMapShader; Shader toonShader; Shader shaders[3]; //project-view matrices glm::mat4 view; glm::mat4 projection; int main() { global_config(); sphere = Sphere(glm::vec3(0.0,0.0,0.0)); cube = Cube(glm::vec3(0.0,0.0,0.0)); piramid = Piramid(glm::vec3(0.0,0.0,0.0)); tet = Tetrahedron(glm::vec3(0.0,0.0,0.0)); std::string path = "../resources/suzanne.obj"; sword = ModelImporter(glm::vec3(0.0f,0.0f,0.0f),path); phongShader = Shader("../src/shaders/phong.vert", "../src/shaders/phong.frag"); normalMapShader = Shader("../src/shaders/normalMapping.vert", "../src/shaders/normalMapping.frag"); toonShader = Shader("../src/shaders/toon.vert", "../src/shaders/toon.frag"); shaders[0] = phongShader; shaders[1] = normalMapShader; shaders[2] = toonShader; Texture text = Texture("../resources/tex.jpg",0,GL_RGB); sphere.addTexture(text,"normalMap"); cube.addTexture(text,"normalMap"); piramid.addTexture(text,"normalMap"); tet.addTexture(text,"normalMap"); sword.addTexture(text,"normalMap"); currShader = &shaders[shaderRendered]; sphere.setShader(*currShader); cube.setShader(*currShader); piramid.setShader(*currShader); tet.setShader(*currShader); sword.setShader(*currShader); Lamp lamp1 = Lamp(lightPos1); Shader lampShader1 = Shader("../src/shaders/vertex.vert", "../src/shaders/brightShader.frag"); lamp1.setShader(lampShader1); Lamp lamp2 = Lamp(lightPos2); Shader lampShader2 = Shader("../src/shaders/vertex.vert", "../src/shaders/brightShader.frag"); lamp2.setShader(lampShader2); l1s[0] = Light(glm::vec3(1.0,1.0,1.0),glm::vec3(0.2f, 0.2f, 0.2f),glm::vec3(0.5f, 0.5f, 0.5f),glm::vec3(0.9f,0.9f,0.9f)); l1s[1] = Light(glm::vec3(0.0,0.0,1.0),glm::vec3(0.0f, 0.0f, 0.2f),glm::vec3(0.0f, 0.0f, 0.5f),glm::vec3(0.0f,0.0f,0.9f)); l1s[2] = Light(glm::vec3(1.0,0.0,0.0),glm::vec3(0.2f, 0.0f, 0.0f),glm::vec3(0.5f, 0.0f, 0.0f),glm::vec3(0.9f,0.0f,0.0f)); l1s[3] = Light(glm::vec3(0.0,1.0,0.0),glm::vec3(0.0f, 0.2f, 0.0f),glm::vec3(0.0f, 0.5f, 0.0f),glm::vec3(0.0f,0.9f,0.0f)); l2s[0] = Light(glm::vec3(1.0,1.0,1.0),glm::vec3(0.2f, 0.2f, 0.2f),glm::vec3(0.5f, 0.5f, 0.5f),glm::vec3(0.9f,0.9f,0.9f)); l2s[1] = Light(glm::vec3(0.0,0.0,1.0),glm::vec3(0.0f, 0.0f, 0.2f),glm::vec3(0.0f, 0.0f, 0.5f),glm::vec3(0.0f,0.0f,0.9f)); l2s[2] = Light(glm::vec3(1.0,0.0,0.0),glm::vec3(0.2f, 0.0f, 0.0f),glm::vec3(0.5f, 0.0f, 0.0f),glm::vec3(0.9f,0.0f,0.0f)); l2s[3] = Light(glm::vec3(0.0,1.0,0.0),glm::vec3(0.0f, 0.2f, 0.0f),glm::vec3(0.0f, 0.5f, 0.0f),glm::vec3(0.0f,0.9f,0.0f)); currLightN = &l1s[0]; currLightM = &l2s[0]; while(!glfwWindowShouldClose(window)){ float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; processInput(); //glClearColor(0.0f, 0.4f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); lamp1.setPos(lightPos1); lamp2.setPos(lightPos2); projection = glm::mat4(1.0f); projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.2f, 100.0f); view = camera.GetViewMatrix(); renderModel(); lamp1.bind(); lampShader1.setVec3("lightColor", currLightN->color); lamp1.draw(view, projection); lamp1.unbind(); lamp2.bind(); lampShader2.setVec3("lightColor", currLightM->color); lamp2.draw(view, projection); lamp2.unbind(); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } void processInput(){ float cameraSpeed = 1.0f * deltaTime; float lightSpeed = 1.0f * deltaTime; if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera.ProcessKeyboard(ROLL_OUT, cameraSpeed); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.ProcessKeyboard(ROLL_IN, cameraSpeed); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.ProcessKeyboard(LEFT, cameraSpeed); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.ProcessKeyboard(RIGHT, cameraSpeed); if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) camera.ProcessKeyboard(FORWARD, cameraSpeed); if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) camera.ProcessKeyboard(BACKWARD, cameraSpeed); if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS){ float prevAngle = atan2(lightPos1.y,lightPos1.x); float rad = glm::length(glm::vec2(lightPos1.x,lightPos1.y)); lightPos1.x = rad*cos(prevAngle-lightSpeed); lightPos1.y = rad*sin(prevAngle-lightSpeed); } if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS){ float prevAngle = atan2(lightPos1.y,lightPos1.x); float rad = glm::length(glm::vec2(lightPos1.x,lightPos1.y)); lightPos1.x = rad*cos(prevAngle+lightSpeed); lightPos1.y = rad*sin(prevAngle+lightSpeed); } if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS){ float prevAngle = atan2(lightPos2.z,lightPos2.x); float rad = glm::length(glm::vec2(lightPos2.x,lightPos2.z)); lightPos2.x = rad*cos(prevAngle-lightSpeed); lightPos2.z = rad*sin(prevAngle-lightSpeed); } if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS){ float prevAngle = atan2(lightPos2.z,lightPos2.x); float rad = glm::length(glm::vec2(lightPos2.x,lightPos2.z)); lightPos2.x = rad*cos(prevAngle+lightSpeed); lightPos2.z = rad*sin(prevAngle+lightSpeed); } if (glfwGetKey(window, GLFW_KEY_T) == GLFW_PRESS){ if(firstChangeModel) { modelRendered=(modelRendered+1)%5; firstChangeModel = false; } }else{ firstChangeModel = true; } if (glfwGetKey(window, GLFW_KEY_P) == GLFW_PRESS){ if(firstChangeShader) { shaderRendered=(shaderRendered+1)%3; firstChangeShader = false; currShader = &shaders[shaderRendered]; } }else{ firstChangeShader = true; } if (glfwGetKey(window, GLFW_KEY_N) == GLFW_PRESS){ if(firstChangeLightN) { lightRenderedN = (lightRenderedN+1)%4; firstChangeLightN = false; currLightN = &l1s[lightRenderedN]; } }else{ firstChangeLightN = true; } if (glfwGetKey(window, GLFW_KEY_M) == GLFW_PRESS){ if(firstChangeLightM) { lightRenderedM = (lightRenderedM+1)%4; firstChangeLightM = false; currLightM = &l2s[lightRenderedM]; } }else{ firstChangeLightM = true; } if(glfwGetKey(window, GLFW_KEY_RIGHT_BRACKET) == GLFW_PRESS){ // pluss in latinamerican spanish keyboard camera.ProcessMouseScroll(0.05); } if(glfwGetKey(window, GLFW_KEY_SLASH) == GLFW_PRESS){ // minnus in latinamerican spanish keyboard camera.ProcessMouseScroll(-0.05); } } void framebuffer_size_callback(GLFWwindow* glfWwindow, int width, int height){ glViewport(0, 0, width, height); } void mouse_callback(GLFWwindow* glfWwindow, double xpos, double ypos){ if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; camera.ProcessMouseMovement(xoffset, yoffset); } void scroll_callback(GLFWwindow* glfWwindow, double xoffset, double yoffset){ camera.ProcessMouseScroll(yoffset); } void global_config(){ //glfw window initialization glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Tarea2GPU", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); exit(-1); } glfwMakeContextCurrent(window); if (glewInit()!=GLEW_OK) { std::cout << "Failed to initialize GLEW" << std::endl; exit(-1); } //viewport and callbacks setting glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_ENABLED); glEnable(GL_DEPTH_TEST); //texture wrapping / filtering / mipmapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //uncoment for debugging models //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } void renderModel(){ currShader->use(); currShader->setVec3("material.ambient", 0.5f, 0.25f, 0.15f); currShader->setVec3("material.diffuse", 1.0f, 0.5f, 0.31f); currShader->setVec3("material.specular", 0.5f, 0.5f, 0.5f); currShader->setFloat("material.shininess", 64.0f); currShader->setVec3("lights[0].color", currLightN->color); currShader->setVec3("lights[0].position", lightPos1); currShader->setVec3("lights[0].ambient", currLightN->ambient); currShader->setVec3("lights[0].diffuse", currLightN->diffuse); currShader->setVec3("lights[0].specular", currLightN->specular); currShader->setVec3("lights[1].color", currLightM->color); currShader->setVec3("lights[1].position", lightPos2); currShader->setVec3("lights[1].ambient", currLightM->ambient); currShader->setVec3("lights[1].diffuse", currLightM->diffuse); currShader->setVec3("lights[1].specular", currLightM->specular); currShader->setVec3("viewPos", camera.getCameraPosition().x,camera.getCameraPosition().y,camera.getCameraPosition().z); if(modelRendered == 1){ sword.setShader(*currShader); sword.bind(); sword.draw(view, projection); sword.unbind(); } if(modelRendered == 0){ sphere.setShader(*currShader); sphere.bind(); sphere.draw(view, projection); sphere.unbind(); } if(modelRendered == 2){ cube.setShader(*currShader); cube.bind(); cube.draw(view, projection); cube.unbind(); } if(modelRendered == 3){ piramid.setShader(*currShader); piramid.bind(); piramid.draw(view, projection); piramid.unbind(); } if(modelRendered == 4){ tet.setShader(*currShader); tet.bind(); tet.draw(view, projection); tet.unbind(); } }
12,888
5,307