hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
8323f883b17865a60856aa732d5400f81d3ac8f5
7,031
cpp
C++
TabGraph/src/Surface/SphereMesh.cpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
1
2020-08-28T09:35:18.000Z
2020-08-28T09:35:18.000Z
TabGraph/src/Surface/SphereMesh.cpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
null
null
null
TabGraph/src/Surface/SphereMesh.cpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
1
2020-10-08T11:21:13.000Z
2020-10-08T11:21:13.000Z
/* * @Author: gpinchon * @Date: 2020-07-28 00:01:40 * @Last Modified by: gpinchon * @Last Modified time: 2020-08-09 11:38:44 */ #include "Surface/SphereMesh.hpp" #include "Material/Material.hpp" #include "Surface/Geometry.hpp" #include "Surface/Mesh.hpp" #include <map> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif std::map<int64_t, unsigned> middlePointIndexCache; glm::vec2 FindUV(const glm::vec3& normal) { glm::vec2 uv; const float& x = normal.x; const float& y = normal.y; const float& z = normal.z; float normalisedX = 0; float normalisedZ = -1; if (((x * x) + (z * z)) > 0) { normalisedX = sqrt((x * x) / ((x * x) + (z * z))); if (x < 0) { normalisedX = -normalisedX; } normalisedZ = sqrt((z * z) / ((x * x) + (z * z))); if (z < 0) { normalisedZ = -normalisedZ; } } if (normalisedZ == 0) { uv.x = ((normalisedX * M_PI) / 2); } else { uv.x = atan(normalisedX / normalisedZ); if (normalisedX < 0) { uv.x = M_PI - uv.x; } if (normalisedZ < 0) { uv.x += M_PI; } } if (uv.x < 0) { uv.x += 2 * M_PI; } uv.x /= 2 * M_PI; uv.y = (-y + 1) / 2; return uv; } unsigned getMiddlePoint(unsigned p1, unsigned p2, std::vector<glm::vec3>& positions) { // first check if we have it already bool firstIsSmaller = p1 < p2; int64_t smallerIndex = firstIsSmaller ? p1 : p2; int64_t greaterIndex = firstIsSmaller ? p2 : p1; auto key = (smallerIndex << 32) + greaterIndex; if (middlePointIndexCache.count(key) > 0) { return middlePointIndexCache[key]; } // not in cache, calculate it glm::vec3 point1 = positions.at(p1); glm::vec3 point2 = positions.at(p2); glm::vec3 middle = glm::vec3( (point1.x + point2.x) / 2.0, (point1.y + point2.y) / 2.0, (point1.z + point2.z) / 2.0); // add vertex makes sure point is on unit sphere positions.push_back(normalize(middle)); auto i = positions.size() - 1; // store it, return index middlePointIndexCache[key] = i; return i; } std::shared_ptr<Geometry> SphereMesh::CreateGeometry(const std::string& name, float radius, unsigned subdivision) { const float t = (1.0 + std::sqrt(5.0)) / 2.0; std::vector<glm::vec3> sphereVertices; sphereVertices.push_back(normalize(glm::vec3(-1.0, t, 0.0))); sphereVertices.push_back(normalize(glm::vec3(1.0, t, 0.0))); sphereVertices.push_back(normalize(glm::vec3(-1.0, -t, 0.0))); sphereVertices.push_back(normalize(glm::vec3(1.0, -t, 0.0))); sphereVertices.push_back(normalize(glm::vec3(0.0, -1.0, t))); sphereVertices.push_back(normalize(glm::vec3(0.0, 1.0, t))); sphereVertices.push_back(normalize(glm::vec3(0.0, -1.0, -t))); sphereVertices.push_back(normalize(glm::vec3(0.0, 1.0, -t))); sphereVertices.push_back(normalize(glm::vec3(t, 0.0, -1.0))); sphereVertices.push_back(normalize(glm::vec3(t, 0.0, 1.0))); sphereVertices.push_back(normalize(glm::vec3(-t, 0.0, -1.0))); sphereVertices.push_back(normalize(glm::vec3(-t, 0.0, 1.0))); std::vector<std::array<unsigned, 3>> faces; // 5 faces around point 0 faces.push_back({ 0, 11, 5 }); faces.push_back({ 0, 5, 1 }); faces.push_back({ 0, 1, 7 }); faces.push_back({ 0, 7, 10 }); faces.push_back({ 0, 10, 11 }); // 5 adjacent faces faces.push_back({ 1, 5, 9 }); faces.push_back({ 5, 11, 4 }); faces.push_back({ 11, 10, 2 }); faces.push_back({ 10, 7, 6 }); faces.push_back({ 7, 1, 8 }); // 5 faces around point 3 faces.push_back({ 3, 9, 4 }); faces.push_back({ 3, 4, 2 }); faces.push_back({ 3, 2, 6 }); faces.push_back({ 3, 6, 8 }); faces.push_back({ 3, 8, 9 }); // 5 adjacent faces faces.push_back({ 4, 9, 5 }); faces.push_back({ 2, 4, 11 }); faces.push_back({ 6, 2, 10 }); faces.push_back({ 8, 6, 7 }); faces.push_back({ 9, 8, 1 }); for (unsigned i = 0; i < subdivision; ++i) { std::vector<std::array<unsigned, 3>> faces2; for (const auto& tri : faces) { // replace triangle by 4 triangles auto a = getMiddlePoint(tri[0], tri[1], sphereVertices); auto b = getMiddlePoint(tri[1], tri[2], sphereVertices); auto c = getMiddlePoint(tri[2], tri[0], sphereVertices); faces2.push_back({ tri[0], a, c }); faces2.push_back({ tri[1], b, a }); faces2.push_back({ tri[2], c, b }); faces2.push_back({ a, b, c }); } faces = faces2; } middlePointIndexCache.clear(); std::vector<glm::vec3> sphereNormals; std::vector<glm::vec2> sphereTexCoords; for (auto& v : sphereVertices) { sphereNormals.push_back(v); sphereTexCoords.push_back(FindUV(v)); v *= radius; } std::vector<unsigned> sphereIndices; for (const auto& tri : faces) { sphereIndices.push_back(tri[0]); sphereIndices.push_back(tri[1]); sphereIndices.push_back(tri[2]); } /*auto verticesBuffer{ Component::Create<Buffer>( sphereVertices.size() * sizeof(glm::vec3) + sphereNormals.size() * sizeof(glm::vec3) + sphereTexCoords.size() * sizeof(glm::vec2) ) };*/ /*verticesBuffer->Set( (std::byte*)sphereVertices.data(), 0, sphereVertices.size() * sizeof(glm::vec3)); verticesBuffer->Set( (std::byte*)sphereNormals.data(), sphereVertices.size() * sizeof(glm::vec3), sphereNormals.size() * sizeof(glm::vec3)); verticesBuffer->Set((std::byte*)sphereTexCoords.data(), sphereVertices.size() * sizeof(glm::vec3) + sphereNormals.size() * sizeof(glm::vec3), sphereTexCoords.size() * sizeof(glm::vec2)); auto vg = Component::Create<Geometry>(name); vg->SetAccessor(Geometry::AccessorKey::Position, BufferHelper::CreateAccessor(sphereVertices, GL_ARRAY_BUFFER)); vg->SetAccessor(Geometry::AccessorKey::Normal, BufferHelper::CreateAccessor(sphereNormals, GL_ARRAY_BUFFER, true)); vg->SetAccessor(Geometry::AccessorKey::TexCoord_0, BufferHelper::CreateAccessor(sphereTexCoords, GL_ARRAY_BUFFER)); vg->SetIndices(BufferHelper::CreateAccessor(sphereIndices, GL_ELEMENT_ARRAY_BUFFER));*/ auto vg = Component::Create<Geometry>(sphereVertices, sphereNormals, sphereTexCoords, sphereIndices); return vg; } std::shared_ptr<Mesh> SphereMesh::Create(const std::string& name, float radius, unsigned subdivision) { auto m = Component::Create<Mesh>(name); m->AddGeometry( SphereMesh::CreateGeometry(name + "Geometry", radius, subdivision), Component::Create<Material>(name + "Material") ); return (m); }
35.510101
120
0.584127
[ "mesh", "geometry", "vector" ]
832e7166261c910589cd159f7b3d664584f50933
42,179
cpp
C++
Nailang/NailangParser.cpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
18
2018-10-22T10:30:20.000Z
2021-12-10T06:29:39.000Z
Nailang/NailangParser.cpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
null
null
null
Nailang/NailangParser.cpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
4
2019-06-04T14:04:43.000Z
2021-07-16T01:41:48.000Z
#include "NailangPch.h" #include "NailangParser.h" #include "NailangParserRely.h" #include "SystemCommon/StringFormat.h" #include <boost/container/small_vector.hpp> namespace xziar::nailang { using tokenizer::NailangToken; void DoThrow() { throw NailangPartedNameException(u"a", U"b", U"c"); } std::u16string NailangParser::DescribeTokenID(const uint16_t tid) const noexcept { #define RET_TK_ID(type) case NailangToken::type: return u ## #type switch (static_cast<NailangToken>(tid)) { RET_TK_ID(Raw); RET_TK_ID(Block); RET_TK_ID(MetaFunc); RET_TK_ID(Func); RET_TK_ID(Var); RET_TK_ID(SubField); RET_TK_ID(OpSymbol); RET_TK_ID(Parenthese); RET_TK_ID(SquareBracket); RET_TK_ID(CurlyBrace); RET_TK_ID(Assign); #undef RET_TK_ID default: return ParserBase::DescribeTokenID(tid); } } common::str::StrVariant<char16_t> NailangParser::GetCurrentFileName() const noexcept { if (SubScopeName.empty()) return ParserBase::GetCurrentFileName(); std::u16string fileName; fileName.reserve(Context.SourceName.size() + SubScopeName.size() + 3); fileName.append(Context.SourceName).append(u" ["sv).append(SubScopeName).append(u"]"); return fileName; } void NailangParser::HandleException(const NailangParseException& ex) const { auto& info = ex.GetInfo(); info.File = GetCurrentFileName().StrView(); if (info.Position.first == 0 && info.Position.second == 0) info.Position = { Context.Row + 1, Context.Col }; if (ex.GetDetailMessage().empty()) ex.Attach("detail", FMTSTR(u"at row[{}] col[{}], file [{}]", info.Position.first, info.Position.second, info.File)); ex.ThrowSelf(); } #define NLPS_THROW_EX(...) HandleException(CREATE_EXCEPTION(NailangParseException, __VA_ARGS__)) common::parser::DetailToken NailangParser::OnUnExpectedToken(const common::parser::DetailToken& token, const std::u16string_view extraInfo) const { const auto msg = fmt::format(FMT_STRING(u"Unexpected token [{}] at [{},{}]{}{}"sv), DescribeToken(token), token.Row, token.Col, extraInfo.empty() ? u' ' : u',', extraInfo); HandleException(UnexpectedTokenException(msg, token)); return token; } struct ExpectParentheseL { static constexpr ParserToken Token = ParserToken(NailangToken::Parenthese, U'('); }; struct ExpectParentheseR { static constexpr ParserToken Token = ParserToken(NailangToken::Parenthese, U')'); }; struct ExpectCurlyBraceL { static constexpr ParserToken Token = ParserToken(NailangToken::CurlyBrace, U'{'); }; struct ExpectCurlyBraceR { static constexpr ParserToken Token = ParserToken(NailangToken::CurlyBrace, U'}'); }; struct ExpectSemoColon { static constexpr ParserToken Token = ParserToken(BaseToken::Delim, U';'); }; void NailangParser::EatLeftParenthese() { EatSingleToken<ExpectParentheseL, tokenizer::ParentheseTokenizer>(); } void NailangParser::EatRightParenthese() { EatSingleToken<ExpectParentheseR, tokenizer::ParentheseTokenizer>(); } void NailangParser::EatLeftCurlyBrace() { EatSingleToken<ExpectCurlyBraceL, tokenizer::CurlyBraceTokenizer>(); } void NailangParser::EatRightCurlyBrace() { EatSingleToken<ExpectCurlyBraceR, tokenizer::CurlyBraceTokenizer>(); } void NailangParser::EatSemiColon() { using SemiColonTokenizer = tokenizer::KeyCharTokenizer<true, BaseToken::Delim, U';'>; EatSingleToken<ExpectSemoColon, SemiColonTokenizer>(); } FuncName* NailangParser::CreateFuncName(std::u32string_view name, FuncName::FuncInfo info) const { info = FuncName::PrepareFuncInfo(name, info); if (name.empty()) NLPS_THROW_EX(u"Does not allow empty function name"sv); try { return FuncName::Create(MemPool, name, info); } catch (const NailangPartedNameException&) { HandleException(NailangParseException(u"FuncCall's name not valid"sv)); } return nullptr; } void NailangParser::FillBlockName(RawBlock& block) { using common::parser::detail::TokenMatcherHelper; using common::parser::detail::EmptyTokenArray; constexpr auto ExpectString = TokenMatcherHelper::GetMatcher(EmptyTokenArray{}, BaseToken::String); EatLeftParenthese(); constexpr auto NameLexer = ParserLexerBase<CommentTokenizer, StringTokenizer>(); const auto sectorNameToken = ExpectNextToken(NameLexer, IgnoreBlank, IgnoreCommentToken, ExpectString); block.Name = sectorNameToken.GetString(); EatRightParenthese(); } void NailangParser::FillFileName(RawBlock& block) const noexcept { block.FileName = Context.SourceName; } FuncCall NailangParser::ParseFuncCall(std::u32string_view name, std::pair<uint32_t, uint32_t> pos, FuncName::FuncInfo info) { const auto funcName = CreateFuncName(name, info); EatLeftParenthese(); std::vector<Expr> args; while (true) { const auto [arg, delim] = ParseExpr(",)"sv); if (arg) args.emplace_back(arg); else if (delim != U')') NLPS_THROW_EX(u"Does not allow empty argument"sv); if (delim == U')') break; if (delim == common::parser::special::CharEnd) NLPS_THROW_EX(u"Expect ')' before reaching end"sv); } const auto sp = MemPool.CreateArray(args); return { funcName, sp, pos }; } RawBlock NailangParser::ParseRawBlock(const std::u32string_view name, std::pair<uint32_t, uint32_t> pos) { RawBlock block; block.Position = pos; block.Type = name; FillBlockName(block); EatLeftCurlyBrace(); ContextReader reader(Context); auto guardString = std::u32string(reader.ReadLine()); FillFileName(block); guardString.append(U"}"); block.Source = reader.ReadUntil(guardString); block.Source.remove_suffix(guardString.size()); return block; } struct ExprOp { uint32_t Val = UINT32_MAX; [[nodiscard]] constexpr explicit operator bool() const noexcept { return Val != UINT32_MAX; } [[nodiscard]] constexpr EmbedOps GetEmbedOp() const noexcept { Expects(Val <= 255); return static_cast<EmbedOps>(Val); } [[nodiscard]] constexpr ExtraOps GetExtraOp() const noexcept { Expects(Val >= 256 && Val <= 383); return static_cast<ExtraOps>(Val); } [[nodiscard]] constexpr AssignOps GetAssignOp() const noexcept { Expects(Val >= 384 && Val <= 511); return static_cast<AssignOps>(Val); } template<typename T> [[nodiscard]] constexpr bool operator==(T val) const noexcept { static_assert(std::is_enum_v<T>); return Val == common::enum_cast(val); } template<typename T> [[nodiscard]] constexpr bool operator!=(T val) const noexcept { static_assert(std::is_enum_v<T>); return Val != common::enum_cast(val); } constexpr void operator=(uint64_t val) noexcept { Val = static_cast<uint32_t>(val); } enum class Category : uint32_t { Binary = 0, Unary = 1, Ternary = 2, Assign = 3, Empty }; [[nodiscard]] static constexpr Category ParseCategory(uint32_t val) noexcept { return static_cast<Category>(std::min(val >> 7, 4u)); } [[nodiscard]] constexpr Category GetCategory() const noexcept { return ParseCategory(Val); } }; [[nodiscard]] static constexpr bool CheckExprLiteral(const Expr& opr) { switch (opr.TypeData) { case Expr::Type::Query: case Expr::Type::Func: case Expr::Type::Unary: case Expr::Type::Binary: case Expr::Type::Var: return false; default: // including assign since should not be here return true; } } struct ExprStack { struct ExprFrame { Expr Vals[2]; ExprOp Op; uint8_t OprIdx = 0; }; MemoryPool& Pool; boost::container::small_vector<ExprFrame, 4> Stack; boost::container::small_vector<Expr, 4> Queries; Expr* TargetExpr = nullptr; // insert new frame always causes a flush, or the expr is in pool, so safe to use ptr QueryExpr::QueryType QType = QueryExpr::QueryType::Index; ExprStack(MemoryPool& pool) : Pool(pool) { } void DoCommitQuery() { Expects(TargetExpr && *TargetExpr); const auto sp = Pool.CreateArray(Queries); *TargetExpr = Pool.Create<QueryExpr>(*TargetExpr, sp, QType); Queries.clear(); } [[nodiscard]] bool PrecheckQuery() const noexcept { Expects(TargetExpr); if (Queries.empty()) // first query { Expects(*TargetExpr); return !CheckExprLiteral(*TargetExpr); } return true; } void PushSubField(std::u32string_view subField) { Expects(TargetExpr); if (!Queries.empty() && QType != QueryExpr::QueryType::Sub) DoCommitQuery(); Queries.emplace_back(subField); QType = QueryExpr::QueryType::Sub; } void PushIndexer(const Expr& indexer) { Expects(TargetExpr); if (!Queries.empty() && QType != QueryExpr::QueryType::Index) DoCommitQuery(); Queries.emplace_back(indexer); QType = QueryExpr::QueryType::Index; } void CommitQuery() { if (!Queries.empty()) DoCommitQuery(); } [[nodiscard]] std::u16string_view CheckExpr() const { if (Stack.empty()) return {}; const auto& frame = Stack.back(); if (!Queries.empty()) return u"need an operator before another operand"sv; switch (frame.Op.GetCategory()) { case ExprOp::Category::Empty: Expects(frame.OprIdx == 1); return u"need an operator before another operand"sv; case ExprOp::Category::Unary: if (frame.OprIdx > 0) return u"already has 1 operand for unary operator"sv; break; case ExprOp::Category::Binary: if (frame.OprIdx > 1) return u"already has 2 operands for binary operator"sv; Expects(frame.OprIdx == 1); break; case ExprOp::Category::Ternary: if (frame.Op == ExtraOps::Quest) { if (frame.OprIdx > 1) return u"expect ':' before 3rd operand for ternary operator"sv; Expects(frame.OprIdx == 1); break; } else { if (frame.OprIdx > 2) return u"already has 3 operands for ternary operator"sv; Expects(frame.Op == ExtraOps::Colon && frame.OprIdx == 2); break; } default: Expects(false); } return {}; } void CommitExpr(Expr expr) { auto updExpr = [&, upd = true](Expr* target) mutable { if (upd) TargetExpr = target, upd = false; }; while (true) { if (Stack.empty()) { auto& frame = Stack.emplace_back(); frame.Vals[0] = expr; frame.OprIdx = 1; updExpr(&frame.Vals[0]); return; } Expects(Stack.back().Op); auto& frame = Stack.back(); switch (frame.Op.GetCategory()) { case ExprOp::Category::Unary: { Expects(frame.OprIdx == 0); const auto texpr = Pool.Create<UnaryExpr>(frame.Op.GetEmbedOp(), expr); updExpr(&texpr->Operand); expr = texpr; Stack.pop_back(); } continue; case ExprOp::Category::Binary: { Expects(frame.OprIdx == 1); const auto texpr = Pool.Create<BinaryExpr>(frame.Op.GetEmbedOp(), frame.Vals[0], expr); updExpr(&texpr->RightOperand); expr = texpr; Stack.pop_back(); } continue; case ExprOp::Category::Ternary: if (frame.Op == ExtraOps::Quest) { Expects(frame.OprIdx == 1); auto& target = frame.Vals[frame.OprIdx++]; target = expr; updExpr(&target); return; } else { Expects(frame.Op == ExtraOps::Colon && frame.OprIdx == 2); const auto texpr = Pool.Create<TernaryExpr>(frame.Vals[0], frame.Vals[1], expr); updExpr(&texpr->RightOperand); expr = texpr; Stack.pop_back(); continue; } default: Expects(false); } } } [[nodiscard]] std::u16string_view AllocUnary(ExprOp op) { if (op == ExtraOps::Quest) op = common::enum_cast(EmbedOps::CheckExist); else if (op.GetCategory() != ExprOp::Category::Unary) return u"only unary operator allowed here"sv; auto& frame = Stack.emplace_back(); frame.Op = op; return {}; } [[nodiscard]] std::u16string_view CheckAssignOp() const { if (Stack.size() > 1) return u"assign operator not allowed in expr"sv; if (!TargetExpr) return u"expect an expr before assign operator"sv; Expects(!Stack.empty()); auto& frame = Stack.back(); if (frame.OprIdx != 1 || frame.Op) return u"assign operator not allowed in expr"sv; Expects(*TargetExpr); if (CheckExprLiteral(*TargetExpr)) return u"Assign should not follow a litteral type"sv; return {}; } [[nodiscard]] std::u16string_view DoCheckCommitOp(ExprOp op) { if (Stack.empty()) return AllocUnary(op); const auto cat = op.GetCategory(); auto& frame = Stack.back(); switch (frame.Op.GetCategory()) { case ExprOp::Category::Empty: Expects(frame.OprIdx == 1); // has 1 operand if (cat != ExprOp::Category::Binary && cat != ExprOp::Category::Ternary) return u"only binary/ternary operator allowed when there's already 1 operand"sv; CommitQuery(); frame.Op = op; // simply assign op break; case ExprOp::Category::Unary: Expects(frame.OprIdx == 0); // should be 0 operand return AllocUnary(op); case ExprOp::Category::Binary: Expects(frame.OprIdx == 1); // should be already 1 operand return AllocUnary(op); case ExprOp::Category::Ternary: { const uint8_t oprCnt = frame.Op == ExtraOps::Quest ? 1 : 2; if (frame.OprIdx == oprCnt) // waiting for an operand return AllocUnary(op); else // already has an operand { Expects(frame.OprIdx == oprCnt + 1); if (cat != ExprOp::Category::Binary && cat != ExprOp::Category::Ternary) return u"only binary/ternary operator allowed when there's already 1 operand"sv; CommitQuery(); if (op == ExtraOps::Colon) { if (frame.Op == ExtraOps::Quest) frame.Op = op; // simply assign op else return u"colon need to follow an existsing terary '?' operator"sv; } else { // move current to next level const auto expr = frame.Vals[--frame.OprIdx]; frame.Vals[frame.OprIdx] = {}; auto& newFrame = Stack.emplace_back(); newFrame.Op = op; newFrame.Vals[0] = expr; newFrame.OprIdx = 1; } } } break; default: Expects(false); } return {}; } [[nodiscard]] std::u16string_view CheckCommitOp(ExprOp op) { const auto ret = DoCheckCommitOp(op); TargetExpr = nullptr; return ret; } }; std::pair<Expr, char32_t> NailangParser::ParseExpr(std::string_view stopDelim, AssignPolicy policy) { using common::parser::detail::TokenMatcherHelper; using common::parser::detail::EmptyTokenArray; const DelimTokenizer StopTokenizer = stopDelim; const auto ArgLexer = ParserLexerBase<CommentTokenizer, DelimTokenizer, tokenizer::ParentheseTokenizer, tokenizer::NormalFuncPrefixTokenizer, StringTokenizer, IntTokenizer, FPTokenizer, BoolTokenizer, tokenizer::VariableTokenizer, tokenizer::OpSymbolTokenizer, tokenizer::SubFieldTokenizer, tokenizer::SquareBracketTokenizer>(StopTokenizer); const auto OpLexer = ParserLexerBase<CommentTokenizer, DelimTokenizer, tokenizer::OpSymbolTokenizer, tokenizer::SubFieldTokenizer, tokenizer::SquareBracketTokenizer>(StopTokenizer); ExprStack stack(MemPool); char32_t stopChar = common::parser::special::CharEnd; bool shouldContinue = true; while (shouldContinue) { auto token = stack.TargetExpr ? GetNextToken(OpLexer, IgnoreBlank, IgnoreCommentToken) : GetNextToken(ArgLexer, IgnoreBlank, IgnoreCommentToken); #define EID(id) common::enum_cast(id) switch (token.GetID()) { case EID(BaseToken::Unknown): case EID(BaseToken::Error): { OnUnExpectedToken(token, stack.TargetExpr ? u"expect an operator"sv : u"unknown or error token"sv); } break; case EID(BaseToken::Delim): case EID(BaseToken::End): { stopChar = token.GetChar(); shouldContinue = false; } break; case EID(NailangToken::Parenthese): { if (const auto err = stack.CheckExpr(); !err.empty()) OnUnExpectedToken(token, err); if (token.GetChar() == U')') OnUnExpectedToken(token, u"Unexpected right parenthese"sv); stack.CommitExpr(ParseExprChecked(")"sv, U")"sv)); } break; case EID(NailangToken::OpSymbol): { ExprOp op{ static_cast<uint32_t>(token.GetUInt()) }; if (op.GetCategory() == ExprOp::Category::Assign) { if (policy == AssignPolicy::Disallow) OnUnExpectedToken(token, u"does not allow assign operator here"sv); if (const auto err = stack.CheckAssignOp(); !err.empty()) OnUnExpectedToken(token, err); stack.CommitQuery(); Expects(stack.Stack.size() == 1 && stack.Stack.back().OprIdx == 1); const auto& opr = stack.Stack.back().Vals[0]; if (opr.TypeData != Expr::Type::Var) { if (policy == AssignPolicy::AllowVar) OnUnExpectedToken(token, FMTSTR(u"assign operator is only allowed after a var, get [{}]"sv, opr.GetTypeName())); if (op == AssignOps::NewCreate || op == AssignOps::NilAssign) OnUnExpectedToken(token, FMTSTR(u"NewCreate and NilAssign can only be applied after a var, get [{}]"sv, opr.GetTypeName())); } // direct construct AssignOp auto [stmt, ch] = ParseExpr(stopDelim); if (!stmt) NLPS_THROW_EX(u"Lack operand for assign expr"sv); using Behavior = NilCheck::Behavior; bool isSelfAssign = false; uint8_t info = 0; switch (op.GetAssignOp()) { case AssignOps::Assign: info = NilCheck(Behavior::Pass, Behavior::Pass).Value; break; case AssignOps::NewCreate: info = NilCheck(Behavior::Throw, Behavior::Pass).Value; break; case AssignOps::NilAssign: info = NilCheck(Behavior::Skip, Behavior::Pass).Value; break; #define SELF_ASSIGN(tname) case AssignOps::tname##Assign: isSelfAssign = true; info = common::enum_cast(EmbedOps::tname); break SELF_ASSIGN(Add); SELF_ASSIGN(Sub); SELF_ASSIGN(Mul); SELF_ASSIGN(Div); SELF_ASSIGN(Rem); SELF_ASSIGN(BitAnd); SELF_ASSIGN(BitOr); SELF_ASSIGN(BitXor); SELF_ASSIGN(BitShiftLeft); SELF_ASSIGN(BitShiftRight); #undef SELF_ASSIGN default: NLPS_THROW_EX(u"Unrecoginzied assign operator"sv); break; } return { MemPool.Create<AssignExpr>(opr, stmt, info, isSelfAssign), ch }; } if (const auto err = stack.CheckCommitOp(op); !err.empty()) OnUnExpectedToken(token, err); } break; case EID(NailangToken::SquareBracket): // Indexer { if (token.GetChar() == U']') OnUnExpectedToken(token, u"Unexpected right square bracket"sv); if (!stack.TargetExpr) OnUnExpectedToken(token, u"Indexer should follow a Expr"sv); if (!stack.PrecheckQuery()) OnUnExpectedToken(token, u"SubQuery should not follow a litteral type"sv); auto index = ParseExprChecked("]"sv, U"]"sv); if (!index) OnUnExpectedToken(token, u"lack of index"sv); stack.PushIndexer(index); } break; case EID(NailangToken::SubField): // SubField { if (!stack.TargetExpr) OnUnExpectedToken(token, u"SubField should follow a Expr"sv); if (!stack.PrecheckQuery()) OnUnExpectedToken(token, u"SubQuery should not follow a litteral type"sv); stack.PushSubField(token.GetString()); } break; default: { if (const auto err = stack.CheckExpr(); !err.empty()) OnUnExpectedToken(token, err); Expr expr; switch (token.GetID()) { case EID(BaseToken::Uint) : expr = token.GetUInt(); break; case EID(BaseToken::Int) : expr = token.GetInt(); break; case EID(BaseToken::FP) : expr = token.GetDouble(); break; case EID(BaseToken::Bool) : expr = token.GetBool(); break; case EID(NailangToken::Var) : expr = LateBindVar(token.GetString()); break; case EID(BaseToken::String) : expr = ProcessString(token.GetString(), MemPool); break; case EID(NailangToken::Func) : expr = MemPool.Create<FuncCall>(ParseFuncCall(token, FuncName::FuncInfo::ExprPart)); break; default: OnUnExpectedToken(token, u"Unrecognized token"sv); } stack.CommitExpr(expr); } break; } #undef EID } switch (stack.Stack.size()) { case 0: break; case 1: if (const auto& frame = stack.Stack.back(); frame.OprIdx == 1 && !frame.Op) { stack.CommitQuery(); return { frame.Vals[0], stopChar }; } [[fallthrough]]; default: NLPS_THROW_EX(u"Incomplete expr"sv); } return { {}, stopChar }; } Expr NailangParser::ParseExprChecked(std::string_view stopDelims, std::u32string_view stopChecker, AssignPolicy policy) { auto [arg, delim] = ParseExpr(stopDelims, policy); if (!stopChecker.empty() && stopChecker.find(delim) == std::u32string_view::npos) NLPS_THROW_EX(FMTSTR(u"Ends with unexpected delim [{}], expects [{}]", delim, stopChecker)); return arg; } void NailangParser::ParseContentIntoBlock(const bool allowNonBlock, Block& block, const bool tillTheEnd) { using common::parser::detail::TokenMatcherHelper; using common::parser::detail::EmptyTokenArray; std::vector<Statement> contents; std::vector<FuncCall> allMetaFuncs; std::vector<FuncCall> metaFuncs; const auto AppendMetaFuncs = [&]() -> std::pair<uint32_t, uint16_t> { const auto offset = gsl::narrow_cast<uint32_t>(allMetaFuncs.size()); const auto count = gsl::narrow_cast<uint16_t>( metaFuncs.size()); allMetaFuncs.reserve(static_cast<size_t>(offset) + count); std::move(metaFuncs.begin(), metaFuncs.end(), std::back_inserter(allMetaFuncs)); metaFuncs.clear(); return { offset, count }; }; while (true) { using common::parser::DetailToken; const auto [expr, ch] = ParseExpr("@#};", AssignPolicy::AllowAny); Expects(Context.Col > 0u || ch == common::parser::special::CharEnd); const auto row = Context.Row, col = Context.Col - (ch == common::parser::special::CharEnd ? 0u : 1u); if (!expr) { switch (ch) { case U'@': // metafunc { ContextReader reader(Context); const DetailToken token = { row, col, tokenizer::MetaFuncPrefixTokenizer::GetToken(reader, U"@") }; Ensures(token.GetIDEnum<NailangToken>() == NailangToken::MetaFunc); metaFuncs.emplace_back(ParseFuncCall(token, FuncName::FuncInfo::Meta)); } continue; case U'#': // block/rawblock { ContextReader reader(Context); const DetailToken token = { row, col, tokenizer::BlockPrefixTokenizer::GetToken(reader, U"#") }; if (token.GetIDEnum<NailangToken>() == NailangToken::Raw) { const auto target = MemPool.Create<RawBlock>(ParseRawBlock(token)); contents.emplace_back(target, AppendMetaFuncs()); } else { Ensures(token.GetIDEnum<NailangToken>() == NailangToken::Block); Block inlineBlk; inlineBlk.Position = GetPosition(token); FillBlockName(inlineBlk); inlineBlk.Type = token.GetString(); EatLeftCurlyBrace(); { ContextReader reader_(Context); reader_.ReadLine(); } FillFileName(inlineBlk); { const auto idxBegin = Context.Index; ParseContentIntoBlock(true, inlineBlk, false); const auto idxEnd = Context.Index; inlineBlk.Source = Context.Source.substr(idxBegin, idxEnd - idxBegin - 1); } const auto target = MemPool.Create<Block>(inlineBlk); contents.emplace_back(target, AppendMetaFuncs()); } } continue; case U';': { const DetailToken token = { row, col, ParserToken(BaseToken::Delim, ch) }; OnUnExpectedToken(token, u"empty statement not allowed"sv); } break; case U'}': { const DetailToken token = { row, col, ParserToken(BaseToken::Delim, ch) }; if (tillTheEnd) OnUnExpectedToken(token, u"when parsing block contents"sv); if (metaFuncs.size() > 0) OnUnExpectedToken(token, u"expect block/assignment/funccall after metafuncs"sv); } break; default: { Expects(ch == common::parser::special::CharEnd); const DetailToken token = { row, col, ParserToken(BaseToken::End, ch) }; /*if (token.GetIDEnum() != BaseToken::End) OnUnExpectedToken(token, u"when parsing block contents"sv);*/ if (metaFuncs.size() > 0) OnUnExpectedToken(token, u"expect block/assignment/funccall after metafuncs"sv); if (!tillTheEnd) OnUnExpectedToken(token, u"expect '}' to close the scope"sv); } break; } } else { if (ch != U';') { const DetailToken token = { row, col, ParserToken(BaseToken::Delim, ch) }; OnUnExpectedToken(token, u"expect '}' to finish a statement"sv); } if (expr.TypeData == Expr::Type::Func) { const auto* funccall = expr.GetVar<Expr::Type::Func>(); if (!allowNonBlock) { const DetailToken token = { funccall->Position.first, funccall->Position.second, ParserToken(NailangToken::Func, funccall->FullFuncName()) }; OnUnExpectedToken(token, u"Function call not supported here"sv); } const_cast<FuncName*>(funccall->Name)->Info() = FuncName::FuncInfo::Empty; contents.emplace_back(funccall, AppendMetaFuncs()); } else if (expr.TypeData == Expr::Type::Assign) { const auto* assignexpr = expr.GetVar<Expr::Type::Assign>(); if (!allowNonBlock) { const DetailToken token = { assignexpr->Position.first, assignexpr->Position.second, ParserToken(NailangToken::Func, U'=') }; OnUnExpectedToken(token, u"Variable assignment not supported here"sv); } contents.emplace_back(assignexpr, AppendMetaFuncs()); } else { NLPS_THROW_EX(FMTSTR(u"Only support block/rawblock{} here, get [{}]"sv, allowNonBlock ? u"/assign/func"sv : u""sv, expr.GetTypeName())); } continue; } break; } block.Content = MemPool.CreateArray(contents); block.MetaFuncations = MemPool.CreateArray(allMetaFuncs); } Expr NailangParser::ProcessString(const std::u32string_view str, MemoryPool& pool) { Expects(str.size() == 0 || str.back() != U'\\'); const auto idx = str.find(U'\\'); if (idx == std::u32string_view::npos) return str; std::u32string output; output.reserve(str.size() - 1); output.assign(str.data(), idx); for (size_t i = idx; i < str.size(); ++i) { if (str[i] != U'\\') output.push_back(str[i]); else { switch (str[++i]) // promise '\' won't be last element. { case U'\\': output.push_back(U'\\'); break; case U'0' : output.push_back(U'\0'); break; case U'r' : output.push_back(U'\r'); break; case U'n' : output.push_back(U'\n'); break; case U't' : output.push_back(U'\t'); break; case U'"' : output.push_back(U'"' ); break; default : output.push_back(str[i]); break; } } } const auto space = pool.CreateArray(output); return std::u32string_view(space.data(), space.size()); } FuncCall NailangParser::ParseFuncBody(std::u32string_view name, MemoryPool& pool, common::parser::ParserContext& context, FuncName::FuncInfo info) { NailangParser parser(pool, context); return parser.ParseFuncCall(name, info); } Expr NailangParser::ParseSingleExpr(MemoryPool& pool, common::parser::ParserContext& context, std::string_view stopDelims, std::u32string_view stopChecker) { NailangParser parser(pool, context); return parser.ParseExprChecked(stopDelims, stopChecker); } RawBlockWithMeta NailangParser::GetNextRawBlock() { using common::parser::detail::TokenMatcherHelper; using common::parser::detail::EmptyTokenArray; constexpr auto ExpectRawOrMeta = TokenMatcherHelper::GetMatcher(EmptyTokenArray{}, NailangToken::Raw, NailangToken::MetaFunc); constexpr auto MainLexer = ParserLexerBase<CommentTokenizer, tokenizer::MetaFuncPrefixTokenizer, tokenizer::BlockPrefixTokenizer>(); std::vector<FuncCall> metaFuncs; while (true) { const auto token = ExpectNextToken(MainLexer, IgnoreBlank, IgnoreCommentToken, ExpectRawOrMeta); switch (token.GetIDEnum<NailangToken>()) { case NailangToken::Raw: { RawBlockWithMeta block; static_cast<RawBlock&>(block) = ParseRawBlock(token); block.MetaFunctions = MemPool.CreateArray(metaFuncs); return block; } break; case NailangToken::MetaFunc: metaFuncs.emplace_back(ParseFuncCall(token, FuncName::FuncInfo::Meta)); break; default: Expects(false); break; } } } std::vector<RawBlockWithMeta> NailangParser::GetAllRawBlocks() { std::vector<RawBlockWithMeta> sectors; while (true) { ContextReader reader(Context); reader.ReadWhile(IgnoreBlank); if (reader.PeekNext() == common::parser::special::CharEnd) break; sectors.emplace_back(GetNextRawBlock()); } return sectors; } Block NailangParser::ParseRawBlock(const RawBlock& block, MemoryPool& pool) { common::parser::ParserContext context(block.Source, block.FileName); std::tie(context.Row, context.Col) = block.Position; NailangParser parser(pool, context); Block ret; static_cast<RawBlock&>(ret) = block; parser.ParseContentIntoBlock(true, ret); return ret; } Block NailangParser::ParseAllAsBlock(MemoryPool& pool, common::parser::ParserContext& context) { NailangParser parser(pool, context); Block ret; ret.Position = parser.GetCurPos(true); parser.FillFileName(ret); parser.ParseContentIntoBlock(false, ret); return ret; } std::optional<size_t> NailangParser::VerifyVariableName(const std::u32string_view name) noexcept { constexpr tokenizer::VariableTokenizer Self = {}; if (name.empty()) return SIZE_MAX; uint32_t state = 0; for (size_t i = 0; i < name.size(); ++i) { const auto [newState, ret] = Self.OnChar(state, name[i], i); if (ret == TokenizerResult::NotMatch) return i; state = newState; } if (state == 0) return name.size() - 1; return {}; } std::u32string_view ReplaceEngine::TrimStrBlank(const std::u32string_view str) noexcept { size_t len = str.size(); while (len--) { if (!IgnoreBlank(str[len])) break; } return str.substr(0, len + 1); } void ReplaceEngine::HandleException(const NailangParseException& ex) const { /*ex.File = GetCurrentFileName().StrView(); ex.Position = GetCurrentPosition();*/ ex.ThrowSelf(); } void ReplaceEngine::OnReplaceOptBlock(std::u32string&, void*, std::u32string_view, std::u32string_view) { NLPS_THROW_EX(u"ReplaceOptBlock unimplemented"sv); } void ReplaceEngine::OnReplaceVariable(std::u32string&, void*, std::u32string_view) { NLPS_THROW_EX(u"ReplaceVariable unimplemented"sv); } void ReplaceEngine::OnReplaceFunction(std::u32string&, void*, std::u32string_view, common::span<const std::u32string_view>) { NLPS_THROW_EX(u"ReplaceFunction unimplemented"sv); } std::u32string ReplaceEngine::ProcessOptBlock(const std::u32string_view source, const std::u32string_view prefix, const std::u32string_view suffix, void* cookie) { Expects(!prefix.empty() && !suffix.empty()); // Illegal prefix/suffix common::parser::ParserContext context(source); ContextReader reader(context); std::u32string output; while (true) { auto before = reader.ReadUntil(prefix); if (before.empty()) // reaching end { output.append(reader.ReadAll()); break; } { before.remove_suffix(prefix.size()); output.append(before); } reader.ReadWhile(IgnoreBlank); if (reader.ReadNext() != U'{') NLPS_THROW_EX(u"Expect '{' for cond"sv); reader.ReadWhile(IgnoreBlank); auto cond = reader.ReadUntil(U"}"); cond.remove_suffix(1); reader.ReadLine(); auto str = reader.ReadUntil(suffix); if (str.empty()) { if (reader.IsEnd()) NLPS_THROW_EX(u"End before block content"sv); else NLPS_THROW_EX(u"No suffix found!"sv); } str.remove_suffix(suffix.size()); // find a opt block replacement OnReplaceOptBlock(output, cookie, TrimStrBlank(cond), str); reader.ReadLine(); } return output; } std::u32string ReplaceEngine::ProcessVariable(const std::u32string_view source, const std::u32string_view prefix, const std::u32string_view suffix, void* cookie) { Expects(!prefix.empty() && !suffix.empty()); // Illegal prefix/suffix common::parser::ParserContext context(source); ContextReader reader(context); std::u32string output; while (true) { auto before = reader.ReadUntil(prefix); if (before.empty()) // reaching end { output.append(reader.ReadAll()); break; } { before.remove_suffix(prefix.size()); output.append(before); } reader.ReadWhile(IgnoreBlank); auto var = reader.ReadUntil(suffix); if (var.empty()) { if (reader.IsEnd()) NLPS_THROW_EX(u"End before variable name"sv); else NLPS_THROW_EX(u"No suffix found!"sv); } var.remove_suffix(suffix.size()); // find a variable replacement OnReplaceVariable(output, cookie, TrimStrBlank(var)); } return output; } std::u32string ReplaceEngine::ProcessFunction(const std::u32string_view source, const std::u32string_view prefix, const std::u32string_view suffix, void* cookie) { Expects(!prefix.empty()); // Illegal suffix common::parser::ParserContext context(source); ContextReader reader(context); std::u32string output; while (true) { auto before = reader.ReadUntil(prefix); if (before.empty()) // reaching end { output.append(reader.ReadAll()); break; } { before.remove_suffix(prefix.size()); output.append(before); } reader.ReadWhile(IgnoreBlank); auto funcName = reader.ReadUntil(U"("sv); if (funcName.empty()) { if (reader.IsEnd()) NLPS_THROW_EX(u"End before func name"sv); else NLPS_THROW_EX(u"No '(' found!"sv); } funcName.remove_suffix(1); std::vector<std::u32string_view> args; enum class States : uint32_t { Init, Pending, InComma, InSlash, End }; States state = States::Init; uint32_t nestedLevel = 0; const auto PushArg = [&]() { Expects(nestedLevel == 0); auto part = reader.CommitRead(); part.remove_suffix(1); args.push_back(TrimStrBlank(part)); }; reader.ReadWhile(IgnoreBlank); while (state != States::End) { const auto ch = reader.PeekNext(); if (ch == common::parser::special::CharEnd) break; reader.MoveNext(); switch (state) { case States::Init: case States::Pending: switch (ch) { case U'"': state = States::InComma; break; case U'(': state = States::Pending; nestedLevel++; break; case U')': if (nestedLevel) { state = States::Pending; nestedLevel--; } else { if (state == States::Init) { if (args.size() > 0) NLPS_THROW_EX(u"empty arg not allowed"sv); reader.CommitRead(); } else PushArg(); state = States::End; } break; case U',': if (state == States::Init) NLPS_THROW_EX(u"empty arg not allowed"sv); else if (nestedLevel == 0) { PushArg(); state = States::Init; reader.ReadWhile(IgnoreBlank); } break; default: state = States::Pending; break; } break; case States::InComma: if (ch == U'"') state = States::Pending; else if (ch == U'\\') state = States::InSlash; break; case States::InSlash: state = States::InComma; break; case States::End: Expects(false); break; } } if (state != States::End) NLPS_THROW_EX(u"End before arg list finishes"sv); if (!suffix.empty()) { reader.ReadWhile(IgnoreBlank); if (!reader.ReadMatch(suffix)) { if (reader.IsEnd()) NLPS_THROW_EX(u"End before suffix"sv); else NLPS_THROW_EX(u"Unexpeccted char before suffix!"sv); } } // find a function replacement OnReplaceFunction(output, cookie, TrimStrBlank(funcName), args); } return output; } ReplaceEngine::~ReplaceEngine() { } }
35.958227
161
0.564855
[ "vector" ]
832e8046bc7d5b2b5781e115c15a2b0320250f9d
1,589
cpp
C++
Numerical methods/Linear algebra methods/src/test/MatrixTests.cpp
ShkalikovOleh/Labs
04161ee96c729d1a8b84906b453c5f0e386aaa8b
[ "MIT" ]
null
null
null
Numerical methods/Linear algebra methods/src/test/MatrixTests.cpp
ShkalikovOleh/Labs
04161ee96c729d1a8b84906b453c5f0e386aaa8b
[ "MIT" ]
null
null
null
Numerical methods/Linear algebra methods/src/test/MatrixTests.cpp
ShkalikovOleh/Labs
04161ee96c729d1a8b84906b453c5f0e386aaa8b
[ "MIT" ]
1
2020-11-22T16:21:14.000Z
2020-11-22T16:21:14.000Z
#include <gtest/gtest.h> #include "Matrix.h" #include "Vector.h" using namespace LinAlg; class MatrixTests : public ::testing::Test { protected: void SetUp() override { matrix = new Matrix<int>(2, 2); (*matrix)(0, 0) = 1; (*matrix)(0, 1) = 2; (*matrix)(1, 0) = 3; (*matrix)(1, 1) = 4; } void TearDown() override { delete matrix; } Matrix<int> *matrix{}; }; TEST_F(MatrixTests, shape) { auto mat = *matrix; EXPECT_EQ(mat.nrow(), 2); EXPECT_EQ(mat.ncol(), 2); } TEST_F(MatrixTests, transpose) { auto mat = *matrix; auto result = mat.transpose(); EXPECT_EQ(result.ncol(), mat.ncol()); EXPECT_EQ(result.nrow(), mat.nrow()); for (int i = 0; i < mat.nrow(); i++) { for (int j = 0; j < mat.ncol(); j++) { EXPECT_EQ(result(i, j), mat(j, i)); } } } TEST_F(MatrixTests, isNotSymmetric) { auto mat = *matrix; ASSERT_FALSE(mat.isSymmetric()); } TEST_F(MatrixTests, isSymmetric) { Matrix<int> mat(2, 2); mat(0, 0) = 1; mat(1, 1) = 2; mat(0, 1) = mat(1, 0) = 3; ASSERT_TRUE(mat.isSymmetric()); } TEST_F(MatrixTests, multMatrix) { auto mat = *matrix; auto prod = mat * mat; EXPECT_EQ(prod(0, 0), 7); EXPECT_EQ(prod(0, 1), 10); EXPECT_EQ(prod(1, 0), 15); EXPECT_EQ(prod(1, 1), 22); } TEST_F(MatrixTests, multVector) { auto mat = *matrix; Vector<int> vec(2); vec(0) = 1; vec(1) = 2; auto prod = mat * vec; EXPECT_EQ(prod(0), 5); EXPECT_EQ(prod(1), 11); }
17.086022
47
0.538074
[ "shape", "vector" ]
8338941173ced9590185ee61c57217c74ba10503
2,527
cpp
C++
gym/102163/B.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
1
2021-07-16T19:59:39.000Z
2021-07-16T19:59:39.000Z
gym/102163/B.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
gym/102163/B.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define endl '\n' typedef pair<int, int> pii; struct graph { int n; vector<vector<int>> adj; graph(int n) : n(n), adj(n) {} void add_edge(int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } vector<int>& operator[](int u) { return adj[u]; } }; graph bridge_blocks(graph &adj) { int n = adj.n; vector<int> num(n), low(n), stk; vector<vector<int>> comps; vector<pair<int, int>> bridges; function<void(int, int, int&)> dfs = [&](int u, int p, int &t) { num[u] = low[u] = ++t; stk.push_back(u); // remove if there isn't parallel edges sort(adj[u].begin(), adj[u].end()); for (int i = 0, sz = adj[u].size(); i < sz; ++i) { int v = adj[u][i]; if (v == p) { if (i + 1 < sz && adj[u][i + 1] == v) low[u] = min(low[u], num[v]); continue; } if (!num[v]) { dfs(v, u, t); low[u] = min(low[u], low[v]); if (low[v] == num[v]) bridges.push_back({u, v}); } else low[u] = min(low[u], num[v]); } if (num[u] == low[u]) { comps.push_back({}); for (int v = -1; v != u; stk.pop_back()) comps.back().push_back(v = stk.back()); } }; for (int u = 0, t; u < n; ++u) if (!num[u]) dfs(u, -1, t = 0); // this is for build the bridge-block tree function<graph()> build_tree = [&]() { vector<int> id(n); for (int i = 0; i < (int) comps.size(); ++i) for (int u : comps[i]) id[u] = i; graph tree(comps.size()); for (auto &e : bridges) tree.add_edge(id[e.first], id[e.second]); return tree; }; return build_tree(); } pii bfs(int s, graph &g){ int n = g.n; queue<int> Q; Q.push(s); vector<int> d(n, -1); d[s] = 0; int last = s; while(!Q.empty()){ int v = Q.front();Q.pop(); last = v; for(auto &u : g[v]){ if(d[u] == -1){ d[u] = d[v] + 1; Q.push(u); } } } return {last, d[last]}; } int get_diam(graph &g){ pii A = bfs(0, g); pii B = bfs(A.first, g); return B.second; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--){ int n, m; cin >> n >> m; graph g(n); for(int i = 0, a, b; i < m; i++){ cin >> a >> b; a--; b--; g.add_edge(a, b); } graph t = bridge_blocks(g); int bridges = t.n - 1; int diam = get_diam(t); cout << bridges - diam << endl; } return 0; }
16.735099
63
0.470914
[ "vector" ]
833e30ef9c22d8a3c30dc80394de07c1706861f0
638
cpp
C++
Estruturas de Dados para Competições de Programação (em C++)/fila.cpp
Garotos-de-Programa/NEPS-Academy
a321fab09909587533697268c907816ecc8522fe
[ "MIT" ]
1
2021-09-17T19:03:41.000Z
2021-09-17T19:03:41.000Z
Estruturas de Dados para Competições de Programação (em C++)/fila.cpp
Garotos-de-Programa/NEPS-Academy
a321fab09909587533697268c907816ecc8522fe
[ "MIT" ]
null
null
null
Estruturas de Dados para Competições de Programação (em C++)/fila.cpp
Garotos-de-Programa/NEPS-Academy
a321fab09909587533697268c907816ecc8522fe
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define fastio ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL) using namespace std; int N,M; int main(){ fastio; int aux; vector<int> entrada,saida; cin>>N; for(int i=0; i<N; i++){ cin>>aux; entrada.push_back(aux); } cin>>M; for(int i=0; i<M; i++){ cin>>aux; saida.push_back(aux); } for(int i=0; i<saida.size(); i++){ for(int j=0; j<entrada.size(); j++){ if(saida.at(i) == entrada.at(j)){ saida.erase(saida.begin()+i); entrada.erase(entrada.begin()+j); } } } for(int i=0; i<entrada.size();i++){ cout<<entrada.at(i)<<" "; } cout<<"\n"; return 0; }
15.560976
78
0.579937
[ "vector" ]
8340e30a3be5abc4a3db671a2d1eed78241bc6ab
7,181
cpp
C++
test/unit/iterator/legacy_iterator.cpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
4
2019-03-02T01:09:07.000Z
2019-10-16T15:46:21.000Z
test/unit/iterator/legacy_iterator.cpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
5
2018-12-16T13:47:32.000Z
2019-10-13T01:27:11.000Z
test/unit/iterator/legacy_iterator.cpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
3
2020-06-08T18:27:28.000Z
2021-03-27T17:49:46.000Z
// Copyright (c) Christopher Di Bella. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // #include "cjdb/detail/iterator/legacy_iterator.hpp" #include "cjdb/detail/iterator/incrementable_traits.hpp" #include "cjdb/detail/iterator/indirectly_readable_traits.hpp" #include <array> #include <deque> #include <forward_list> #include <iterator> #include <list> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <vector> template<typename T> void check_legacy_iterator() { using cjdb::detail_iterator_associated_types::legacy_iterator; static_assert(legacy_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_input_iterator; static_assert(not legacy_input_iterator<T>); } template<typename T> void check_legacy_input_iterator() { using cjdb::detail_iterator_associated_types::legacy_iterator; static_assert(legacy_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_input_iterator; static_assert(legacy_input_iterator<T>); } template<typename T> void check_legacy_forward_iterator() { using cjdb::detail_iterator_associated_types::legacy_iterator; static_assert(legacy_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_input_iterator; static_assert(legacy_input_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_forward_iterator; static_assert(legacy_forward_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_bidirectional_iterator; static_assert(not legacy_bidirectional_iterator<T>); } template<typename T> void check_legacy_bidirectional_iterator() { using cjdb::detail_iterator_associated_types::legacy_iterator; static_assert(legacy_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_input_iterator; static_assert(legacy_input_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_forward_iterator; static_assert(legacy_forward_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_bidirectional_iterator; static_assert(legacy_bidirectional_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_random_access_iterator; static_assert(not legacy_random_access_iterator<T>); } template<typename T> void check_legacy_random_access_iterator() { using cjdb::detail_iterator_associated_types::legacy_iterator; static_assert(legacy_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_input_iterator; static_assert(legacy_input_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_forward_iterator; static_assert(legacy_forward_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_bidirectional_iterator; static_assert(legacy_bidirectional_iterator<T>); using cjdb::detail_iterator_associated_types::legacy_random_access_iterator; static_assert(legacy_random_access_iterator<T>); } int main() { check_legacy_iterator<std::ostream_iterator<int>>(); check_legacy_iterator<std::ostream_iterator<double>>(); check_legacy_iterator<std::back_insert_iterator<std::vector<long>>>(); check_legacy_iterator<std::back_insert_iterator<std::list<std::vector<int>>>>(); check_legacy_iterator<std::front_insert_iterator<std::deque<long>>>(); check_legacy_iterator<std::front_insert_iterator<std::list<std::vector<int>>>>(); check_legacy_input_iterator<std::istream_iterator<int>>(); check_legacy_input_iterator<std::istream_iterator<long>>(); check_legacy_forward_iterator<std::forward_list<std::vector<std::map<int, int>>>::iterator>(); check_legacy_forward_iterator<std::forward_list<std::vector<std::map<int, int>>>::const_iterator>(); check_legacy_forward_iterator<std::unordered_set<int>::iterator>(); check_legacy_forward_iterator<std::unordered_set<int>::const_iterator>(); check_legacy_forward_iterator<std::unordered_multiset<int>::iterator>(); check_legacy_forward_iterator<std::unordered_multiset<int>::const_iterator>(); check_legacy_forward_iterator<std::unordered_map<double, int>::iterator>(); check_legacy_forward_iterator<std::unordered_map<double, int>::const_iterator>(); check_legacy_forward_iterator<std::unordered_multimap<double, long long>::iterator>(); check_legacy_forward_iterator<std::unordered_multimap<double, long long>::const_iterator>(); check_legacy_bidirectional_iterator<std::list<int>::iterator>(); check_legacy_bidirectional_iterator<std::list<int>::const_iterator>(); check_legacy_bidirectional_iterator<std::list<int>::reverse_iterator>(); check_legacy_bidirectional_iterator<std::list<int>::const_reverse_iterator>(); check_legacy_bidirectional_iterator<std::set<double>::iterator>(); check_legacy_bidirectional_iterator<std::set<double>::const_iterator>(); check_legacy_bidirectional_iterator<std::set<double>::reverse_iterator>(); check_legacy_bidirectional_iterator<std::set<double>::const_reverse_iterator>(); check_legacy_bidirectional_iterator<std::multiset<char>::iterator>(); check_legacy_bidirectional_iterator<std::multiset<char>::const_iterator>(); check_legacy_bidirectional_iterator<std::multiset<char>::reverse_iterator>(); check_legacy_bidirectional_iterator<std::multiset<char>::const_reverse_iterator>(); check_legacy_bidirectional_iterator<std::map<int, double>::iterator>(); check_legacy_bidirectional_iterator<std::map<int, double>::const_iterator>(); check_legacy_bidirectional_iterator<std::map<int, double>::reverse_iterator>(); check_legacy_bidirectional_iterator<std::map<int, double>::const_reverse_iterator>(); check_legacy_bidirectional_iterator<std::multimap<char, signed char>::iterator>(); check_legacy_bidirectional_iterator<std::multimap<char, signed char>::const_iterator>(); check_legacy_bidirectional_iterator<std::multimap<char, signed char>::reverse_iterator>(); check_legacy_bidirectional_iterator<std::multimap<char, signed char>::const_reverse_iterator>(); check_legacy_random_access_iterator<std::vector<int>::iterator>(); check_legacy_random_access_iterator<std::vector<int>::const_iterator>(); check_legacy_random_access_iterator<std::vector<int>::reverse_iterator>(); check_legacy_random_access_iterator<std::vector<int>::const_reverse_iterator>(); check_legacy_random_access_iterator<std::array<short, 1>::iterator>(); check_legacy_random_access_iterator<std::array<short, 1>::const_iterator>(); check_legacy_random_access_iterator<std::array<short, 1>::reverse_iterator>(); check_legacy_random_access_iterator<std::array<short, 1>::const_reverse_iterator>(); struct dummy {}; constexpr auto arbitrary_size = 23; check_legacy_random_access_iterator<std::array<dummy, arbitrary_size>::iterator>(); check_legacy_random_access_iterator<std::array<dummy, arbitrary_size>::const_iterator>(); check_legacy_random_access_iterator<std::array<dummy, arbitrary_size>::reverse_iterator>(); check_legacy_random_access_iterator<std::array<dummy, arbitrary_size>::const_reverse_iterator>(); check_legacy_random_access_iterator<std::deque<int>::iterator>(); check_legacy_random_access_iterator<std::deque<int>::const_iterator>(); check_legacy_random_access_iterator<std::deque<int>::reverse_iterator>(); check_legacy_random_access_iterator<std::deque<int>::const_reverse_iterator>(); }
45.163522
101
0.824119
[ "vector" ]
8341777f6a4433e85b971d3ad4492c3d08549697
1,544
cpp
C++
third_party/mlir/test/lib/Transforms/TestLowerVectorTransfers.cpp
scentini/tensorflow
204ed332c0886a0e0ab10b22ba8d67b97e1c83c4
[ "Apache-2.0" ]
2
2018-12-28T15:11:25.000Z
2020-12-08T08:11:02.000Z
third_party/mlir/test/lib/Transforms/TestLowerVectorTransfers.cpp
scentini/tensorflow
204ed332c0886a0e0ab10b22ba8d67b97e1c83c4
[ "Apache-2.0" ]
1
2018-04-02T23:42:30.000Z
2018-05-03T23:12:23.000Z
third_party/mlir/test/lib/Transforms/TestLowerVectorTransfers.cpp
scentini/tensorflow
204ed332c0886a0e0ab10b22ba8d67b97e1c83c4
[ "Apache-2.0" ]
3
2017-09-20T22:52:39.000Z
2018-10-14T11:10:21.000Z
//===- TestLowerVectorTransfers.cpp - Test VectorTransfers lowering -------===// // // Copyright 2019 The MLIR 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 <type_traits> #include "mlir/Conversion/VectorConversions/VectorConversions.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Pass/Pass.h" #include "mlir/Transforms/Passes.h" using namespace mlir; namespace { struct TestLowerVectorTransfersPass : public FunctionPass<TestLowerVectorTransfersPass> { void runOnFunction() override { OwningRewritePatternList patterns; auto *context = &getContext(); populateVectorToAffineLoopsConversionPatterns(context, patterns); applyPatternsGreedily(getFunction(), patterns); } }; } // end anonymous namespace static PassRegistration<TestLowerVectorTransfersPass> pass("test-affine-lower-vector-transfers", "Materializes vector transfer ops to a " "proper abstraction for the hardware");
34.311111
80
0.71114
[ "vector" ]
836431e8268491c77442ffa5e8bfe522a67ca51d
376
cpp
C++
util/rand.cpp
tlming16/Projec_Euler
797824c5159fae67493de9eba24c22cc7512d95d
[ "MIT" ]
4
2018-11-14T12:03:05.000Z
2019-09-03T14:33:28.000Z
util/rand.cpp
tlming16/Projec_Euler
797824c5159fae67493de9eba24c22cc7512d95d
[ "MIT" ]
null
null
null
util/rand.cpp
tlming16/Projec_Euler
797824c5159fae67493de9eba24c22cc7512d95d
[ "MIT" ]
1
2018-11-17T14:39:22.000Z
2018-11-17T14:39:22.000Z
# include <random> # include <iostream> # include <vector> # include <iterator> int main(){ std::random_device rd; std::mt19937 g(rd()); std::uniform_real_distribution<double> u(0,10); std::vector<double> v; int n; std::cin>>n; while(n--){ v.push_back( u(g)); } std::copy( v.begin(),v.end(),std::ostream_iterator<double>(std::cout,",")); return 0; }
19.789474
77
0.619681
[ "vector" ]
83678f7a755eccebefeb2cb059f0deca1a510c40
2,837
cpp
C++
Kick Start 2021/Round B/C.cpp
Mandrenkov/Contests
077e3177965280d39903288a713c951fc1a199c8
[ "MIT" ]
null
null
null
Kick Start 2021/Round B/C.cpp
Mandrenkov/Contests
077e3177965280d39903288a713c951fc1a199c8
[ "MIT" ]
null
null
null
Kick Start 2021/Round B/C.cpp
Mandrenkov/Contests
077e3177965280d39903288a713c951fc1a199c8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // Macros #ifdef D3BUG #define cerrd if (D3BUG) cerr #else #define cerrd if (false) cerr #endif // Types template <typename T> using vector1D = vector<T>; template <typename T> using vector2D = vector<vector1D<T>>; template <typename T> using vector3D = vector<vector2D<T>>; // Output Stream Overloads template< // Multiple template arguments may be needed for containers like std::map. template<class...> class Range, class... Ts, // This overload must be disabled for std::string to avoid ambiguity. typename = std::enable_if_t<!std::is_same_v<Range<Ts...>, std::string>> > std::ostream& operator<<(std::ostream& out, const Range<Ts...>& range) { out << '{'; for (auto it = range.begin(); it != range.end(); ++it) { out << *it << (std::next(it) != range.end() ? ", " : ""); } return out << '}'; } template <class F, class S> ostream& operator<<(ostream& out, const pair<F, S>& pair) { return out << '(' << pair.first << ", " << pair.second << ')'; } // Hash Template Specializations template<class T, class U> struct hash<pair<T, U>> { size_t operator()(const pair<T, U>& p) const noexcept { return hash<T>{}(p.first) ^ (hash<U>{}(p.second) << 1); } }; void solution(); // Initalize the execution environment and call the solution function. int main() { ios_base::sync_with_stdio(false); cin.tie(0); solution(); } // ----------------------------------------------------------------------------- using int_t = unsigned long long; // Returns true if the given number is prime. bool is_prime(int_t n) { if (n < 4) { return true; } else if (n % 2 == 0) { return false; } for (int_t i = 3; i * i <= n; i += 2) { if (n % i == 0) { return false; } } return true; } void solution() { int T; cin >> T; for (int t = 1; t <= T; ++t) { int_t Z; cin >> Z; // Find the smallest integer `n` whose square is not less than `Z`. int_t n = sqrt(Z); while ((n + 1) * (n + 1) <= Z) { ++n; } // Find the smallest prime greater than `n`. vector<int_t> primes; int_t m = n + 1; while (!is_prime(m)) { ++m; } primes.emplace_back(m); // Find the two largest primes no greater than `n`. while (primes.size() < 3) { if (is_prime(n)) { primes.emplace_back(n); } --n; } // Note that `primes` is sorted in descending order. int_t secret = primes[0] * primes[1] <= Z ? primes[0] * primes[1] : (primes[1] * primes[2]); cout << "Case #" << t << ": " << secret << "\n"; } }
26.268519
80
0.513571
[ "vector" ]
8370a1ee889dba3db9f58659b6bdca82b2b1e6eb
2,349
hpp
C++
bryllite-core/base58.hpp
bryllite/bcp-concept-prototype
3ded79a85ee4c876fbbd0c1ee51680346874494e
[ "MIT" ]
null
null
null
bryllite-core/base58.hpp
bryllite/bcp-concept-prototype
3ded79a85ee4c876fbbd0c1ee51680346874494e
[ "MIT" ]
null
null
null
bryllite-core/base58.hpp
bryllite/bcp-concept-prototype
3ded79a85ee4c876fbbd0c1ee51680346874494e
[ "MIT" ]
null
null
null
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /** * Why base-58 instead of standard base-64 encoding? * - Don't want 0OIl characters that look the same in some fonts and * could be used to create visually identical looking data. * - A string with non-alphanumeric characters is not as easily accepted as input. * - E-mail usually won't line-break if there's no punctuation to break at. * - Double-clicking selects the whole string as one word if it's all alphanumeric. */ #ifndef BITCOIN_BASE58_H #define BITCOIN_BASE58_H /** * Encode a byte sequence as a base58-encoded string. * pbegin and pend cannot be nullptr, unless both are. */ std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend); /** * Encode a byte vector as a base58-encoded string */ std::string EncodeBase58(const std::vector<unsigned char>& vch); /** * Decode a base58-encoded string (psz) into a byte vector (vchRet). * return true if decoding is successful. * psz cannot be nullptr. */ bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet); /** * Decode a base58-encoded string (str) into a byte vector (vchRet). * return true if decoding is successful. */ bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet); /** * Encode a byte vector into a base58-encoded string, including checksum */ std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn); /** * Decode a base58-encoded string (psz) that includes a checksum into a byte * vector (vchRet), return true if decoding is successful */ bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet); /** * Decode a base58-encoded string (str) that includes a checksum into a byte * vector (vchRet), return true if decoding is successful */ bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet); // encode/decode base58 check std::string encode_base58_check( byte prefix, std::string str ); bool decode_base58_check( const char* psz, std::vector<byte>& vchOut ); bool decode_base58_check( const std::string& str, std::vector<byte>& vchOut ); #endif // BITCOIN_BASE58_H
35.590909
83
0.738612
[ "vector" ]
83817bdb5578eebc8194d57f635a26af86ef4974
16,230
cpp
C++
src/NetworkBinding.cpp
Fastcode/NUClearNet.js
4ec3a307021bdc262194ba508e366a084f5e4447
[ "MIT" ]
null
null
null
src/NetworkBinding.cpp
Fastcode/NUClearNet.js
4ec3a307021bdc262194ba508e366a084f5e4447
[ "MIT" ]
2
2019-06-21T12:28:42.000Z
2021-09-20T13:10:29.000Z
src/NetworkBinding.cpp
Fastcode/NUClearNet.js
4ec3a307021bdc262194ba508e366a084f5e4447
[ "MIT" ]
4
2015-11-22T05:05:43.000Z
2021-05-23T05:32:02.000Z
/* * Copyright (C) 2013-2016 Trent Houliston <trent@houliston.me>, Jake Woods <jake.f.woods@gmail.com> * * 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 "NetworkBinding.hpp" #include "NetworkListener.hpp" #include "nuclear/src/util/serialise/xxhash.h" namespace NUClear { using extension::network::NUClearNetwork; NetworkBinding::NetworkBinding(const Napi::CallbackInfo& info): Napi::ObjectWrap<NetworkBinding>(info) {} Napi::Value NetworkBinding::Hash(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); if (info.Length() > 0 && info[0].IsString()) { // Calculate hash std::string s = info[0].As<Napi::String>().Utf8Value(); uint64_t hash = XXH64(s.c_str(), s.size(), 0x4e55436c); // Return hash return Napi::Buffer<char>::Copy(env, reinterpret_cast<const char*>(&hash), sizeof(uint64_t)).As<Napi::Value>(); } else { Napi::TypeError::New(env, "Invalid input for hash(): expected a string").ThrowAsJavaScriptException(); return env.Null(); } } void NetworkBinding::Send(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); if (info.Length() < 4) { Napi::TypeError::New(env, "Expected 4 arguments, got fewer").ThrowAsJavaScriptException(); return; } const Napi::Value& arg_hash = info[0]; const Napi::Value& arg_payload = info[1]; const Napi::Value& arg_target = info[2]; const Napi::Value& arg_reliable = info[3]; uint64_t hash = 0; std::vector<char> payload; std::string target = ""; bool reliable = false; // Read reliability information if (arg_reliable.IsBoolean()) { reliable = arg_reliable.As<Napi::Boolean>().Value(); } else { Napi::TypeError::New(env, "Invalid `reliable` option for send(): expected a boolean").ThrowAsJavaScriptException(); return; } // Read target information: if we have a string, use it as the target if (arg_target.IsString()) { target = arg_target.As<Napi::String>().Utf8Value(); } // Otherwise, we accept null and undefined to mean everybody else if (!arg_target.IsUndefined() && !arg_target.IsNull()) { Napi::TypeError::New(env, "Invalid `target` option for send(): expected a string (for targeted), or null/undefined (for untargeted)").ThrowAsJavaScriptException(); return; } // Read the data information if (arg_payload.IsTypedArray()) { Napi::TypedArray typed_array = arg_payload.As<Napi::TypedArray>(); Napi::ArrayBuffer buffer = typed_array.ArrayBuffer(); char* data = reinterpret_cast<char*>(buffer.Data()); char* start = data + typed_array.ByteOffset(); char* end = start + typed_array.ByteLength(); payload.insert(payload.begin(), start, end); } else { Napi::TypeError::New(env, "Invalid `payload` option for send(): expected a Buffer").ThrowAsJavaScriptException(); return; } // If we have a string, apply XXHash to get the hash if (arg_hash.IsString()) { std::string s = arg_hash.As<Napi::String>().Utf8Value(); hash = XXH64(s.c_str(), s.size(), 0x4e55436c); } // Otherwise try to interpret it as a buffer that contains the hash else if (arg_hash.IsTypedArray()) { Napi::TypedArray typed_array = arg_hash.As<Napi::TypedArray>(); Napi::ArrayBuffer buffer = typed_array.ArrayBuffer(); uint8_t* data = reinterpret_cast<uint8_t*>(buffer.Data()); uint8_t* start = data + typed_array.ByteOffset(); uint8_t* end = start + typed_array.ByteLength(); if (std::distance(start, end) == 8) { std::memcpy(&hash, start, 8); } else { Napi::TypeError::New(env, "Invalid `hash` option for send(): provided Buffer length is not 8").ThrowAsJavaScriptException(); return; } } else { Napi::TypeError::New(env, "Invalid `hash` option for send(): expected a string or Buffer").ThrowAsJavaScriptException(); return; } // Perform the send try { this->net.send(hash, payload, target, reliable); } catch (const std::exception& ex) { Napi::Error::New(env, ex.what()).ThrowAsJavaScriptException(); } } void NetworkBinding::On(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); if (info[0].IsString() && info[1].IsFunction()) { std::string event = info[0].As<Napi::String>().Utf8Value(); // `ThreadSafeCallback` is from the napi-thread-safe-callback npm package. It allows for running a JS callback // from a thread that isn't the main addon thread (like where the NUClearNet packet callbacks are called from). // Similar thread-safe callback functionality has been added to NAPI natively, but it's still experimental at // the time of writing. auto cb = std::make_shared<ThreadSafeCallback>(info[1].As<Napi::Function>()); if (event == "packet") { this->net.set_packet_callback([cb = std::move(cb)]( const NUClearNetwork::NetworkTarget& t, const uint64_t& hash, const bool& reliable, std::vector<char>&& payload) { std::string name = t.name; std::string address; uint16_t port = 0; // Extract the IP address and port char c[255]; std::memset(c, 0, sizeof(c)); switch (t.target.sock.sa_family) { case AF_INET: inet_ntop(t.target.sock.sa_family, const_cast<in_addr*>(&t.target.ipv4.sin_addr), c, sizeof(c)); port = ntohs(t.target.ipv4.sin_port); break; case AF_INET6: inet_ntop( t.target.sock.sa_family, const_cast<in6_addr*>(&t.target.ipv6.sin6_addr), c, sizeof(c)); port = ntohs(t.target.ipv6.sin6_port); break; } address = c; cb->call([name, address, port, reliable, hash, payload](Napi::Env env, std::vector<napi_value> &args) { args = { Napi::String::New(env, name), Napi::String::New(env, address), Napi::Number::New(env, port), Napi::Boolean::New(env, reliable), Napi::Buffer<char>::Copy(env, reinterpret_cast<const char*>(&hash), sizeof(uint64_t)), Napi::Buffer<char>::Copy(env, payload.data(), payload.size()) }; }); }); } else if (event == "join" || event == "leave") { auto f = [cb = std::move(cb)](const NUClearNetwork::NetworkTarget& t) { std::string name = t.name; std::string address; uint16_t port = 0; // Extract the IP address and port char c[255]; std::memset(c, 0, sizeof(c)); switch (t.target.sock.sa_family) { case AF_INET: inet_ntop(t.target.sock.sa_family, const_cast<in_addr*>(&t.target.ipv4.sin_addr), c, sizeof(c)); port = ntohs(t.target.ipv4.sin_port); break; case AF_INET6: inet_ntop( t.target.sock.sa_family, const_cast<in6_addr*>(&t.target.ipv6.sin6_addr), c, sizeof(c)); port = ntohs(t.target.ipv6.sin6_port); break; default: // The system has a corrupted network peer record, but we can't throw to JS from here, since we // don't have an env object. cb->callError(string) is available from the // napi-thread-safe-callback library, but that requires changing the callback signature on the // JS side to accept a potential error as the first argument. This would be a breaking change, // but we can do it if deemed necessary, and update all users of nuclearnet.js. return; } address = c; cb->call([name, address, port](Napi::Env env, std::vector<napi_value> &args) { args = { Napi::String::New(env, name), Napi::String::New(env, address), Napi::Number::New(env, port), }; }); }; if (event == "join") { this->net.set_join_callback(std::move(f)); } else { this->net.set_leave_callback(std::move(f)); } } else if (event == "wait") { this->net.set_next_event_callback([cb = std::move(cb)](std::chrono::steady_clock::time_point t) { using namespace std::chrono; int ms = duration_cast<std::chrono::duration<int, std::milli>>(t - steady_clock::now()).count(); ms++; // Add 1 to account for any funky rounding cb->call([ms](Napi::Env env, std::vector<napi_value> &args) { args = {Napi::Number::New(env, ms)}; }); }); } else { Napi::TypeError::New(env, "Invalid `eventName` argument for on(): expected one of 'packet', 'join', 'leave', or 'wait'").ThrowAsJavaScriptException(); return; } } else { Napi::TypeError::New(env, "Invalid arguments for on(): expected an event name (string) and a callback (function)").ThrowAsJavaScriptException(); } } void NetworkBinding::Reset(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); const Napi::Value& arg_name = info[0]; const Napi::Value& arg_group = info[1]; const Napi::Value& arg_port = info[2]; const Napi::Value& arg_mtu = info[3]; std::string name = ""; std::string group = "239.226.152.162"; uint32_t port = arg_port.IsNumber() ? arg_port.As<Napi::Number>().Uint32Value() : 7447; uint32_t network_mtu = arg_mtu.IsNumber() ? arg_mtu.As<Napi::Number>().Uint32Value() : 1500; // Multicast Group if (arg_group.IsString()) { group = arg_group.As<Napi::String>().Utf8Value(); } else { Napi::TypeError::New(env, "Invalid `group` option for reset(): multicast group must be a string").ThrowAsJavaScriptException(); return; } // Name Group if (arg_name.IsString()) { name = arg_name.As<Napi::String>().Utf8Value(); } else { Napi::Error::New(env, "Invalid `name` option for reset(): name must be a string").ThrowAsJavaScriptException(); return; } // Perform the reset try { this->net.reset(name, group, port, network_mtu); // NetworkListener extends AsyncProgressWorker, which will automatically // destruct itself when done (i.e. when Execute() returns and OnOK() or // OnError() are called and return) auto asyncWorker = new NetworkListener(env, this); #ifdef _WIN32 // Keep track of the NetworkListener notifier, so we can signal it to exit WSAWaitForMultipleEvents() this->listenerNotifier = asyncWorker->notifier; #endif // Queue the worker asyncWorker->Queue(); } catch (const std::exception& ex) { Napi::Error::New(env, ex.what()).ThrowAsJavaScriptException(); } } void NetworkBinding::Process(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); // Perform the process function try { this->net.process(); } catch (const std::exception& ex) { Napi::Error::New(env, ex.what()).ThrowAsJavaScriptException(); } } void NetworkBinding::Shutdown(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); // Perform the shutdown function try { this->net.shutdown(); } catch (const std::exception& ex) { Napi::Error::New(env, ex.what()).ThrowAsJavaScriptException(); } } void NetworkBinding::Destroy(const Napi::CallbackInfo& info) { // Set destroyed, to exit the read loop in the network listener this->destroyed = true; #ifdef _WIN32 // Signal the network listener notifier, to exit WSAWaitForMultipleEvents() WSASetEvent(this->listenerNotifier); #endif // Replace the ThreadSafeCallback instances to clean up the extra threads they created this->net.set_packet_callback([](const NUClearNetwork::NetworkTarget& t, const uint64_t& hash, const bool& reliable, std::vector<char>&& payload) {}); this->net.set_join_callback([](const NUClearNetwork::NetworkTarget& t) {}); this->net.set_leave_callback([](const NUClearNetwork::NetworkTarget& t) {}); this->net.set_next_event_callback([](std::chrono::steady_clock::time_point t) {}); } void NetworkBinding::Init(Napi::Env env, Napi::Object exports) { Napi::Function func = DefineClass(env, "NetworkBinding", {InstanceMethod<&NetworkBinding::Send>("send", static_cast<napi_property_attributes>(napi_writable | napi_configurable)), InstanceMethod<&NetworkBinding::On>("on", static_cast<napi_property_attributes>(napi_writable | napi_configurable)), InstanceMethod<&NetworkBinding::Reset>("reset", static_cast<napi_property_attributes>(napi_writable | napi_configurable)), InstanceMethod<&NetworkBinding::Process>("process", static_cast<napi_property_attributes>(napi_writable | napi_configurable)), InstanceMethod<&NetworkBinding::Shutdown>("shutdown", static_cast<napi_property_attributes>(napi_writable | napi_configurable)), InstanceMethod<&NetworkBinding::Hash>("hash", static_cast<napi_property_attributes>(napi_writable | napi_configurable)), InstanceMethod<&NetworkBinding::Destroy>("destroy", static_cast<napi_property_attributes>(napi_writable | napi_configurable))}); Napi::FunctionReference* constructor = new Napi::FunctionReference(); // Create a persistent reference to the class constructor. This will allow // a function called on a class prototype and a function // called on instance of a class to be distinguished from each other. *constructor = Napi::Persistent(func); env.SetInstanceData(constructor); exports.Set("NetworkBinding", func); // Store the constructor as the add-on instance data. This will allow this // add-on to support multiple instances of itself running on multiple worker // threads, as well as multiple instances of itself running in different // contexts on the same thread. // // By default, the value set on the environment here will be destroyed when // the add-on is unloaded using the `delete` operator, but it is also // possible to supply a custom deleter. env.SetInstanceData<Napi::FunctionReference>(constructor); } } // namespace NUClear
43.050398
171
0.608564
[ "object", "vector" ]
83830716c833c86c6af647138afd2206f1b34e95
1,128
cc
C++
src/ray_cast.cc
dmraji/Probabalistic_TSO
a4c9ebf1ae6baa6aebfd59b02320aad8790841a5
[ "MIT" ]
null
null
null
src/ray_cast.cc
dmraji/Probabalistic_TSO
a4c9ebf1ae6baa6aebfd59b02320aad8790841a5
[ "MIT" ]
null
null
null
src/ray_cast.cc
dmraji/Probabalistic_TSO
a4c9ebf1ae6baa6aebfd59b02320aad8790841a5
[ "MIT" ]
1
2018-08-27T22:26:55.000Z
2018-08-27T22:26:55.000Z
// Ray-casting non-member (source) #include "ray_cast.hh" //_//_//_//_//_//_//_//_//_//_//_//_//_//_//_//_//_//_//_//_//_//_//_//_//_//_// void cast_ray(pt &origin, pt &end, float resolution, std::vector<pt> & ray ) { // Calculate Euclidean distance between origin (current pose) and end (point in cloud) pt dist = {end.x-origin.x, end.y-origin.y, end.z-origin.z}; // Calculate magnitude of Euclidean distance float mag = std::sqrt(sq(dist.x) + sq(dist.y) + sq(dist.z)); // Discretize magnitude by resolution of voxels int disc = int(std::ceil(mag/resolution)); // Define size of increment along path of ray pt inc = {dist.x / disc, dist.y / disc, dist.z / disc}; // Warn on short ray if(disc < 1) { std::cout << "WARNING: Ray of length less than 1!" << std::endl; } // Do not mark end (point in cloud) as free ray.reserve(disc-1); // Iterate along discretized ray for(int i = 0; i < disc-1; ++i) { // Add points to ray vector ray.push_back({origin.x + inc.x * i, origin.y + inc.y * i, origin.z + inc.z * i}); } }
26.857143
88
0.579787
[ "vector" ]
83853b3e4bc0f8a1682fd0269f09ceab753b9e95
7,852
cpp
C++
ext/annotations/reader.cpp
unisys12/phalcon-hhvm
ceeabc4f8d2e51b7cae9d0e100bb4055affe65bf
[ "BSD-2-Clause" ]
13
2015-01-10T23:34:25.000Z
2017-08-25T15:16:29.000Z
ext/annotations/reader.cpp
unisys12/phalcon-hhvm
ceeabc4f8d2e51b7cae9d0e100bb4055affe65bf
[ "BSD-2-Clause" ]
1
2015-04-14T06:47:20.000Z
2015-10-02T04:07:34.000Z
ext/annotations/reader.cpp
unisys12/phalcon-hhvm
ceeabc4f8d2e51b7cae9d0e100bb4055affe65bf
[ "BSD-2-Clause" ]
null
null
null
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez <andres@phalconphp.com> | | Eduar Carvajal <eduar@phalconphp.com> | +------------------------------------------------------------------------+ */ #include "annotations/reader.h" #include "annotations/readerinterface.h" #include "annotations/annot.h" #include "annotations/exception.h" #include "annotations/scanner.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/exception.h" #include "kernel/object.h" #include "kernel/fcall.h" #include "kernel/array.h" #include "kernel/file.h" #include "kernel/reflection.h" /** * Phalcon\Annotations\Reader * * Parses docblocks returning an array with the found annotations */ zend_class_entry *phalcon_annotations_reader_ce; PHP_METHOD(Phalcon_Annotations_Reader, parse); PHP_METHOD(Phalcon_Annotations_Reader, parseDocBlock); static const zend_function_entry phalcon_annotations_reader_method_entry[] = { PHP_ME(Phalcon_Annotations_Reader, parse, arginfo_phalcon_annotations_readerinterface_parse, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Annotations_Reader, parseDocBlock, arginfo_phalcon_annotations_readerinterface_parsedocblock, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_FE_END }; /** * Phalcon\Annotations\Reader initializer */ PHALCON_INIT_CLASS(Phalcon_Annotations_Reader){ PHALCON_REGISTER_CLASS(Phalcon\\Annotations, Reader, annotations_reader, phalcon_annotations_reader_method_entry, 0); zend_class_implements(phalcon_annotations_reader_ce TSRMLS_CC, 1, phalcon_annotations_readerinterface_ce); return SUCCESS; } /** * Reads annotations from the class dockblocks, its methods and/or properties * * @param string $className * @return array */ PHP_METHOD(Phalcon_Annotations_Reader, parse){ zval *class_name, *annotations; zval *class_annotations, *annotations_properties, *annotations_methods; zend_class_entry *class_ce; const char *file; zend_uint line; phalcon_fetch_params(0, 1, 0, &class_name); if (unlikely(Z_TYPE_P(class_name) != IS_STRING)) { PHALCON_THROW_EXCEPTION_STRW(phalcon_annotations_exception_ce, "The class name must be a string"); return; } class_ce = zend_fetch_class(Z_STRVAL_P(class_name), Z_STRLEN_P(class_name), ZEND_FETCH_CLASS_AUTO | ZEND_FETCH_CLASS_SILENT TSRMLS_CC); if (!class_ce) { zend_throw_exception_ex(phalcon_annotations_exception_ce, 0 TSRMLS_CC, "Class %s does not exist", Z_STRVAL_P(class_name)); return; } if (class_ce->type != ZEND_USER_CLASS) { array_init(return_value); return; } PHALCON_MM_GROW(); PHALCON_INIT_VAR(annotations); array_init(annotations); file = phalcon_get_class_filename(class_ce); if (!file) { file = "(unknown)"; } /* Class info */ { const char *cmt; zend_uint cmt_len; if (phalcon_get_class_doc_comment(class_ce, &cmt, &cmt_len)) { line = phalcon_get_class_startline(class_ce); PHALCON_INIT_VAR(class_annotations); RETURN_MM_ON_FAILURE(phannot_parse_annotations(class_annotations, cmt, cmt_len, file, line TSRMLS_CC)); if (Z_TYPE_P(class_annotations) == IS_ARRAY) { phalcon_array_update_string(&annotations, SL("class"), class_annotations, PH_COPY); } } } /* Get class properties */ { HashTable *props = &class_ce->properties_info; if (zend_hash_num_elements(props) > 0) { HashPosition hp; zend_property_info *property; PHALCON_INIT_VAR(annotations_properties); array_init_size(annotations_properties, zend_hash_num_elements(props)); for ( zend_hash_internal_pointer_reset_ex(props, &hp); zend_hash_get_current_data_ex(props, (void**)&property, &hp) != FAILURE; zend_hash_move_forward_ex(props, &hp) ) { const char *cmt; zend_uint cmt_len; if (phalcon_get_property_doc_comment(property, &cmt, &cmt_len)) { zval *property_annotations; MAKE_STD_ZVAL(property_annotations); if (FAILURE == phannot_parse_annotations(property_annotations, cmt, cmt_len, file, 0 TSRMLS_CC)) { zval_ptr_dtor(&property_annotations); RETURN_MM(); } if (Z_TYPE_P(property_annotations) == IS_ARRAY) { #if PHP_VERSION_ID >= 50400 { const char *prop_name, *class_name; if (zend_unmangle_property_name(property->name, property->name_length - 1, &class_name, &prop_name) == SUCCESS) { add_assoc_zval_ex(annotations_properties, prop_name, strlen(prop_name) + 1, property_annotations); } } #else { char *prop_name, *class_name; if (zend_unmangle_property_name(property->name, property->name_length - 1, &class_name, &prop_name) == SUCCESS) { add_assoc_zval_ex(annotations_properties, prop_name, strlen(prop_name) + 1, property_annotations); } } #endif } else { zval_ptr_dtor(&property_annotations); } } } if (zend_hash_num_elements(Z_ARRVAL_P(annotations_properties))) { phalcon_array_update_string(&annotations, SL("properties"), annotations_properties, PH_COPY); } } } /* Get class methods */ { HashTable *methods = &class_ce->function_table; if (zend_hash_num_elements(methods) > 0) { HashPosition hp; zend_function *method; PHALCON_INIT_VAR(annotations_methods); array_init_size(annotations_methods, zend_hash_num_elements(methods)); for ( zend_hash_internal_pointer_reset_ex(methods, &hp); zend_hash_get_current_data_ex(methods, (void**)&method, &hp) != FAILURE; zend_hash_move_forward_ex(methods, &hp) ) { const char *cmt; zend_uint cmt_len; if (phalcon_get_function_doc_comment(method, &cmt, &cmt_len)) { zval *method_annotations; line = phalcon_get_function_startline(method); MAKE_STD_ZVAL(method_annotations); if (FAILURE == phannot_parse_annotations(method_annotations, cmt, cmt_len, file, line TSRMLS_CC)) { zval_ptr_dtor(&method_annotations); RETURN_MM(); } if (Z_TYPE_P(method_annotations) == IS_ARRAY) { add_assoc_zval_ex(annotations_methods, method->common.function_name, strlen(method->common.function_name) + 1, method_annotations); } else { zval_ptr_dtor(&method_annotations); } } } if (zend_hash_num_elements(Z_ARRVAL_P(annotations_methods))) { phalcon_array_update_string(&annotations, SL("methods"), annotations_methods, PH_COPY); } } } RETURN_CTOR(annotations); } /** * Parses a raw doc block returning the annotations found * * @param string $docBlock * @param string $file * @param int $line * @return array */ PHP_METHOD(Phalcon_Annotations_Reader, parseDocBlock) { zval **doc_block, **file = NULL, **line = NULL; phalcon_fetch_params_ex(3, 0, &doc_block, &file, &line); PHALCON_ENSURE_IS_STRING(doc_block); PHALCON_ENSURE_IS_STRING(file); PHALCON_ENSURE_IS_LONG(line); RETURN_ON_FAILURE(phannot_parse_annotations(return_value, Z_STRVAL_PP(doc_block), Z_STRLEN_PP(doc_block), Z_STRVAL_PP(file), Z_RESVAL_PP(line) TSRMLS_CC)); }
32.312757
156
0.681737
[ "object" ]
8b5182698ec31a834a1b7e22ecb6c3f437dc49ad
1,055
cpp
C++
src/Tetris/GameObjects/GameOver.cpp
emersonmx/tetris-sfml
badb834cd59f30cd3dd75115f1e7a67865c1703e
[ "MIT" ]
null
null
null
src/Tetris/GameObjects/GameOver.cpp
emersonmx/tetris-sfml
badb834cd59f30cd3dd75115f1e7a67865c1703e
[ "MIT" ]
7
2016-06-23T00:50:17.000Z
2016-07-05T01:55:12.000Z
src/Tetris/GameObjects/GameOver.cpp
emersonmx/tetris-sfml
badb834cd59f30cd3dd75115f1e7a67865c1703e
[ "MIT" ]
null
null
null
#include "Tetris/GameObjects/GameOver.hpp" #include <SFML/Graphics/RenderTarget.hpp> #include <SFML/Graphics/RenderStates.hpp> #include "Tetris/Utils.hpp" namespace tetris { namespace gameobjects { void GameOver::create() { sf::Text text("GAME OVER", *font_, characterSize_); text.setFillColor(foregroundColor_); auto origin = tetris::utils::calculateCenterOfRect(text.getLocalBounds()); text.setOrigin(origin); text_ = text; background_.setFillColor(backgroundColor_); auto size = tetris::utils::calculateSizeOfRect(text.getLocalBounds()); size.x += 64; size.y += 20; background_.setSize(size); origin = tetris::utils::calculateCenterOfRect(background_.getLocalBounds()); background_.setOrigin(origin); } void GameOver::draw(sf::RenderTarget& target, sf::RenderStates states) const { if (!getActive()) { return; } states.transform *= getTransform(); target.draw(background_, states); target.draw(text_, states); } } /* namespace gameobjects */ } /* namespace tetris */
26.375
80
0.703318
[ "transform" ]
8b6b3d68e5c71969b5379aca6db3f3f5e07613df
2,399
cc
C++
chrome/browser/ui/views/harmony/bulleted_label_list_view.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/ui/views/harmony/bulleted_label_list_view.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/ui/views/harmony/bulleted_label_list_view.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/harmony/bulleted_label_list_view.h" #include "chrome/browser/ui/views/harmony/chrome_layout_provider.h" #include "ui/gfx/canvas.h" #include "ui/views/controls/label.h" #include "ui/views/layout/grid_layout.h" namespace { constexpr int kColumnSetId = 0; class BulletView : public views::View { public: explicit BulletView(SkColor color) : color_(color) {} void OnPaint(gfx::Canvas* canvas) override; private: SkColor color_; DISALLOW_COPY_AND_ASSIGN(BulletView); }; void BulletView::OnPaint(gfx::Canvas* canvas) { View::OnPaint(canvas); SkScalar radius = std::min(height(), width()) / 8.0; gfx::Point center = GetLocalBounds().CenterPoint(); SkPath path; path.addCircle(center.x(), center.y(), radius); cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kStrokeAndFill_Style); flags.setColor(color_); flags.setAntiAlias(true); canvas->DrawPath(path, flags); } } // namespace BulletedLabelListView::BulletedLabelListView() : BulletedLabelListView(std::vector<base::string16>()) {} BulletedLabelListView::BulletedLabelListView( const std::vector<base::string16>& texts) { constexpr auto FILL = views::GridLayout::FILL; constexpr auto USE_PREF = views::GridLayout::USE_PREF; constexpr auto FIXED = views::GridLayout::FIXED; views::GridLayout* layout = SetLayoutManager(std::make_unique<views::GridLayout>(this)); views::ColumnSet* columns = layout->AddColumnSet(kColumnSetId); int width = ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_UNRELATED_CONTROL_HORIZONTAL); columns->AddColumn(FILL, FILL, 0, FIXED, width, width); columns->AddColumn(FILL, FILL, 1, USE_PREF, 0, 0); for (const auto& text : texts) AddLabel(text); } BulletedLabelListView::~BulletedLabelListView() {} void BulletedLabelListView::AddLabel(const base::string16& text) { views::GridLayout* layout = static_cast<views::GridLayout*>(GetLayoutManager()); layout->StartRow(0, kColumnSetId); auto label = std::make_unique<views::Label>(text); label->SetMultiLine(true); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); layout->AddView(new BulletView(label->enabled_color())); layout->AddView(label.release()); }
28.903614
73
0.73489
[ "vector" ]
8b70009ba669b538fceed5fc3aa2c3ef7abe5073
2,268
hpp
C++
include/codegen/include/System/Collections/IList.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Collections/IList.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Collections/IList.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:52 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Collections.ICollection #include "System/Collections/ICollection.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: System.Collections namespace System::Collections { // Autogenerated type: System.Collections.IList class IList : public System::Collections::ICollection, public System::Collections::IEnumerable { public: // public System.Object get_Item(System.Int32 index) // Offset: 0xFFFFFFFF ::Il2CppObject* System_Collections_IList_get_Item(int index); // public System.Void set_Item(System.Int32 index, System.Object value) // Offset: 0xFFFFFFFF void System_Collections_IList_set_Item(int index, ::Il2CppObject* value); // public System.Int32 Add(System.Object value) // Offset: 0xFFFFFFFF int System_Collections_IList_Add(::Il2CppObject* value); // public System.Boolean Contains(System.Object value) // Offset: 0xFFFFFFFF bool System_Collections_IList_Contains(::Il2CppObject* value); // public System.Void Clear() // Offset: 0xFFFFFFFF void System_Collections_IList_Clear(); // public System.Boolean get_IsReadOnly() // Offset: 0xFFFFFFFF bool System_Collections_IList_get_IsReadOnly(); // public System.Int32 IndexOf(System.Object value) // Offset: 0xFFFFFFFF int System_Collections_IList_IndexOf(::Il2CppObject* value); // public System.Void Insert(System.Int32 index, System.Object value) // Offset: 0xFFFFFFFF void System_Collections_IList_Insert(int index, ::Il2CppObject* value); // public System.Void Remove(System.Object value) // Offset: 0xFFFFFFFF void System_Collections_IList_Remove(::Il2CppObject* value); // public System.Void RemoveAt(System.Int32 index) // Offset: 0xFFFFFFFF void System_Collections_IList_RemoveAt(int index); }; // System.Collections.IList } DEFINE_IL2CPP_ARG_TYPE(System::Collections::IList*, "System.Collections", "IList"); #pragma pack(pop)
42.792453
98
0.723104
[ "object" ]
8b7313c8f837b0aa94c4cf8fd9c474122de6018b
1,489
cpp
C++
tests/use_case/object_detection/ExpectedObjectDetectionResults.cpp
emza-vs/face_detection_example_arm_u55
21636e52de887deac8cde4c791527bb466387f2a
[ "Apache-2.0" ]
2
2022-01-13T17:30:55.000Z
2022-02-26T02:08:15.000Z
tests/use_case/object_detection/ExpectedObjectDetectionResults.cpp
emza-vs/face_detection_example_arm_u55
21636e52de887deac8cde4c791527bb466387f2a
[ "Apache-2.0" ]
null
null
null
tests/use_case/object_detection/ExpectedObjectDetectionResults.cpp
emza-vs/face_detection_example_arm_u55
21636e52de887deac8cde4c791527bb466387f2a
[ "Apache-2.0" ]
1
2022-01-13T17:31:02.000Z
2022-01-13T17:31:02.000Z
#include "ExpectedObjectDetectionResults.hpp" /* //Reference results Got 2 boxes 0) (0.999246) -> Detection box: {x=89,y=17,w=41,h=56} 1) (0.995367) -> Detection box: {x=27,y=81,w=48,h=53} Entering TestInference Got 1 boxes 0) (0.998107) -> Detection box: {x=87,y=35,w=53,h=64} Entering TestInference Got 2 boxes 0) (0.999244) -> Detection box: {x=105,y=73,w=58,h=66} 1) (0.985984) -> Detection box: {x=34,y=40,w=70,h=95} Entering TestInference Got 2 boxes 0) (0.993294) -> Detection box: {x=22,y=43,w=39,h=53} 1) (0.992021) -> Detection box: {x=63,y=60,w=38,h=45} */ void get_expected_ut_results(std::vector<std::vector<arm::app::DetectionResult>> &expected_results) { expected_results.resize(4); std::vector<arm::app::DetectionResult> img_1(2); std::vector<arm::app::DetectionResult> img_2(1); std::vector<arm::app::DetectionResult> img_3(2); std::vector<arm::app::DetectionResult> img_4(2); img_1[0] = arm::app::DetectionResult(0.99,89,17,41,56); img_1[1] = arm::app::DetectionResult(0.99,27,81,48,53); img_2[0] = arm::app::DetectionResult(0.99,87,35,53,64); img_3[0] = arm::app::DetectionResult(0.99,105,73,58,66); img_3[1] = arm::app::DetectionResult(0.98,34,40,70,95); img_4[0] = arm::app::DetectionResult(0.99,22,43,39,53); img_4[1] = arm::app::DetectionResult(0.99,63,60,38,45); expected_results[0] = img_1; expected_results[1] = img_2; expected_results[2] = img_3; expected_results[3] = img_4; }
29.196078
99
0.660846
[ "vector" ]
8b753c415d929c97031f910e8ae01f2588bbdf99
4,551
cpp
C++
rest/src/core/tests/TestOcrLine.cpp
cisocrgroup/pocoweb
93546d026321744602f6ee90fd82503da56da3b7
[ "Apache-2.0" ]
10
2018-04-09T20:46:49.000Z
2021-08-07T17:29:02.000Z
rest/src/core/tests/TestOcrLine.cpp
cisocrgroup/pocoweb
93546d026321744602f6ee90fd82503da56da3b7
[ "Apache-2.0" ]
61
2018-01-03T09:49:16.000Z
2022-02-18T12:26:11.000Z
rest/src/core/tests/TestOcrLine.cpp
cisocrgroup/pocoweb
93546d026321744602f6ee90fd82503da56da3b7
[ "Apache-2.0" ]
3
2020-01-10T15:44:18.000Z
2021-05-19T13:39:53.000Z
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE OcrLineTest #include "core/Line.hpp" #include <boost/test/unit_test.hpp> #include <functional> #include <iostream> #include <vector> using namespace pcw; struct Fixture { static const char* ocr; static const Box box; Fixture() : line(std::make_shared<Line>(1, box)) { line->append(ocr, 0, 100, 0.8); BOOST_REQUIRE(not line->empty()); BOOST_CHECK_EQUAL(line->box, box); } LinePtr line; }; const char* Fixture::ocr = "pectũeſt: quioo te mp"; const Box Fixture::box{ 0, 0, 100, 20 }; //////////////////////////////////////////////////////////////////////////////// BOOST_FIXTURE_TEST_SUITE(OcrLineTest, Fixture) //////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(Line) { BOOST_CHECK_EQUAL(line->ocr(), ocr); BOOST_CHECK_EQUAL(line->cor(), ocr); // cor and ocr must be the same BOOST_CHECK_CLOSE(line->average_conf(), .8, .001); // it's not rocket sience BOOST_CHECK_EQUAL(line->chars().back().cut, 100); BOOST_CHECK(not line->is_fully_corrected()); } //////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(Tokens) { auto tokens = line->tokens(); BOOST_REQUIRE(tokens.size() == 7); BOOST_CHECK(tokens[0].is_normal()); BOOST_CHECK_EQUAL(tokens[0].ocr(), "pectũeſt"); BOOST_CHECK_EQUAL(tokens[0].cor(), "pectũeſt"); BOOST_CHECK_EQUAL(tokens[0].cor(), "pectũeſt"); BOOST_CHECK(not tokens[0].is_fully_corrected()); BOOST_CHECK(not tokens[1].is_normal()); BOOST_CHECK_EQUAL(tokens[1].ocr(), ": "); BOOST_CHECK_EQUAL(tokens[1].cor(), ": "); BOOST_CHECK(not tokens[1].is_fully_corrected()); BOOST_CHECK(tokens[2].is_normal()); BOOST_CHECK_EQUAL(tokens[2].ocr(), "quioo"); BOOST_CHECK_EQUAL(tokens[2].cor(), "quioo"); BOOST_CHECK(not tokens[2].is_fully_corrected()); BOOST_CHECK(not tokens[3].is_normal()); BOOST_CHECK_EQUAL(tokens[3].ocr(), " "); BOOST_CHECK_EQUAL(tokens[3].cor(), " "); BOOST_CHECK(not tokens[3].is_fully_corrected()); BOOST_CHECK(tokens[4].is_normal()); BOOST_CHECK_EQUAL(tokens[4].ocr(), "te"); BOOST_CHECK_EQUAL(tokens[4].cor(), "te"); BOOST_CHECK(not tokens[4].is_fully_corrected()); BOOST_CHECK(not tokens[5].is_normal()); BOOST_CHECK_EQUAL(tokens[5].ocr(), " "); BOOST_CHECK_EQUAL(tokens[5].cor(), " "); BOOST_CHECK(not tokens[5].is_fully_corrected()); BOOST_CHECK(tokens[6].is_normal()); BOOST_CHECK_EQUAL(tokens[6].ocr(), "mp"); BOOST_CHECK_EQUAL(tokens[6].cor(), "mp"); BOOST_CHECK(not tokens[6].is_fully_corrected()); } //////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(Words) { auto words = line->words(); BOOST_CHECK_EQUAL(words.size(), 4); BOOST_CHECK(std::all_of( begin(words), end(words), [](const auto& c) { return c.is_normal(); })); BOOST_CHECK_EQUAL(words[0].ocr(), "pectũeſt"); BOOST_CHECK_EQUAL(words[0].cor(), "pectũeſt"); BOOST_CHECK(not words[0].is_fully_corrected()); BOOST_CHECK_EQUAL(words[1].ocr(), "quioo"); BOOST_CHECK_EQUAL(words[1].cor(), "quioo"); BOOST_CHECK(not words[1].is_fully_corrected()); BOOST_CHECK_EQUAL(words[2].ocr(), "te"); BOOST_CHECK_EQUAL(words[2].cor(), "te"); BOOST_CHECK(not words[2].is_fully_corrected()); BOOST_CHECK_EQUAL(words[3].ocr(), "mp"); BOOST_CHECK_EQUAL(words[3].cor(), "mp"); BOOST_CHECK(not words[3].is_fully_corrected()); } //////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(WordBoundinBoxes) { auto words = line->words(); BOOST_CHECK_EQUAL(words.size(), 4); BOOST_CHECK_EQUAL(words[0].box.top(), 0); BOOST_CHECK_EQUAL(words[0].box.bottom(), 20); BOOST_CHECK_EQUAL(words[0].box.height(), 20); BOOST_CHECK(words[0].box.width() > 0); BOOST_CHECK_EQUAL(words[1].box.top(), 0); BOOST_CHECK_EQUAL(words[1].box.bottom(), 20); BOOST_CHECK_EQUAL(words[1].box.height(), 20); BOOST_CHECK(words[1].box.width() > 0); BOOST_CHECK_EQUAL(words[2].box.top(), 0); BOOST_CHECK_EQUAL(words[2].box.bottom(), 20); BOOST_CHECK_EQUAL(words[2].box.height(), 20); BOOST_CHECK(words[2].box.width() > 0); BOOST_CHECK_EQUAL(words[3].box.top(), 0); BOOST_CHECK_EQUAL(words[3].box.bottom(), 20); BOOST_CHECK_EQUAL(words[3].box.right(), 100); BOOST_CHECK_EQUAL(words[3].box.height(), 20); BOOST_CHECK(words[3].box.width() > 0); } //////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE_END()
32.978261
80
0.617886
[ "vector" ]
8b757498ad63ea806fd750de28ba233d15c03a1d
3,371
cpp
C++
src/geo_bsd/hpgl/sequential_gaussian_simulation.cpp
hpgl/hpgl
72d8c4113c242295de740513093f5779c94ba84a
[ "BSD-3-Clause" ]
70
2015-01-21T12:24:50.000Z
2022-03-16T02:10:45.000Z
src/geo_bsd/hpgl/sequential_gaussian_simulation.cpp
hpgl/hpgl
72d8c4113c242295de740513093f5779c94ba84a
[ "BSD-3-Clause" ]
8
2015-04-22T13:14:30.000Z
2021-11-23T12:16:32.000Z
src/geo_bsd/hpgl/sequential_gaussian_simulation.cpp
hpgl/hpgl
72d8c4113c242295de740513093f5779c94ba84a
[ "BSD-3-Clause" ]
18
2015-02-15T18:04:31.000Z
2021-01-16T08:54:32.000Z
#include "stdafx.h" #include "api.h" #include "property_array.h" #include "sugarbox_grid.h" #include "sgs_params.h" #include "pretty_printer.h" #include "sequential_simulation.h" #include "calc_mean.h" #include "mean_provider.h" #include "my_kriging_weights.h" #include "sugarbox_indexed_neighbour_lookup.h" #include "lvm_utils.h" #include "gaussian_distribution.h" #include "non_parametric_cdf.h" namespace hpgl { void sequential_gaussian_simulation( const sugarbox_grid_t & grid, const sgs_params_t & params, cont_property_array_t & output, const hpgl_non_parametric_cdf_t * cdf, const unsigned char * mask) { print_algo_name("Sequential Gaussian Simulation"); print_params(params); if (output.size() != grid.size()) throw hpgl_exception("sequential_gaussian_simulation", boost::format("Input property size: %s. Grid size: %s. Must be equal.") % output.size() % grid.size()); if (cdf != 0) { transform_cdf_p(output, non_parametric_cdf_2_t(cdf), gaussian_cdf_t()); } if (params.m_kriging_kind == KRIG_SIMPLE) { double mean = 0; if (mask != NULL) { do_sequential_gausian_simulation( output, grid, params, single_mean_t(mean), sk_weight_calculator_t(), mask); } else { do_sequential_gausian_simulation( output, grid, params, single_mean_t(mean), sk_weight_calculator_t(), no_mask_t()); } } else { if (mask != NULL) { do_sequential_gausian_simulation( output, grid, params, no_mean_t(), ok_weight_calculator_t(), mask); } else { do_sequential_gausian_simulation( output, grid, params, no_mean_t(), ok_weight_calculator_t(), no_mask_t()); } } if (cdf != 0) transform_cdf_p(output, gaussian_cdf_t(), non_parametric_cdf_2_t(cdf)); } void sequential_gaussian_simulation_lvm( const sugarbox_grid_t & grid, const sgs_params_t & params, const mean_t * mean_data, cont_property_array_t & output, const hpgl_non_parametric_cdf_t * cdf, const unsigned char * mask ) { print_algo_name("Sequential Gaussian Simulation with Local Varying Mean"); print_params(params); if (output.size() != grid.size()) throw hpgl_exception("sequential_gaussian_simulation_lvm", boost::format("Input property size: %s. Grid size: %s. Must be equal.") % output.size() % grid.size()); if (output.size() != grid.size()) throw hpgl_exception("sequential_gaussian_simulation", boost::format("Input property size: %s. Grid size: %s. Must be equal.") % output.size() % grid.size()); std::vector<mean_t> mean_data_vec; mean_data_vec.assign(mean_data, mean_data + output.size() ); if (cdf != 0) { non_parametric_cdf_2_t new_cdf(cdf); transform_cdf_p(output, new_cdf, gaussian_cdf_t()); transform_cdf_ptr(mean_data, mean_data_vec, new_cdf, gaussian_cdf_t()); } if (mask != NULL) { do_sequential_gausian_simulation( output, grid, params, mean_data_vec, sk_weight_calculator_t(), mask); } else { do_sequential_gausian_simulation( output, grid, params, mean_data_vec, sk_weight_calculator_t(), no_mask_t()); } if (cdf != 0) { non_parametric_cdf_2_t new_cdf(cdf); transform_cdf_p(output, gaussian_cdf_t(), new_cdf); } } }
25.930769
112
0.677247
[ "vector" ]
8b85be30fc5c662c764643a2c05844b1564a5140
1,003
hpp
C++
include/lol/def/LolChampSelectLegacyLobbyStatus.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LolChampSelectLegacyLobbyStatus.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LolChampSelectLegacyLobbyStatus.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" namespace lol { struct LolChampSelectLegacyLobbyStatus { int32_t queueId; bool isCustom; bool isLeader; bool isSpectator; bool allowedPlayAgain; std::vector<uint64_t> memberSummonerIds; }; inline void to_json(json& j, const LolChampSelectLegacyLobbyStatus& v) { j["queueId"] = v.queueId; j["isCustom"] = v.isCustom; j["isLeader"] = v.isLeader; j["isSpectator"] = v.isSpectator; j["allowedPlayAgain"] = v.allowedPlayAgain; j["memberSummonerIds"] = v.memberSummonerIds; } inline void from_json(const json& j, LolChampSelectLegacyLobbyStatus& v) { v.queueId = j.at("queueId").get<int32_t>(); v.isCustom = j.at("isCustom").get<bool>(); v.isLeader = j.at("isLeader").get<bool>(); v.isSpectator = j.at("isSpectator").get<bool>(); v.allowedPlayAgain = j.at("allowedPlayAgain").get<bool>(); v.memberSummonerIds = j.at("memberSummonerIds").get<std::vector<uint64_t>>(); } }
35.821429
82
0.664008
[ "vector" ]
8b8f4d8ac115e0797a65960d19114ef7bb62aad5
1,627
cpp
C++
LeetCode/Problems/Algorithms/#332_ReconstructItinerary_sol1_euler_path_40ms_13.6MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#332_ReconstructItinerary_sol1_euler_path_40ms_13.6MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#332_ReconstructItinerary_sol1_euler_path_40ms_13.6MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { private: void euler(vector<vector<int>>& g, int node, stack<int>& st){ while(!g[node].empty()){ int next_node = g[node].back(); g[node].pop_back(); euler(g, next_node, st); } st.push(node); } public: vector<string> findItinerary(vector<vector<string>>& tickets) { // Step 1: build the graph map<string, int> airport_idx; for(const vector<string>& ticket: tickets){ airport_idx[ticket[0]] = 1; airport_idx[ticket[1]] = 1; } int idx = 0; for(pair<const string, int>& p: airport_idx){ p.second = ++idx; } const int N = idx; vector<string> airport_names(N + 1); for(const pair<string, int>& p: airport_idx){ airport_names[p.second] = p.first; } vector<vector<int>> g(N + 1); for(const vector<string>& ticket: tickets){ g[airport_idx[ticket[0]]].push_back(airport_idx[ticket[1]]); } // Step 2: sort the neighbors of each node for(int node = 1; node <= N; ++node){ sort(g[node].begin(), g[node].end(), greater<int>()); } // Step 3: save the euler path of the graph vector<string> answer; stack<int> st; euler(g, airport_idx["JFK"], st); while(!st.empty()){ answer.push_back(airport_names[st.top()]); st.pop(); } return answer; } };
30.12963
73
0.477566
[ "vector" ]
8b91ae912119836e36a92b8fdd03f787d353a8af
1,419
hpp
C++
player/playerlib/AudioRender.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
player/playerlib/AudioRender.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
player/playerlib/AudioRender.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
/* * This file is part of FFL project. * * The MIT License (MIT) * Copyright (C) 2017-2018 zhufeifei All rights reserved. * * AudioRender.hpp * Created by zhufeifei(34008081@qq.com) on 2018/04/07 * https://github.com/zhenfei2016/FFL-v2.git * * 声音的渲染类 * */ #ifndef _AUDIO_RENDER_HPP_ #define _AUDIO_RENDER_HPP_ #include "Render.hpp" #include "VideoSurface.hpp" #include "VideoTexture.hpp" #include "AudioSample.hpp" #include "Statistic.hpp" #include "TimestampExtrapolator.hpp" namespace player { class AudioResample; class AudioDevice; class AudioRender : public Render { public: AudioRender(FFL::sp<AudioDevice> device); ~AudioRender(); void pause(); void resume(); void onCreate(); public: // // 获取渲染时钟,可以改变时钟速度 // virtual FFL::sp<FFL::Clock> getRenderClock(); // // 外部setDataInput时候调用此函数,创建对应conn // virtual FFL::sp<FFL::PipelineConnector > onCreateConnector(const OutputInterface& output, const InputInterface& input,void* userdata); bool handleReceivedData(const FFL::sp<FFL::PipelineMessage>& msg, void* userdata); private: // // 开始显示 // virtual void onShowSamples(AudioSample* samples); protected: IStatisticAudioRender* mStatistic; TimestampExtrapolator* mTimestampExtrapolator; FFL::sp<AudioDevice> mDevice; int64_t mFrameIndex; FFL::sp<FFL::Clock> mClock; // // 是否需要重置同步时钟 // volatile bool mResetSyncClock; }; } #endif
19.985915
91
0.714588
[ "render" ]
8b9606b9c3288a334290f7e9cf616ca7442266ef
10,666
cpp
C++
intersectionsplitter/tests/intersectionsplittertest.cpp
csteuer/LineSegmentsIntersectionSplitter
22222e66dabd62fe0d9ea000d2be84e3aec18a46
[ "MIT" ]
3
2020-12-29T20:23:40.000Z
2021-11-02T16:48:18.000Z
intersectionsplitter/tests/intersectionsplittertest.cpp
ClausSteuer/LineSegmentsIntersectionSplitter
22222e66dabd62fe0d9ea000d2be84e3aec18a46
[ "MIT" ]
null
null
null
intersectionsplitter/tests/intersectionsplittertest.cpp
ClausSteuer/LineSegmentsIntersectionSplitter
22222e66dabd62fe0d9ea000d2be84e3aec18a46
[ "MIT" ]
1
2021-08-11T02:22:09.000Z
2021-08-11T02:22:09.000Z
#include <gmock/gmock.h> #include <intersectionsplitter/intersectionsplitter.h> #include "testutils.hpp" using namespace intersectionsplitter; TEST(WallFragmentIntersectionSplitterTest, singleFragment) { std::vector<LineSegmentPtr> input = {Segment(0, 0, 1, 0)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 0, 1, 0))); } TEST(WallFragmentIntersectionSplitterTest, twoFragmentsNoIntersection) { std::vector<LineSegmentPtr> input = {Segment(0, 0, 1, 0), Segment(2, 0, 2, 2)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 0, 1, 0), SegmentMatch(2, 0, 2, 2))); } TEST(WallFragmentIntersectionSplitterTest, twoFragmentsWithIntersection) { std::vector<LineSegmentPtr> input = {Segment(0, 0, 2, 4), Segment(2, 0, 0, 4)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 0, 1, 2), SegmentMatch(1, 2, 2, 4), SegmentMatch(2, 0, 1, 2), SegmentMatch(1, 2, 0, 4))); } TEST(WallFragmentIntersectionSplitterTest, twoFragmentsNoIntersectionButSameEndPoint) { std::vector<LineSegmentPtr> input = {Segment(0, 0, 1, 2), Segment(1, 2, 2, 4)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 0, 1, 2), SegmentMatch(1, 2, 2, 4))); } TEST(WallFragmentIntersectionSplitterTest, threeFragmentsIntersectingAtSamePoint) { std::vector<LineSegmentPtr> input = { Segment(0, 0, 2, 4), Segment(2, 0, 0, 4), Segment(0, 2, 2, 2), }; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 0, 1, 2), SegmentMatch(1, 2, 2, 4), SegmentMatch(2, 0, 1, 2), SegmentMatch(1, 2, 0, 4), SegmentMatch(0, 2, 1, 2), SegmentMatch(1, 2, 2, 2))); } TEST(WallFragmentIntersectionSplitterTest, intersectionPointOnLine) { std::vector<LineSegmentPtr> input = {Segment(0, 0, 2, 2), Segment(2, 0, 2, 4)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 0, 2, 2), SegmentMatch(2, 0, 2, 2), SegmentMatch(2, 2, 2, 4))); } TEST(WallFragmentIntersectionSplitterTest, lineIntersectedTwoTimes) { std::vector<LineSegmentPtr> input = {Segment(0, 0, 10, 5), Segment(2, 0, 6, 4), Segment(9, 3, 7, 5)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 0, 4, 2), SegmentMatch(4, 2, 8, 4), SegmentMatch(8, 4, 10, 5), SegmentMatch(2, 0, 4, 2), SegmentMatch(4, 2, 6, 4), SegmentMatch(9, 3, 8, 4), SegmentMatch(8, 4, 7, 5))); } TEST(WallFragmentIntersectionSplitterTest, multipleIntersections) { std::vector<LineSegmentPtr> input = {Segment(0, 3, 4, 3), Segment(4, 2, 8, 2), Segment(5, 2, 3, 4), Segment(8, 0, 8, 2)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 3, 4, 3), SegmentMatch(4, 3, 3, 4), SegmentMatch(4, 3, 5, 2), SegmentMatch(4, 2, 5, 2), SegmentMatch(5, 2, 8, 2), SegmentMatch(8, 2, 8, 0))); } TEST(WallFragmentIntersectionSplitterTest, intersectWithExtendForward) { std::vector<LineSegmentPtr> input = {Segment(0, 0, 2, 0), Segment(4, 0, 4, 4)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input, 2.f); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 0, 2, 0), SegmentMatch(2, 0, 4, 0), SegmentMatch(4, 0, 4, 4))); } TEST(WallFragmentIntersectionSplitterTest, intersectWithExtendBackward) { std::vector<LineSegmentPtr> input = {Segment(2, 0, 4, 0), Segment(0, 0, 0, 4)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input, 2.f); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 0, 0, 4), SegmentMatch(0, 0, 2, 0), SegmentMatch(2, 0, 4, 0))); } TEST(WallFragmentIntersectionSplitterTest, intersectWithExtendTwice) { std::vector<LineSegmentPtr> input = {Segment(0, 0, 2, 0), Segment(4, 0, 4, 4), Segment(5, 0, 5, 4)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input, 4.f); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 0, 2, 0), SegmentMatch(2, 0, 4, 0), SegmentMatch(4, 0, 5, 0), SegmentMatch(4, 0, 4, 4), SegmentMatch(5, 0, 5, 4))); } TEST(WallFragmentIntersectionSplitterTest, floatCoordinates) { std::vector<LineSegmentPtr> input = {Segment(239, 335, 245, 328), Segment(243, 332, 235, 332)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(239, 335, 241.57143f, 332), SegmentMatch(241.57143f, 332, 245, 328), SegmentMatch(243, 332, 241.57143f, 332), SegmentMatch(241.57143f, 332, 235, 332))); } TEST(WallFragmentIntersectionSplitterTest, noIntersectRegression) { std::vector<LineSegmentPtr> input = {Segment(233, 398, 233, 384), Segment(243, 401, 237, 395)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(233, 398, 233, 384), SegmentMatch(243, 401, 237, 395))); } TEST(WallFragmentIntersectionSplitterTest, intersectFirstNormalAndThemWithExtendForward) { std::vector<LineSegmentPtr> input = {Segment(5, 20, 5, 5), Segment(0, 15, 10, 15), Segment(0, 4, 10, 4)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input, 4.f); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(5, 20, 5, 15), SegmentMatch(5, 15, 5, 5), SegmentMatch(5, 5, 5, 4), SegmentMatch(0, 15, 5, 15), SegmentMatch(5, 15, 10, 15), SegmentMatch(0, 4, 5, 4), SegmentMatch(5, 4, 10, 4))); } TEST(WallFragmentIntersectionSplitterTest, intersectInPast) { std::vector<LineSegmentPtr> input = {Segment(0, 5, 0, 0), Segment(4, 4, 10, 4), Segment(0, -1, 10, -1)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input, 4.f); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 5, 0, 4), SegmentMatch(0, 4, 0, 0), SegmentMatch(0, 0, 0, -1), SegmentMatch(0, 4, 4, 4), SegmentMatch(4, 4, 10, 4), SegmentMatch(0, -1, 10, -1))); } TEST(WallFragmentIntersectionSplitterTest, intersectTwoLeft) { std::vector<LineSegmentPtr> input = {Segment(0, 5, 0, 0), Segment(1, 2, 2, 1), Segment(2, 0, 4, 0)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input, 4.f); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 5, 0, 3), SegmentMatch(0, 3, 0, 0), SegmentMatch(0, 3, 1, 2), SegmentMatch(1, 2, 2, 1), SegmentMatch(2, 1, 3, 0), SegmentMatch(0, 0, 2, 0), SegmentMatch(2, 0, 3, 0), SegmentMatch(3, 0, 4, 0))); } TEST(WallFragmentIntersectionSplitterTest, intersectTwoRight) { std::vector<LineSegmentPtr> input = {Segment(5, 4, 5, 0), Segment(2, 5, 4, 3), Segment(1, 1, 3, 1)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input, 4.f); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(5, 4, 5, 2), SegmentMatch(5, 2, 5, 1), SegmentMatch(5, 1, 5, 0), SegmentMatch(2, 5, 4, 3), SegmentMatch(4, 3, 5, 2), SegmentMatch(5, 2, 6, 1), SegmentMatch(1, 1, 3, 1), SegmentMatch(3, 1, 5, 1), SegmentMatch(5, 1, 6, 1))); } TEST(WallFragmentIntersectionSplitterTest, intersectTwoRegression) { std::vector<LineSegmentPtr> input = {Segment(5, 510, 5, 485), Segment(9, 483, 47, 483)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input, 4.f); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(5, 510, 5, 485), SegmentMatch(5, 485, 5, 483), SegmentMatch(5, 483, 9, 483), SegmentMatch(9, 483, 47, 483))); } TEST(WallFragmentIntersectionSplitterTest, intersectAtEndpointRegression) { std::vector<LineSegmentPtr> input = {Segment(1253, 2406, 1231.448, 2371.106), Segment(1251.831, 2406.73, 1262.438, 2400.101)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input, 4.f); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(1253, 2406, 1231.448, 2371.106), SegmentMatch(1251.831, 2406.73, 1253, 2406), SegmentMatch(1253, 2406, 1262.438, 2400.101))); } TEST(WallFragmentIntersectionSplitterTest, intersectAtEndpointAndLeft) { std::vector<LineSegmentPtr> input = { Segment(0, 10, 0, 0), Segment(2, 10, 2, 0), Segment(4, 10, 4, 0), Segment(4, 5, 10, 5), }; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input, 4.f); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(0, 10, 0, 5), SegmentMatch(0, 5, 0, 0), SegmentMatch(2, 10, 2, 5), SegmentMatch(2, 5, 2, 0), SegmentMatch(4, 10, 4, 5), SegmentMatch(4, 5, 4, 0), SegmentMatch(0, 5, 2, 5), SegmentMatch(2, 5, 4, 5), SegmentMatch(4, 5, 10, 5))); } TEST(WallFragmentIntersectionSplitterTest, intersectionNearStartOfBothFragments) { std::vector<LineSegmentPtr> input = {Segment(641.6922, 1519.385, 649, 1515), Segment(641.8182, 1519.364, 640, 1518)}; std::vector<LineSegmentPtr> result = splitLineSegmentsAtIntersections(input, 0.f); EXPECT_THAT(result, testing::UnorderedElementsAre(SegmentMatch(641.6922, 1519.385, 649, 1515), SegmentMatch(641.8182, 1519.364, 640, 1518))); }
49.841121
159
0.641196
[ "vector" ]
8ba29d5fc3adb9a3263a4f987ca48308fef2bdf3
2,522
cpp
C++
laboratory/1065/Seminar_4/Source.cpp
catalinboja/catalinboja-cpp_2020
ff1d2dc8620ff722aef151c9c823ec20f766d5b2
[ "MIT" ]
4
2020-10-13T13:37:15.000Z
2021-07-10T15:40:40.000Z
laboratory/1065/Seminar_4/Source.cpp
catalinboja/catalinboja-cpp_2020
ff1d2dc8620ff722aef151c9c823ec20f766d5b2
[ "MIT" ]
null
null
null
laboratory/1065/Seminar_4/Source.cpp
catalinboja/catalinboja-cpp_2020
ff1d2dc8620ff722aef151c9c823ec20f766d5b2
[ "MIT" ]
7
2020-10-16T08:32:42.000Z
2021-03-02T14:38:28.000Z
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string.h> using namespace std; class Product { // private: - added by default unsigned int id = 0; //4B float price = 0; //4B public: bool isFragile = false; //1B char name[50] = "Nothing"; //50B private: int* salesVolume = nullptr; //sales recorded each month //4B int noMonths = 0; //4B //Total: 67B public: //accessor methods //give read and/or write accesss (rights) on private attributes int getId() { //receives by default the address of the object that will call this method //that address is stored in the this pointer return this->id; } float getPrice() { return this->price; } //we don't need it because is already public //bool getIsFragile() { // return this->isFragile; //} int* getSalesVolume() { return this->salesVolume; } int getNoMonths() { return this->noMonths; } void printProductData() { cout << endl << "------------------------------------"; cout << endl << "The product name is " << this->name; cout << endl << "The product id is " << this->id; cout << endl << "The product price is " << this->price; cout << endl << "The product no of monthly records " << this->noMonths; cout << endl << "The product is fragile " << (this->isFragile ? "yes" : "no"); if (this->salesVolume != nullptr) { cout << endl << "Sales volume: "; for (int i = 0; i < this->noMonths; i++) { cout << " " << this->salesVolume[i]; } } else { cout << endl << "No sales records"; } } //for write access void setPrice(float value) { if (value > 0) { this->price = value; } else { throw "Wrong value"; } } }; int main(int argc, char* argv[]) { //create an object Product prod1; //prod1.name[9] = '\0'; strcpy(prod1.name, "Milk"); prod1.setPrice(23); //cout << endl << "The size of a product is " << sizeof(prod1); //it's different than 67 because of cache optimization - compiler //cout << endl << "The product name is " << prod1.name; //cout << endl << "The product id is " << prod1.getId(); //cout << endl << "The product no of monthly records " << prod1.getNoMonths(); //cout << endl << "The product is fragile " << (prod1.isFragile ? "yes" : "no"); // //int* sales = prod1.getSalesVolume(); //if (sales != nullptr) { // cout << endl << "The product volume sales for 1st month " // << prod1.getSalesVolume()[0]; // cout << endl << "The product volume sales for 1st month " // << sales[0]; //} prod1.printProductData(); }
25.474747
130
0.605472
[ "object" ]
8ba81a5fe0942f2933725c4f3093b1abc9c5dc00
1,308
cpp
C++
modules/dnn/src/data_augmentor.cpp
anotherhelloworld/opencv
e46f5e25f911a5fe24d2d09c2310ae4287588762
[ "BSD-3-Clause" ]
null
null
null
modules/dnn/src/data_augmentor.cpp
anotherhelloworld/opencv
e46f5e25f911a5fe24d2d09c2310ae4287588762
[ "BSD-3-Clause" ]
null
null
null
modules/dnn/src/data_augmentor.cpp
anotherhelloworld/opencv
e46f5e25f911a5fe24d2d09c2310ae4287588762
[ "BSD-3-Clause" ]
null
null
null
#include "opencv2/dnn/data_augmentor.hpp" namespace cv { namespace dnn { DataAugment::DataAugment(const std::vector<cv::Mat>& images) : images(images) { std::function<cv::Mat(const cv::Mat&)> flipFunc = DataAugment::flipAugmentor; methods.push_back(Method(flipFunc)); } void DataAugment::createSample(std::vector<cv::Mat>& resImages) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> imageDis(0, images.size() - 1); std::uniform_real_distribution<> probabilityDis(0.0, 1.0); cv::Mat image = images[imageDis(gen)]; for (auto& method: methods) { double r = probabilityDis(gen); if (r <= method.getProbability()) { resImages.push_back(method.runAugmentor(image)); } } } void DataAugment::addMethod(std::function<cv::Mat(const cv::Mat&)>& augmentor) { methods.push_back(Method(augmentor)); } cv::Mat DataAugment::flipAugmentor(const cv::Mat& image) { cv::Mat flipped; cv::flip(image, flipped, 1); return flipped; } Method::Method(std::function<cv::Mat(const cv::Mat&)>& augmentor) : augmentor(augmentor) { } double Method::getProbability() const { return probability; } cv::Mat Method::runAugmentor(const cv::Mat& image) { return augmentor(image); } } }
21.8
81
0.66055
[ "vector" ]
8baf7c5435445127758de3ceca980335abe15a54
3,180
cpp
C++
src/execution/aggregation_executor.cpp
yshihao/my-bustub
2b67400587e936cd08ea9095936894c5469b49be
[ "MIT" ]
null
null
null
src/execution/aggregation_executor.cpp
yshihao/my-bustub
2b67400587e936cd08ea9095936894c5469b49be
[ "MIT" ]
null
null
null
src/execution/aggregation_executor.cpp
yshihao/my-bustub
2b67400587e936cd08ea9095936894c5469b49be
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // // BusTub // // aggregation_executor.cpp // // Identification: src/execution/aggregation_executor.cpp // // Copyright (c) 2015-19, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include <vector> #include "execution/executors/aggregation_executor.h" namespace bustub { AggregationExecutor::AggregationExecutor(ExecutorContext *exec_ctx, const AggregationPlanNode *plan, std::unique_ptr<AbstractExecutor> &&child) : AbstractExecutor(exec_ctx), plan_(plan), child_(std::move(child)), aht_({plan_->GetAggregates(), plan_->GetAggregateTypes()}), aht_iterator_({}) {} const AbstractExecutor *AggregationExecutor::GetChildExecutor() const { return child_.get(); } void AggregationExecutor::Init() { try { Tuple mytuple; RID rid; child_->Init(); if (!plan_->GetGroupBys().empty()) { while (child_->Next(&mytuple, &rid)) { AggregateKey group_by = MakeKey(&mytuple); AggregateValue aggre_value = MakeVal(&mytuple); aht_.InsertCombine(group_by, aggre_value); } } else { while (child_->Next(&mytuple, &rid)) { AggregateValue aggre_value = MakeVal(&mytuple); aht_.InsertCombine(AggregateKey{}, aggre_value); } } } catch (Exception &e) { throw "you met error"; } aht_iterator_ = aht_.Begin(); } bool AggregationExecutor::Next(Tuple *tuple, RID *rid) { while (aht_iterator_ != aht_.End()) { AggregateValue aggre_value = aht_iterator_.Val(); if (plan_->GetHaving() != nullptr) { if (plan_->GetHaving() ->EvaluateAggregate(aht_iterator_.Key().group_bys_, aht_iterator_.Val().aggregates_) .GetAs<bool>()) { // 把值给 tuple 还是要拼凑 std::vector<Value> aggreVector = aht_iterator_.Val().aggregates_; std::vector<Value> groupbyVector = aht_iterator_.Key().group_bys_; std::vector<Value> result; result.reserve(GetOutputSchema()->GetColumnCount()); for (auto &mycolumn : GetOutputSchema()->GetColumns()) { Value value = mycolumn.GetExpr()->EvaluateAggregate(groupbyVector, aggreVector); result.emplace_back(value); } *tuple = Tuple(result, GetOutputSchema()); ++aht_iterator_; return true; } ++aht_iterator_; continue; } std::vector<Value> aggreVector = aht_iterator_.Val().aggregates_; std::vector<Value> groupbyVector = aht_iterator_.Key().group_bys_; std::vector<Value> result; result.reserve(GetOutputSchema()->GetColumnCount()); for (auto &mycolumn : GetOutputSchema()->GetColumns()) { Value value = mycolumn.GetExpr()->EvaluateAggregate(groupbyVector, aggreVector); result.emplace_back(value); } *tuple = Tuple(result, GetOutputSchema()); ++aht_iterator_; return true; } return false; } } // namespace bustub
34.565217
101
0.593711
[ "vector" ]
8bb1e592f11687181314b0f3ffc9a14123384844
7,074
cpp
C++
src/type3_AndroidCloud/anbox-master/src/anbox/graphics/emugl/TextureDraw.cpp
akraino-edge-stack/iec
b01bce6165ef8368a607e17e1f3d4697b79db31b
[ "Apache-2.0" ]
null
null
null
src/type3_AndroidCloud/anbox-master/src/anbox/graphics/emugl/TextureDraw.cpp
akraino-edge-stack/iec
b01bce6165ef8368a607e17e1f3d4697b79db31b
[ "Apache-2.0" ]
null
null
null
src/type3_AndroidCloud/anbox-master/src/anbox/graphics/emugl/TextureDraw.cpp
akraino-edge-stack/iec
b01bce6165ef8368a607e17e1f3d4697b79db31b
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2015 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. #include "anbox/graphics/emugl/TextureDraw.h" #include "anbox/graphics/emugl/DispatchTables.h" #include "anbox/logger.h" #include <math.h> #include <string.h> #include <vector> #include <stdio.h> // M_PI isn't defined in C++ (when strict ISO compliance is enabled) #ifndef M_PI #define M_PI 3.14159265358979323846264338327 #endif namespace { // Helper function to create a new shader. // |shaderType| is the shader type (e.g. GL_VERTEX_SHADER). // |shaderText| is a 0-terminated C string for the shader source to use. // On success, return the handle of the new compiled shader, or 0 on failure. GLuint createShader(GLint shaderType, const char* shaderText) { // Create new shader handle and attach source. GLuint shader = s_gles2.glCreateShader(shaderType); if (!shader) { return 0; } const GLchar* text = static_cast<const GLchar*>(shaderText); const GLint textLen = ::strlen(shaderText); s_gles2.glShaderSource(shader, 1, &text, &textLen); // Compiler the shader. GLint success; s_gles2.glCompileShader(shader); s_gles2.glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (success == GL_FALSE) { s_gles2.glDeleteShader(shader); return 0; } return shader; } // No scaling / projection since we want to fill the whole viewport with // the texture, hence a trivial vertex shader. const char kVertexShaderSource[] = "attribute vec4 position;\n" "attribute vec2 inCoord;\n" "varying lowp vec2 outCoord;\n" "void main(void) {\n" " gl_Position.x = position.x;\n" " gl_Position.y = position.y;\n" " gl_Position.zw = position.zw;\n" " outCoord = inCoord;\n" "}\n"; // Similarly, just interpolate texture coordinates. const char kFragmentShaderSource[] = "varying lowp vec2 outCoord;\n" "uniform sampler2D texture;\n" "void main(void) {\n" " gl_FragColor = texture2D(texture, outCoord);\n" "}\n"; // Hard-coded arrays of vertex information. struct Vertex { float pos[3]; float coord[2]; }; const Vertex kVertices[] = { {{+1, -1, +0}, {+1, +1}}, {{+1, +1, +0}, {+1, +0}}, {{-1, +1, +0}, {+0, +0}}, {{-1, -1, +0}, {+0, +1}}, }; const GLubyte kIndices[] = {0, 1, 2, 2, 3, 0}; const GLint kIndicesLen = sizeof(kIndices) / sizeof(kIndices[0]); } // namespace TextureDraw::TextureDraw(EGLDisplay) : mVertexShader(0), mFragmentShader(0), mProgram(0), mPositionSlot(-1), mInCoordSlot(-1), mTextureSlot(-1) { // Create shaders and program. mVertexShader = createShader(GL_VERTEX_SHADER, kVertexShaderSource); mFragmentShader = createShader(GL_FRAGMENT_SHADER, kFragmentShaderSource); mProgram = s_gles2.glCreateProgram(); s_gles2.glAttachShader(mProgram, mVertexShader); s_gles2.glAttachShader(mProgram, mFragmentShader); GLint success; s_gles2.glLinkProgram(mProgram); s_gles2.glGetProgramiv(mProgram, GL_LINK_STATUS, &success); if (success == GL_FALSE) { GLchar messages[256]; s_gles2.glGetProgramInfoLog(mProgram, sizeof(messages), 0, &messages[0]); ERROR("Could not create/link program: %s", messages); s_gles2.glDeleteProgram(mProgram); mProgram = 0; return; } s_gles2.glUseProgram(mProgram); // Retrieve attribute/uniform locations. mPositionSlot = s_gles2.glGetAttribLocation(mProgram, "position"); s_gles2.glEnableVertexAttribArray(mPositionSlot); mInCoordSlot = s_gles2.glGetAttribLocation(mProgram, "inCoord"); s_gles2.glEnableVertexAttribArray(mInCoordSlot); mTextureSlot = s_gles2.glGetUniformLocation(mProgram, "texture"); // Create vertex and index buffers. s_gles2.glGenBuffers(1, &mVertexBuffer); s_gles2.glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer); s_gles2.glBufferData(GL_ARRAY_BUFFER, sizeof(kVertices), kVertices, GL_STATIC_DRAW); s_gles2.glGenBuffers(1, &mIndexBuffer); s_gles2.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer); s_gles2.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(kIndices), kIndices, GL_STATIC_DRAW); } bool TextureDraw::draw(GLuint texture) { if (!mProgram) { ERROR(" No program"); return false; } // TODO(digit): Save previous program state. GLenum err; s_gles2.glUseProgram(mProgram); err = s_gles2.glGetError(); if (err != GL_NO_ERROR) { ERROR("Could not use program error 0x%x", err); } // Setup the |position| attribute values. s_gles2.glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer); err = s_gles2.glGetError(); if (err != GL_NO_ERROR) { ERROR("Could not bind GL_ARRAY_BUFFER error=0x%x", err); } s_gles2.glEnableVertexAttribArray(mPositionSlot); s_gles2.glVertexAttribPointer(mPositionSlot, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); err = s_gles2.glGetError(); if (err != GL_NO_ERROR) { ERROR("Could glVertexAttribPointer with mPositionSlot error 0x%x", err); } // Setup the |inCoord| attribute values. s_gles2.glEnableVertexAttribArray(mInCoordSlot); s_gles2.glVertexAttribPointer( mInCoordSlot, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<GLvoid*>(static_cast<uintptr_t>(sizeof(float) * 3))); // setup the |texture| uniform value. s_gles2.glActiveTexture(GL_TEXTURE0); s_gles2.glBindTexture(GL_TEXTURE_2D, texture); s_gles2.glUniform1i(mTextureSlot, 0); // Validate program, just to be sure. s_gles2.glValidateProgram(mProgram); GLint validState = 0; s_gles2.glGetProgramiv(mProgram, GL_VALIDATE_STATUS, &validState); if (validState == GL_FALSE) { GLchar messages[256]; s_gles2.glGetProgramInfoLog(mProgram, sizeof(messages), 0, &messages[0]); ERROR("Could not run program: %s", messages); return false; } // Do the rendering. s_gles2.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer); err = s_gles2.glGetError(); if (err != GL_NO_ERROR) { ERROR("Could not glBindBuffer(GL_ELEMENT_ARRAY_BUFFER) error 0x%x", err); } s_gles2.glDrawElements(GL_TRIANGLES, kIndicesLen, GL_UNSIGNED_BYTE, 0); err = s_gles2.glGetError(); if (err != GL_NO_ERROR) { ERROR("Could not glDrawElements() error 0x%x", err); } // TODO(digit): Restore previous program state. return true; } TextureDraw::~TextureDraw() { s_gles2.glDeleteBuffers(1, &mIndexBuffer); s_gles2.glDeleteBuffers(1, &mVertexBuffer); if (mFragmentShader) { s_gles2.glDeleteShader(mFragmentShader); } if (mVertexShader) { s_gles2.glDeleteShader(mVertexShader); } }
30.756522
77
0.705966
[ "vector" ]
8bb91416d78a07f96109bd4459cfa257c8bd6637
780
cpp
C++
notebook/graphs/bipartite-checking.cpp
brnpapa/icpc
8149397daddc630e0fe2395f3f48e017154d223d
[ "MIT" ]
19
2020-10-05T08:02:40.000Z
2021-08-17T08:13:16.000Z
notebook/graphs/bipartite-checking.cpp
brnpapa/judge-resolutions
8149397daddc630e0fe2395f3f48e017154d223d
[ "MIT" ]
null
null
null
notebook/graphs/bipartite-checking.cpp
brnpapa/judge-resolutions
8149397daddc630e0fe2395f3f48e017154d223d
[ "MIT" ]
10
2020-10-05T08:03:43.000Z
2021-08-19T17:19:25.000Z
/* Bipartite checking Motivação: dado um connected and undirected graph G(V, E), determine se ele é bipartido. */ #include <bits/stdc++.h> using namespace std; /* input */ vector<vector<int>> adj_list; int V; /* O(V+E) - returns true if the connected component is bipartite */ bool bfs(int s) { enum { WHITE, BLACK, WITHOUT_COLOR }; vector<int> state(V, WITHOUT_COLOR); state[s] = WHITE; queue<int> q; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); for (int v : adj_list[u]) { if (state[v] == WITHOUT_COLOR) { // não visitado state[v] = (state[u]+1) % 2; // BLACK ou WHITE q.push(v); } else if (state[v] == state[u]) // conflito de cor return false; } } return true; } int main() { cout << bfs(0) << endl; }
21.081081
91
0.598718
[ "vector" ]
8bc3d46e57c248186231214216c398a28b878008
1,294
hpp
C++
include/darwin/generation.hpp
nathiss/Darwin
5248376e6179ed1ba461e4d01aa92c51ecc1632d
[ "MIT" ]
null
null
null
include/darwin/generation.hpp
nathiss/Darwin
5248376e6179ed1ba461e4d01aa92c51ecc1632d
[ "MIT" ]
null
null
null
include/darwin/generation.hpp
nathiss/Darwin
5248376e6179ed1ba461e4d01aa92c51ecc1632d
[ "MIT" ]
null
null
null
// // Created by nathiss on 12/11/2019. // #ifndef DARWIN_GENERATION_HPP #define DARWIN_GENERATION_HPP #include <cstdlib> #include <memory> #include <utility> #include <vector> #include <darwin/image.hpp> namespace darwin { class Generation { public: Generation(std::size_t generation_size, std::size_t best_size, Image ideal) noexcept; [[nodiscard]] auto begin() const noexcept { return this->specimens_.begin(); } [[nodiscard]] auto begin() noexcept { return this->specimens_.begin(); } [[nodiscard]] auto end() const noexcept { return this->specimens_.end(); } [[nodiscard]] auto end() noexcept { return this->specimens_.end(); } [[nodiscard]] auto begin_empty() noexcept { return this->begin() + this->best_size; } [[nodiscard]] auto end_empty() noexcept { return this->end(); } [[nodiscard]] auto operator[](std::size_t idx) const noexcept { return this->specimens_[idx]; } [[nodiscard]] auto operator[](std::size_t idx) noexcept { return this->specimens_[idx]; } void sort() noexcept; [[nodiscard]] const Image& getIdeal() const noexcept { return this->ideal_; } const std::size_t best_size; const std::size_t size; private: std::vector<Image> specimens_; Image ideal_; }; } // namespace darwin #endif //DARWIN_GENERATION_HPP
22.310345
97
0.694745
[ "vector" ]
8bc4d3a94b5ff16056189879fe64fe86460d3b0b
1,175
cpp
C++
Math/Math/math/Vector2D.cpp
sunshineheader/Math
58578625465abfb91fc97ce7110328b41762c23f
[ "Apache-2.0" ]
null
null
null
Math/Math/math/Vector2D.cpp
sunshineheader/Math
58578625465abfb91fc97ce7110328b41762c23f
[ "Apache-2.0" ]
null
null
null
Math/Math/math/Vector2D.cpp
sunshineheader/Math
58578625465abfb91fc97ce7110328b41762c23f
[ "Apache-2.0" ]
null
null
null
#include "Vector2D.h" namespace Math{ void Vector2D::normalize() { float normalize = x * x + y * y; // Already normalizeormalized. if (normalize == 1.0f) return; normalize = sqrt(normalize); // Too close to zero. if (normalize < 0.000001f) return; normalize = 1.0f / normalize; x *= normalize; y *= normalize; } Vector2D Vector2D::getNormalized() { Vector2D vector(*this); vector.normalize(); return vector; } float Vector2D::length()const { return std::sqrt(x*x + y*y); } float Vector2D::lengthSquared()const { return (x*x + y*y); } float Vector2D::distance(const Vector2D & vector) const { float dx = vector.x - x; float dy = vector.y - y; return std::sqrt(dx * dx + dy * dy); } float Vector2D::distanceSquared(const Vector2D & vector) const { float dx = vector.x - x; float dy = vector.y - y; return (dx * dx + dy * dy); } float Vector2D::crossProduct(const Vector2D & vector) const { return x*vector.y - y*vector.x; } std::ostream& operator<<(std::ostream& stream, const Vector2D & vector) { stream << "Vector2D (" << vector.x << "," << vector.y << ")" << std::endl; return stream; } }
18.951613
76
0.624681
[ "vector" ]
8bcc359f0b21875fc469bf51223be413ce4ef146
2,797
hpp
C++
src/scene/md2/header.hpp
IsraelEfraim/cpp-engine
039bcad97d55635a7a8f31d0d80ce59095ebb6cb
[ "MIT" ]
null
null
null
src/scene/md2/header.hpp
IsraelEfraim/cpp-engine
039bcad97d55635a7a8f31d0d80ce59095ebb6cb
[ "MIT" ]
null
null
null
src/scene/md2/header.hpp
IsraelEfraim/cpp-engine
039bcad97d55635a7a8f31d0d80ce59095ebb6cb
[ "MIT" ]
2
2021-03-15T18:51:32.000Z
2021-07-19T23:45:49.000Z
#ifndef CPP_ENGINE_HEADER_HPP #define CPP_ENGINE_HEADER_HPP #include <array> #include <cstdint> #include <string> #include <glm/gtx/rotate_vector.hpp> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> namespace engine::md2 { constexpr auto IDP2 = std::uint32_t(('2' << 24) + ('P' << 16) + ('D' << 8) + 'I'); constexpr auto VERSION = std::uint32_t(8); struct Header { int ident; int version; int skin_width; int skin_height; int frame_size; int num_skins; int num_points; int num_tex; int num_mesh; int num_gl_cmds; int num_frames; int ofs_skins; int ofs_tex; int ofs_mesh; int ofs_frames; int ofs_gl_cmds; int ofs_end; }; struct Texture_Vec { std::int16_t s; std::int16_t t; }; struct Frame_Point { std::array<std::uint8_t, 3> vertex_data; std::uint8_t normal_index; }; struct Frame { std::array<float, 3> scale; std::array<float, 3> translate; std::array<char, 16> name; std::array<Frame_Point, 1> fp; }; struct Mesh { std::array<std::uint16_t, 3> vec_index; std::array<std::uint16_t, 3> tex_index; }; struct Texture { int width; int height; std::int64_t scaled_width; std::int64_t scaled_height; std::uint32_t id; std::vector<std::uint8_t> buffer; }; struct Resource { int num_frames; int num_points; int num_mesh; int num_tex; int frame_size; int tex_width; int tex_height; std::vector<Mesh> mesh; std::vector<glm::vec2> tex; std::vector<glm::vec3> point; Texture tex_data; std::vector<int> gl_cmds; }; struct Sprint_Key { std::uint32_t first_frame; std::uint32_t last_frame; std::uint32_t fps; }; struct Sprint_State { Sprint_Key current_sprint; std::uint32_t current_frame; std::uint32_t next_frame; float current_time; float old_time; float lerp; }; /* Quake2 sprints */ constexpr auto Model_Sprints = std::array<Sprint_Key, 21> {{ { 0, 39, 9 }, /* STAND */ { 40, 45, 10 }, /* RUN */ { 46, 53, 10 }, /* ATTACK */ { 54, 57, 7 }, /* PAIN_A */ { 58, 61, 7 }, /* PAIN_B */ { 62, 65, 7 }, /* PAIN_C */ { 66, 71, 7 }, /* JUMP */ { 72, 83, 7 }, /* FLIP */ { 84, 94, 7 }, /* SALUTE */ { 95, 111, 10 }, /* FALLBACK */ { 112, 122, 7 }, /* WAVE */ { 123, 134, 6 }, /* POINT */ { 135, 153, 10 }, /* CROUCH_STAND */ { 154, 159, 7 }, /* CROUCH_WALK */ { 160, 168, 10 }, /* CROUCH_ATTACK */ { 169, 172, 7 }, /* CROUCH_PAIN */ { 173, 177, 5 }, /* CROUCH_DEATH */ { 178, 183, 7 }, /* DEATH_FALLBACK */ { 184, 189, 7 }, /* DEATH_FALLFORWARD */ { 190, 197, 7 }, /* DEATH_FALLBACKSLOW */ { 198, 198, 5 }, /* BOOM */ }}; } #endif //CPP_ENGINE_HEADER_HPP
22.198413
82
0.581337
[ "mesh", "vector", "transform" ]
8bda65235c22269e66e99afd48cc308f6c35664f
2,553
cpp
C++
D&D Wrath of Silumgar/Motor2D/j1Language.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
3
2019-06-21T04:40:16.000Z
2020-07-07T13:09:53.000Z
D&D Wrath of Silumgar/Motor2D/j1Language.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
56
2018-05-07T10:30:08.000Z
2018-05-15T08:27:06.000Z
D&D Wrath of Silumgar/Motor2D/j1Language.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
3
2019-01-03T17:24:57.000Z
2019-05-04T08:49:12.000Z
#include "ctDefs.h" #include "ctLog.h" #include "j1Language.h" #include "ctApp.h" j1Language::j1Language() : ctModule() { name = "language"; } // Destructor j1Language::~j1Language() {} bool j1Language::Load(pugi::xml_node& save) { bool ret = true; return ret; } bool j1Language::Save(pugi::xml_node& save)const { bool ret = true; return ret; } // Called before render is available bool j1Language::Awake(pugi::xml_node& config) { LOG("Loading Languages"); bool ret = true; pugi::xml_document language_file; pugi::xml_node* node = &App->LoadLanguages(language_file); current_language = config.attribute("current").as_string(); for (pugi::xml_node languages = node->first_child() ; languages && ret; languages = languages.next_sibling()) { string tmp_language; tmp_language = languages.name(); posible_languages.push_back(tmp_language); } node = &node->child(current_language.c_str()); dictionary.MM_about_btn = (node->child("MM_about_btn").attribute("string").as_string()); dictionary.MM_continue_btn = (node->child("MM_continue_btn").attribute("string").as_string()); dictionary.MM_new_game_btn = (node->child("MM_new_game_btn").attribute("string").as_string()); dictionary.MM_quit_btn = (node->child("MM_quit_btn").attribute("string").as_string()); dictionary.MM_settings_btn = (node->child("MM_settings_btn").attribute("string").as_string()); return ret; } bool j1Language::Update(float dt) { return true; } // Called before quitting bool j1Language::CleanUp() { return true; } void j1Language::ChangeCurrentLanguage(string new_language) { current_language = new_language; bool ret = true; pugi::xml_document language_file; pugi::xml_node* node = &App->LoadLanguages(language_file); for (pugi::xml_node languages = node->first_child(); languages && ret; languages = languages.next_sibling()) { string tmp_language; tmp_language = (languages.name()); posible_languages.push_back(tmp_language); } node = &node->child(current_language.c_str()); dictionary.MM_about_btn = (node->child("MM_about_btn").attribute("string").as_string()); dictionary.MM_continue_btn = (node->child("MM_continue_btn").attribute("string").as_string()); dictionary.MM_new_game_btn = (node->child("MM_new_game_btn").attribute("string").as_string()); dictionary.MM_quit_btn = (node->child("MM_quit_btn").attribute("string").as_string()); dictionary.MM_settings_btn = (node->child("MM_settings_btn").attribute("string").as_string()); } Dictionary j1Language::GetDictionary() const { return dictionary; }
25.787879
110
0.73208
[ "render" ]
8bdc55c98e2a2664e7148ad135c16eaebe745d83
11,121
cpp
C++
src/full_connected_layer.cpp
ashen7/LeNet-5
2902223688ca6127d5fbccd3a3fae824f38a3158
[ "Apache-2.0" ]
2
2020-01-15T08:40:40.000Z
2021-03-24T12:55:27.000Z
src/full_connected_layer.cpp
bitph/LeNet-6
2902223688ca6127d5fbccd3a3fae824f38a3158
[ "Apache-2.0" ]
null
null
null
src/full_connected_layer.cpp
bitph/LeNet-6
2902223688ca6127d5fbccd3a3fae824f38a3158
[ "Apache-2.0" ]
1
2021-04-15T02:10:48.000Z
2021-04-15T02:10:48.000Z
/* * ===================================================================================== * * Filename: full_connected_layer.cpp * * Description: * * Version: 1.0 * Created: 2020年01月04日 10时44分21秒 * Revision: none * Compiler: gcc * * Author: yipeng * Organization: * * ===================================================================================== */ #include "full_connected_layer.h" #include <memory> #include <vector> #include <functional> #include <glog/logging.h> #include "utility/matrix_math_function.hpp" #include "utility/matrix_gpu.h" namespace dnn { //静态成员的初始化 FullConnectedLayer::SigmoidActivatorCallback FullConnectedLayer::sigmoid_forward_callback_(nullptr); FullConnectedLayer::SigmoidActivatorCallback FullConnectedLayer::sigmoid_backward_callback_(nullptr); FullConnectedLayer::ReLuActivatorCallback FullConnectedLayer::relu_forward_callback_(nullptr); FullConnectedLayer::ReLuActivatorCallback FullConnectedLayer::relu_backward_callback_(nullptr); FullConnectedLayer::Matrix2d FullConnectedLayer::binomial_array_(1, FullConnectedLayer::Matrix1d(1)); FullConnectedLayer::FullConnectedLayer() { } FullConnectedLayer::~FullConnectedLayer() { } /* * 初始化全连接层 * 初始化权重数组 偏置数组为一个很小的值 */ int FullConnectedLayer::Initialize(size_t input_node_size, size_t output_node_size) { input_node_size_ = input_node_size; output_node_size_ = output_node_size; //初始化权重数组 和 偏置数组 //比如第一层3136个节点 第二层512个 权重就是512行3136列 //每行的3136列是权重 和对应神经元输入相乘相加 结果是输出神经元的值 if (-1 == Random::Uniform(-0.1, 0.1, output_node_size_, input_node_size_, weights_array_)) { LOG(ERROR) << "full connected layer initialize failed"; return -1; } Matrix::CreateZeros(output_node_size_, 1, biases_array_); //初始化权重梯度 偏置梯度 输出数组 Matrix::CreateZeros(output_node_size_, input_node_size, weights_gradient_array_); Matrix::CreateZeros(output_node_size_, 1, biases_gradient_array_); Matrix::CreateZeros(output_node_size_, 1, output_array_); return 0; } /* * 前向计算 a = f(w .* x + b) 输出等于激活函数(权重数组 点积 输入数组 最后数组和偏置数组相加) * 下一层前向计算的输入数组 就是上一层的输出数组 */ int FullConnectedLayer::Forward(const Matrix2d& input_array, bool dropout, float p) { //得到本层输入矩阵 也就是本层的节点值 input_array_ = input_array; #if GPU if (is_input_layer_) { if (dropout) { if (-1 == calculate::cuda::FullConnectedLayerForward(weights_array_, input_array_, biases_array_, binomial_array_, output_array_, is_input_layer_, dropout, p)) { LOG(ERROR) << "full connected layer forward failed"; return -1; } } else { if (-1 == calculate::cuda::FullConnectedLayerForward(weights_array_, input_array_, biases_array_, output_array_, is_input_layer_)) { LOG(ERROR) << "full connected layer forward failed"; return -1; } } } else { if (-1 == calculate::cuda::FullConnectedLayerForward(weights_array_, input_array_, biases_array_, output_array_)) { LOG(ERROR) << "full connected layer forward failed"; return -1; } } #else //矩阵相乘 w .* x 得到输出数组 if (-1 == Matrix::DotProduct(weights_array_, input_array_, output_array_)) { LOG(ERROR) << "full connected layer forward failed"; return -1; } //矩阵相加 w .* x + b if (-1 == Matrix::Add(output_array_, biases_array_, output_array_)) { LOG(ERROR) << "full connected layer forward failed"; return -1; } //激活函数 得到本层输出数组 f(w .* x + b) if (is_input_layer_) { //输入层就用relu做激活函数 如果是train有dropout 还要dropout一下 测试没有 if (relu_forward_callback_) { //relu_forward_callback_(output_array_, output_array_); sigmoid_forward_callback_(output_array_, output_array_); if (dropout) { if (-1 == Random::DropOut(output_array_, 1, p, binomial_array_, output_array_)) { LOG(ERROR) << "full connected layer forward failed, dropout occur error"; return -1; } } } else { LOG(ERROR) << "full connected layer forward failed, relu forward activator is empty"; return -1; } } else { //输出层用sigmoid激活函数 不用dropout if (sigmoid_forward_callback_) { sigmoid_forward_callback_(output_array_, output_array_); } else { LOG(ERROR) << "full connected layer forward failed, sigmoid forward activator is empty"; return -1; } } #endif return 0; } /* * 反向计算 x是本层节点的值 WT是权重数组的转置矩阵 .*是点积 delta_array是下一层的误差数组 * 本层的误差项 = x * (1 - x) * WT .* delta_array * w权重的梯度 就是 delta_array .* xT 下一层的误差项 点积 本层节点值的转置矩阵 * b偏置的梯度 就是 delta_array */ int FullConnectedLayer::Backward(const Matrix2d& output_delta_array, bool dropout, float p) { #if GPU if (!is_input_layer_ && dropout) { if (-1 == calculate::cuda::FullConnectedLayerBackward(output_delta_array, weights_array_, input_array_, binomial_array_, delta_array_, weights_gradient_array_, biases_gradient_array_, is_input_layer_, dropout, p)) { LOG(ERROR) << "full connected layer backward failed"; return -1; } } else { if (-1 == calculate::cuda::FullConnectedLayerBackward(output_delta_array, weights_array_, input_array_, delta_array_, weights_gradient_array_, biases_gradient_array_)) { LOG(ERROR) << "full connected layer backward failed"; return -1; } } #else Matrix2d temp_array1; if (sigmoid_backward_callback_) { // 计算x * (1 - x) sigmoid_backward_callback_(input_array_, temp_array1); } else { LOG(ERROR) << "full connected layer backward failed, sigmoid backward activator is empty"; return -1; } //计算w的转置矩阵 WT Matrix2d weights_transpose_array; if (-1 == Matrix::Transpose(weights_array_, weights_transpose_array)) { LOG(ERROR) << "full connected layer backward failed"; return -1; } Matrix2d temp_array2; //计算WT .* delta_array if (-1 == Matrix::DotProduct(weights_transpose_array, output_delta_array, temp_array2)) { LOG(ERROR) << "full connected layer backward failed"; return -1; } //计算x * (1 - x) * WT .* delta_array 得到本层的delta_array if (-1 == Matrix::HadamarkProduct(temp_array1, temp_array2, delta_array_)) { LOG(ERROR) << "full connected layer backward failed"; return -1; } //如果有dropout if (!is_input_layer_ && dropout) { if (-1 == Matrix::HadamarkProduct(delta_array_, binomial_array_, delta_array_)) { LOG(ERROR) << "full connected layer backward failed"; return -1; } if (-1 == Matrix::MatrixDivValue(delta_array_, 1.0 - p, delta_array_)) { LOG(ERROR) << "full connected layer backward failed"; return -1; } Matrix2d temp_array; if (relu_backward_callback_) { relu_backward_callback_(input_array_, temp_array); } if (-1 == Matrix::HadamarkProduct(delta_array_, temp_array, delta_array_)) { LOG(ERROR) << "full connected layer backward failed"; return -1; } } //利用上一层的误差项delta_array 计算weights的梯度 delta_array .* xT Matrix2d input_transpose_array; Matrix2d weights_gradient_array; if (-1 == Matrix::Transpose(input_array_, input_transpose_array)) { LOG(ERROR) << "full connected layer backward failed"; return -1; } if (-1 == Matrix::DotProduct(output_delta_array, input_transpose_array, weights_gradient_array)) { LOG(ERROR) << "full connected layer backward failed"; return -1; } //一个batch反向传播计算的权重梯度累加起来 Matrix::Add(weights_gradient_array_, weights_gradient_array, weights_gradient_array_); //利用上一层的误差项delta_array 计算biases的梯度 delta_array //一个batch反向传播计算的偏置梯度累加起来 Matrix::Add(biases_gradient_array_, output_delta_array, biases_gradient_array_); #endif return 0; } /* * 利用梯度下降优化算法(就是让值朝着梯度的反方向走) 更新权重 * w = w + learning_rate * w_gradient * b = b + learning_rate * b_gradient */ void FullConnectedLayer::UpdateWeights(double learning_rate, int batch_size) { //梯度下降优化 Matrix::GradientDescent(weights_gradient_array_, biases_gradient_array_, learning_rate, batch_size, weights_array_, biases_array_); //将权重梯度置0 方便下个batch计算平均梯度 Matrix::CreateZeros(Matrix::GetShape(weights_gradient_array_), weights_gradient_array_); //将偏置梯度置0 方便下个batch计算平均梯度 Matrix::CreateZeros(Matrix::GetShape(biases_gradient_array_), biases_gradient_array_); } /* * 利用梯度下降优化算法(就是让值朝着梯度的反方向走) 更新权重 * w = w + learning_rate * w_gradient * b = b + learning_rate * b_gradient */ void FullConnectedLayer::UpdateWeightsOld(double learning_rate, int batch_size) { //得到一个batch的平均权重梯度 Matrix::MatrixDivValue(weights_gradient_array_, batch_size, weights_gradient_array_); //权重的变化数组 Matrix2d weights_delta_array; Matrix::ValueMulMatrix(learning_rate, weights_gradient_array_, weights_delta_array); Matrix::Add(weights_array_, weights_delta_array, weights_array_); //将权重梯度置0 方便下个batch计算平均梯度 Matrix::CreateZeros(Matrix::GetShape(weights_gradient_array_), weights_gradient_array_); //得到一个batch的平均偏置梯度 Matrix::MatrixDivValue(biases_gradient_array_, batch_size, biases_gradient_array_); //偏置的变化数组 Matrix2d biases_delta_array; Matrix::ValueMulMatrix(learning_rate, biases_gradient_array_, biases_delta_array); Matrix::Add(biases_array_, biases_delta_array, biases_array_); //将偏置梯度置0 方便下个batch计算平均梯度 Matrix::CreateZeros(Matrix::GetShape(biases_gradient_array_), biases_gradient_array_); } void FullConnectedLayer::Dump() const noexcept { LOG(INFO) << "权重数组:"; Matrix::MatrixShow(weights_array_); LOG(INFO) << "偏置数组:"; Matrix::MatrixShow(biases_array_); } } //namespace dnn
37.318792
103
0.598417
[ "vector" ]
8bde6c2dd61f375791a43a1f8be96cd8936c2081
1,579
cc
C++
17summer/hdu5869_ac.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
1
2018-07-22T04:52:10.000Z
2018-07-22T04:52:10.000Z
17summer/hdu5869_ac.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
1
2018-08-11T13:29:59.000Z
2018-08-11T13:31:28.000Z
17summer/hdu5869_ac.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
null
null
null
#include<cstdio> #include<algorithm> #include<vector> #include<cstdlib> #include<cstring> #include<utility> using namespace std; #define MS(m,z) memset(m,z,sizeof(m)) typedef unsigned U; typedef pair<int,int > P; typedef long long ll; void inp(); int gcd(int a,int b){return a?gcd(b%a,a):b;} int main(){ #ifdef XS freopen("hdu5869.in","r",stdin); #endif //printf("%d",gcd(13,130)); while(1)inp(); return 0; } const int N = 100000+100,A=1000000+10; int T[N]; int rec[A]; int a[N]; int ans[N]; struct Qu{ int l,r,i; }Q[N]; typedef vector<P> VI; VI dp[N]; #define lb(z) ((z)&(-z)) int sum(int p){ int ans=0; while(p){ ans+=T[p]; p-=lb(p); } return ans; } int i,n,q; void ad(int p, int v){ while(p<=n){ T[p]+=v; p+=lb(p); } } void inp(){ MS(T,0),MS(rec,-1);if(scanf("%d%d",&n,&q)==EOF)exit(0); for(i=1;i<=n;i++)scanf("%d",&a[i]); for(i=1;i<=q;i++)scanf("%d%d",&Q[i].l,&Q[i].r),Q[i].i=i; for(i=1;i<=n;i++){dp[i].clear(),dp[i].reserve(20);} int g,x; for(i=1;i<=n;i++){ #define pb(z,x) push_back(P(z,x)) dp[i].pb(a[i],i); g = a[i]; for(P p:dp[i-1]){ x=gcd(p.first,a[i]); if(g!=x)dp[i].pb(x,p.second); g=x; } } sort(Q+1,Q+1+q,[](Qu &a,Qu&b){return a.r<b.r;}); int l,r,ind; int cur=0; for(i=1;i<=q;i++){ l=Q[i].l,r=Q[i].r,ind=Q[i].i; for(;cur<=r;cur++){ for(P p:dp[cur]){ if(rec[p.first]!=-1)ad(rec[p.first],-1); rec[p.first]=p.second,ad(p.second,1); } } ans[ind]=sum(r)-sum(l-1); } for(i=1;i<=q;i++)printf("%d\n",ans[i]); } //hdu5869.cc by xsthunder at Sat Aug 5 20:21:52 2017 //AC at Sat Aug 5 21:20:43 2017
19.987342
67
0.555415
[ "vector" ]
8beb463d56a2ef565a6e4b5041ca21edc44199e5
9,405
cpp
C++
src/sys_render.cpp
nkga/vp9-player
fb2fb56ac448f1d0770afa43de08cc71092b5467
[ "MIT" ]
1
2018-12-12T15:42:46.000Z
2018-12-12T15:42:46.000Z
src/sys_render.cpp
nkga/vp9-player
fb2fb56ac448f1d0770afa43de08cc71092b5467
[ "MIT" ]
null
null
null
src/sys_render.cpp
nkga/vp9-player
fb2fb56ac448f1d0770afa43de08cc71092b5467
[ "MIT" ]
1
2022-03-18T09:52:56.000Z
2022-03-18T09:52:56.000Z
#include "sys_render.h" #include "sys_com.h" #include "sys_window.h" #include "core_util.h" namespace sys { #include "shd_yuv_ps.h" #include "shd_yuv_vs.h" render_t::render_t(sys::window_t* window) { core::util::zero(this); this->window = window; if (window->hwnd == 0) { return; } if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) { return; } if (FAILED(factory->EnumAdapters(0, &adapter))) { return; } if (FAILED(D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, 0, D3D11_CREATE_DEVICE_DEBUG, 0, 0, D3D11_SDK_VERSION, &device, 0, &context))) { return; } DXGI_SWAP_CHAIN_DESC1 desc = {}; desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; desc.SampleDesc.Count = 1; desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; desc.BufferCount = 2; if (FAILED(factory->CreateSwapChainForHwnd(device, window->hwnd, &desc, 0, 0, &swap))) { return; } factory->MakeWindowAssociation(window->hwnd, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES); ID3D11Debug* debug = nullptr; if (SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&debug)))) { ID3D11InfoQueue* iq = nullptr; if (SUCCEEDED(debug->QueryInterface(IID_PPV_ARGS(&iq)))) { iq->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true); iq->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, true); iq->Release(); } debug->Release(); } create_d3d_bs(&bs_solid, D3D11_BLEND_ONE, D3D11_BLEND_ZERO); create_d3d_ds(&ds_disabled, FALSE, FALSE); create_d3d_rs(&rs_yuv, D3D11_CULL_NONE, D3D11_FILL_SOLID, FALSE); create_d3d_ss(&ss_linear, D3D11_FILTER_MIN_MAG_MIP_LINEAR, D3D11_TEXTURE_ADDRESS_CLAMP); create_d3d_vs(&vs_yuv, bc_shd_yuv_vs); create_d3d_ps(&ps_yuv, bc_shd_yuv_ps); valid = reset(); } render_t::~render_t() { if (swap) { swap->SetFullscreenState(FALSE, nullptr); } for (auto& plane : planes) { plane.destroy(); } com::release(&ps_yuv); com::release(&vs_yuv); com::release(&ss_linear); com::release(&rs_yuv); com::release(&ds_disabled); com::release(&bs_solid); com::release(&backbuffer_rtv); com::release(&backbuffer_tex); com::release(&swap); com::release(&context); com::release(&device); com::release(&adapter); com::release(&factory); } bool render_t::frame_begin() { if (valid == false) { return false; } if (window->size_x && window->size_y) { if (backbuffer_w != window->size_x || backbuffer_h != window->size_y) { if (reset() == false) { valid = false; return false; } } } static const FLOAT clear_color[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; context->ClearRenderTargetView(backbuffer_rtv, clear_color); context->OMSetRenderTargets(1, &backbuffer_rtv, nullptr); FLOAT const blend_factor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; context->OMSetBlendState(bs_solid, blend_factor, 0xFFFFFFFF); context->OMSetDepthStencilState(ds_disabled, 0); context->RSSetState(rs_yuv); context->VSSetShader(vs_yuv, nullptr, 0); context->PSSetShader(ps_yuv, nullptr, 0); context->PSSetSamplers(0, 1, &ss_linear); context->IASetInputLayout(nullptr); context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); ID3D11ShaderResourceView* srvs[3]; srvs[0] = planes[0].srv; srvs[1] = planes[1].srv; srvs[2] = planes[2].srv; context->PSSetShaderResources(0, COUNT(srvs), srvs); D3D11_VIEWPORT viewport = {}; viewport.Width = backbuffer_w; viewport.Height = backbuffer_h; viewport.MaxDepth = 1.0f; context->RSSetViewports(1, &viewport); return true; } void render_t::frame_finish() { context->Draw(3, 0); HRESULT hr = swap->Present(1, 0); if (FAILED(hr) && hr != DXGI_STATUS_OCCLUDED && hr != DXGI_ERROR_WAS_STILL_DRAWING) { valid = false; } } void render_t::update_plane(u32 idx, void const* src, u32 stride, u32 w, u32 h) { if (idx < COUNT(planes)) { planes[idx].create(this, w, h); planes[idx].update(this, src, w, h, stride); } } bool render_t::reset() { context->ClearState(); com::release(&backbuffer_tex); com::release(&backbuffer_rtv); if (FAILED(swap->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0))) { return false; } if (FAILED(swap->GetBuffer(0, IID_PPV_ARGS(&backbuffer_tex)))) { return false; } D3D11_TEXTURE2D_DESC bb_desc; backbuffer_tex->GetDesc(&bb_desc); backbuffer_w = bb_desc.Width; backbuffer_h = bb_desc.Height; D3D11_RENDER_TARGET_VIEW_DESC rtv_desc = {}; rtv_desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; if (FAILED(device->CreateRenderTargetView(backbuffer_tex, &rtv_desc, &backbuffer_rtv))) { return false; } return true; } void render_t::create_d3d_bs(ID3D11BlendState** out, D3D11_BLEND src_blend, D3D11_BLEND dst_blend) { D3D11_BLEND_DESC desc = {}; desc.RenderTarget[0].BlendEnable = (src_blend != D3D11_BLEND_ONE) || (dst_blend != D3D11_BLEND_ZERO); desc.RenderTarget[0].SrcBlend = src_blend; desc.RenderTarget[0].SrcBlendAlpha = src_blend; desc.RenderTarget[0].DestBlend = dst_blend; desc.RenderTarget[0].DestBlendAlpha = dst_blend; desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; device->CreateBlendState(&desc, out); } void render_t::create_d3d_ds(ID3D11DepthStencilState** out, BOOL enable, BOOL write_enable) { D3D11_DEPTH_STENCIL_DESC desc = {}; desc.DepthEnable = enable; desc.DepthWriteMask = write_enable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; desc.DepthFunc = D3D11_COMPARISON_LESS; desc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; desc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; desc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; desc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; desc.BackFace = desc.FrontFace; device->CreateDepthStencilState(&desc, out); } void render_t::create_d3d_rs(ID3D11RasterizerState** out, D3D11_CULL_MODE cull_mode, D3D11_FILL_MODE fill_mode, BOOL scissor) { D3D11_RASTERIZER_DESC desc = {}; desc.CullMode = cull_mode; desc.FillMode = fill_mode; desc.DepthClipEnable = TRUE; desc.MultisampleEnable = TRUE; desc.ScissorEnable = scissor; device->CreateRasterizerState(&desc, out); } void render_t::create_d3d_ss(ID3D11SamplerState** out, D3D11_FILTER filter, D3D11_TEXTURE_ADDRESS_MODE address_mode) { D3D11_SAMPLER_DESC desc = {}; desc.Filter = filter; desc.AddressU = address_mode; desc.AddressV = address_mode; desc.AddressW = address_mode; desc.MaxLOD = D3D11_FLOAT32_MAX; desc.ComparisonFunc = D3D11_COMPARISON_NEVER; device->CreateSamplerState(&desc, out); } void render_t::create_d3d_rtv(ID3D11RenderTargetView** out, ID3D11Texture2D* tex, DXGI_FORMAT format) { if (tex == nullptr) { *out = nullptr; return; } D3D11_RENDER_TARGET_VIEW_DESC rtv_desc = {}; rtv_desc.Format = format; rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; device->CreateRenderTargetView(tex, &rtv_desc, out); } void render_t::create_d3d_srv(ID3D11ShaderResourceView** out, ID3D11Texture2D* tex, DXGI_FORMAT format) { if (tex == nullptr) { *out = nullptr; return; } D3D11_SHADER_RESOURCE_VIEW_DESC desc = {}; desc.Format = format; desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; desc.Texture2D.MipLevels = 1; device->CreateShaderResourceView(tex, &desc, out); } void render_t::create_d3d_tex(ID3D11Texture2D** out, u32 size_x, u32 size_y, DXGI_FORMAT format, D3D11_USAGE usage, UINT bind_flags, UINT cpu_flags) { if (size_x == 0 || size_y == 0) { return; } D3D11_TEXTURE2D_DESC desc = {}; desc.Width = size_x; desc.Height = size_y; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = format; desc.SampleDesc.Count = 1; desc.Usage = usage; desc.BindFlags = bind_flags; desc.CPUAccessFlags = cpu_flags; device->CreateTexture2D(&desc, nullptr, out); } void render_t::texture_t::create(render_t* render, u32 size_x, u32 size_y) { if (this->size_x != size_x || this->size_y != size_y) { destroy(); const DXGI_FORMAT format = DXGI_FORMAT_R8_UNORM; render->create_d3d_tex(&tex, size_x, size_y, format, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0); render->create_d3d_tex(&stage, size_x, size_y, format, D3D11_USAGE_STAGING, 0, D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE); render->create_d3d_srv(&srv, tex, format); this->size_x = size_x; this->size_y = size_y; } } void render_t::texture_t::destroy() { com::release(&srv); com::release(&stage); com::release(&tex); size_x = 0; size_y = 0; } bool render_t::texture_t::lock(render_t* render, map_t* map) { if (stage == nullptr) { return false; } D3D11_MAPPED_SUBRESOURCE ms; if (FAILED(render->context->Map(stage, 0, D3D11_MAP_WRITE, 0, &ms))) { return false; } map->data = ms.pData; map->pitch = ms.RowPitch; return true; } void render_t::texture_t::unlock(render_t* render) { if (stage) { auto ctx = render->context; render->context->Unmap(stage, 0); render->context->CopyResource(tex, stage); } } void render_t::texture_t::update(render_t * render, void const * src, u32 size_x, u32 size_y, u32 stride) { map_t map; if (lock(render, &map)) { auto src_buf = (BYTE const*)src; auto dst_buf = (BYTE*)map.data; for (u32 y = 0; y < size_y; ++y) { __movsb(dst_buf, src_buf, size_x); src_buf += stride; dst_buf += map.pitch; } unlock(render); } } }
26.871429
150
0.733546
[ "render" ]
8bee0fc33bf45844dd149fbfce6b5b7d7ebed0c5
7,258
cpp
C++
code/src/boids2D/StateRenderable.cpp
Shutter-Island-Team/Shutter-island
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
[ "MIT" ]
4
2016-06-24T09:22:18.000Z
2019-06-13T13:50:53.000Z
code/src/boids2D/StateRenderable.cpp
Shutter-Island-Team/Shutter-island
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
[ "MIT" ]
null
null
null
code/src/boids2D/StateRenderable.cpp
Shutter-Island-Team/Shutter-island
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
[ "MIT" ]
2
2016-06-10T12:46:17.000Z
2018-10-14T06:37:21.000Z
#include "./../../include/boids2D/StateRenderable.hpp" #include "./../../include/gl_helper.hpp" #include "./../../include/log.hpp" #include "./../../include/Utils.hpp" #include <glm/gtc/type_ptr.hpp> #include <GL/glew.h> StateRenderable::StateRenderable(ShaderProgramPtr shaderProgram, MovableBoidPtr boid) : HierarchicalRenderable(shaderProgram), m_display(true), m_pBuffer(0), m_cBuffer(0), m_nBuffer(0) { m_boid = boid; m_savedState = boid->getStateType(); glm::vec4 color = getColorFromState(); double startAngle = 0.0; double endAngle = 2.0 * M_PI; double numberFace = 16; double incr = M_PI/numberFace; double ptheta = startAngle; double ntheta = ptheta + incr; double pcos = cos(ptheta); double psin = sin(ptheta); double ncos, nsin; while(ptheta < endAngle){ ncos = cos(ntheta); nsin = sin(ntheta); m_positions.push_back( glm::vec3(pcos, psin, -0.2) ); m_positions.push_back( glm::vec3(ncos, nsin, -0.2) ); m_positions.push_back( glm::vec3(0.0, 0.0, -0.2) ); for(int i = 0; i < 3; i++) { m_normals.push_back( glm::vec3(0.0, 0.0, 1.0) ); m_colors.push_back(color); } ptheta = ntheta; ntheta += incr; pcos = ncos; psin = nsin; } //Create buffers glGenBuffers(1, &m_pBuffer); //vertices glGenBuffers(1, &m_cBuffer); //colors glGenBuffers(1, &m_nBuffer); //normals //Activate buffer and send data to the graphics card glcheck(glBindBuffer(GL_ARRAY_BUFFER, m_pBuffer)); glcheck(glBufferData(GL_ARRAY_BUFFER, m_positions.size()*sizeof(glm::vec3), m_positions.data(), GL_STATIC_DRAW)); glcheck(glBindBuffer(GL_ARRAY_BUFFER, m_cBuffer)); glcheck(glBufferData(GL_ARRAY_BUFFER, m_colors.size()*sizeof(glm::vec4), m_colors.data(), GL_DYNAMIC_DRAW)); glcheck(glBindBuffer(GL_ARRAY_BUFFER, m_nBuffer)); glcheck(glBufferData(GL_ARRAY_BUFFER, m_normals.size()*sizeof(glm::vec3), m_normals.data(), GL_STATIC_DRAW)); } void StateRenderable::do_draw() { if (!m_display) { return; } if (m_savedState != m_boid->getStateType()) { m_savedState = m_boid->getStateType(); glm::vec4 color = getColorFromState(); for (size_t i = 0; i<m_colors.size(); ++i) { m_colors[i] = color; } //Update color buffer and send data to the graphics card glcheck(glBindBuffer(GL_ARRAY_BUFFER, m_cBuffer)); glcheck(glBufferData(GL_ARRAY_BUFFER, m_colors.size()*sizeof(glm::vec4), m_colors.data(), GL_DYNAMIC_DRAW)); } //Location int positionLocation = m_shaderProgram->getAttributeLocation("vPosition"); int colorLocation = m_shaderProgram->getAttributeLocation("vColor"); int normalLocation = m_shaderProgram->getAttributeLocation("vNormal"); int modelLocation = m_shaderProgram->getUniformLocation("modelMat"); //Send data to GPU if(modelLocation != ShaderProgram::null_location) { glcheck(glUniformMatrix4fv(modelLocation, 1, GL_FALSE, glm::value_ptr(getModelMatrix()))); } if(positionLocation != ShaderProgram::null_location) { //Activate location glcheck(glEnableVertexAttribArray(positionLocation)); //Bind buffer glcheck(glBindBuffer(GL_ARRAY_BUFFER, m_pBuffer)); //Specify internal format glcheck(glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, 0, (void*)0)); } if(colorLocation != ShaderProgram::null_location) { glcheck(glEnableVertexAttribArray(colorLocation)); glcheck(glBindBuffer(GL_ARRAY_BUFFER, m_cBuffer)); glcheck(glVertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, 0, (void*)0)); } if(normalLocation != ShaderProgram::null_location) { glcheck(glEnableVertexAttribArray(normalLocation)); glcheck(glBindBuffer(GL_ARRAY_BUFFER, m_nBuffer)); glcheck(glVertexAttribPointer(normalLocation, 3, GL_FLOAT, GL_FALSE, 0, (void*)0)); } glm::mat4 transformation(1.0); glm::mat4 model = getModelMatrix(); float scale = m_boid->getScale(); glm::vec3 position = m_boid->getLocation(); //position.z = m_boidsManager->getHeight(position.x, position.y) + 1.0; transformation[0][0] = scale; transformation[0][1] = 0; transformation[1][1] = scale; transformation[1][0] = 0; transformation[2][2] = scale; transformation[3][0] = position.x; transformation[3][1] = position.y; transformation[3][2] = position.z + 1.0f; transformation[3][3] = 1; glcheck(glUniformMatrix4fv( modelLocation, 1, GL_FALSE, glm::value_ptr(model * transformation))); //Draw triangles elements glcheck(glDrawArrays(GL_TRIANGLES,0, m_positions.size())); if(positionLocation != ShaderProgram::null_location) { glcheck(glDisableVertexAttribArray(positionLocation)); } if(colorLocation != ShaderProgram::null_location) { glcheck(glDisableVertexAttribArray(colorLocation)); } if(normalLocation != ShaderProgram::null_location) { glcheck(glDisableVertexAttribArray(normalLocation)); } } void StateRenderable::do_animate(float time) {} StateRenderable::~StateRenderable() { glcheck(glDeleteBuffers(1, &m_pBuffer)); glcheck(glDeleteBuffers(1, &m_cBuffer)); glcheck(glDeleteBuffers(1, &m_nBuffer)); } void StateRenderable::do_keyPressedEvent( sf::Event& e ) { if(e.key.code == sf::Keyboard::P) { m_display = !m_display; } } glm::vec4 StateRenderable::getColorFromState() { glm::vec4 color; switch (m_savedState) { case WALK_STATE: // Red color = glm::vec4(0.95, 0.26, 0.21, 1.0); break; case STAY_STATE: // Indigo color = glm::vec4(0.24, 0.31, 0.70, 1.0); break; case FIND_FOOD_STATE: // Green color = glm::vec4(0.29, 0.68, 0.31, 1.0); break; case ATTACK_STATE: // Orange color = glm::vec4(1.0, 0.59, 0.0, 1.0); break; case EAT_STATE: // Brown color = glm::vec4(0.47, 0.33, 0.28, 1.0); break; case LOST_STATE: // Gray color = glm::vec4(0.61, 0.61, 0.61, 1.0); break; case SLEEP_STATE: // Yellow color = glm::vec4(1.0, 0.92, 0.23, 1.0); break; case FLEE_STATE: // Deep Purple color = glm::vec4(0.40, 0.22, 0.71, 1.0); break; case FIND_WATER_STATE: // Teal color = glm::vec4(0.0, 0.58, 0.53, 1.0); break; case DRINK_STATE: // Light Blue color = glm::vec4(0.01, 0.66, 0.95, 1.0); break; case MATE_STATE: // Pink color = glm::vec4(0.94, 0.38, 0.57, 1.0); break; case DEAD_STATE: // Black color = glm::vec4(0.13, 0.13, 0.13, 1.0); break; default: // Black color = glm::vec4(0.0, 0.0, 0.0, 1.0); break; } return color; }
30.624473
117
0.605952
[ "model" ]
8bf0d3181241a9763c027dede7aff7fc32f85de3
2,346
cpp
C++
DerydocaEngine/src/Resources/Resource.cpp
Derydoca/derydocaengine
a9cdb71082fbb879d9448dc0c1a95581681d61f1
[ "BSD-3-Clause" ]
37
2018-05-21T15:21:26.000Z
2020-11-16T17:50:44.000Z
DerydocaEngine/src/Resources/Resource.cpp
Derydoca/derydocaengine
a9cdb71082fbb879d9448dc0c1a95581681d61f1
[ "BSD-3-Clause" ]
38
2018-03-09T23:57:07.000Z
2020-07-10T20:52:42.000Z
DerydocaEngine/src/Resources/Resource.cpp
Derydoca/derydocaengine
a9cdb71082fbb879d9448dc0c1a95581681d61f1
[ "BSD-3-Clause" ]
5
2018-08-28T11:12:18.000Z
2019-09-05T09:30:41.000Z
#include "EnginePch.h" #include "Resources\Resource.h" #include "Files\Serializers\FileSerializerLibrary.h" #include "Resources\Serializers\ResourceSerializerLibrary.h" namespace DerydocaEngine::Resources { Resource::Resource() : Resource("", ResourceType::UnknownResourceType, "", "") { } Resource::Resource(ResourceType type) : Resource("", type, "", "") { } Resource::Resource(const uuids::uuid& id, const std::filesystem::path& sourceFilePath, const std::filesystem::path& metaFilePath, const ResourceType type) : Resource(id, "", type, sourceFilePath, metaFilePath) { auto filePath = std::filesystem::path(sourceFilePath); if (filePath.has_stem()) { m_name = filePath.stem().string(); } } Resource::Resource(const std::string & name, const ResourceType type, const std::filesystem::path& sourceFilePath, const std::filesystem::path& metaFilePath) : Object(), m_name(name), m_type(type), m_sourceFilePath(sourceFilePath), m_metaFilePath(metaFilePath), m_resourceObjectPointer(nullptr) { } Resource::Resource(const uuids::uuid& id, const std::string & name, const ResourceType type, const std::filesystem::path& sourceFilePath, const std::filesystem::path& metaFilePath) : Object(id), m_name(name), m_type(type), m_sourceFilePath(sourceFilePath), m_metaFilePath(metaFilePath), m_resourceObjectPointer(nullptr) { } void Resource::generateAndSetId() { static uuids::uuid_time_generator gen; m_ID = gen(); } void Resource::setFilePaths(const std::filesystem::path& sourceFilePath, const std::filesystem::path& metaFilePath) { m_sourceFilePath = sourceFilePath; m_metaFilePath = metaFilePath; auto filePath = std::filesystem::path(sourceFilePath); if (filePath.has_stem()) { m_name = filePath.stem().string(); } } std::shared_ptr<void> Resource::getResourceObjectPointer() { if (m_resourceObjectPointer == 0) { // Find the loader that should be used auto loader = Serializers::ResourceSerializerLibrary::getInstance().getSerializer(getType()); // If the loader could not be found, return null if (loader == nullptr) { return nullptr; } // Load the object from the related object loader and return it m_resourceObjectPointer = loader->deserializePointer(shared_from_this()); } return m_resourceObjectPointer; } }
26.359551
183
0.725064
[ "object" ]
8bf87b9d83a165709e4bdbf9d9e12220f9272f7f
12,114
hpp
C++
dev/l0_tools/zexx.hpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
188
2016-04-16T12:11:48.000Z
2018-01-12T12:42:55.000Z
dev/l0_tools/zexx.hpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
1,198
2020-03-24T17:26:18.000Z
2022-03-31T08:06:15.000Z
dev/l0_tools/zexx.hpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
93
2018-01-23T01:59:23.000Z
2020-03-16T11:04:19.000Z
/******************************************************************************* * Copyright 2021 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. *******************************************************************************/ #pragma once #include <cassert> #include <stdexcept> #include <vector> #include <optional> #include <fmt/core.h> #include <level_zero/ze_api.h> #include <level_zero/zes_api.h> namespace zexx { inline std::string get_ze_error_message(ze_result_t status) { switch (status) { case ZE_RESULT_SUCCESS: return "success"; case ZE_RESULT_NOT_READY: return "synchronization primitive not signaled"; case ZE_RESULT_ERROR_DEVICE_LOST: return "device hung, reset, was removed, or driver update occurred"; case ZE_RESULT_ERROR_OUT_OF_HOST_MEMORY: return "insufficient host memory to satisfy call"; case ZE_RESULT_ERROR_OUT_OF_DEVICE_MEMORY: return "insufficient device memory to satisfy call"; case ZE_RESULT_ERROR_MODULE_BUILD_FAILURE: return "error occurred when building module, see build log for details"; case ZE_RESULT_ERROR_MODULE_LINK_FAILURE: return "error occurred when linking modules, see build log for details"; case ZE_RESULT_ERROR_INSUFFICIENT_PERMISSIONS: return "access denied due to permission level"; case ZE_RESULT_ERROR_NOT_AVAILABLE: return "resource already in use and simultaneous access not allowed or resource was removed"; case ZE_RESULT_ERROR_DEPENDENCY_UNAVAILABLE: return "external required dependency is unavailable or missing"; case ZE_RESULT_ERROR_UNINITIALIZED: return "driver is not initialized"; case ZE_RESULT_ERROR_UNSUPPORTED_VERSION: return "generic error code for unsupported versions"; case ZE_RESULT_ERROR_UNSUPPORTED_FEATURE: return "generic error code for unsupported features"; case ZE_RESULT_ERROR_INVALID_ARGUMENT: return "generic error code for invalid arguments"; case ZE_RESULT_ERROR_INVALID_NULL_HANDLE: return "handle argument is not valid"; case ZE_RESULT_ERROR_HANDLE_OBJECT_IN_USE: return "object pointed to by handle still in-use by device"; case ZE_RESULT_ERROR_INVALID_NULL_POINTER: return "pointer argument may not be nullptr"; case ZE_RESULT_ERROR_INVALID_SIZE: return "size argument is invalid (e.g., must not be zero)"; case ZE_RESULT_ERROR_UNSUPPORTED_SIZE: return "size argument is not supported by the device (e.g., too large)"; case ZE_RESULT_ERROR_UNSUPPORTED_ALIGNMENT: return "alignment argument is not supported by the device (e.g.,"; case ZE_RESULT_ERROR_INVALID_SYNCHRONIZATION_OBJECT: return "synchronization object in invalid state"; case ZE_RESULT_ERROR_INVALID_ENUMERATION: return "enumerator argument is not valid"; case ZE_RESULT_ERROR_UNSUPPORTED_ENUMERATION: return "enumerator argument is not supported by the device"; case ZE_RESULT_ERROR_UNSUPPORTED_IMAGE_FORMAT: return "image format is not supported by the device"; case ZE_RESULT_ERROR_INVALID_NATIVE_BINARY: return "native binary is not supported by the device"; case ZE_RESULT_ERROR_INVALID_GLOBAL_NAME: return "global variable is not found in the module"; case ZE_RESULT_ERROR_INVALID_KERNEL_NAME: return "kernel name is not found in the module"; case ZE_RESULT_ERROR_INVALID_FUNCTION_NAME: return "function name is not found in the module"; case ZE_RESULT_ERROR_INVALID_GROUP_SIZE_DIMENSION: return "group size dimension is not valid for the kernel or"; case ZE_RESULT_ERROR_INVALID_GLOBAL_WIDTH_DIMENSION: return "global width dimension is not valid for the kernel or"; case ZE_RESULT_ERROR_INVALID_KERNEL_ARGUMENT_INDEX: return "kernel argument index is not valid for kernel"; case ZE_RESULT_ERROR_INVALID_KERNEL_ARGUMENT_SIZE: return "kernel argument size does not match kernel"; case ZE_RESULT_ERROR_INVALID_KERNEL_ATTRIBUTE_VALUE: return "value of kernel attribute is not valid for the kernel or"; case ZE_RESULT_ERROR_INVALID_MODULE_UNLINKED: return "module with imports needs to be linked before kernels can"; case ZE_RESULT_ERROR_INVALID_COMMAND_LIST_TYPE: return "command list type does not match command queue type"; case ZE_RESULT_ERROR_OVERLAPPING_REGIONS: return "copy operations do not support overlapping regions of"; default: return "unknown or internal error"; } } inline void check_ze(ze_result_t status) { if (status != ZE_RESULT_SUCCESS) { throw std::runtime_error{ fmt::format("L0 returned error: {}", get_ze_error_message(status)) }; } } template <typename T, typename Init> inline T get_or_init(std::optional<T>& optional_value, Init&& init) { if (!optional_value) { optional_value = T{ init() }; } return *optional_value; } template <typename Handle> class handled { public: explicit handled(const Handle& handle) : handle_(handle) { if constexpr (std::is_pointer_v<Handle>) { assert(handle != nullptr); } } protected: const Handle& get_handle() const { return handle_; } private: Handle handle_; }; class frequency_domain_properties : public handled<zes_freq_properties_t> { public: using handled<zes_freq_properties_t>::handled; std::string get_type_name() const { return get_or_init(type_name_, [&]() { switch (get_handle().type) { case ZES_FREQ_DOMAIN_GPU: return "core"; case ZES_FREQ_DOMAIN_MEMORY: return "memory"; default: return "Unknown"; } }); } double get_min() const { return get_handle().min; } double get_max() const { return get_handle().max; } private: mutable std::optional<std::string> type_name_; }; class frequency_domain_state : public handled<zes_freq_state_t> { public: using handled<zes_freq_state_t>::handled; double get_actual() const { return get_handle().actual; } }; class frequency_domain : public handled<zes_freq_handle_t> { public: using handled<zes_freq_handle_t>::handled; frequency_domain_properties get_properties() const { return get_or_init(properties_, [&]() { zes_freq_properties_t properties; check_ze(zesFrequencyGetProperties(get_handle(), &properties)); return properties; }); } frequency_domain_state get_state() const { zes_freq_state_t state; check_ze(zesFrequencyGetState(get_handle(), &state)); return frequency_domain_state{ state }; } private: mutable std::optional<frequency_domain_properties> properties_; }; class device_properties : public handled<ze_device_properties_t> { public: using handled<ze_device_properties_t>::handled; std::string get_name() const { return get_or_init(name_, [&]() { return get_handle().name; }); } std::string get_type_name() const { return get_or_init(type_name_, [&]() { switch (get_handle().type) { case ZE_DEVICE_TYPE_CPU: return "CPU"; case ZE_DEVICE_TYPE_GPU: return "GPU"; case ZE_DEVICE_TYPE_FPGA: return "FPGA"; default: return "Unknown"; } }); } std::uint32_t get_id() const { return get_handle().deviceId; } std::uint32_t get_thread_count_per_unit() const { return get_handle().numThreadsPerEU; } std::uint32_t get_simd_width() const { return get_handle().physicalEUSimdWidth; } std::uint32_t get_unit_count_per_subslice() const { return get_handle().numEUsPerSubslice; } std::uint32_t get_subslices_count_per_slice() const { return get_handle().numSubslicesPerSlice; } std::uint32_t get_slice_count() const { return get_handle().numSlices; } std::uint32_t get_total_unit_count() const { return get_unit_count_per_subslice() * // get_subslices_count_per_slice() * // get_slice_count(); } std::uint32_t get_float_mads_per_clock() const { return get_simd_width() * get_total_unit_count(); } bool is_integrated() const { return bool(get_handle().flags & ZE_DEVICE_PROPERTY_FLAG_INTEGRATED); } private: mutable std::optional<std::string> name_; mutable std::optional<std::string> type_name_; }; class device : public handled<ze_device_handle_t> { public: using handled<ze_device_handle_t>::handled; device_properties get_properties() const { return get_or_init(properties_, [&]() { ze_device_properties_t handle; check_ze(zeDeviceGetProperties(get_handle(), &handle)); return handle; }); } std::vector<frequency_domain> get_frequency_domains() const { std::uint32_t domain_count = 0; check_ze(zesDeviceEnumFrequencyDomains(get_zes_handle(), &domain_count, nullptr)); std::vector<zes_freq_handle_t> domain_handles(domain_count); check_ze( zesDeviceEnumFrequencyDomains(get_zes_handle(), &domain_count, domain_handles.data())); std::vector<frequency_domain> domains; domains.reserve(domain_handles.size()); for (auto handle : domain_handles) { domains.emplace_back(handle); } return domains; } private: zes_device_handle_t get_zes_handle() const { return static_cast<zes_device_handle_t>(get_handle()); } mutable std::optional<device_properties> properties_; }; class driver : public handled<ze_driver_handle_t> { public: using handled<ze_driver_handle_t>::handled; std::vector<device> get_devices() const { std::uint32_t device_count = 0; check_ze(zeDeviceGet(get_handle(), &device_count, nullptr)); std::vector<ze_device_handle_t> device_handles(device_count); check_ze(zeDeviceGet(get_handle(), &device_count, device_handles.data())); std::vector<device> devices; devices.reserve(device_handles.size()); for (auto handle : device_handles) { devices.emplace_back(handle); } return devices; } }; class system_manager { public: explicit system_manager() { setenv("ZES_ENABLE_SYSMAN", "1", true); check_ze(zeInit(0)); } std::vector<driver> get_drivers() const { std::uint32_t driver_count = 0; check_ze(zeDriverGet(&driver_count, nullptr)); std::vector<ze_driver_handle_t> driver_handles(driver_count); check_ze(zeDriverGet(&driver_count, driver_handles.data())); std::vector<driver> drivers; drivers.reserve(driver_handles.size()); for (auto handle : driver_handles) { drivers.emplace_back(handle); } return drivers; } std::vector<device> get_devices() const { std::vector<device> devices; for (auto driver : get_drivers()) { for (auto device : driver.get_devices()) { devices.push_back(device); } } return devices; } }; } // namespace zexx
35.317784
105
0.665263
[ "object", "vector" ]
e30103d5af86265aa6b63be3602f482b29550c60
749
cpp
C++
lab_03/libs/driver/src/scene/scene.cpp
migregal/bmstu_iu7_oop
a17b2b5b5eaa175ae3ad4fa5a217b2664d4aa331
[ "MIT" ]
5
2021-05-24T20:03:38.000Z
2021-06-22T23:32:52.000Z
lab_03/libs/driver/src/scene/scene.cpp
migregal/bmstu_iu7_oop
a17b2b5b5eaa175ae3ad4fa5a217b2664d4aa331
[ "MIT" ]
null
null
null
lab_03/libs/driver/src/scene/scene.cpp
migregal/bmstu_iu7_oop
a17b2b5b5eaa175ae3ad4fa5a217b2664d4aa331
[ "MIT" ]
1
2021-06-17T19:32:26.000Z
2021-06-17T19:32:26.000Z
#include <scene/scene.h> #include <iterator> void Scene::add_model(const std::shared_ptr<Object> &model) { models->add(model); } void Scene::remove_model(const std::size_t index) { auto it = models->begin(); std::advance(it, index); models->remove(it); } void Scene::add_camera(const std::shared_ptr<Camera> &camera) { cams.push_back(camera); } void Scene::remove_camera(const std::size_t index) { auto it = cams.begin(); std::advance(it, index); cams.erase(it); } std::vector<std::shared_ptr<Object>> Scene::get_models() { return models->get_objects(); } std::shared_ptr<Composite> Scene::get_composite() { return models; } std::vector<std::shared_ptr<Camera>> Scene::get_cams() { return cams; }
20.805556
63
0.671562
[ "object", "vector", "model" ]
bde1f37eba5f1c4687b7bff98b94f83760189a24
2,025
cpp
C++
code/source/Scene.cpp
MajiKau/MoosEngine
3fca25f52129a33f438d0b3477a810d1f6c83a3f
[ "MIT" ]
null
null
null
code/source/Scene.cpp
MajiKau/MoosEngine
3fca25f52129a33f438d0b3477a810d1f6c83a3f
[ "MIT" ]
null
null
null
code/source/Scene.cpp
MajiKau/MoosEngine
3fca25f52129a33f438d0b3477a810d1f6c83a3f
[ "MIT" ]
null
null
null
#include "code/headers/Scene.h" Scene::Scene() { m_root = new Entity("Root"); m_root->AddRenderLayer(0); } void Scene::Update(float deltaTime) { m_root->Update(deltaTime); /*for each (auto entity in m_entities) { entity->Update(deltaTime); }*/ } void Scene::Render(BatchRenderer * renderer) { m_root->Render(renderer); /*for each (auto entity in m_entities) { entity->Render(renderer); }*/ } Entity * Scene::SpawnEntity() { return m_root->SpawnChild(); /*Entity* new_entity = new Entity(); m_entities.emplace_back(new_entity); return new_entity;*/ } Entity * Scene::SpawnEntity(std::string name) { return m_root->SpawnChild(name); /*Entity* new_entity = new Entity(name); m_entities.emplace_back(new_entity); return new_entity;*/ } Entity * Scene::GetRoot() { return m_root; } Entity * Scene::GetChild(int index) { return m_root->GetChild(index); /*if (m_entities.size() <= index) { printf("Child doesn't exist!\n"); return NULL; } return m_entities[index];*/ } std::vector<Entity*> Scene::GetChildren() { return m_root->GetChildren(); /*return m_entities;*/ } Entity * Scene::FindEntityWithId(int id) { if (m_root->GetId() == id) { return m_root; } Entity* result = m_root->FindChildWithId(id); if (result != NULL) { return result; } return NULL; /*for each (auto entity in m_entities) { if (entity->GetId() == id) return entity; } for each (auto entity in m_entities) { Entity* result = entity->FindChildWithId(id); if (result != NULL) return result; } return NULL;*/ } Entity * Scene::FindEntityWithName(std::string name) { if (m_root->GetName() == name) { return m_root; } Entity* result = m_root->FindChildWithName(name); if (result != NULL) { return result; } return NULL; /*for each (auto entity in m_entities) { if (entity->GetName() == name) return entity; } for each (auto entity in m_entities) { Entity* result = entity->FindChildWithName(name); if (result != NULL) return result; } return NULL;*/ }
16.330645
52
0.66716
[ "render", "vector" ]
bde6ef4e1c01159eca0d8d4dcd2bab71bd0c895e
1,261
hpp
C++
tests/framework/types.hpp
tacticalmelonfarmer/callable
36a7a75ffb104d0f2be6c1e52bd6c1844996bc39
[ "MIT" ]
1
2019-09-29T01:21:31.000Z
2019-09-29T01:21:31.000Z
tests/framework/types.hpp
tacticalmelonfarmer/callable
36a7a75ffb104d0f2be6c1e52bd6c1844996bc39
[ "MIT" ]
null
null
null
tests/framework/types.hpp
tacticalmelonfarmer/callable
36a7a75ffb104d0f2be6c1e52bd6c1844996bc39
[ "MIT" ]
null
null
null
#pragma once #include <callable.hpp> #include <type_traits> using testing_type = tmf::callable<int(int, int&, int const&, int&&, int*)>; inline int parameter_test_function(int val, int& ref, int const& cref, int&& rval, int* ptr) { int result = (val + ref + cref + rval + *ptr); ref = 0; *ptr = 0; return result; } struct functor { int operator()(int val, int& ref, int const& cref, int&& rval, int* ptr) { return parameter_test_function(val, ref, cref, std::move(rval), ptr); } }; struct object { int method(int val, int& ref, int const& cref, int&& rval, int* ptr) { return parameter_test_function(val, ref, cref, std::move(rval), ptr); } static int static_method(int val, int& ref, int const& cref, int&& rval, int* ptr) { return parameter_test_function(val, ref, cref, std::move(rval), ptr); } }; inline int free_function(int val, int& ref, int const& cref, int&& rval, int* ptr) { return parameter_test_function(val, ref, cref, std::move(rval), ptr); } struct non_trivial_destructing { private: int* check; public: non_trivial_destructing(int* init_check) : check{ init_check } {} int operator()(int, int&, int const&, int&&, int*) { return 0; } ~non_trivial_destructing() { *check += 1; } };
22.517857
84
0.657415
[ "object" ]
bde7ed9c3bf57b61fe83aebaf5fabe7b25813b3c
24,805
cpp
C++
src/json_sqlbuilder.cpp
lymslive/jsonkit
1f119a4fb2bb5ea4e7799deb48a48c11e80f7d68
[ "MIT" ]
null
null
null
src/json_sqlbuilder.cpp
lymslive/jsonkit
1f119a4fb2bb5ea4e7799deb48a48c11e80f7d68
[ "MIT" ]
null
null
null
src/json_sqlbuilder.cpp
lymslive/jsonkit
1f119a4fb2bb5ea4e7799deb48a48c11e80f7d68
[ "MIT" ]
null
null
null
#include "json_sqlbuilder.h" #include "json_operator.h" #include "jsonkit_internal.h" #define SQL_ASSERT(expr) do { \ if (!expr) { \ LOGF("build sql failed: %s", #expr); \ return false; \ } \ } while(0) namespace jsonkit { /* ************************************************************ */ // static helper functions static sql_config_t s_config; sql_config_t set_sql_config(const sql_config_t* cfg) { if (!cfg) { return s_config; } sql_config_t old = s_config; s_config = *cfg; return old; } const char SINGLE_QUOTE = '\''; const char BACK_QUOTE = '`'; const char STATE_END = ';'; /* ************************************************************ */ // Section: /** A simple sql builder buffer implementation. * @details It is algorithm more than class, it's member is just reference or * pointer to user provided std::string and config, but not owner then. It only * append to that string buffer, try to avoid string copy as much as possible. * */ class CSqlBuildBuffer { public: CSqlBuildBuffer(std::string& buffer, sql_config_t* pConfig = nullptr) : m_buffer(buffer), m_pConfig(pConfig) { if (!m_pConfig) { m_pConfig = &s_config; } } typedef CSqlBuildBuffer SelfType; CSqlBuildBuffer(const SelfType& that) = delete; SelfType& operator=(const SelfType& that) = delete; size_t Size() { return m_buffer.size(); } const char* c_str() { return m_buffer.c_str(); } const std::string& Buffer() { return m_buffer; } public: SelfType& Append(char ch) { m_buffer.push_back(ch); return *this; } SelfType& Append(const char* psz) { m_buffer.append(psz); return *this; } SelfType& Append(const char* psz, size_t count) { m_buffer.append(psz, count); return *this; } SelfType& Append(const std::string& str) { m_buffer.append(str); return *this; } SelfType& Append(const SelfType& that) { m_buffer.append(that.m_buffer); return *this; } char TopEnd() { return m_buffer.empty() ? '\0' : m_buffer.back(); } void PopEnd(char ch) { if (!m_buffer.empty() && m_buffer.back() == ch) { m_buffer.pop_back(); } } void Space() { char end = TopEnd(); if (end != ' ' && end != '\0' && end != ',') { Append(' '); } } bool PutWord(const char* psz) { return PutWord(psz, strlen(psz)); } bool PutWord(const char* psz, size_t count); bool PutWord(const rapidjson::Value& json); bool PutWord(const rapidjson::Value& json, std::string& last); bool PutEscape(const char* psz, size_t count); bool PutEscape(const rapidjson::Value& json); bool LikeEscape(const char* psz, size_t count); bool LikeEscape(const rapidjson::Value& json); bool PutValue(const char* psz, size_t count); bool PutValue(const rapidjson::Value& json); bool PushTable(const rapidjson::Value& json); bool PushField(const rapidjson::Value& json); bool PushSetValue(const rapidjson::Value& json); bool PushSetValue(const rapidjson::Value& json, const rapidjson::Value& field); bool DoSetValue(const rapidjson::Value& json); bool DoBatchValue(const rapidjson::Value& json); bool DoPushWhere(const rapidjson::Value& json, const char* relation = nullptr); bool DoCmpWhere(const rapidjson::Value& json, const std::string& field, const char* relation = nullptr); bool PushWhere(const rapidjson::Value& json); bool PushHaving(const rapidjson::Value& json); bool PushGroup(const rapidjson::Value& json); bool PushOrder(const rapidjson::Value& json); bool PushLimit(const rapidjson::Value& json); protected: bool DoInsert(const rapidjson::Value& json); public: // user interface for typical sql statements bool Insert(const rapidjson::Value& json) { Append("INSERT INTO "); return DoInsert(json); } bool Replace(const rapidjson::Value& json) { Append("REPLACE INTO "); return DoInsert(json); } bool Update(const rapidjson::Value& json); bool Select(const rapidjson::Value& json); bool Count(const rapidjson::Value& json); bool Delete(const rapidjson::Value& json); protected: sql_config_t* m_pConfig; std::string& m_buffer; }; bool CSqlBuildBuffer::PutWord(const char* psz, size_t count) { if (psz == nullptr || count == 0 || *psz == '\0') { return false; } for (size_t i = 0; i < count; ++i) { char ch = psz[i]; if (ch == SINGLE_QUOTE || ch == BACK_QUOTE || ch == STATE_END) { return false; } Append(ch); } return true; } bool CSqlBuildBuffer::PutEscape(const char* psz, size_t count) { for (size_t i = 0; i < count; ++i) { char ch = psz[i]; // escape single quote: ' --> '' if (ch == SINGLE_QUOTE) { Append(ch); } Append(ch); } return true; } bool CSqlBuildBuffer::LikeEscape(const char* psz, size_t count) { std::string metachar = "\\%_?*[]"; for (size_t i = 0; i < count; ++i) { char ch = psz[i]; if (metachar.find(ch) != std::string::npos) { Append('\\'); } Append(ch); } return true; } bool CSqlBuildBuffer::PutValue(const char* psz, size_t count) { if (psz == nullptr) { return false; } else if (count == 0 || *psz == '\0') { Append(SINGLE_QUOTE).Append(SINGLE_QUOTE); return true; } // keep origin string in `` quote, eg. `now()` `null` if (psz[0] == BACK_QUOTE) { if (count > 2 && psz[count-1] == BACK_QUOTE) { return PutWord(psz+1, count-2); } else { return false; } } Append(SINGLE_QUOTE); PutEscape(psz, count); Append(SINGLE_QUOTE); return true; } bool CSqlBuildBuffer::PutEscape(const rapidjson::Value& json) { if (json.IsString()) { return PutEscape(json.GetString(), json.GetStringLength()); } return false; } bool CSqlBuildBuffer::LikeEscape(const rapidjson::Value& json) { if (json.IsString()) { return LikeEscape(json.GetString(), json.GetStringLength()); } return false; } // a single string word or list of word separated by , bool CSqlBuildBuffer::PutWord(const rapidjson::Value& json) { if (json.IsString()) { return PutWord(json.GetString(), json.GetStringLength()); } else if (json.IsArray() && !json.Empty()) { for (auto it = json.Begin(); it != json.End(); ++it) { if (!it->IsString()) { return false; } SQL_ASSERT(PutWord(*it)); Append(','); } PopEnd(','); return true; } return false; } // put a word in buffer, and save a copy in string last bool CSqlBuildBuffer::PutWord(const rapidjson::Value& json, std::string& last) { size_t tail = m_buffer.size(); SQL_ASSERT(PutWord(json)); last = m_buffer.substr(tail); return true; } bool CSqlBuildBuffer::PutValue(const rapidjson::Value& json) { if (json.IsString()) { return PutValue(json.GetString(), json.GetStringLength()); } else if (json.IsArray()) { Append('('); for (auto it = json.Begin(); it != json.End(); ++it) { SQL_ASSERT(PutValue(*it)); Append(','); } PopEnd(','); Append(')'); return true; } else if (json.IsObject()) { return false; } else if (json.IsNull()) { Append("null"); } else if (json.IsBool()) { if (json.GetBool()) { Append('1'); } else { Append('0'); } } else { // numeric value Append(stringfy(json)); } return true; } bool CSqlBuildBuffer::PushTable(const rapidjson::Value& json) { if (json.IsString()) { return PutWord(json.GetString(), json.GetStringLength()); } else if (json.IsArray()) { int idx = 0; for (auto it = json.Begin(); it != json.End(); ++it) { if (idx++ > 0) { Append(' '); } SQL_ASSERT(PushTable(*it)); } return true; } else if (json.IsObject()) { for (auto it = json.MemberBegin(); it != json.MemberEnd(); ++it) { const char* key = it->name.GetString(); if (0 == strcmp(key, "join")) { // the 2nd table or later should specify join type SQL_ASSERT(PutWord(it->value)); } else if (0 == strcmp(key, "table")) { // Append(' '); Space(); if (it->value.IsObject()) { Append("("); SQL_ASSERT(Select(it->value)); Append(")"); } else { SQL_ASSERT(PutWord(it->value)); } } else if (0 == strcmp(key, "as")) { Append(" AS "); SQL_ASSERT(PutWord(it->value)); } else if (0 == strcmp(key, "on")) { Append(" ON "); SQL_ASSERT(PutWord(it->value)); } else if (0 == strcmp(key, "use")) { PutWord(" USING("); SQL_ASSERT(PutWord(it->value)); Append(")"); } } return true; } return false; } bool CSqlBuildBuffer::PushField(const rapidjson::Value& json) { if (!json || json.IsNull()) { Append('*'); return true; } if (json.IsString()) { return PutWord(json.GetString(), json.GetStringLength()); } else if (json.IsArray()) { return PutWord(json); } return false; } bool CSqlBuildBuffer::PushSetValue(const rapidjson::Value& json) { if (json.IsObject() && json.MemberCount() > 0) { Append(" SET "); return DoSetValue(json); } else if (json.IsArray() && json.Size() > 0) { return DoBatchValue(json); } return false; } /** Generate: SET field1=value1, field2=value2, ... */ bool CSqlBuildBuffer::DoSetValue(const rapidjson::Value& json) { for (auto it = json.MemberBegin(); it != json.MemberEnd(); ++it) { // skip json null, if really mean to set null use string "`null`" if (it->value.IsNull()) { continue; } SQL_ASSERT(PutWord(it->name)); Append('='); SQL_ASSERT(PutValue(it->value)); Append(','); } PopEnd(','); return true; } /** Generate: (field1, feild2, ...) VALUES (value1, value2, ...), ... * @param json: array of object which has the same fields set * */ bool CSqlBuildBuffer::DoBatchValue(const rapidjson::Value& json) { auto& first = json[0]; if (!first.IsObject() || first.ObjectEmpty()) { return false; } Append(' '); std::vector<std::string> field; std::string value; // store first row value with field CSqlBuildBuffer another(value, m_pConfig); Append('('); another.Append('('); for (auto it = first.MemberBegin(); it != first.MemberEnd(); ++it) { if (it->value.IsNull()) { continue; } std::string last; SQL_ASSERT(PutWord(it->name, last)); Append(','); field.push_back(last); SQL_ASSERT(another.PutValue(it->value)); another.Append(','); } PopEnd(','); Append(')'); another.PopEnd(','); another.Append(')'); Append(" VALUES "); Append(value); uint32_t size = json.Size(); for (uint32_t i = 1; i < size; ++i) { Append(", ("); auto& row = json[i]; for (auto& key : field) { auto& val = row/key; if (!val) { Append("null"); } else { SQL_ASSERT(PutValue(val)); } Append(','); } PopEnd(','); Append(')'); } return true; } /** Generate: (field1, feild2, ...) VALUES (value1, value2, ...), ... * @param json: array of array which has the same fields order * @param field: array of string specify the field names * */ bool CSqlBuildBuffer::PushSetValue(const rapidjson::Value& json, const rapidjson::Value& field) { if (!json.IsArray() || json.Empty()) { return false; } if (!field.IsArray() || field.Empty()) { return false; } Append(' '); Append('('); SQL_ASSERT(PutWord(field)); Append(')'); Append(" VALUES "); for (auto it = json.Begin(); it != json.End(); ++it) { if (!it->IsArray()) { continue; } if (it->Size() != field.Size()) { return false; } if (it != json.Begin()) { Append(", "); } SQL_ASSERT(PutValue(*it)); } return true; } bool CSqlBuildBuffer::PushWhere(const rapidjson::Value& json) { if (!json || !json.IsObject()) { return true; } Append(" WHERE 1=1"); return DoPushWhere(json); } bool CSqlBuildBuffer::PushHaving(const rapidjson::Value& json) { if (!json || !json.IsObject()) { return true; } Append(" HAVING 1=1"); return DoPushWhere(json); } /** generate where statemnet if possible, otherwise emtpy stirng on failure * @code * { * "field1" : "value1", // AND field1='value1' * "field2" : [v1, v2, v3], // AND field2 IN (v1,v2,v3) * "field3" : { // AND field3 > min-value AND field3 < max-value * "gt" : "min-value", * "lt" : "max-value" * } * } * @endcode * */ bool CSqlBuildBuffer::DoPushWhere(const rapidjson::Value& json, const char* relation) { if (relation == nullptr) { relation = " AND "; } for (auto it = json.MemberBegin(); it != json.MemberEnd(); ++it) { if (it->value.IsNull()) { continue; } std::string field; CSqlBuildBuffer another(field, m_pConfig); SQL_ASSERT(another.PutWord(it->name)); if (it->value.IsArray()) { Append(relation).Append(field).Append(" IN "); SQL_ASSERT(PutValue(it->value)); } else if (it->value.IsObject()) { if (field == "-or") { Append(" AND (1!=1"); SQL_ASSERT(DoPushWhere(it->value, " OR ")); Append(")"); } else { SQL_ASSERT(DoCmpWhere(it->value, field, relation)); } } else { Append(relation).Append(field).Append('='); SQL_ASSERT(PutValue(it->value)); } } return true; } /** Generate multiple comparision * @code * "field": { * "eq": ..., "ne": ..., "gt": ..., "lt": ..., "ge": ..., "le": ..., * "between": [min, max] * "like": ..., "not in": [...], * "null": true/false * } * @endcode * */ bool CSqlBuildBuffer::DoCmpWhere(const rapidjson::Value& json, const std::string& field, const char* relation) { if (relation == nullptr) { relation = " AND "; } for (auto it = json.MemberBegin(); it != json.MemberEnd(); ++it) { if (it->value.IsNull()) { continue; } const char* op = it->name.GetString(); if (0 == strcmp(op, "like")) { Append(relation).Append(field).Append(" like "); Append(SINGLE_QUOTE); if (m_pConfig->fix_like_value & SQL_LIKE_PREFIX) { Append('%'); } if (m_pConfig->escape_like_metachar) { SQL_ASSERT(LikeEscape(it->value)); } else { SQL_ASSERT(PutEscape(it->value)); } if (m_pConfig->fix_like_value & SQL_LIKE_POSTFIX) { Append('%'); } Append(SINGLE_QUOTE); continue; } if (0 == strcmp(op, "between")) { if (it->value.IsArray() && it->value.Size() == 2) { Append(relation).Append(field).Append(" BETWEEN "); SQL_ASSERT(PutValue(it->value[0])); Append(relation); SQL_ASSERT(PutValue(it->value[1])); } continue; } if (0 == strcmp(op, "null")) { if (it->value.IsBool() && it->value.GetBool()) { Append(relation).Append(field).Append(" is NULL"); } else { Append(relation).Append(field).Append(" is not NULL"); } continue; } // sub-select query in where if (it->value.IsObject()) { Append(relation).Append(field).Append(" "); SQL_ASSERT(PutWord(op, it->name.GetStringLength())); Append(" "); Append("("); SQL_ASSERT(Select(it->value)); Append(")"); continue; } // normal comparision if (0 == strcmp(op, "eq")) { Append(relation).Append(field).Append('='); } else if (0 == strcmp(op, "gt")) { Append(relation).Append(field).Append('>'); } else if (0 == strcmp(op, "lt")) { Append(relation).Append(field).Append('<'); } else if (0 == strcmp(op, "ne")) { Append(relation).Append(field).Append("!="); } else if (0 == strcmp(op, "ge")) { Append(relation).Append(field).Append(">="); } else if (0 == strcmp(op, "le")) { Append(relation).Append(field).Append("<="); } else if (0 == strcmp(op, "not in") && it->value.IsArray()) { Append(relation).Append(field).Append(" not IN "); } else { continue; } SQL_ASSERT(PutValue(it->value)); } return true; } bool CSqlBuildBuffer::PushOrder(const rapidjson::Value& json) { if (!json || json.IsNull()) { return true; } Append(" ORDER BY "); return PutWord(json); } bool CSqlBuildBuffer::PushGroup(const rapidjson::Value& json) { if (!json || json.IsNull()) { return true; } Append(" GROUP BY "); return PutWord(json); } /** limit clause. * support data: * "limit": COUNT, * "limit": [OFFSET, COUNT], * "limit": {"offset": OFFSET, "count": COUNT} * in which COUNT and OFFSET should be number to generate valid sql * */ bool CSqlBuildBuffer::PushLimit(const rapidjson::Value& json) { if (!json || json.IsNull()) { return true; } Append(" LIMIT "); if (json.IsUint() || json.IsUint64()) { return PutValue(json); } else if (json.IsArray() && json.Size() == 2) { auto& offset = json[0]; auto& count = json[1]; if (offset.IsUint() || offset.IsUint64()) { PutValue(offset); Append(','); } return PutValue(count); } else if (json.IsObject()) { auto& offset = json/"offset"; auto& count = json/"count"; if (offset.IsUint() || offset.IsUint64()) { PutValue(offset); Append(','); } return PutValue(count); } return false; } /* ------------------------------------------------------------ */ // Section: bool CSqlBuildBuffer::DoInsert(const rapidjson::Value& json) { auto& table = json/"table"; auto& value = json/"value"; if (!table || !value) { return false; } SQL_ASSERT(PushTable(table)); auto& field = json/"field"; if (!!field) { SQL_ASSERT(PushSetValue(value, field)); } else { SQL_ASSERT(PushSetValue(value)); } auto& update = json/"update"; if (!!update && update.IsObject()) { Append(" ON DUPLICATE KEY UPDATE "); SQL_ASSERT(DoSetValue(update)); } // need to select last auto increment id after insert if (json/"last_insert_id" | false) { Append("; SELECT last_insert_id()"); } return true; } bool CSqlBuildBuffer::Update(const rapidjson::Value& json) { auto& table = json/"table"; auto& value = json/"value"; if (!table || !value) { return false; } Append("UPDATE "); SQL_ASSERT(PushTable(table)); SQL_ASSERT(PushSetValue(value)); size_t last = Size(); SQL_ASSERT(PushWhere(json/"where")); if (m_pConfig->refuse_update_without_where && Size() < last + sizeof(" WHERE 1=1")) { return false; } SQL_ASSERT(PushOrder(json/"order")); SQL_ASSERT(PushLimit(json/"limit")); return true; } bool CSqlBuildBuffer::Select(const rapidjson::Value& json) { auto& table = json/"table"; if (!table) { return false; } Append("SELECT "); SQL_ASSERT(PushField(json/"field")); Append(" FROM "); SQL_ASSERT(PushTable(table)); SQL_ASSERT(PushWhere(json/"where")); auto& group = json/"group"; if (!!group) { SQL_ASSERT(PushGroup(group)); SQL_ASSERT(PushHaving(json/"having")); } SQL_ASSERT(PushOrder(json/"order")); SQL_ASSERT(PushLimit(json/"limit")); return true; } bool CSqlBuildBuffer::Count(const rapidjson::Value& json) { auto& table = json/"table"; if (!table) { return false; } Append("SELECT COUNT(1) FROM "); SQL_ASSERT(PushTable(table)); SQL_ASSERT(PushWhere(json/"where")); return true; } bool CSqlBuildBuffer::Delete(const rapidjson::Value& json) { auto& table = json/"table"; if (!table) { return false; } Append("DELETE FROM "); SQL_ASSERT(PushTable(table)); size_t last = Size(); SQL_ASSERT(PushWhere(json/"where")); if (m_pConfig->refuse_delete_without_where && Size() <= last + sizeof(" WHERE 1=1")) { return false; } SQL_ASSERT(PushOrder(json/"order")); SQL_ASSERT(PushLimit(json/"limit")); return true; } /* ************************************************************ */ // Section: public class interface bool CSqlBuilder::Insert(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql, &m_config); return obj.Insert(json); } bool CSqlBuilder::Replace(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql, &m_config); return obj.Replace(json); } bool CSqlBuilder::Update(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql, &m_config); return obj.Update(json); } bool CSqlBuilder::Select(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql, &m_config); return obj.Select(json); } bool CSqlBuilder::Count(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql, &m_config); return obj.Count(json); } bool CSqlBuilder::Delete(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql, &m_config); return obj.Delete(json); } /* ************************************************************ */ // Section: public function interface bool sql_insert(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql); return obj.Insert(json); } bool sql_replace(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql); return obj.Replace(json); } bool sql_update(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql); return obj.Update(json); } bool sql_select(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql); return obj.Select(json); } bool sql_count(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql); return obj.Count(json); } bool sql_delete(const rapidjson::Value& json, std::string& sql) { CSqlBuildBuffer obj(sql); return obj.Delete(json); } /* ************************************************************ */ } /* jsonkit */
23.668893
110
0.520218
[ "object", "vector" ]
bdf4866a8b76786974a8583214c9a0350504fb3b
7,449
cpp
C++
src/collapse_edges.cpp
sgsellan/opening-and-closing-surfaces
57127178c2e8d50396c02a853c4456a90e9220c5
[ "MIT" ]
16
2020-10-27T00:03:03.000Z
2022-02-01T19:44:35.000Z
src/collapse_edges.cpp
sgsellan/opening-and-closing-surfaces
57127178c2e8d50396c02a853c4456a90e9220c5
[ "MIT" ]
null
null
null
src/collapse_edges.cpp
sgsellan/opening-and-closing-surfaces
57127178c2e8d50396c02a853c4456a90e9220c5
[ "MIT" ]
3
2020-10-27T01:40:44.000Z
2021-02-23T13:42:16.000Z
#include <igl/per_vertex_normals.h> #include <igl/principal_curvature.h> #include <igl/avg_edge_length.h> #include <igl/massmatrix.h> #include <igl/adjacency_list.h> #include <igl/per_face_normals.h> #include <igl/barycenter.h> #include <igl/pinv.h> #include <igl/edges.h> #include <Eigen/SparseCore> #include <igl/adjacency_list.h> #include <igl/adjacency_matrix.h> #include <igl/per_face_normals.h> #include <igl/per_vertex_normals.h> #include <igl/avg_edge_length.h> #include <igl/edge_flaps.h> #include <igl/unique_edge_map.h> #include <igl/vertex_triangle_adjacency.h> #include <igl/principal_curvature.h> #include <igl/collapse_edge.h> #include <igl/is_edge_manifold.h> #include <igl/C_STR.h> #include <igl/circulation.h> #include <igl/decimate.h> #include <igl/shortest_edge_and_midpoint.h> #include <igl/infinite_cost_stopping_condition.h> using namespace std; void collapse_edges(Eigen::MatrixXd & V,Eigen::MatrixXi & F, Eigen::VectorXi & feature, Eigen::VectorXd & high, Eigen::VectorXd & low){ using namespace Eigen; MatrixXi E,uE,EI,EF; VectorXi EMAP,I,J; VectorXd data; Eigen::MatrixXd U; Eigen::MatrixXi G; // VectorXd p; std::vector<std::vector<int>> uE2E; std::vector<std::vector<int>> vertex_face_adjacency; std::vector<int> small_edges; int e1,e2,f1,f2,e; int n = V.rows(); int num_feature = feature.size(); std::vector<std::vector<int>> A; igl::adjacency_list(F,A); std::vector<bool> is_feature_vertex; is_feature_vertex.resize(n); for (int s = 0; s < num_feature; s++) { is_feature_vertex[feature(s)] = true; } //igl::is_edge_manifold(F); std::function<bool( const Eigen::MatrixXd &, const Eigen::MatrixXi &, const Eigen::MatrixXi &, const Eigen::VectorXi &, const Eigen::MatrixXi &, const Eigen::MatrixXi &, const igl::min_heap< std::tuple<double,int,int> > &, const Eigen::VectorXi &, const Eigen::MatrixXd &, const int, const int, const int, const int, const int)> stopping_condition; std::function<void( const int, const Eigen::MatrixXd &, const Eigen::MatrixXi &, const Eigen::MatrixXi &, const Eigen::VectorXi &, const Eigen::MatrixXi &, const Eigen::MatrixXi &, double &, Eigen::RowVectorXd &)> shortest_edge_and_midpoint_lambda = [&A,&feature,&low,&high,&is_feature_vertex]( const int e, const Eigen::MatrixXd & V, const Eigen::MatrixXi & F, const Eigen::MatrixXi & E, const Eigen::VectorXi & EMAP, const Eigen::MatrixXi & EF, const Eigen::MatrixXi & EI, double & cost, Eigen::RowVectorXd & p)->void{ igl::shortest_edge_and_midpoint(e,V,F,E,EMAP,EF,EI,cost,p); if (is_feature_vertex[E(e,0)] || is_feature_vertex[E(e,1)] ) { cost = std::numeric_limits<double>::infinity(); return; } if ( (V.row(E(e,0))-V.row(E(e,1))).norm() > ((low(E(e,0))+low(E(e,1)))/2) ) { cost = std::numeric_limits<double>::infinity(); return; } for(int i = 0; i < A[E(e,1)].size(); i++){ if((V.row(A[E(e,1)][i])-p).norm() > high(E(e,1))){ cost = std::numeric_limits<double>::infinity(); return; } } for(int r = 0; r < A[E(e,0)].size(); r++){ if((V.row(A[E(e,0)][r])-p).norm() > high(E(e,0))){ cost = std::numeric_limits<double>::infinity(); return; } } //std::cout << "Mathing..." << std::endl; // consider both directions to circulate for(int direction = 0;direction<2;direction++) { // consider each face for(const int f : igl::circulation(e,direction,EMAP,EF,EI)) { if (f < 0) {//????? cost = std::numeric_limits<double>::infinity(); return; } //std::cout << f << std::endl; if( f == 0 || f == igl::circulation(e,direction,EMAP,EF,EI).size()-1) { // skip continue; } // Grab the three corners of the face Eigen::RowVector3d p_before[3], p_after[3]; for(int c = 0;c<3;c++) { // vertex index // std::cout << e << std::endl; // std::cout << f << std::endl; // std::cout << c << std::endl; const int v = F(f,c); if( v == E(e,0) || v == E(e,1)) { p_after[c] = p; }else { p_after[c] = V.row(v); } p_before[c] = V.row(v); } const Eigen::RowVector3d n_before = ((p_before[1]- p_before[0]).cross(p_before[2]- p_before[0])).normalized(); const Eigen::RowVector3d n_after = ((p_after[1]- p_after[0]).cross(p_after[2]- p_after[0])).normalized(); if( n_before.dot(n_after) < n_after.norm()/2 ) { cost = std::numeric_limits<double>::infinity(); } } } //std::cout << "Mathed!" << std::endl; }; igl::infinite_cost_stopping_condition(shortest_edge_and_midpoint_lambda,stopping_condition); //std::cout << "??" << std::endl; igl::decimate(V,F,shortest_edge_and_midpoint_lambda,stopping_condition,U,G,J,I); //std::cout << "!!" << std::endl; Eigen::VectorXd high_new,low_new; Eigen::VectorXi feature_new; feature_new.resize(num_feature); high_new.resize(U.rows()); low_new.resize(U.rows()); int j = 0; for (int s = 0; s<U.rows(); s++) { high_new(s) = high(I(s)); low_new(s) = low(I(s)); if (is_feature_vertex[I(s)]) { feature_new(j) = s; j = j+1; } } // PLACEHOLDER V = U; F = G; high = high_new; low = low_new; feature = feature_new; } // g++ -I/usr/local/libigl/external/eigen -I/usr/local/libigl/include -std=c++11 -framework Accelerate main.cpp remesh_botsch.cpp -o main
36.514706
137
0.458585
[ "vector" ]
bdf893ccca840aa2a27387097f712e4677f3ebc1
28,478
cc
C++
src/sdg-untangler.cc
KatOfCats/sdg
1916e5c86dd88e601ab7476f38daef2bd3b3b6fc
[ "MIT" ]
null
null
null
src/sdg-untangler.cc
KatOfCats/sdg
1916e5c86dd88e601ab7476f38daef2bd3b3b6fc
[ "MIT" ]
null
null
null
src/sdg-untangler.cc
KatOfCats/sdg
1916e5c86dd88e601ab7476f38daef2bd3b3b6fc
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <sdglib/workspace/WorkSpace.hpp> #include <sdglib/processors/LinkageUntangler.hpp> #include <sdglib/processors/LocalHaplotypeAssembler.hpp> #include <sdglib/processors/GraphEditor.hpp> #include "sdglib/utilities/OutputLog.hpp" #include "cxxopts.hpp" int main(int argc, char * argv[]) { std::cout << "Welcome to sdg-untangler"<<std::endl<<std::endl; std::cout << "Git origin: " << GIT_ORIGIN_URL << " -> " << GIT_BRANCH << std::endl; std::cout << "Git commit: " << GIT_COMMIT_HASH << std::endl<<std::endl; std::cout << "Executed command:"<<std::endl; for (auto i=0;i<argc;i++) std::cout<<argv[i]<<" "; std::cout<<std::endl<<std::endl; std::string workspace_file,output_prefix; sdglib::OutputLogLevel=sdglib::LogLevels::INFO; bool repeat_expansion=false, neighbour_connection_graph=false, bubbly_paths=false; bool unroll_loops=false,pop_errors=false, paired_scaff=false, select_hspnps=false; bool explore_homopolymers=false; uint64_t min_backbone_node_size=1000; float min_backbone_ci=0.5; float max_backbone_ci=1.25; float tag_imbalance_ends=.1; int min_pairs=7; int min_shared_tags=10; int dev_max_lines=0; uint8_t dev_local_k=63; int dev_local_min_cvg=7; uint16_t dev_min_nodes=2,dev_min_total_size=0; std::string create_linkage,dev_skate_linkage,make_patches, load_patches, patch_backbones, patch_workspace,load_linkage; bool dev_local_patching=false; bool remap_reads=true; bool dump_gfa=false; bool dev_linkage_paths=false; bool dev_test_make_patches=false; std::string dev_linkage_stats; int dev_dump_local_problems_from=-1; int dev_dump_local_problems_to=-1; bool dev_test_assembly_and_patching=false; bool small_component_cleanup=false; try { cxxopts::Options options("sdg-untangler", "graph-based haplotype separation"); options.add_options() ("help", "Print help") ("w,workspace", "input workspace", cxxopts::value<std::string>(workspace_file)) ("o,output", "output file prefix", cxxopts::value<std::string>(output_prefix)) ("m,remap_reads","remap all reads on final workspace (default: true)",cxxopts::value<bool>(remap_reads)) ("dump_gfa","dump the final graph in GFA (default: false)",cxxopts::value<bool>(dump_gfa)); options.add_options("Backbone (unique anchors linkage)") ("min_backbone_node_size","minimum size of nodes to use in backbones",cxxopts::value<uint64_t>(min_backbone_node_size)) ("min_backbone_ci","minimum ci of nodes to use in backbones",cxxopts::value<float>(min_backbone_ci)) ("max_backbone_ci","minimum ci of nodes to use in backbones",cxxopts::value<float>(max_backbone_ci)) ("select_hspnp","select only Haplotype Specific Parallel Node Pairs to base scaffolding", cxxopts::value<bool>(select_hspnps)); options.add_options("Untangling") ("p,paired_reads","paired read scaffolding (experimental)",cxxopts::value<bool>(paired_scaff)) ("l,unroll_loops", "unroll simple loops",cxxopts::value<bool>(unroll_loops)) ("e,pop_errors", "pop unsupported short-bubbles (as errors)",cxxopts::value<bool>(pop_errors)) ("r,repeat_expansion","run tag-based repeat expansion", cxxopts::value<bool>(repeat_expansion)) ("c,small_component_cleanup","remove small unconnected components",cxxopts::value<bool>(small_component_cleanup)) ("b,bubbly_paths","run bubbly paths phasing", cxxopts::value<bool>(bubbly_paths)) ("min_pairs","minimum number of pairs to connect two nodes",cxxopts::value<int>(min_pairs)) ("tag_imbalance_ends","percentage of node to use as tag-imbalanced end",cxxopts::value<float>(tag_imbalance_ends)) ("min_shared_tags","minimum shared tags to evaluate tag-imbalanced connection",cxxopts::value<int>(min_shared_tags)); options.add_options("Linkage untangling") ("create_linkage","Creates and simplifies linkage and dumps to file",cxxopts::value<std::string>(create_linkage)) ("load_linkage","Linkage file to load",cxxopts::value<std::string>(load_linkage)) ("make_patches","Creates patches from local assemblies",cxxopts::value<std::string>(make_patches)) ("load_patches","Load patches form file",cxxopts::value<std::string>(load_patches)) ("patch_backbones","Patches backbones and outputs stitched sequences",cxxopts::value<std::string>(patch_backbones)) ("patch_workspace","Patches the workspace graph and outputs a gfa",cxxopts::value<std::string>(patch_workspace)) ("full_local_patching","run a whole round of linked lines and local patching, with a final remap", cxxopts::value<bool>(dev_local_patching)); options.add_options("Development") ("dev_test_assembly_and_patching", "solves 1/25 of the local assemblies, applies the patches and dumps detailed output",cxxopts::value<bool>(dev_test_assembly_and_patching)) ("dev_linkage_paths", "tag linkage uses read pathing rather than simple mapping",cxxopts::value<bool>(dev_linkage_paths)) //("dev_skate_linkage","Loads linkage from file and skates",cxxopts::value<std::string>(dev_skate_linkage)) ("dev_linkage_stats","Loads linkage from file and computes local assemblies stats",cxxopts::value<std::string>(dev_linkage_stats)) ("dev_max_lines","Limits lines to be skated on dev",cxxopts::value<int>(dev_max_lines)) ("dev_min_nodes","Limits lines to be locally assembled on dev to at least min_nodes",cxxopts::value<uint16_t >(dev_min_nodes)) ("dev_min_total_size","Limits lines to be locally assembled on dev to at least min_total_size",cxxopts::value<uint16_t>(dev_min_total_size)) ("dev_local_k","k value for local assembly",cxxopts::value<uint8_t>(dev_local_k)) ("dev_local_min_cvg","minimum coverage for local assemblies",cxxopts::value<int>(dev_local_min_cvg)) ("dev_dump_local_problems_from","dumps local problems from",cxxopts::value<int>(dev_dump_local_problems_from)) ("dev_dump_local_problems_to","dumps local problems from",cxxopts::value<int>(dev_dump_local_problems_to)); auto result(options.parse(argc, argv)); if (result.count("help")) { std::cout << options.help({"","Backbone (unique anchors linkage)","Untangling functions","Development"}) << std::endl; exit(0); } if (result.count("w")!=1 or result.count("o")!=1) { throw cxxopts::OptionException(" please specify input workspace and output prefix"); } } catch (const cxxopts::OptionException& e) { std::cout << "Error parsing options: " << e.what() << std::endl << std::endl <<"Use option --help to check command line arguments." << std::endl; exit(1); } std::cout<<std::endl; //======= WORKSPACE LOAD AND CHECKS ====== WorkSpace ws; sdglib::OutputLog()<<"Loading Workspace..."<<std::endl; ws.load_from_disk(workspace_file); if (!ws.sg.is_sane()) { sdglib::OutputLog()<<"ERROR: sg.is_sane() = false"<<std::endl; return 1; } //TODO: other checks? reads mapped to valid nodes and such? ws.add_log_entry("sdg-untangler run started"); sdglib::OutputLog()<<"Loading Workspace DONE"<<std::endl; if (remap_reads) sdglib::OutputLog()<<"This run WILL remap reads at the end"<<std::endl; else sdglib::OutputLog()<<"This run will NOT remap reads at the end"<<std::endl; //======= FUNCTIONS FOR REAL-LIFE USE ====== if (unroll_loops){ Untangler u(ws); u.unroll_simple_loops(); ws.sg.join_all_unitigs(); } if (pop_errors){ Untangler u(ws); u.pop_errors_by_ci_and_paths(60,200); ws.sg.join_all_unitigs(); ws.kci.reindex_graph(); for (auto &m:ws.linked_read_mappers) { m.remap_all_reads(); } } if (repeat_expansion) { //TODO: parameters are hardcoded here Untangler u(ws); u.expand_canonical_repeats_by_tags(.5,1.25,20); ws.sg.join_all_unitigs(); } if (bubbly_paths){ Untangler u(ws); u.solve_bubbly_paths(); ws.sg.join_all_unitigs(); } //======= DEVELOPMENT FUNCTIONS ====== LinkageDiGraph tag_ldg(ws.sg); if (!create_linkage.empty()) { LinkageUntangler lu(ws); lu.select_nodes_by_size_and_ci(min_backbone_node_size,min_backbone_ci,max_backbone_ci); tag_ldg.links=lu.make_and_simplify_linkage(min_shared_tags).links; tag_ldg.dump_to_text(create_linkage); const auto& tag_con_nodes(tag_ldg.get_connected_nodes()); std::vector<sgNodeID_t> connected_nodes(tag_con_nodes.begin(), tag_con_nodes.end()); tag_ldg.write_to_gfa1(output_prefix+"_linkage.gfa", connected_nodes); auto lines=tag_ldg.get_all_lines(dev_min_nodes); std::ofstream linesf(output_prefix+"_linkage_lines.txt"); for (auto l:lines){ for (auto n:l) linesf<<n<<","; linesf<<std::endl; for (auto n:l) linesf<<"seq"<<llabs(n)<<","; linesf<<std::endl; } exit(0); } if (!load_linkage.empty()){ tag_ldg.load_from_text(load_linkage); } if (dev_dump_local_problems_from>-1 and dev_dump_local_problems_from<dev_dump_local_problems_to){ sdglib::OutputLog()<<"Analysing connectivity"<<std::endl; tag_ldg.report_connectivity(); sdglib::OutputLog()<<"Creating local assembly problems..."<<std::endl; auto lines=tag_ldg.get_all_lines(dev_min_nodes); if (dev_max_lines) { sdglib::OutputLog()<<"dev_max_lines set, solving only "<<dev_max_lines<<" / "<<lines.size()<<std::endl; lines.resize(dev_max_lines); } uint64_t li=0; uint64_t i=0; sdglib::OutputLog()<<"Dumping from "<< dev_dump_local_problems_from <<" to "<< dev_dump_local_problems_to << " of " <<lines.size()<<" local assembly problems..."<<std::endl; for (auto li=dev_dump_local_problems_from;li<lines.size() and li<=dev_dump_local_problems_to;++li) { auto &l = lines[li]; LocalHaplotypeAssembler lha(ws); lha.init_from_backbone(l); lha.write_full(output_prefix + "_local_" + std::to_string(li) + ".bsglhapf"); } exit(0); } std::vector<std::pair<std::pair<sgNodeID_t ,sgNodeID_t>,std::string>> patches; if (!make_patches.empty()) { std::vector<std::string> full_patched_backbones; std::vector<std::vector<std::string>> patched_backbone_parts; sdglib::OutputLog()<<"Analysing connectivity"<<std::endl; tag_ldg.report_connectivity(); sdglib::OutputLog()<<"Creating local assembly problems..."<<std::endl; auto lines=tag_ldg.get_all_lines(dev_min_nodes); if (dev_max_lines) { sdglib::OutputLog()<<"dev_max_lines set, solving only "<<dev_max_lines<<" / "<<lines.size()<<std::endl; lines.resize(dev_max_lines); } uint64_t li=0; uint64_t i=0; sdglib::OutputLog()<<"Solving "<<lines.size()<<" local assembly problems..."<<std::endl; #pragma omp parallel for schedule(dynamic,10) for (auto li=0;li<lines.size();++li) { auto &l=lines[li]; std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); LocalHaplotypeAssembler lha(ws); lha.init_from_backbone(l); lha.assemble(63, 7, false, false); lha.create_63mer_index(false); lha.path_linked_reads_informative_singles(); lha.expand_canonical_repeats(); lha.assembly.join_all_unitigs(); lha.create_63mer_index(false); lha.path_linked_reads_informative_singles(); lha.expand_canonical_repeats(); lha.assembly.join_all_unitigs(); lha.construct_patches(); //lha.write_patches("local_"+std::to_string(i)+"_patches.fasta"); std::chrono::steady_clock::time_point end= std::chrono::steady_clock::now(); #pragma omp critical(patch_collection) { patches.insert(patches.end(),lha.patches.begin(),lha.patches.end()); sdglib::OutputLog() << "Local assembly #"<<li<<" from " << l.size() << " anchors done in " << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << " seconds, produced " << lha.patches.size() << " patches" << std::endl; } lha.construct_patched_backbone(); #pragma omp critical(backbone_collection1) { full_patched_backbones.insert(full_patched_backbones.end(),lha.patched_backbone.begin(),lha.patched_backbone.end()); } lha.construct_patched_backbone(false); #pragma omp critical(backbone_collection2) { patched_backbone_parts.push_back(lha.patched_backbone); } } sdglib::OutputLog()<<patches.size()<<" patches found"<<std::endl; std::ofstream patchf(make_patches); for (auto &p:patches){ patchf << ">patch_" << -p.first.first << "_" << p.first.second << std::endl; patchf << p.second << std::endl; } std::ofstream patchbf(make_patches+"_fullbackbones.fasta"); uint64_t fpbi=0; for (auto &s:full_patched_backbones){ patchbf << ">fpb_" <<++fpbi << std::endl << s << std::endl; } std::ofstream patchbpf(make_patches+"_backbone_parts.fasta"); fpbi=0; for (auto &bbp:patched_backbone_parts){ ++fpbi; auto p=0; for (auto s:bbp) patchbpf << ">fpb_" << fpbi << "_" << ++p << std::endl << s << std::endl; } exit(0); } if (!load_patches.empty()){ std::ifstream pf(load_patches); auto i=0; while (!pf.eof()){ std::string l; pf>>l; if (l.empty()) break; l=l.substr(7,l.size()); auto l2=l.substr(l.find('_')+1,l.size()); sgNodeID_t n1=atol(l.c_str()); sgNodeID_t n2=atol(l2.c_str()); std::string seq; pf>>seq; patches.emplace_back(std::make_pair(n1,n2),seq); } } if (!dev_linkage_stats.empty()) { LinkageUntangler lu(ws); sdglib::OutputLog()<<"Analysing connectivity"<<std::endl; tag_ldg.report_connectivity(); auto lines=tag_ldg.get_all_lines(dev_min_nodes); if (dev_max_lines) lines.resize(dev_max_lines); uint64_t li=0; LinkageUntangler lu2(ws); for (auto l:lines) { for (auto ln:l) lu2.selected_nodes[llabs(ln)]=true; } sdglib::OutputLog()<<"---NODES CONNECTED ON GLOBAL PROBLEM: "<<std::endl; for (auto n=1;n<ws.sg.nodes.size();++n) { if (tag_ldg.get_fw_links(n).size()>0 or tag_ldg.get_bw_links(n).size()>0) lu.selected_nodes[n]=true; } lu.report_node_selection(); sdglib::OutputLog()<<"Bubbles in the linkage digraph: "<<tag_ldg.find_bubbles(0,10000000).size()<<std::endl; sdglib::OutputLog()<<"---NODES USED ON LOCAL PROBLEMS ("<<lines.size()<<" lines): "<<std::endl; lu2.report_node_selection(); exit(0); } if (dev_local_patching) { int min_sizes[6]={750,1000,1500,750,1000,1500}; int min_coverages[6]={7,7,7,5,5,5}; for (int cycle=0;cycle<6;++cycle) { min_backbone_node_size=min_sizes[cycle]; int min_coverage=min_coverages[cycle]; { //=================now linkage LinkageUntangler lu(ws); lu.select_nodes_by_size_and_ci(min_backbone_node_size, min_backbone_ci, max_backbone_ci); tag_ldg.links=lu.make_and_simplify_linkage(min_shared_tags).links; } //now create patches { patches.clear(); auto lines = tag_ldg.get_all_lines(dev_min_nodes); sdglib::OutputLog() << "Solving " << lines.size() << " local assembly problems..." << std::endl; #pragma omp parallel for schedule(dynamic, 10) for (auto li = 0; li < lines.size(); ++li) { auto &l = lines[li]; std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); LocalHaplotypeAssembler lha(ws); lha.init_from_backbone(l); lha.assemble(63, min_coverage, false, false); lha.create_63mer_index(false); lha.path_linked_reads_informative_singles(); lha.expand_canonical_repeats(); lha.assembly.join_all_unitigs(); lha.create_63mer_index(false); lha.path_linked_reads_informative_singles(); lha.expand_canonical_repeats(); lha.assembly.join_all_unitigs(); lha.construct_patches(); //lha.write_patches("local_"+std::to_string(i)+"_patches.fasta"); std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); #pragma omp critical(patch_collection) { patches.insert(patches.end(), lha.patches.begin(), lha.patches.end()); sdglib::OutputLog() << "Local assembly #" << li << " from " << l.size() << " anchors done in " << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << " seconds, produced " << lha.patches.size() << " patches" << std::endl; } } } //now apply patches { sdglib::OutputLog() << "Patching workspace!!!" << std::endl; GraphEditor ge(ws); uint64_t patch_results[6]={0,0,0,0,0,0}; for (auto p:patches) { auto r=ge.patch_between(p.first.first,p.first.second,p.second); ++patch_results[r]; } sdglib::OutputLog() << "Patches with no anchor ends: "<< patch_results[1] <<std::endl; sdglib::OutputLog() << "Patches with no SG paths: "<< patch_results[2] <<std::endl; sdglib::OutputLog() << "Patches with failed expansion: "<< patch_results[5] <<std::endl; sdglib::OutputLog() << "Patches correctly applied: "<< patch_results[0] <<std::endl; auto juc=ws.sg.join_all_unitigs(); sdglib::OutputLog() << juc << " unitigs joined after patching"<<std::endl; //ws.sg.write_to_gfa(patch_workspace); } ws.sg.write_to_gfa1(output_prefix+"fulllocal_cycle_"+std::to_string(cycle)+".gfa"); //reindex KCI ws.kci.reindex_graph(); //remap reads (k63) ws.remap_all63(); //dump workspace and graph ws.dump_to_disk(output_prefix+"fulllocal_cycle_"+std::to_string(cycle)+".bsgws"); } } if (dev_test_assembly_and_patching) { //=================now linkage LinkageUntangler lu(ws); lu.select_nodes_by_size_and_ci(min_backbone_node_size, min_backbone_ci, max_backbone_ci); tag_ldg.links=lu.make_and_simplify_linkage(min_shared_tags).links; //TODO:dump linkage maybe? patches.clear(); auto lines = tag_ldg.get_all_lines(dev_min_nodes); sdglib::OutputLog() << "Solving 1/25 of " << lines.size() << " local assembly problems..." << std::endl; uint64_t all_patches=0,assembled_patches=0; #pragma omp parallel for schedule(dynamic, 10) reduction(+:all_patches,assembled_patches) for (auto li = 0; li < lines.size(); li+=25) { auto &l = lines[li]; std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); LocalHaplotypeAssembler lha(ws); lha.init_from_backbone(l); lha.assemble(63, dev_local_min_cvg, false, false); lha.create_63mer_index(false); lha.path_linked_reads_informative_singles(); lha.expand_canonical_repeats(); lha.assembly.join_all_unitigs(); lha.create_63mer_index(false); lha.path_linked_reads_informative_singles(); lha.expand_canonical_repeats(); lha.assembly.join_all_unitigs(); lha.construct_patches(); all_patches+=l.size()-1; assembled_patches+=lha.patches.size(); lha.write_full(output_prefix+"_local_"+std::to_string(li)); lha.write_gfa(output_prefix+"_local_"+std::to_string(li)+".gfa"); lha.write_anchors(output_prefix+"_local_"+std::to_string(li)+"_anchors.fasta"); lha.write_patches(output_prefix+"_local_"+std::to_string(li)+"_patches.fasta"); lha.construct_patched_backbone(); lha.write_patched_backbone(output_prefix+"_local_"+std::to_string(li)+"_patchedbackbone.fasta"); std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); #pragma omp critical(patch_collection) { patches.insert(patches.end(), lha.patches.begin(), lha.patches.end()); sdglib::OutputLog() << "Local assembly #" << li << " from " << l.size() << " anchors done in " << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << " seconds, produced " << lha.patches.size() << " patches" << std::endl; } } sdglib::OutputLog() << "Local assembly produced "<<assembled_patches<<" / "<<all_patches<<" patches"<<std::endl; //now apply patches { sdglib::OutputLog() << "Patching workspace!!!" << std::endl; GraphEditor ge(ws); std::ofstream pstatsf(output_prefix+"_patching_stats.csv"); pstatsf<<"from,to,size,code,fromfw_before,fromfw_after,tobw_before,tobw_after"<<std::endl; uint64_t patch_results[6]={0,0,0,0,0,0}; for (auto p:patches) { auto fromfw_before=ws.sg.get_fw_links(p.first.first).size(); auto tobw_before=ws.sg.get_bw_links(p.first.second).size(); auto r=ge.patch_between(p.first.first,p.first.second,p.second); auto fromfw_after=ws.sg.get_fw_links(p.first.first).size(); auto tobw_after=ws.sg.get_bw_links(p.first.second).size(); ++patch_results[r]; //TODO: check the collection of unitigs has changed. pstatsf<<-p.first.first<<","<<p.first.second<<","<<p.second.size()<<","<<r<<","<<fromfw_before<<","<<fromfw_after<<","<<tobw_before<<","<<tobw_after<<std::endl; } sdglib::OutputLog() << "Patches with no anchor ends: "<< patch_results[1] <<std::endl; sdglib::OutputLog() << "Patches with no SG paths: "<< patch_results[2] <<std::endl; sdglib::OutputLog() << "Patches with failed expansion: "<< patch_results[5] <<std::endl; sdglib::OutputLog() << "Patches correctly applied: "<< patch_results[0] <<std::endl; ws.sg.write_to_gfa1(output_prefix+"_patched_notjoined.gfa"); auto juc=ws.sg.join_all_unitigs(); sdglib::OutputLog() << juc << " unitigs joined after patching"<<std::endl; //ws.sg.write_to_gfa(patch_workspace); } ws.sg.write_to_gfa1(output_prefix+"_patched.gfa"); exit(0); } if (!patch_backbones.empty()) { std::ofstream patched_backbones_file(patch_backbones); sdglib::OutputLog() << "Analysing connectivity" << std::endl; tag_ldg.report_connectivity(); sdglib::OutputLog() << "Creating local assembly problems..." << std::endl; auto lines = tag_ldg.get_all_lines(dev_min_nodes); if (dev_max_lines) { sdglib::OutputLog() << "dev_max_lines set, solving only " << dev_max_lines << " / " << lines.size() << std::endl; lines.resize(dev_max_lines); } uint64_t li = 0; uint64_t i = 0; std::map<std::pair<sgNodeID_t, sgNodeID_t>, std::string> patchmap; for (auto p:patches) patchmap[p.first]=p.second; sdglib::OutputLog() << "Patching in " << lines.size() << " local assembly problems from " << patches.size() << " patches..." << std::endl; int endsize=200; for (auto li = 0; li < lines.size(); ++li) { auto &l = lines[li]; std::string name=">"+std::to_string(l[0]); auto n=ws.sg.nodes[llabs(l[0])]; if (l[0]<0)n.make_rc(); std::string seq=n.sequence; for (auto ni=0;ni<l.size()-1;++ni){ //for each transition, either put the patch, or start a new sequence if (patchmap.count(std::make_pair(-l[ni],l[ni+1]))==0){ //patch not found patched_backbones_file<<name<<std::endl<<seq<<std::endl; name=">"+std::to_string(l[ni+1]); n=ws.sg.nodes[llabs(l[ni+1])]; if (l[ni+1]<0)n.make_rc(); seq=n.sequence; } else { //patch found //create/add patch substring std::string p=patchmap[std::make_pair(-l[ni],l[ni+1])]; seq+=p.substr(endsize+1,p.size()-endsize*3-1); //add next node name+="_"+std::to_string(l[ni+1]); n=ws.sg.nodes[llabs(l[ni+1])]; if (l[ni+1]<0)n.make_rc(); seq+=n.sequence; } } patched_backbones_file<<name<<std::endl<<seq<<std::endl; } exit(0); } if (!patch_workspace.empty()) { sdglib::OutputLog() << "Patching workspace!!!" << std::endl; GraphEditor ge(ws); std::ofstream pstatsf(output_prefix+"_patching_stats.csv"); pstatsf<<"from,to,size,code,fromfw_before,fromfw_after,tobw_before,tobw_after"<<std::endl; uint64_t patch_results[6]={0,0,0,0,0,0}; for (auto p:patches) { auto fromfw_before=ws.sg.get_fw_links(-p.first.first).size(); auto tobw_before=ws.sg.get_bw_links(p.first.second).size(); auto r=ge.patch_between(-p.first.first,p.first.second,p.second); auto fromfw_after=ws.sg.get_fw_links(-p.first.first).size(); auto tobw_after=ws.sg.get_bw_links(p.first.second).size(); ++patch_results[r]; //TODO: check the collection of unitigs has changed. pstatsf<<-p.first.first<<","<<p.first.second<<","<<p.second.size()<<","<<r<<","<<fromfw_before<<","<<fromfw_after<<","<<tobw_before<<","<<tobw_after<<std::endl; } sdglib::OutputLog() << "Patches with no anchor ends: "<< patch_results[1] <<std::endl; sdglib::OutputLog() << "Patches with no SG paths: "<< patch_results[2] <<std::endl; sdglib::OutputLog() << "Patches with failed expansion: "<< patch_results[5] <<std::endl; sdglib::OutputLog() << "Patches correctly applied: "<< patch_results[0] <<std::endl; auto juc=ws.sg.join_all_unitigs(); sdglib::OutputLog() << juc << " unitigs joined after patching"<<std::endl; ws.sg.write_to_gfa1(patch_workspace); } if (small_component_cleanup) { GraphEditor ge(ws); ge.remove_small_components(20,1000,3000); } ws.kci.reindex_graph(); if (dump_gfa) ws.sg.write_to_gfa(output_prefix+".gfa"); if (remap_reads) ws.remap_all(); ws.dump_to_disk(output_prefix+".bsgws"); return 0; }
51.219424
189
0.595793
[ "vector" ]
da0d8ac7057b904325d23bcbd98d29c4f81aa053
3,350
hpp
C++
include/mbgl/actor/established_actor.hpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
4,234
2015-01-09T08:10:16.000Z
2022-03-30T14:13:55.000Z
include/mbgl/actor/established_actor.hpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
12,771
2015-01-01T20:27:42.000Z
2022-03-24T18:14:44.000Z
include/mbgl/actor/established_actor.hpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
1,571
2015-01-08T08:24:53.000Z
2022-03-28T06:30:53.000Z
#pragma once #include <mbgl/actor/aspiring_actor.hpp> #include <mbgl/actor/mailbox.hpp> #include <mbgl/actor/message.hpp> #include <mbgl/actor/actor_ref.hpp> #include <memory> #include <future> #include <type_traits> #include <cassert> namespace mbgl { /* An `EstablishedActor<O>` is one half of the pair of types that comprise an actor (see `Actor<O>`), the other half being `AspiringActor<O>`. It is responsible for managing the lifetime of the target object `O` and the open/closed state of the parent's `mailbox`. The `O` object's lifetime is contained by that of its owning `EstablishedActor<O>`: the `EstablishedActor` constructor executes the `O` constructor via "placement new", constructing it at the address provided by the parent `AspiringActor`, and the `~EstablishedActor` destructor similarly executes the `~O` destructor (after closing the mailbox). `EstablishedActor` should therefore live entirely on the thread intended to own `O`. */ template <class Object> class EstablishedActor { public: // Construct the Object from a parameter pack `args` (i.e. `Object(args...)`) template <typename U = Object, class... Args, typename std::enable_if< std::is_constructible<U, Args...>::value || std::is_constructible<U, ActorRef<U>, Args...>::value >::type * = nullptr> EstablishedActor(Scheduler& scheduler, AspiringActor<Object>& parent_, Args&& ... args) : parent(parent_) { emplaceObject(std::forward<Args>(args)...); parent.mailbox->open(scheduler); } // Construct the `Object` from a tuple containing the constructor arguments (i.e. // `Object(std::get<0>(args), std::get<1>(args), ...)`) template <class ArgsTuple, std::size_t ArgCount = std::tuple_size<std::decay_t<ArgsTuple>>::value> EstablishedActor(Scheduler& scheduler, AspiringActor<Object>& parent_, ArgsTuple&& args) : parent(parent_) { emplaceObject(std::forward<ArgsTuple>(args), std::make_index_sequence<ArgCount>{}); parent.mailbox->open(scheduler); } EstablishedActor(const EstablishedActor&) = delete; ~EstablishedActor() { parent.mailbox->close(); parent.object().~Object(); } private: // Enabled for Objects with a constructor taking ActorRef<Object> as the first parameter template <typename U = Object, class... Args, typename std::enable_if<std::is_constructible<U, ActorRef<U>, Args...>::value>::type * = nullptr> void emplaceObject(Args&&... args_) { new (&parent.objectStorage) Object(parent.self(), std::forward<Args>(args_)...); } // Enabled for plain Objects template <typename U = Object, class... Args, typename std::enable_if<std::is_constructible<U, Args...>::value>::type * = nullptr> void emplaceObject(Args&&... args_) { new (&parent.objectStorage) Object(std::forward<Args>(args_)...); } // Used to expand a tuple holding the constructor arguments template <class ArgsTuple, std::size_t... I> void emplaceObject(ArgsTuple&& args, std::index_sequence<I...>) { emplaceObject(std::move(std::get<I>(std::forward<ArgsTuple>(args)))...); (void) args; // mark args as used: if it's empty tuple, it's not actually used above. } AspiringActor<Object>& parent; }; } // namespace mbgl
41.358025
147
0.676716
[ "object" ]
da129ff32aa31544052c72ba37e7da8d1ff31b70
1,991
cpp
C++
spot_micro_motion_cmd/src/utils.cpp
bwees/spotMicro
48a505e6b66de135f7ef196736049132f8111d6c
[ "MIT" ]
1,563
2020-06-09T09:49:32.000Z
2022-03-31T04:39:45.000Z
spot_micro_motion_cmd/src/utils.cpp
bwees/spotMicro
48a505e6b66de135f7ef196736049132f8111d6c
[ "MIT" ]
71
2020-07-02T16:30:39.000Z
2022-03-24T07:46:06.000Z
spot_micro_motion_cmd/src/utils.cpp
bwees/spotMicro
48a505e6b66de135f7ef196736049132f8111d6c
[ "MIT" ]
390
2020-06-10T00:18:57.000Z
2022-03-30T12:42:52.000Z
#include "utils.h" #include <ros/ros.h> #include <eigen3/Eigen/Geometry> #include "tf2/LinearMath/Quaternion.h" #include "tf2_eigen/tf2_eigen.h" #include "tf2_geometry_msgs/tf2_geometry_msgs.h" using namespace Eigen; using namespace geometry_msgs; Affine3d matrix4fToAffine3d(const Matrix4f& in) { // Convert a Eigen Matrix4F to an Affine3d by first casting // float to double (to a Matrix4d), then calling the constructor for Affine3d // with the Matrix4d return Affine3d(in.cast<double>()); } // Create a ROS tf2 TransformStamped from a Eigen Affine3d, // parent frame id and child frame id. Stamped with current time, // so should be broadcast ASAP TransformStamped eigAndFramesToTrans( const Affine3d& transform, std::string parent_frame_id, std::string child_frame_id) { TransformStamped transform_stamped = tf2::eigenToTransform(transform); transform_stamped.header.stamp = ros::Time::now(); transform_stamped.header.frame_id = parent_frame_id; transform_stamped.child_frame_id = child_frame_id; return transform_stamped; } // Create a transform from a translation, rotation, and parent and // child frame IDs. Will stamp the transform with ros::Time::now(), // so the returned transform should be broadcast asap TransformStamped createTransform( std::string parent_frame_id, std::string child_frame_id, double x, double y, double z, double roll, double pitch, double yaw) { TransformStamped tr_stamped; tr_stamped.header.stamp = ros::Time::now(); tr_stamped.header.frame_id = parent_frame_id; tr_stamped.child_frame_id = child_frame_id; tr_stamped.transform.translation.x = x; tr_stamped.transform.translation.y = y; tr_stamped.transform.translation.z = z; tf2::Quaternion q; q.setRPY(roll, pitch, yaw); tr_stamped.transform.rotation.x = q.x(); tr_stamped.transform.rotation.y = q.y(); tr_stamped.transform.rotation.z = q.z(); tr_stamped.transform.rotation.w = q.w(); return tr_stamped; }
30.630769
79
0.750879
[ "geometry", "transform" ]
da1994f2e74f1c51d50559b9dcbd44d2e750e000
14,243
cc
C++
src/module/builtins.cc
ArgonLang/Argon
462d3d8721acd5131894bcbfa0214b0cbcffdf66
[ "Apache-2.0" ]
13
2021-06-24T17:50:20.000Z
2022-03-13T23:00:16.000Z
src/module/builtins.cc
ArgonLang/Argon
462d3d8721acd5131894bcbfa0214b0cbcffdf66
[ "Apache-2.0" ]
null
null
null
src/module/builtins.cc
ArgonLang/Argon
462d3d8721acd5131894bcbfa0214b0cbcffdf66
[ "Apache-2.0" ]
1
2022-03-31T22:58:42.000Z
2022-03-31T22:58:42.000Z
// This source file is part of the Argon project. // // Licensed under the Apache License v2.0 #include <vm/context.h> #include <vm/runtime.h> #include <object/datatype/bool.h> #include <object/datatype/bounds.h> #include <object/datatype/bytes.h> #include <object/datatype/code.h> #include <object/datatype/decimal.h> #include <object/datatype/error.h> #include <object/datatype/function.h> #include "object/datatype/io/io.h" #include <object/datatype/integer.h> #include <object/datatype/list.h> #include <object/datatype/map.h> #include <object/datatype/module.h> #include <object/datatype/namespace.h> #include <object/datatype/nil.h> #include <object/datatype/option.h> #include <object/datatype/set.h> #include <object/datatype/string.h> #include <object/datatype/tuple.h> #include "modules.h" using namespace argon::object; using namespace argon::module; ARGON_FUNCTION(bind, "Return a partial-applied function(currying)." "" "Calling bind(func, args...) is equivalent to the following expression:" "func(args...) " "IF AND ONLY IF the number of arguments is less than the arity of the function," "otherwise the expression invokes the function call. " "This does not happen with the use of bind which allows to bind a number of arguments" "equal to the arity of the function." "" "- Parameters:" " - func: callable object(function)." " - ...obj: list of arguments to bind." "- Returns: partial-applied function.", 1, true) { auto *base = (Function *) argv[0]; Function *fnew; List *currying; if (!AR_TYPEOF(func, type_function_)) return ErrorFormat(type_type_error_, "bind expect a function as its first argument, not '%s'", AR_TYPE_NAME(func)); if (count - 1 > 0) { if ((currying = ListNew(count - 1)) == nullptr) return nullptr; for (ArSize i = 1; i < count; i++) ListAppend(currying, argv[i]); fnew = FunctionNew(base, currying); Release(currying); return fnew; } return IncRef(func); } ARGON_FUNCTION(callable, "Return true if argument appears callable, false otherwise." "" "- Parameter obj: object to check." "- Returns: true if object is callable, false otherwise.", 1, false) { // This definition may be change in future if (argv[0]->type == type_function_) return True; return False; } ARGON_FUNCTION(exit, "Close STDIN and starts panicking state with RuntimeExit error." "" "This is a convenient function to terminate your interactive session." "" "- Returns: this function does not return to the caller.", 0, false) { auto *in = (io::File *) argon::vm::ContextRuntimeGetProperty("stdin", io::type_file_); if (in != nullptr) { io::Close(in); // If fail, just ignore it and move on if (argon::vm::IsPanicking()) Release(argon::vm::GetLastError()); } Release(in); return argon::vm::Panic(ErrorNew(type_runtime_exit_error_, NilVal)); } ARGON_FUNCTION(hasnext, "Return true if the iterator has more elements." "" "- Parameter iterator: iterator object." "- Returns: true if the iterator has more elements, false otherwise.", 1, false) { return BoolToArBool(AR_ITERATOR_SLOT(*argv)->has_next(*argv)); } ARGON_FUNCTION(input, "Allowing user input." "" "- Parameter prompt: string representing a default message before the input." "- Returns: string containing user input.", 1, false) { auto in = (io::File *) argon::vm::ContextRuntimeGetProperty("stdin", io::type_file_); auto out = (io::File *) argon::vm::ContextRuntimeGetProperty("stdout", io::type_file_); unsigned char *line = nullptr; ArObject *str = nullptr; ArSSize len; if (in == nullptr || out == nullptr) goto error; if ((str = ToString(argv[0])) == nullptr) goto error; if (io::WriteObject(out, str) < 0) goto error; io::Flush(out); Release(str); Release(out); if ((len = io::ReadLine(in, &line, 0)) < 0) goto error; Release(in); return StringNewBufferOwnership(line, len); error: Release(in); Release(out); Release(str); return nullptr; } ARGON_FUNCTION(isinstance, "Check if object is an instance of indicated type." "" "- Parameter obj: object to check." "- Returns: true if the object is an instance of indicated type, false otherwise.", 2, false) { return BoolToArBool(argv[0]->type == argv[1]); } ARGON_FUNCTION(isimpl, "Check if object implements all the indicated traits." "" "- Parameters:" " - obj: object to check." " - ...traits: traits list." "- Returns: true if the object implements ALL indicated traits, false otherwise.", 2, true) { for (ArSize i = 1; i < count; i++) { if (!TraitIsImplemented(argv[0], (TypeInfo *) argv[i])) return BoolToArBool(false); } return BoolToArBool(true); } ARGON_FUNCTION(iter, "Return an iterator object." "" "- Parameter obj: iterable object." "- Returns: new iterator." "- Panic TypeError: object is not iterable." "" "# SEE" "- riter: to obtain a reverse iterator.", 1, false) { return IteratorGet(*argv); } ARGON_FUNCTION(len, "Returns the length of an object." "" "- Parameter obj: object to check." "- Returns: the length of the object." "- Panics:" " - TypeError: object has no len." " - OverflowError: object is too long.", 1, false) { ArSize length; if (AsSequence(argv[0])) length = argv[0]->type->sequence_actions->length(argv[0]); else if (AsMap(argv[0])) length = argv[0]->type->map_actions->length(argv[0]); else return ErrorFormat(type_type_error_, "type '%s' has no len", argv[0]->type->name); return IntegerNew(length); } ARGON_FUNCTION(next, "Retrieve the next item from the iterator." "" "- Parameter iterator: iterator object." "- Returns: object." "- Panics:" " - TypeError: invalid iterator." " - ExhaustedIteratorError: reached the end of the collection.", 1, false) { ArObject *ret = IteratorNext(*argv); if (ret == nullptr) return ErrorFormat(type_exhausted_iterator_, "reached the end of the collection"); return ret; } ARGON_FUNCTION(panic, "Stops normal execution of current ArRoutine." "" "When a function F calls panic, it's execution stops immediately, " "after that, any deferred function run in usual way, and then F returns to its caller." "To the caller, the invocation of function F behaves like a call to panic," "terminating caller function and executing any deferred functions." "This behaviour continues until all function in the current ArRoutine have stopped." "At that point, the program terminated with a non-zero exit code." "You can control this termination sequence (panicking) using the built-in function recover." "" "- Parameter obj: an object that describe this error." "- Returns: this function does not return to the caller.", 1, false) { return argon::vm::Panic(argv[0]); } ARGON_FUNCTION(recover, "Allows a program to manage behavior of panicking ArRoutine." "" "Executing a call to recover inside a deferred function stops" "the panicking sequence by restoring normal execution flow." "After that the function retrieve and returns the error value passed" "to the call of function panic." "" "# WARNING" "Calling this function outside of deferred function has no effect." "" "- Returns: argument supplied to panic call, or nil if ArRoutine is not panicking.", 0, false) { return ReturnNil(argon::vm::GetLastError()); } ARGON_FUNCTION(returns, "Set and/or get the return value of the function that invoked a defer." "" "If returns is called with:" " * 0 argument: no value is set as a return value." " * 1 argument: argument is set as a return value." " * n arguments: the return value is a tuple containing all the passed values." "" "In any case, the current return value is returned." "" "- Parameters:" " - ...objs: return value." "- Returns: current return value.", 0, true) { ArObject *ret; ArObject *current; current = ReturnNil(argon::vm::RoutineReturnGet(argon::vm::GetRoutine())); if (count > 0) { if (count > 1) { if ((ret = TupleNew(argv, count)) == nullptr) return nullptr; argon::vm::RoutineReturnSet(argon::vm::GetRoutine(), ret); Release(ret); return current; } argon::vm::RoutineReturnSet(argon::vm::GetRoutine(), *argv); } return current; } ARGON_FUNCTION(riter, "Return an reverse iterator object." "" "- Parameter obj: iterable object." "- Returns: new reverse iterator." "- Panic TypeError: object is not iterable." "" "# SEE" "- iter: to obtain an iterator.", 1, false) { return IteratorGetReversed(*argv); } ARGON_FUNCTION(type, "Returns type of the object passed as parameter." "" "- Parameter obj: object to get the type from." "- Returns: obj type.", 1, false) { IncRef((ArObject *) argv[0]->type); return (ArObject *) argv[0]->type; } ARGON_FUNCTION(print, "Print objects to the stdout, separated by space." "" "- Parameters:" " - ...obj: objects to print." "- Returns: nil", 0, true) { auto out = (io::File *) argon::vm::ContextRuntimeGetProperty("stdout", io::type_file_); ArObject *str; ArSize i = 0; if (out == nullptr) return nullptr; while (i < count) { if ((str = ToString(argv[i++])) == nullptr) return nullptr; if (io::WriteObject(out, str) < 0) { Release(str); return nullptr; } Release(str); if (i < count) { if (io::Write(out, (unsigned char *) " ", 1) < 0) return nullptr; } } return NilVal; } ARGON_FUNCTION(println, "Same as print, but add new-line at the end." "" "- Parameters:" " - ...obj: objects to print." "- Returns: nil" "" "# SEE" "- print.", 0, true) { ArObject *success = ARGON_CALL_FUNC(print, func, self, argv, count); if (success != nullptr) { auto out = (io::File *) argon::vm::ContextRuntimeGetProperty("stdout", io::type_file_); if (out == nullptr) return nullptr; if (io::Write(out, (unsigned char *) "\n", 1) < 0) { Release(success); return nullptr; } } return success; } const PropertyBulk builtins_bulk[] = { MODULE_EXPORT_TYPE_ALIAS("bool", type_bool_), MODULE_EXPORT_TYPE_ALIAS("bounds", type_bounds_), MODULE_EXPORT_TYPE_ALIAS("bytes", type_bytes_), MODULE_EXPORT_TYPE_ALIAS("code", type_code_), MODULE_EXPORT_TYPE_ALIAS("decimal", type_decimal_), MODULE_EXPORT_TYPE_ALIAS("function", type_function_), MODULE_EXPORT_TYPE_ALIAS("integer", type_integer_), MODULE_EXPORT_TYPE_ALIAS("list", type_list_), MODULE_EXPORT_TYPE_ALIAS("map", type_map_), MODULE_EXPORT_TYPE_ALIAS("module", type_module_), MODULE_EXPORT_TYPE_ALIAS("namespace", type_namespace_), MODULE_EXPORT_TYPE_ALIAS("niltype", type_nil_), MODULE_EXPORT_TYPE_ALIAS("option", type_option_), MODULE_EXPORT_TYPE_ALIAS("set", type_set_), MODULE_EXPORT_TYPE_ALIAS("str", type_string_), MODULE_EXPORT_TYPE_ALIAS("tuple", type_tuple_), // Functions MODULE_EXPORT_FUNCTION(bind_), MODULE_EXPORT_FUNCTION(callable_), MODULE_EXPORT_FUNCTION(exit_), MODULE_EXPORT_FUNCTION(input_), MODULE_EXPORT_FUNCTION(isinstance_), MODULE_EXPORT_FUNCTION(isimpl_), MODULE_EXPORT_FUNCTION(iter_), MODULE_EXPORT_FUNCTION(hasnext_), MODULE_EXPORT_FUNCTION(len_), MODULE_EXPORT_FUNCTION(next_), MODULE_EXPORT_FUNCTION(panic_), MODULE_EXPORT_FUNCTION(print_), MODULE_EXPORT_FUNCTION(println_), MODULE_EXPORT_FUNCTION(recover_), MODULE_EXPORT_FUNCTION(returns_), MODULE_EXPORT_FUNCTION(riter_), MODULE_EXPORT_FUNCTION(type_), MODULE_EXPORT_SENTINEL }; const ModuleInit module_builtins = { "builtins", "Built-in functions and other things", builtins_bulk, nullptr, nullptr }; const ModuleInit *argon::module::module_builtins_ = &module_builtins;
33.671395
110
0.567928
[ "object" ]
da1a7b743775ab447e7991c44475925dc66c1107
1,076
cc
C++
matI.cc
v0idx/matrixes
9c016c32ae39e90a4bbbf7fe4f2798712a190a1e
[ "BSD-2-Clause" ]
null
null
null
matI.cc
v0idx/matrixes
9c016c32ae39e90a4bbbf7fe4f2798712a190a1e
[ "BSD-2-Clause" ]
null
null
null
matI.cc
v0idx/matrixes
9c016c32ae39e90a4bbbf7fe4f2798712a190a1e
[ "BSD-2-Clause" ]
null
null
null
#include "mat.hh" using std::pair; using std::vector; namespace matrix { void swap(vector<vector<int>> &m, pair<int, int> i, pair<int, int> j) { int temp = m.at(i.first).at(i.second); m.at(i.first).at(i.second) = m.at(j.first).at(j.second); m.at(j.first).at(j.second) = temp; } mat transpose(mat m) { if (m.order % 2 == 0) { for (int i = 0; i < m.x - 1; i++) { for (int j = i + 1; j < m.x; j++) { swap(m.content, std::make_pair(i, j), std::make_pair(j, i)); } } } else { mat mT; mT.content = vector<vector<int>>(); for (int i = 0; i < m.x; i++) { mT.content.push_back(vector<int>()); for (int j = 0; j < m.y; j++) { } } } return m; } mat mult(mat a, mat b) { } } // namespace matrix
23.391304
81
0.3671
[ "vector" ]
da1a927ee8315e574c5f1a4d137850589eff62cc
16,646
hpp
C++
src/LinkedBuffer.hpp
frantic0/BitalinoRapidMix
b59862ceaf33994abd22fedfb6d88b85103c7764
[ "BSD-2-Clause" ]
2
2018-08-08T01:10:34.000Z
2021-03-04T14:49:40.000Z
src/LinkedBuffer.hpp
frantic0/BitalinoRapidMix
b59862ceaf33994abd22fedfb6d88b85103c7764
[ "BSD-2-Clause" ]
null
null
null
src/LinkedBuffer.hpp
frantic0/BitalinoRapidMix
b59862ceaf33994abd22fedfb6d88b85103c7764
[ "BSD-2-Clause" ]
null
null
null
// // LinkedBuffer.hpp // Lock-free (except when linking atm) buffer which propagates its changes to linked buffers // All linked buffers can be in different threads (read: should be) // Requires an update function to be called in the thread which it resides in // Concurrent sets must be ordered to have synchronized operations, accumulation can be nonsync // // Created by James on 04/01/2018. // Copyright © 2017 James Frink. All rights reserved. // /* TODOS: - Cache line optimization!!! - Write own underlying allocator so ( AUTO ) resizing can be lock-free - !!!!! Add iterators ( But not the c++17 deprecated one ) - ACCUMULATOR!! ( This and certain operations can be concurrent without passing a + b, just + and b) - Make linking lock-free - Check for feedback loops when linking and throw error / return false if thats the case - !! Add more instructions, such as: - Curves? - !Summing - !Checksum sharing - Function? - Make something useful of double operator setter? < Test new implementation - Resizing! - Allow different sized buffers with relative - interpolated - sets? allow all integer and float types in subscript operator */ // This is mostly just an experiment #ifndef LinkedBuffer_hpp #define LinkedBuffer_hpp #include <stdint.h> #include <stdio.h> #include <math.h> #include "Spinlock.hpp" #include "RingBufferAny.hpp" template < class T > class LinkedBuffer { public: template < class subT > struct Subscript { subT index; LinkedBuffer< T >* parent; T operator= ( const T& val ) { parent->set( index, val ); return val; } operator T ( void ) const { return parent->get( index ); } }; const T& get ( size_t index ) const; const T& get ( double index ) const; Subscript< size_t > operator[ ] ( const int index ); // Set single value Subscript< double > operator[ ] ( const double index ); // Set interpolated void set ( size_t index, T value ); void set ( double index, T value ); // For interpolated setting //void accumulate ( size_t index, T value ); void assign ( size_t startIndex, T* values, size_t numItems ); void setRangeToConstant ( size_t startIndex, size_t stopIndex, T value ); void setLine ( double startIndex, T startValue, double stopIndex, T stopValue ); void setup ( size_t bufferSize ); // Sets up buffer size and queue sizes void resize ( size_t bufferSize ); // TODO: propegate resize message? void resizeBounded ( size_t bufferSize ); // Resize without trying to alloc size_t size ( void ) const; // TODO: Check for possible feedback loops bool linkTo ( LinkedBuffer* const other ); // Returns true on link (false on == this or if null) bool unLinkFrom ( LinkedBuffer* const other ); // Returns true on unlink, false if doesn't exist bool update ( void ); uint32_t maxDataToParsePerUpdate = 4096; // Set this to a value that doesn't block your thread for forever size_t trueSize; private: template < class TT > void propagate ( const LinkedBuffer* from, TT* const data, size_t numItems ); RingBufferAny comQueue; // Lock-free linked buffer communications queue std::vector< LinkedBuffer< T >* > links; Spinlock editLinks; std::vector< T > localMemory; size_t memorySize; enum MessageTypes { BOUNDED_MEMORY_RESIZE, SINGLE_INDEX, SET_RANGE_TO_CONSTANT, SET_LINE, INDEX_SPECIFIER_ACCUM, // TODO DATA, NONE }; // Command struct headers struct ControlMessage { const LinkedBuffer* lastSource; // For propagation ( don't send back to source ) MessageTypes type = NONE; union message { struct BoundedResizeHeader { size_t size; } boundedResizeHeader; struct SingleIndexHeader { size_t index; } singleIndexHeader; struct SetRangeToConstantHeader { size_t startIndex; size_t stopIndex; T value; } setRangeToConstantHeader; struct SetLineHeader { double startIndex; T startValue; double distance; T deltaIncrement; } setLineHeader; } containedMessage; }; // Add instructions such as resize buffer etc // TODO: Union or something like it to create better header instruction storage ControlMessage lastIndexSpecifier; static const size_t tSize = sizeof ( T ); }; template < class T > const T& LinkedBuffer< T >::get ( const size_t index ) const { return localMemory[ index ]; } template < class T > const T& LinkedBuffer< T >::get ( const double index ) const { size_t truncPos = index; // Truncate double fractAmt = index - truncPos; return localMemory[ truncPos ] * ( 1.0 - fractAmt ) + localMemory[ ++truncPos ] * fractAmt; } template < class T > typename LinkedBuffer< T >::template Subscript< size_t > LinkedBuffer< T >::operator[ ] ( const int index ) { // Single value setting through subscript operator return Subscript< size_t > { static_cast< size_t >( index ), this }; } template < class T > typename LinkedBuffer< T >::template Subscript< double > LinkedBuffer< T >::operator[ ] ( const double index ) { // Interpolated setting through subscript operator return Subscript< double > { index , this }; } template < class T > void LinkedBuffer< T >::set ( size_t index, T value ) { // Single value ControlMessage hm; hm.lastSource = this; hm.type = SINGLE_INDEX; hm.containedMessage.singleIndexHeader.index = index; if ( !comQueue.push( &hm, 1 ) ) throw std::runtime_error( "Item(s) does not fit in queue, add auto-resizing here once == non-blocking" ); // Propagate the value on next update if ( !comQueue.push( &value, 1 ) ) throw std::runtime_error( "Item(s) does not fit in queue, add auto-resizing here once == non-blocking" ); } template < class T > void LinkedBuffer< T >::set ( double index, T value ) { // Linear interpolated set T values[2]; // Linear interpolated values starting at index x size_t truncPos = index; // Truncate if ( truncPos >= 0 && truncPos < memorySize ) { // Only set value if within bounds ( unsigned ) double fractAmt = index - truncPos; size_t secondPos = truncPos + 1; bool fits = ( secondPos < memorySize ); if ( fits ) { double iFractAmt = ( 1.0 - fractAmt ); values[ 0 ] = ( localMemory[ truncPos ] * fractAmt ) + ( value * iFractAmt ); values[ 1 ] = ( localMemory[ secondPos ] * iFractAmt ) + ( value * fractAmt ); } else { values[0] = value; } ControlMessage hm; hm.lastSource = this; hm.type = SINGLE_INDEX; hm.containedMessage.singleIndexHeader.index = truncPos; // Propagate the header on next update if ( !comQueue.push( &hm, 1 ) ) throw std::runtime_error( "Item(s) does not fit in queue, add auto-resizing here once == non-blocking" ); // Propagate the value(s) on next update if ( !comQueue.push( values, ( fits ) ? 2 : 1 ) ) throw std::runtime_error( "Item(s) does not fit in queue, add auto-resizing here once == non-blocking" ); } } template < class T > void LinkedBuffer< T >::assign ( size_t startIndex, T* values, size_t numItems ) { ControlMessage hm; hm.lastSource = this; hm.type = SINGLE_INDEX; hm.containedMessage.singleIndexHeader.index = index; // Propagate the header on next update if ( !comQueue.push( &hm, 1 ) ) throw std::runtime_error( "Item(s) does not fit in queue, add auto-resizing here once == non-blocking" ); // Propagate the value(s) on next update if ( !comQueue.push( &values, numItems ) ) throw std::runtime_error( "Item(s) does not fit in queue, add auto-resizing here once == non-blocking" ); } template < class T > void LinkedBuffer< T >::setRangeToConstant( size_t startIndex, size_t stopIndex, T value ) { ControlMessage hm; hm.lastSource = this; hm.type = SET_RANGE_TO_CONSTANT; hm.containedMessage.setRangeToConstantHeader.startIndex = startIndex; hm.containedMessage.setRangeToConstantHeader.stopIndex = stopIndex; hm.containedMessage.setRangeToConstantHeader.value = value; // Propagate header if ( !comQueue.push( &hm, 1 ) ) throw std::runtime_error( "Item(s) does not fit in queue, add auto-resizing here once == non-blocking" ); } template < class T > void LinkedBuffer< T >::setLine ( double startIndex, T startValue, double stopIndex, T stopValue ) { double distance = stopIndex - startIndex; if ( distance < 0 ) { distance = std::abs( distance ); std::swap( startValue, stopValue ); std::swap( startIndex, stopIndex ); } if ( distance > 0 ) { // Disallow div by zero ControlMessage hm; hm.lastSource = this; hm.type = SET_LINE; hm.containedMessage.setLineHeader.startIndex = startIndex; hm.containedMessage.setLineHeader.startValue = startValue; hm.containedMessage.setLineHeader.distance = distance; hm.containedMessage.setLineHeader.deltaIncrement = ( stopValue - startValue ) / distance; // Propagate the header on next update if ( !comQueue.push( &hm, 1 ) ) throw std::runtime_error( "Item(s) does not fit in queue, add auto-resizing here once == non-blocking" ); } } template < class T > void LinkedBuffer< T >::setup ( size_t bufferSize ) { resize( bufferSize ); } template < class T > void LinkedBuffer< T >::resize ( size_t bufferSize ) { localMemory.resize( bufferSize ); memorySize = bufferSize; trueSize = memorySize; comQueue.resize( ( bufferSize * tSize ) * 4 ); // This is the memory overhead } template < class T > void LinkedBuffer< T >::resizeBounded ( size_t bufferSize ) { // Just sets memory size ( unless > trueSize ) ControlMessage hm; hm.lastSource = this; hm.type = BOUNDED_MEMORY_RESIZE; hm.containedMessage.boundedResizeHeader.size = bufferSize; // Propagate the header on next update if ( !comQueue.push( &hm, 1 ) ) throw std::runtime_error( "Item(s) does not fit in queue, add auto-resizing here once == non-blocking" ); } template < class T > size_t LinkedBuffer< T >::size ( void ) const { return memorySize; } template < class T > bool LinkedBuffer< T >::linkTo ( LinkedBuffer< T >* const other ) { if ( other == this || other == nullptr ) return false; // TODO: Check here for feedback loop // TODO: Should effort be made to make this lock-free? // Reasoning: live linking, not only in setup? editLinks.lock( ); links.push_back( other ); editLinks.unlock( ); return true; } template < class T > bool LinkedBuffer< T >::unLinkFrom ( LinkedBuffer< T >* const other ) { if ( other == this || other == nullptr ) return false; bool success = false; // TODO: Should effort be made to make this lock-free? // Reasoning: live linking, not only in setup? editLinks.lock( ); auto it = std::find( links.begin( ), links.end( ), other ); if ( it != links.end( ) ) { links.erase( it ); success = true; } editLinks.unlock( ); return success; } template < class T > bool LinkedBuffer< T >::update ( void ) { uint32_t parsedData = 0; bool anyNewData = false; RingBufferAny::VariableHeader headerInfo; while ( comQueue.anyAvailableForPop( headerInfo ) && ( ++parsedData < maxDataToParsePerUpdate ) ) { if ( headerInfo.type_index == typeid( ControlMessage ) ) { comQueue.pop( &lastIndexSpecifier, 1 ); switch ( lastIndexSpecifier.type ) { case SET_RANGE_TO_CONSTANT: { auto m = lastIndexSpecifier.containedMessage.setRangeToConstantHeader; if ( m.stopIndex <= memorySize ) std::fill( localMemory.begin( ) + m.startIndex, localMemory.begin( ) + m.stopIndex, m.value ); anyNewData = true; break; } case SET_LINE: { auto m = lastIndexSpecifier.containedMessage.setLineHeader; double currentIndex = m.startIndex; if ( m.startIndex >= 0 && m.startIndex < memorySize ) { T startValue = m.startValue; T deltaIncrement = m.deltaIncrement; for ( size_t i = 0; i < m.distance; ++i ) { size_t truncPos = currentIndex; // Truncate double fractAmt = currentIndex - truncPos; size_t secondPos = truncPos + 1; T value = startValue + deltaIncrement * i; if ( secondPos < memorySize ) { double iFractAmt = ( 1.0 - fractAmt ); localMemory[ truncPos ] = ( localMemory[ truncPos ] * fractAmt ) + ( value * iFractAmt ); localMemory[ secondPos ] = ( localMemory[ secondPos ] * iFractAmt ) + ( value * fractAmt ); } else { localMemory[ truncPos ] = value; } currentIndex += 1; } anyNewData = true; } break; } case BOUNDED_MEMORY_RESIZE: { size_t newSize = lastIndexSpecifier.containedMessage.boundedResizeHeader.size; if ( newSize <= trueSize ) { memorySize = newSize; } else { // TODO: Allocator resize( newSize ); } break; } default: break; } // Propagate header ControlMessage nextIndexSpecifier( lastIndexSpecifier ); nextIndexSpecifier.lastSource = this; propagate( lastIndexSpecifier.lastSource, &nextIndexSpecifier, 1 ); } else if ( headerInfo.type_index == typeid( T ) ) { if ( lastIndexSpecifier.type == SINGLE_INDEX ) { auto m = lastIndexSpecifier.containedMessage.singleIndexHeader; if ( m.index < memorySize ) { // Set the value(s) locally auto setIndex = ( localMemory.begin( ) + m.index ).operator->(); comQueue.pop( setIndex, headerInfo.valuesPassed ); propagate( lastIndexSpecifier.lastSource, setIndex, headerInfo.valuesPassed ); anyNewData = true; } } else { std::runtime_error( "Data was not expected" ); } lastIndexSpecifier = ControlMessage( ); // Reset } else { throw std::runtime_error( "Uncaught data" ); } } return anyNewData; } template < class T > template < class TT > void LinkedBuffer< T >::propagate ( const LinkedBuffer* from, TT* const data, size_t numItems ) { if ( from == nullptr ) throw std::runtime_error( " Propagation source is null " ); // Propagation is spread across update methods of multiple threads for ( LinkedBuffer* lb : links ) { if ( lb != from ) { if ( !lb->comQueue.push( data, numItems ) ) throw std::runtime_error( "Item(s) does not fit in queue, add auto-resizing here once == non-blocking" ); } } } #endif /* LinkedBuffer_hpp */
35.118143
124
0.578337
[ "vector" ]
da23cf54f1e752f2e37b43526543328878403c58
7,951
cpp
C++
rh-/rh-/RenderableSystem.cpp
ShiroixD/Rh-
33db74b21bb9a7255d72b14afd6746f142c1784b
[ "Apache-2.0" ]
null
null
null
rh-/rh-/RenderableSystem.cpp
ShiroixD/Rh-
33db74b21bb9a7255d72b14afd6746f142c1784b
[ "Apache-2.0" ]
null
null
null
rh-/rh-/RenderableSystem.cpp
ShiroixD/Rh-
33db74b21bb9a7255d72b14afd6746f142c1784b
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "RenderableSystem.h" #include "RenderableComponent.h" #include "PostProcess.h" #include <codecvt> #include <locale> RenderableSystem::RenderableSystem(ID3D11Device1* device, ID3D11DeviceContext1* context, shared_ptr<PhysicsSystem> physicsSystem) { _device = device; _context = context; _states = std::make_unique<DirectX::CommonStates>(_device); _ShadowsfxFactory = std::make_shared<ShadowFactory>(_device); _noShadowsfxFactory = std::make_shared<ToonFactory>(_device); _ReflectFactory = std::make_shared<ReflectionFactory>(_device); _CeilingfxFactory = std::make_shared<EffectFactory>(_device); DebugDrawAction = std::make_unique<DebugDraw>(_device, _context); _shadowMap = std::make_unique<ShadowMap>(device, 1024, 1024); _renderTargetView = nullptr; _depthStencilView = nullptr; _isSent = false; _player = nullptr; _physicsSystem = physicsSystem; _screenSizeChanged = true; _postProcess = std::make_unique<BasicPostProcess>(_device); } RenderableSystem::~RenderableSystem() { } void RenderableSystem::CreateScreenTextureResources() { CD3D11_TEXTURE2D_DESC sceneDesc( DXGI_FORMAT_R16G16B16A16_FLOAT, _screenWidth, _screenHeight, 1, 1, D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE); DX::ThrowIfFailed( _device->CreateTexture2D(&sceneDesc, nullptr, _sceneTex.GetAddressOf()) ); DX::ThrowIfFailed( _device->CreateShaderResourceView(_sceneTex.Get(), nullptr, _sceneSRV.ReleaseAndGetAddressOf()) ); DX::ThrowIfFailed( _device->CreateRenderTargetView(_sceneTex.Get(), nullptr, _sceneRT.ReleaseAndGetAddressOf() )); } void RenderableSystem::Iterate() { if (_screenSizeChanged) { CreateScreenTextureResources(); _screenSizeChanged = false; } PrepareToRenderShadows(); vector<int> objectsToRender = _physicsSystem->GetEntitiesIDWithinFrustum(); for (auto renderableComponent : _world->GetComponents<RenderableComponent>()) { if (renderableComponent->_isEnabled) { std::vector<int>::iterator it = std::find(objectsToRender.begin(), objectsToRender.end(), renderableComponent->GetParent()->GetId()); if (it != objectsToRender.end()) { if (renderableComponent->_model == nullptr) { if (renderableComponent->_modelSkinned->isVisible) { renderableComponent->_modelSkinned->drawToShadows = true; if (renderableComponent->_modelSkinned->playingAnimation) { renderableComponent->_modelSkinned->GetAnimatorPlayer()->StartClip(renderableComponent->_modelSkinned->currentAnimation); renderableComponent->_modelSkinned->GetAnimatorPlayer()->Update(Coroutine::GetElapsedTime()); // update animation } renderableComponent->_modelSkinned->DrawModel( _context, *_states, renderableComponent->GetParent()->GetWorldMatrix(), _shadowMap->_lightView, _shadowMap->_lightProj ); renderableComponent->_modelSkinned->drawToShadows = false; } } else if (renderableComponent->_model != nullptr) { if (renderableComponent->_canCastShadows) { renderableComponent->_model->Draw( _context, *_states, renderableComponent->GetParent()->GetWorldMatrix(), _shadowMap->_lightView, _shadowMap->_lightProj ); } } } } } ClearAfterRenderShadows(); for (auto renderableComponent : _world->GetComponents<RenderableComponent>()) { if (renderableComponent->_isEnabled) { std::vector<int>::iterator it = std::find(objectsToRender.begin(), objectsToRender.end(), renderableComponent->GetParent()->GetId()); if (it != objectsToRender.end()) { if (renderableComponent->_model != nullptr) { renderableComponent->_model->Draw( _context, *_states, renderableComponent->GetParent()->GetWorldMatrix(), renderableComponent->_camera->GetViewMatrix(), renderableComponent->_camera->GetProjectionMatrix() ); } } } } BloomBlur(); if (vampireMode) { _terrain->Draw(*_camera); } for (auto renderableComponent : _world->GetComponents<RenderableComponent>()) { if (renderableComponent->_isEnabled) { std::vector<int>::iterator it = std::find(objectsToRender.begin(), objectsToRender.end(), renderableComponent->GetParent()->GetId()); if (it != objectsToRender.end()) { if (renderableComponent->_model == nullptr) { if (renderableComponent->_modelSkinned->isVisible) { renderableComponent->_modelSkinned->DrawModel( _context, *_states, renderableComponent->GetParent()->GetWorldMatrix(), renderableComponent->_camera->GetViewMatrix(), renderableComponent->_camera->GetProjectionMatrix() ); } } } } } } void RenderableSystem::Initialize() { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; for (auto renderableComponent : _world->GetComponents<RenderableComponent>()) { if (renderableComponent->_modelPath.find(L".cmo") != std::wstring::npos) { if (renderableComponent->_canRenderShadows) { renderableComponent->_model = DirectX::Model::CreateFromCMO(_device, renderableComponent->_modelPath.c_str(), *_ShadowsfxFactory); } else if (renderableComponent->_canReflect) { renderableComponent->_model = DirectX::Model::CreateFromCMO(_device, renderableComponent->_modelPath.c_str(), *_ReflectFactory); } else if (renderableComponent->_ignoreShadows) { renderableComponent->_model = DirectX::Model::CreateFromCMO(_device, renderableComponent->_modelPath.c_str(), *_CeilingfxFactory); } else { renderableComponent->_model = DirectX::Model::CreateFromCMO(_device, renderableComponent->_modelPath.c_str(), *_noShadowsfxFactory); } } else { renderableComponent->_modelSkinned = std::make_unique<ModelSkinned>(_device, converter.to_bytes(renderableComponent->_modelPath.c_str()), _context); } } } void RenderableSystem::SentResources(ID3D11RenderTargetView* renderTargetView, ID3D11DepthStencilView* depthStencilView, std::shared_ptr<Entity> Player, int screenWidth, int screenHeight, bool vampireMode) { //if (!_isSent) //{ _renderTargetView = renderTargetView; _depthStencilView = depthStencilView; _player = Player; _isSent = true; //} if (_screenWidth != screenWidth || _screenHeight != screenHeight) { _screenSizeChanged = true; _screenWidth = screenWidth; _screenHeight = screenHeight; } this->vampireMode = vampireMode; } void RenderableSystem::PrepareToRenderShadows() { _shadowMap->BuildShadowTransform(_player->GetTransform()->GetPosition()); _shadowMap->BindDsvAndSetNullRenderTarget(_context); //_ShadowsfxFactory->SetRenderingShadowMap(true); _context->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); } void RenderableSystem::ClearAfterRenderShadows() { _shadowMap->UnbindTargetAndViewport(_context); _context->RSSetState(0); XMVECTORF32 myColor = { { { 0.0f, 0.0f, 0.0f, 1.000000000f } } }; _context->ClearRenderTargetView(_renderTargetView, myColor); _context->ClearDepthStencilView(_depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); _ShadowsfxFactory->SetShadowMapEnabled(true); _ShadowsfxFactory->SetShadowMap(_shadowMap->GetDepthMapSRV()); //_ShadowsfxFactory->SetRenderingShadowMap(false); _ShadowsfxFactory->SetShadowMapTransform(_shadowMap->_lightShadowTransform); _context->ClearRenderTargetView(_sceneRT.Get(), myColor); _context->ClearDepthStencilView(_depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); _context->OMSetRenderTargets(1, _sceneRT.GetAddressOf(), _depthStencilView); } void RenderableSystem::BloomBlur() { _context->OMSetRenderTargets(1, &_renderTargetView, _depthStencilView); _postProcess->SetEffect(BasicPostProcess::BloomBlur); _postProcess->SetBloomBlurParameters(BloomBlurParams.horizontal, BloomBlurParams.size, BloomBlurParams.brightness); _postProcess->SetSourceTexture(_sceneSRV.Get()); _postProcess->Process(_context); }
30.003774
205
0.745315
[ "vector", "model" ]
da28f3f5951692dd7eb8ad34441d2c7a62017438
1,417
cpp
C++
src/native/devicecontrol.cpp
nonomal/node-tap
f8e5fa21b6f53bebbf948e52982d631be638a2c4
[ "Apache-2.0" ]
780
2018-02-25T13:32:44.000Z
2022-03-20T17:48:22.000Z
src/native/devicecontrol.cpp
nonomal/node-tap
f8e5fa21b6f53bebbf948e52982d631be638a2c4
[ "Apache-2.0" ]
59
2018-02-26T21:00:01.000Z
2020-06-16T02:59:21.000Z
src/native/devicecontrol.cpp
nonomal/node-tap
f8e5fa21b6f53bebbf948e52982d631be638a2c4
[ "Apache-2.0" ]
161
2018-04-01T04:21:18.000Z
2021-10-17T07:56:32.000Z
#include <nan.h> #include "./error.hpp" using namespace std; NAN_METHOD(N_DeviceControl) { if (info.Length() != 4) { Nan::ThrowError("Wrong number of arguments."); return; } if (!info[0]->IsNumber()) { Nan::ThrowError("Wrong type of handle."); return; } long handle = (long)info[0]->NumberValue(); if (!info[1]->IsNumber()) { Nan::ThrowError("Wrong type of CTLCode."); return; } DWORD CTLCode = (DWORD)info[1]->NumberValue(); v8::Local<v8::Object> inputJsBuffer = v8::Local<v8::Object>::Cast(info[2]); void *inputData = (void *)node::Buffer::Data(inputJsBuffer); DWORD inputDataLength = node::Buffer::Length(inputJsBuffer); if (!info[3]->IsNumber()) { Nan::ThrowError("Wrong type of output length."); return; } DWORD outputDataLength = (DWORD)info[3]->NumberValue(); void *outputData = malloc(outputDataLength); DWORD outputDataReturned; DeviceIoControl((HANDLE)handle, CTLCode, inputData, inputDataLength, outputData, outputDataLength, &outputDataReturned, NULL); DWORD errorCode = GetLastError(); if (errorCode != ERROR_SUCCESS) { Nan::ThrowError("DeviceIoControl Failed: " + errorCode); return; } info.GetReturnValue().Set(Nan::CopyBuffer((char *)outputData, outputDataReturned).ToLocalChecked()); free(outputData); }
27.25
130
0.628088
[ "object" ]
da2cecc1cde0fd58a7e3a21fd4df27e62ce4c066
4,716
hpp
C++
src/core/TChem_IgnitionZeroD_SacadoJacobianInternal.hpp
sandialabs/TChem
c9d00d7d283c8687a5aa4549161e29a08d3d39d6
[ "BSD-2-Clause" ]
30
2020-10-28T08:07:36.000Z
2022-03-29T15:22:30.000Z
src/core/TChem_IgnitionZeroD_SacadoJacobianInternal.hpp
sandialabs/TChem
c9d00d7d283c8687a5aa4549161e29a08d3d39d6
[ "BSD-2-Clause" ]
2
2021-02-22T21:47:47.000Z
2022-03-16T16:38:07.000Z
src/core/TChem_IgnitionZeroD_SacadoJacobianInternal.hpp
sandialabs/TChem
c9d00d7d283c8687a5aa4549161e29a08d3d39d6
[ "BSD-2-Clause" ]
10
2020-10-28T01:11:41.000Z
2021-06-16T08:15:28.000Z
#include "TChem_IgnitionZeroD_SacadoJacobian.hpp" namespace TChem { template<typename PolicyType, typename ValueType, typename DeviceType> void IgnitionZeroD_SacadoJacobian_TemplateRun( /// input const std::string& profile_name, const ValueType& dummyValueType, /// team size setting const PolicyType& policy, const Tines::value_type_2d_view<real_type,DeviceType>& state, const Tines::value_type_3d_view<real_type,DeviceType>& jacobian, const Tines::value_type_2d_view<real_type,DeviceType>& workspace, const KineticModelConstData<DeviceType>& kmcd) { Kokkos::Profiling::pushRegion(profile_name); using policy_type = PolicyType; using device_type = DeviceType; using value_type = ValueType; using range_type = Kokkos::pair<ordinal_type, ordinal_type>; using real_type_1d_view_type = Tines::value_type_1d_view<real_type, device_type>; using real_type_2d_view_type = Tines::value_type_2d_view<real_type, device_type>; using value_type_1d_view_type = Tines::value_type_1d_view<value_type, device_type>; const ordinal_type level = 1; const ordinal_type per_team_extent = IgnitionZeroD_SacadoJacobian::getWorkSpaceSize(kmcd); const ordinal_type n = state.extent(0); if (workspace.span()) { TCHEM_CHECK_ERROR(workspace.extent(0) < policy.league_size(), "Workspace is allocated smaller than the league size"); TCHEM_CHECK_ERROR(workspace.extent(1) < per_team_extent, "Workspace is allocated smaller than the required"); } Kokkos::parallel_for (profile_name, policy, KOKKOS_LAMBDA(const typename policy_type::member_type& member) { /// either of these two is used real_type_1d_view_type work; Scratch<real_type_1d_view_type> swork; if (workspace.span()) { work = Kokkos::subview(workspace, member.league_rank(), Kokkos::ALL()); } else { /// assume that the workspace is given from scratch space swork = Scratch<real_type_1d_view_type>(member.team_scratch(level), per_team_extent); work = real_type_1d_view_type(swork.data(), swork.span()); } auto wptr = work.data(); const ordinal_type m = kmcd.nSpec + 1;; const ordinal_type len = ats<value_type>::sacadoStorageCapacity(); value_type_1d_view_type x_fad(wptr, m, m+1); wptr += m*len; value_type_1d_view_type f_fad(wptr, m, m+1); wptr += m*len; const ordinal_type ws = Impl::SourceTerm<value_type,device_type>::getWorkSpaceSize(kmcd); real_type_1d_view_type w(wptr, ws); wptr += w.span(); ordinal_type ibeg(0), iend(0), iinc(0); Impl::getLeagueRange(member, n, ibeg, iend, iinc); for (ordinal_type i=ibeg;i<iend;i+=iinc) { const real_type_1d_view_type s = Kokkos::subview(state, i, Kokkos::ALL()); const Impl::StateVector<real_type_1d_view_type> sv(kmcd.nSpec, s); TCHEM_CHECK_ERROR(!sv.isValid(), "Error: input state vector is not valid"); const real_type t = sv.Temperature(); const real_type p = sv.Pressure(); const real_type_1d_view_type Ys = sv.MassFractions(); Kokkos::parallel_for (Kokkos::TeamVectorRange(member, m), [=](const ordinal_type k) { if (k == 0) { x_fad(0) = value_type(m, k, t); } else { x_fad(k) = value_type(m, k, Ys(k-1)); } }); member.team_barrier(); value_type t_fad = x_fad(0); value_type_1d_view_type Ys_fad = Kokkos::subview(x_fad, range_type(1, m)); Impl::SourceTerm<value_type, device_type>::team_invoke_sacado(member, t_fad, p, Ys_fad, f_fad, w, kmcd); member.team_barrier(); // { // Kokkos::single(Kokkos::PerTeam(member), [=]() { // if (i ==0) { // printf("SourceTerm\n"); // for (int k=0;k<4;++k) // printf("%e\n", f_fad(k).val()); // } // }); // } Kokkos::parallel_for (Kokkos::TeamVectorRange(member, m*m), [=](const ordinal_type k) { const ordinal_type k0 = k/m, k1 = k%m; jacobian(i,k0,k1) = f_fad(k0).fastAccessDx(k1); }); member.team_barrier(); } }); #if defined(KOKKOS_ENABLE_CUDA) { auto err = cudaGetLastError(); if (err) printf("error %s \n", cudaGetErrorString(err)); } #endif Kokkos::Profiling::popRegion(); } } // namespace TChem
40.655172
123
0.612595
[ "vector" ]
da3249113f1361a3f78a793ca8c9388c3cec6a86
34,345
cpp
C++
Src/Layouts/MXNewStringSearchLayout.cpp
L-Spiro/MhsX
9cc71fbbac93ba54a01839db129cd9b47a68f29e
[ "BSD-2-Clause" ]
19
2016-09-07T18:22:09.000Z
2022-03-25T23:05:39.000Z
Src/Layouts/MXNewStringSearchLayout.cpp
L-Spiro/MhsX
9cc71fbbac93ba54a01839db129cd9b47a68f29e
[ "BSD-2-Clause" ]
1
2021-09-30T14:24:54.000Z
2021-11-13T14:58:02.000Z
Src/Layouts/MXNewStringSearchLayout.cpp
L-Spiro/MhsX
9cc71fbbac93ba54a01839db129cd9b47a68f29e
[ "BSD-2-Clause" ]
5
2018-04-10T16:52:25.000Z
2021-05-11T02:40:17.000Z
#include "MXNewStringSearchLayout.h" #include "../Layouts/MXLayoutMacros.h" #include "../Strings/MXStringDecoder.h" #include "../System/MXSystem.h" #include "MXLayoutManager.h" #include <Base/LSWBase.h> namespace mx { #define MX_SEARCH_W 280 //#define MX_SEARCH_H (200) #define MX_SEARCH_GROUP_TOP MX_TOP_JUST #define MX_LEFT_ALIGN MX_LEFT_JUST #define MX_CENTER (MX_SEARCH_W / 2) #define MX_1_3RD_W ((MX_SEARCH_W - (MX_LEFT_ALIGN + MX_GROUP_LEFT) - (MX_LEFT_ALIGN + MX_GROUP_RIGHT)) / 3) #define MX_1_3RD_LEFT (MX_LEFT_ALIGN + MX_GROUP_LEFT) #define MX_2_3RD_LEFT (MX_1_3RD_LEFT + MX_1_3RD_W) #define MX_3_3RD_LEFT (MX_1_3RD_LEFT + MX_1_3RD_W * 2) #define MX_WIDTH_TO_CENTER( L ) ((MX_SEARCH_W / 2) - (L)) #define MX_SEARCH_GROUP_HEIGHT ((MX_DEF_COMBO_HEIGHT + 2) * 2 + ((MX_DEF_EDIT_HEIGHT + 2) * 3) + MX_GROUP_TOP + MX_GROUP_BOTTOM + 2) #define MX_COMBOBOXES_LEFT (MX_LEFT_ALIGN + MX_GROUP_LEFT + 50) #define MX_OPTIONS_TOP (MX_SEARCH_GROUP_HEIGHT + MX_SEARCH_GROUP_TOP) #define MX_OPTIONS_H (MX_GROUP_TOP + MX_GROUP_BOTTOM + MX_DEF_CHECK_HEIGHT * 4 + MX_DEF_BUTTON_HEIGHT) #define MX_SEARCH_RANGE_TOP (MX_OPTIONS_TOP + MX_OPTIONS_H) #define MX_SEARCH_RANGE_H (MX_GROUP_TOP + MX_GROUP_BOTTOM + MX_DEF_STATIC_HEIGHT + MX_DEF_COMBO_HEIGHT) #define MX_SEARCH_H (MX_SEARCH_RANGE_TOP + MX_SEARCH_RANGE_H + (MX_TOP_JUST * 4 + MX_DEF_BUTTON_HEIGHT)) // == Members. // The layout for the New Data-Type Search dialog. LSW_WIDGET_LAYOUT CNewStringSearchLayout::m_wlNewStringSearchDialog[] = { { MX_NEW_STRING_SEARCH, // ltType MX_SSI_DIALOG, // wId nullptr, // lpwcClass TRUE, // bEnabled FALSE, // bActive 0, // iLeft 0, // iTop MX_SEARCH_W, // dwWidth MX_SEARCH_H, // dwHeight WS_CAPTION | WS_POPUP | WS_VISIBLE | WS_CLIPSIBLINGS | WS_SYSMENU | DS_3DLOOK | DS_FIXEDSYS | DS_MODALFRAME | DS_CENTER, // dwStyle WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT, // dwStyleEx MX_MAKE_WCHAR( _T_9468D604_String_Search ), // pwcText _LEN_9468D604, // sTextLen MX_SSI_NONE, // dwParentId }, { LSW_LT_BUTTON, // ltType MX_SSI_OK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled TRUE, // bActive MX_LEFT_ALIGN, // iLeft MX_SEARCH_H - MX_TOP_JUST - MX_DEF_BUTTON_HEIGHT, // iTop MX_DEF_BUTTON_WIDTH, // dwWidth MX_DEF_BUTTON_HEIGHT, // dwHeight MX_DEFBUTTONSTYLE, // dwStyle WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR | WS_EX_NOPARENTNOTIFY, // dwStyleEx MX_MAKE_WCHAR( _T_D736D92D_OK ), // pwcText _LEN_D736D92D, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_BUTTON, // ltType MX_SSI_CANCEL, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_SEARCH_W - MX_DEF_BUTTON_WIDTH - MX_LEFT_ALIGN, // iLeft MX_SEARCH_H - MX_TOP_JUST - MX_DEF_BUTTON_HEIGHT, // iTop MX_DEF_BUTTON_WIDTH, // dwWidth MX_DEF_BUTTON_HEIGHT, // dwHeight MX_BUTTONSTYLE, // dwStyle WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR | WS_EX_NOPARENTNOTIFY, // dwStyleEx MX_MAKE_WCHAR( _T_51BAC044_Cancel ), // pwcText _LEN_51BAC044, // sTextLen MX_SSI_DIALOG, // dwParentId }, // ==== Search ==== // { LSW_LT_GROUPBOX, // ltType MX_SSI_SEARCH_GROUP, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_LEFT_ALIGN, // iLeft MX_SEARCH_GROUP_TOP, // iTop MX_SEARCH_W - (MX_LEFT_ALIGN * 2), // dwWidth MX_SEARCH_GROUP_HEIGHT, // dwHeight MX_GROUPSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_B35CDE91_Search ), // pwcText _LEN_B35CDE91, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_LABEL, // ltType MX_SSI_TYPE_LABEL, // wId WC_STATICW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_LEFT_ALIGN + MX_GROUP_LEFT, // iLeft (MX_SEARCH_GROUP_TOP + MX_GROUP_TOP + 2), // iTop 50, // dwWidth MX_DEF_STATIC_HEIGHT, // dwHeight MX_STATICSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_97F15F00_Type_ ), // pwcText _LEN_97F15F00, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_COMBOBOX, // ltType MX_SSI_STRING_TYPE_COMBO, // wId WC_COMBOBOXW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_COMBOBOXES_LEFT, // iLeft MX_SEARCH_GROUP_TOP + MX_GROUP_TOP, // iTop MX_SEARCH_W - MX_LEFT_JUST - MX_GROUP_RIGHT - MX_COMBOBOXES_LEFT, // dwWidth MX_DEF_COMBO_HEIGHT, // dwHeight MX_COMBOSTYLE_LIST, // dwStyle MX_COMBOSTYLEEX_LIST, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_LABEL, // ltType MX_SSI_CHAR_TYPE_LABEL, // wId WC_STATICW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_CENTER, // iLeft (MX_SEARCH_GROUP_TOP + MX_GROUP_TOP + 2), // iTop 50, // dwWidth MX_DEF_STATIC_HEIGHT, // dwHeight MX_STATICSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_1B8339E8_Character_Type_ ), // pwcText _LEN_1B8339E8, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_LABEL, // ltType MX_SSI_REGEX_ENCODING_LABEL, // wId WC_STATICW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_CENTER, // iLeft (MX_SEARCH_GROUP_TOP + MX_GROUP_TOP + 2), // iTop 33, // dwWidth MX_DEF_STATIC_HEIGHT, // dwHeight MX_STATICSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_70F4A064_Encoding_ ), // pwcText _LEN_70F4A064, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_COMBOBOX, // ltType MX_SSI_CHAR_TYPE_COMBO, // wId WC_COMBOBOXW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_CENTER + 50, // iLeft MX_SEARCH_GROUP_TOP + MX_GROUP_TOP, // iTop MX_SEARCH_W - MX_LEFT_JUST - MX_GROUP_RIGHT - (MX_CENTER + 50), // dwWidth MX_DEF_COMBO_HEIGHT, // dwHeight MX_COMBOSTYLE_LIST, // dwStyle MX_COMBOSTYLEEX_LIST, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_COMBOBOX, // ltType MX_SSI_REGEX_ENCODING_COMBO, // wId WC_COMBOBOXW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_CENTER + 33, // iLeft MX_SEARCH_GROUP_TOP + MX_GROUP_TOP, // iTop MX_SEARCH_W - MX_LEFT_JUST - MX_GROUP_RIGHT - (MX_CENTER + 33), // dwWidth MX_DEF_COMBO_HEIGHT, // dwHeight MX_COMBOSTYLE_LIST, // dwStyle MX_COMBOSTYLEEX_LIST, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_LABEL, // ltType MX_SSI_STRING_TO_FIND_LABEL, // wId WC_STATICW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_LEFT_ALIGN + MX_GROUP_LEFT, // iLeft (MX_SEARCH_GROUP_TOP + MX_GROUP_TOP + 2) + MX_DEF_COMBO_HEIGHT + 2, // iTop 50, // dwWidth MX_DEF_STATIC_HEIGHT, // dwHeight MX_STATICSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_21CE2C3B_String_to_Find_ ), // pwcText _LEN_21CE2C3B, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_COMBOBOX, // ltType MX_SSI_STRING_TO_FIND_COMBO, // wId WC_COMBOBOXW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_COMBOBOXES_LEFT, // iLeft (MX_SEARCH_GROUP_TOP + MX_GROUP_TOP) + MX_DEF_COMBO_HEIGHT + 2, // iTop MX_SEARCH_W - MX_LEFT_JUST - MX_GROUP_RIGHT - MX_COMBOBOXES_LEFT, // dwWidth MX_DEF_COMBO_HEIGHT, // dwHeight MX_COMBOSTYLE, // dwStyle 0, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_LABEL, // ltType MX_SSI_PREVIEW_LABEL, // wId WC_STATICW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_LEFT_ALIGN + MX_GROUP_LEFT, // iLeft ((MX_SEARCH_GROUP_TOP + MX_GROUP_TOP + 2) + MX_DEF_COMBO_HEIGHT + 2) + MX_DEF_COMBO_HEIGHT + 2, // iTop 50, // dwWidth MX_DEF_STATIC_HEIGHT, // dwHeight MX_STATICSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_CB18E1EA_Preview_ ), // pwcText _LEN_CB18E1EA, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_LABEL, // ltType MX_SSI_REGEX_FLAVOR_LABEL, // wId WC_STATICW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_LEFT_ALIGN + MX_GROUP_LEFT, // iLeft ((MX_SEARCH_GROUP_TOP + MX_GROUP_TOP + 2) + MX_DEF_COMBO_HEIGHT + 2) + MX_DEF_COMBO_HEIGHT + 2, // iTop 50, // dwWidth MX_DEF_STATIC_HEIGHT, // dwHeight MX_STATICSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_B709BF7A_Flavor_ ), // pwcText _LEN_B709BF7A, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_EDIT, // ltType MX_SSI_PREVIEW_EDIT, // wId nullptr, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_COMBOBOXES_LEFT, // iLeft ((MX_SEARCH_GROUP_TOP + MX_GROUP_TOP) + MX_DEF_COMBO_HEIGHT + 2) + MX_DEF_COMBO_HEIGHT + 2, // iTop MX_SEARCH_W - MX_LEFT_JUST - MX_GROUP_RIGHT - MX_COMBOBOXES_LEFT, // dwWidth MX_DEF_EDIT_HEIGHT, // dwHeight MX_EDITSTYLE | ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY, // dwStyle WS_EX_CLIENTEDGE, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_COMBOBOX, // ltType MX_SSI_REGEX_FLAVOR_COMBO, // wId nullptr, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_COMBOBOXES_LEFT, // iLeft ((MX_SEARCH_GROUP_TOP + MX_GROUP_TOP) + MX_DEF_COMBO_HEIGHT + 2) + MX_DEF_COMBO_HEIGHT + 2, // iTop MX_SEARCH_W - MX_LEFT_JUST - MX_GROUP_RIGHT - MX_COMBOBOXES_LEFT, // dwWidth MX_DEF_COMBO_HEIGHT, // dwHeight MX_COMBOSTYLE_LIST, // dwStyle MX_COMBOSTYLEEX_LIST, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_EDIT, // ltType MX_SSI_PREVIEW_HEX_EDIT, // wId nullptr, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_COMBOBOXES_LEFT, // iLeft (((MX_SEARCH_GROUP_TOP + MX_GROUP_TOP) + MX_DEF_COMBO_HEIGHT + 2) + MX_DEF_COMBO_HEIGHT + 2) + (MX_DEF_EDIT_HEIGHT) + 2, // iTop MX_SEARCH_W - MX_LEFT_JUST - MX_GROUP_RIGHT - MX_COMBOBOXES_LEFT, // dwWidth MX_DEF_EDIT_HEIGHT, // dwHeight MX_EDITSTYLE | ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY, // dwStyle WS_EX_CLIENTEDGE, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_LABEL, // ltType MX_SSI_BYTE_HELPER_LABEL, // wId WC_STATICW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_LEFT_ALIGN + MX_GROUP_LEFT, // iLeft (MX_SEARCH_GROUP_TOP + MX_GROUP_TOP) + (MX_DEF_COMBO_HEIGHT + 2) * 4, // iTop MX_SEARCH_W - MX_LEFT_JUST - MX_GROUP_RIGHT - (MX_LEFT_ALIGN + MX_GROUP_LEFT), // dwWidth MX_DEF_STATIC_HEIGHT * 2, // dwHeight MX_STATICSTYLE, // dwStyle 0, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, // { LSW_LT_LABEL, // ltType MX_SSI_UTF_HELPER_LABEL, // wId WC_STATICW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_LEFT_ALIGN + MX_GROUP_LEFT, // iLeft (MX_SEARCH_GROUP_TOP + MX_GROUP_TOP) + (MX_DEF_COMBO_HEIGHT + 2) * 4 + 2, // iTop 50, // dwWidth MX_DEF_STATIC_HEIGHT, // dwHeight MX_STATICSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_BA612FFE_Unicode_Chars_ ), // pwcText _LEN_BA612FFE, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_COMBOBOX, // ltType MX_SSI_UTF_HELPER_COMBO, // wId WC_COMBOBOXW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_COMBOBOXES_LEFT, // iLeft (MX_SEARCH_GROUP_TOP + MX_GROUP_TOP) + (MX_DEF_COMBO_HEIGHT + 2) * 4, // iTop MX_SEARCH_W - MX_LEFT_JUST - MX_GROUP_RIGHT - MX_COMBOBOXES_LEFT, // dwWidth MX_DEF_COMBO_HEIGHT, // dwHeight MX_COMBOSTYLE_LIST, // dwStyle MX_COMBOSTYLEEX_LIST, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, // // { LSW_LT_LABEL, // ltType MX_SSI_REGEX_HELPER_LABEL, // wId WC_STATICW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_LEFT_ALIGN + MX_GROUP_LEFT, // iLeft (MX_SEARCH_GROUP_TOP + MX_GROUP_TOP) + (MX_DEF_COMBO_HEIGHT + 2) * 4 + 2, // iTop 150, // dwWidth MX_DEF_STATIC_HEIGHT, // dwHeight MX_STATICSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_F3327DB2_Regex_Sheet_ ), // pwcText _LEN_F3327DB2, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_COMBOBOX, // ltType MX_SSI_REGEX_HELPER_COMBO, // wId WC_COMBOBOXW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_COMBOBOXES_LEFT, // iLeft (MX_SEARCH_GROUP_TOP + MX_GROUP_TOP) + (MX_DEF_COMBO_HEIGHT + 2) * 4, // iTop MX_SEARCH_W - MX_LEFT_JUST - MX_GROUP_RIGHT - MX_COMBOBOXES_LEFT, // dwWidth MX_DEF_COMBO_HEIGHT, // dwHeight MX_COMBOSTYLE_LIST, // dwStyle MX_COMBOSTYLEEX_LIST, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, // // ==== Options ==== // { LSW_LT_GROUPBOX, // ltType MX_SSI_OPTIONS_GROUP, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_LEFT_ALIGN, // iLeft MX_OPTIONS_TOP, // iTop MX_SEARCH_W - (MX_LEFT_ALIGN * 2), // dwWidth MX_OPTIONS_H, // dwHeight MX_GROUPSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_1F88C31B_Options ), // pwcText _LEN_1F88C31B, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_CHECK, // ltType MX_SSI_IGNORE_CASE_CHECK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_1_3RD_LEFT, // iLeft MX_OPTIONS_TOP + MX_GROUP_TOP, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_73A2F867_Ignore_Case ), // pwcText _LEN_73A2F867, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_73A2F867_Ignore_Case, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_ALIGNED_CHECK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_2_3RD_LEFT, // iLeft MX_OPTIONS_TOP + MX_GROUP_TOP, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_22E9689D_Aligned ), // pwcText _LEN_22E9689D, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_EA556272_Characters_in_the_string_are_type_aligned_, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_ESCAPES_CHECK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_3_3RD_LEFT, // iLeft MX_OPTIONS_TOP + MX_GROUP_TOP, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_78F75E9B_Resolve_Escapes_____ ), // pwcText _LEN_78F75E9B, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_A9CD0C35_Resolves_escape_sequences____a__b__f__n__r__t__v____________nnn__xnn__unnnn__Unnnnnnnn____, WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_WHOLE_WORD_CHECK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_1_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_40CE1008_Whole_Word_Only ), // pwcText _LEN_40CE1008, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_8A60E2C0_Requires_matches_to_be_surrounded_by_word_boundaries_, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_HEX_CHECK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_2_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_800B4890_Array_is_in_Hex ), // pwcText _LEN_800B4890, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_9C4FF69C_Indicates_that_each_element_in_the_array_is_a_hexadecimal_value_, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_WILDCARD_CHECK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_3_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_003B75E3_Wildcard ), // pwcText _LEN_003B75E3, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_05F7A799___and___characters_are_treated_as_wildcards_, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_LINGUISTIC_IGNORECASE_CHECK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_1_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT * 2, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_9D23A539_Linguistic_Ignore_Case ), // pwcText _LEN_9D23A539, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_A8F450F1_Ignore_case__as_linguistically_appropriate____________, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_REGEX_SINGLELINE, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_1_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT * 2, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_6C2A854F_Single_Line ), // pwcText _LEN_6C2A854F, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_98F37FD9___________A_____________Z_, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_LINGUISTIC_IGNOREDIACRITIC_CHECK,// wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_2_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT * 2, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_899EFB13_Linguistic_Ignore_Diacritic ), // pwcText _LEN_899EFB13, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_645BF5AE_Ignore_nonspacing_characters__as_linguistically_appropriate__________A, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_REGEX_MULTILINE, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_2_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT * 2, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_95B3789A_Multiline ), // pwcText _LEN_95B3789A, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_0474EC48_____matches_with_new_line_characters_, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_NORM_IGNOREKANATYPE_CHECK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_3_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT * 2, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_4E17788D_Ignore_Kana ), // pwcText _LEN_4E17788D, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_2165F244_Do_not_differentiate_between_hiragana_and_katakana_characters______________, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_REGEX_EXTENDED, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_3_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT * 2, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_DCCBE329_Extended ), // pwcText _LEN_DCCBE329, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_77AB5C2E_Use_Extended_Regex_, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_NORM_IGNORENONSPACE_CHECK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_1_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT * 3, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_5F5A587A_Ignore_Non_Space ), // pwcText _LEN_5F5A587A, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_44CE7F22_Ignore_nonspacing_characters_, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_REGEX_FIND_LONGEST, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_1_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT * 3, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_5F59C830_Find_Longest ), // pwcText _LEN_5F59C830, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_6A177D05_Finds_the_longest_match_, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_NORM_IGNORESYMBOLS_CHECK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_2_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT * 3, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_DFF728E7_Ignore_Symbols ), // pwcText _LEN_DFF728E7, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_EDA70C5F_Ignore_symbols_and_punctuation__________, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_NORM_IGNOREWIDTH_CHECK, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_3_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT * 3, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_58AADFAC_Ignore_Width ), // pwcText _LEN_58AADFAC, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_339AE0D6_Ignore_the_difference_between_half_width_and_full_width_characters___________A, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_CHECK, // ltType MX_SSI_REGEX_NEGATE_SINGLELINE, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_3_3RD_LEFT, // iLeft (MX_OPTIONS_TOP + MX_GROUP_TOP) + MX_DEF_CHECK_HEIGHT * 3, // iTop MX_1_3RD_W, // dwWidth MX_DEF_CHECK_HEIGHT, // dwHeight MX_CHECKSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_7B9E8326_Negate_Single_Line ), // pwcText _LEN_7B9E8326, // sTextLen MX_SSI_DIALOG, // dwParentId LSW_NO_SIZE_EXP, _T_LEN_A893C9A7_Negates_the_single_line_attribute_enabled_in_Java__POSIX__and_Perl_, // pcToolTip, sToolTipLen WS_EX_TOPMOST, // dwToolTipStyleEx MX_TOOLTIP_STYLE, // dwToolTipStyle }, { LSW_LT_BUTTON, // ltType MX_SSI_GENERAL_SEARCH_OPTIONS_BUTTON, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_LEFT_ALIGN + MX_GROUP_LEFT, // iLeft MX_OPTIONS_TOP + MX_GROUP_TOP + MX_DEF_CHECK_HEIGHT * 4, // iTop MX_SEARCH_W - ((MX_LEFT_ALIGN + MX_GROUP_LEFT) * 2), // dwWidth MX_DEF_BUTTON_HEIGHT, // dwHeight MX_BUTTONSTYLE, // dwStyle WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR | WS_EX_NOPARENTNOTIFY, // dwStyleEx MX_MAKE_WCHAR( _T_5FE14262_General_Search_Options ), // pwcText _LEN_5FE14262, // sTextLen MX_SSI_DIALOG, // dwParentId }, // ==== Search Range ==== // { LSW_LT_GROUPBOX, // ltType MX_SSI_SEARCH_RANGE_GROUP, // wId WC_BUTTONW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_LEFT_ALIGN, // iLeft MX_SEARCH_RANGE_TOP, // iTop MX_SEARCH_W - (MX_LEFT_ALIGN * 2), // dwWidth MX_SEARCH_RANGE_H, // dwHeight MX_GROUPSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_8436D248_Search_Range ), // pwcText _LEN_8436D248, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_LABEL, // ltType MX_SSI_FROM_LABEL, // wId WC_STATICW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_EVEN_DIVIDE_EX( MX_SEARCH_W - ((MX_LEFT_ALIGN + MX_GROUP_LEFT) * 2), MX_LEFT_ALIGN + MX_GROUP_LEFT, 2, 0, MX_LEFT_JUST ), // iLeft MX_SEARCH_RANGE_TOP + MX_GROUP_TOP, // iTop MX_EVEN_DIVIDE_WIDTH_EX( MX_SEARCH_W - ((MX_LEFT_ALIGN + MX_GROUP_LEFT) * 2), MX_LEFT_ALIGN + MX_GROUP_LEFT, 2, 0, MX_LEFT_JUST ), // dwWidth MX_DEF_STATIC_HEIGHT, // dwHeight MX_STATICSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_857372A6_From_ ), // pwcText _LEN_857372A6, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_LABEL, // ltType MX_SSI_TO_LABEL, // wId WC_STATICW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_EVEN_DIVIDE_EX( MX_SEARCH_W - ((MX_LEFT_ALIGN + MX_GROUP_LEFT) * 2), MX_LEFT_ALIGN + MX_GROUP_LEFT, 2, 1, MX_LEFT_JUST ), // iLeft MX_SEARCH_RANGE_TOP + MX_GROUP_TOP, // iTop MX_EVEN_DIVIDE_WIDTH_EX( MX_SEARCH_W - ((MX_LEFT_ALIGN + MX_GROUP_LEFT) * 2), MX_LEFT_ALIGN + MX_GROUP_LEFT, 2, 1, MX_LEFT_JUST ), // dwWidth MX_DEF_STATIC_HEIGHT, // dwHeight MX_STATICSTYLE, // dwStyle 0, // dwStyleEx MX_MAKE_WCHAR( _T_B09DF1A4_To_ ), // pwcText _LEN_B09DF1A4, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_COMBOBOX, // ltType MX_SSI_FROM_COMBO, // wId WC_COMBOBOXW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_EVEN_DIVIDE_EX( MX_SEARCH_W - ((MX_LEFT_ALIGN + MX_GROUP_LEFT) * 2), MX_LEFT_ALIGN + MX_GROUP_LEFT, 2, 0, MX_LEFT_JUST ), // iLeft MX_SEARCH_RANGE_TOP + MX_GROUP_TOP + MX_DEF_STATIC_HEIGHT, // iTop MX_EVEN_DIVIDE_WIDTH_EX( MX_SEARCH_W - ((MX_LEFT_ALIGN + MX_GROUP_LEFT) * 2), MX_LEFT_ALIGN + MX_GROUP_LEFT, 2, 0, MX_LEFT_JUST ), // dwWidth MX_DEF_COMBO_HEIGHT, // dwHeight MX_COMBOSTYLE, // dwStyle 0, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, { LSW_LT_COMBOBOX, // ltType MX_SSI_TO_COMBO, // wId WC_COMBOBOXW, // lpwcClass TRUE, // bEnabled FALSE, // bActive MX_EVEN_DIVIDE_EX( MX_SEARCH_W - ((MX_LEFT_ALIGN + MX_GROUP_LEFT) * 2), MX_LEFT_ALIGN + MX_GROUP_LEFT, 2, 1, MX_LEFT_JUST ), // iLeft MX_SEARCH_RANGE_TOP + MX_GROUP_TOP + MX_DEF_STATIC_HEIGHT, // iTop MX_EVEN_DIVIDE_WIDTH_EX( MX_SEARCH_W - ((MX_LEFT_ALIGN + MX_GROUP_LEFT) * 2), MX_LEFT_ALIGN + MX_GROUP_LEFT, 2, 1, MX_LEFT_JUST ), // dwWidth MX_DEF_COMBO_HEIGHT, // dwHeight MX_COMBOSTYLE, // dwStyle 0, // dwStyleEx nullptr, // pwcText 0, // sTextLen MX_SSI_DIALOG, // dwParentId }, }; // == Functions. // Creates the New String Search dialog. Makes an in-memory copy of the LSW_WIDGET_LAYOUT's so it can decode strings etc. DWORD CNewStringSearchLayout::CreateNewStringSearchDialog( CWidget * _pwParent, CMemHack * _pmhMemHack ) { std::vector<CSecureString> sStrings; std::vector<CSecureWString> sStringsW; std::vector<LSW_WIDGET_LAYOUT> vLayouts; CLayoutManager::UnencryptLayouts( m_wlNewStringSearchDialog, MX_ELEMENTS( m_wlNewStringSearchDialog ), vLayouts, sStringsW, sStrings ); mx::CLayoutManager * plmLayout = static_cast<mx::CLayoutManager *>(lsw::CBase::LayoutManager()); INT_PTR ipProc = plmLayout->DialogBoxX( &vLayouts[0], MX_ELEMENTS( m_wlNewStringSearchDialog ), _pwParent, reinterpret_cast<uint64_t>(_pmhMemHack) ); CLayoutManager::CleanEncryptedStrings( sStringsW, sStrings ); if ( ipProc != 0 ) { // Success. Do stuff. return TRUE; } return FALSE; } #undef MX_SEARCH_RANGE_H #undef MX_SEARCH_RANGE_TOP #undef MX_OPTIONS_TOP #undef MX_COMBOBOXES_LEFT #undef MX_SEARCH_GROUP_HEIGHT #undef MX_WIDTH_TO_CENTER #undef MX_3_3RD_LEFT #undef MX_2_3RD_LEFT #undef MX_1_3RD_LEFT #undef MX_1_3RD_W #undef MX_CENTER #undef MX_LEFT_ALIGN #undef MX_SEARCH_GROUP_TOP #undef MX_SEARCH_H #undef MX_SEARCH_W } // namespace mx
37.412854
151
0.605794
[ "vector" ]
da374d46dfe1cab2ef8ec0ebcde1db6a7c3c1461
1,987
cpp
C++
src/interfaces/matlab/opengm/mex-src/model/loadModel.cpp
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
318
2015-01-07T15:22:02.000Z
2022-01-22T10:10:29.000Z
src/interfaces/matlab/opengm/mex-src/model/loadModel.cpp
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
89
2015-03-24T14:33:01.000Z
2020-07-10T13:59:13.000Z
src/interfaces/matlab/opengm/mex-src/model/loadModel.cpp
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
119
2015-01-13T08:35:03.000Z
2022-03-01T01:49:08.000Z
//include matlab headers #include "mex.h" // matlab handle #include "../helper/handle/handle.hxx" #include "matlabModelType.hxx" /** * @brief This file implements an interface to load an opengm model in MatLab. * * This routine accepts a string containing the filename of an opengm model * stored in hd5 format. The model is loaded and a handle to the model will be * passed back to MatLab for further usage. * * @param[in] nlhs number of output arguments expected from MatLab * (needs to be 1). * @param[out] plhs pointer to the mxArrays containing the results. If the model * can be loaded, plhs[0] contains the handle to the model. * @param[in] nrhs number of input arguments provided from MatLab. * (needs to be 2) * @param[in] prhs pointer to the mxArrays containing the input data provided by * matlab. prhs[0] needs to contain the file location of the opengm model stored * in hdf5 format. prhs[1] needs to contain the desired dataset. */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { //check if data is in correct format if(nrhs != 2) { mexErrMsgTxt("Wrong number of input variables specified (one needed)\n"); } if(nlhs != 1) { mexErrMsgTxt("Wrong number of output variables specified (one needed)\n"); } // get file name and corresponding dataset std::string modelFilename = mxArrayToString(prhs[0]); if(modelFilename.data()==NULL) { mexErrMsgTxt("load: could not convert input to string."); } std::string dataset = mxArrayToString(prhs[1]); if(dataset.data()==NULL) { mexErrMsgTxt("load: could not convert input to string."); } // load model typedef opengm::interface::MatlabModelType::GmType GmType; GmType* gm = new GmType(); std::cout << "Loading model..." << std::endl; opengm::hdf5::load(*gm, modelFilename, dataset); std::cout << "Loading model done" << std::endl; // create handle to model plhs[0] = opengm::interface::handle<GmType>::createHandle(gm); }
36.127273
80
0.703573
[ "model" ]
da376fdde90fa91ee01076321ace961c5a368924
2,965
cc
C++
src/tir/schedule/transform.cc
mozga-intel/tvm
544724439efb9a795c92bd7ec9f7929e41c843c6
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
1
2021-09-30T01:31:50.000Z
2021-09-30T01:31:50.000Z
src/tir/schedule/transform.cc
mozga-intel/tvm
544724439efb9a795c92bd7ec9f7929e41c843c6
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
null
null
null
src/tir/schedule/transform.cc
mozga-intel/tvm
544724439efb9a795c92bd7ec9f7929e41c843c6
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
2
2021-09-30T21:06:03.000Z
2022-02-25T00:52:12.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 "./transform.h" #include "./utils.h" namespace tvm { namespace tir { /******** Annotation ********/ Block WithAnnotation(const BlockNode* block, const String& attr_key, const ObjectRef& attr_value) { Map<String, ObjectRef> annotations = block->annotations; annotations.Set(attr_key, attr_value); ObjectPtr<BlockNode> new_block = make_object<BlockNode>(*block); new_block->annotations = std::move(annotations); return Block(new_block); } /******** Buffer Related ********/ Buffer WithScope(const Buffer& buffer, const String& scope) { ObjectPtr<BufferNode> new_buffer = make_object<BufferNode>(*buffer.get()); ObjectPtr<VarNode> new_var = make_object<VarNode>(*buffer->data.get()); const auto* ptr_type = TVM_TYPE_AS(ptr_type, buffer->data->type_annotation, PointerTypeNode); new_var->type_annotation = PointerType(ptr_type->element_type, scope); new_buffer->data = Var(new_var->name_hint + "_" + scope, new_var->type_annotation); new_buffer->name = buffer->name + "_" + scope; return Buffer(new_buffer); } Array<BufferRegion> ReplaceBuffer(Array<BufferRegion> regions, const Buffer& source, const Buffer& target) { regions.MutateByApply([&source, &target](BufferRegion region) -> BufferRegion { if (region->buffer.same_as(source)) { ObjectPtr<BufferRegionNode> n = make_object<BufferRegionNode>(*region.get()); n->buffer = target; return BufferRegion(n); } return region; }); return regions; } Array<MatchBufferRegion> ReplaceBuffer(Array<MatchBufferRegion> match_buffers, const Buffer& source, const Buffer& target) { match_buffers.MutateByApply([&source, &target](MatchBufferRegion match_buffer) -> MatchBufferRegion { if (match_buffer->source->buffer.same_as(source)) { ObjectPtr<MatchBufferRegionNode> n = make_object<MatchBufferRegionNode>(*match_buffer.get()); n->source = BufferRegion(target, n->source->region); return MatchBufferRegion(n); } return match_buffer; }); return match_buffers; } } // namespace tir } // namespace tvm
39.013158
100
0.702867
[ "transform" ]
da3a8687101538c407cc31f9bcc7aac8205177f3
10,200
hpp
C++
src/sqlite/sqlite_statement.hpp
gsalomao/cppdbc
2f481dfa2b938eff819e711222c31539d34cb54a
[ "MIT" ]
null
null
null
src/sqlite/sqlite_statement.hpp
gsalomao/cppdbc
2f481dfa2b938eff819e711222c31539d34cb54a
[ "MIT" ]
null
null
null
src/sqlite/sqlite_statement.hpp
gsalomao/cppdbc
2f481dfa2b938eff819e711222c31539d34cb54a
[ "MIT" ]
null
null
null
/* * Copyright (C) 2020 Gustavo Salomao * * 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. */ /** * @brief SQLite statement. * @file */ #ifndef SQLITE_STATEMENT_HPP #define SQLITE_STATEMENT_HPP #include <memory> #include <string> #include <sqlite3.h> #include "cppdbc/statement.hpp" namespace cppdbc { // Forward declarations class SQLiteDatabase; /** * @brief SQLite statement. * * A SQLite statement object manages a single SQL query for a SQLite database. */ class SQLiteStatement : public Statement, public std::enable_shared_from_this<SQLiteStatement> { public: /** * @brief Create SQLite statement. * * Constructor of the SQLite statements. * * @param[in] database SQLite database which the statement will be executed. * @param[in] query SQL query to be executed on database. * * @throw std::invalid_argument in case of invalid database or query. */ SQLiteStatement(const std::shared_ptr<SQLiteDatabase>& database, const std::string& query); /** * @brief Remove copy constructor. * * SQLite statement is not copyable. */ SQLiteStatement(const SQLiteStatement&) = delete; /** * @brief Move constructor. * * Move constructor of the SQLite statement. */ SQLiteStatement(SQLiteStatement&& other) noexcept; /** * @brief Destroy SQLite statement. * * Destructor of the SQLite statement. */ ~SQLiteStatement() override; /** * @brief Remove copy assignment. * * SQLite statement is not copyable. */ SQLiteStatement& operator=(const SQLiteStatement&) = delete; /** * @brief Move assignment. * * Move assignment of the SQLite statement. */ SQLiteStatement& operator=(SQLiteStatement&& other) noexcept; /** * @brief Check if SQLite statement is pending. * * Check if the SQLite statement is pending. When a statement is created it * shall be pending and can be executed only once. After that, it shall * not be pending anymore. * * @retval true - statement pending. * @retval false - statement is not pending. */ [[nodiscard]] bool pending() const noexcept override; /** * @brief Execute SQLite statement. * * Once the SQLite statement has been created, it can be executed in the * SQLite database. Statements, when executed, it generates a result set or * not. * * @retval Pointer to the result set. * @retval nullptr when there's no result set. * @throw cppdbc::constraint_violation in case of the statement violates * any constraint. * @throw std::logic_error in case of failure to execute the statement. */ std::shared_ptr<ResultSet> execute() override; /** * @brief Bind unsigned integer (8-bits). * * Bind unsigned integer (8-bits) value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(uint8_t value, uint16_t index) override; /** * @brief Bind unsigned integer (16-bits). * * Bind unsigned integer (16-bits) value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(uint16_t value, uint16_t index) override; /** * @brief Bind unsigned integer (32-bits). * * Bind unsigned integer (32-bits) value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(uint32_t value, uint16_t index) override; /** * @brief Bind unsigned integer (64-bits). * * Bind unsigned integer (64-bits) value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(uint64_t value, uint16_t index) override; /** * @brief Bind signed integer (8-bits). * * Bind signed integer (8-bits) value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(int8_t value, uint16_t index) override; /** * @brief Bind signed integer (16-bits). * * Bind signed integer (16-bits) value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(int16_t value, uint16_t index) override; /** * @brief Bind signed integer (32-bits). * * Bind signed integer (32-bits) value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(int32_t value, uint16_t index) override; /** * @brief Bind signed integer (64-bits). * * Bind signed integer (64-bits) value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(int64_t value, uint16_t index) override; /** * @brief Bind boolean. * * Bind boolean value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(bool value, uint16_t index) override; /** * @brief Bind string. * * Bind string value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(const std::string& value, uint16_t index) override; /** * @brief Bind float. * * Bind float value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(float value, uint16_t index) override; /** * @brief Bind double. * * Bind double value to a given index of the statement. * * @param[in] value Value to be bound. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(double value, uint16_t index) override; /** * @brief Bind BLOB. * * Bind BLOB to a given index of the statement. * * @param[in] value Pointer to memory location to be bound. * @param[in] size Number of bytes of the bound memory. * @param[in] index Index which the value shall be bound. * * @throw std::invalid_argument in case of failure to bind the value to * column. */ void bind(const void* value, size_t size, uint16_t index) override; private: /** * @brief SQLite result set is friend. * * Defining SQL result set as friend of SQLite statement, the result set * can execute statement directly. */ friend class SQLiteResultSet; /** * @brief Check SQLite result. * * Check if result returned from SQLite is SQLITE_OK. If it's not, it * throws an exception. * * @param[in] result Result value from SQLite. * @param[in] message Message of the exception. * * @throw std::invalid_argument in case of the result value is not * SQLITE_OK. */ static void check_sqlite_result(int result, const std::string& message); /** * @brief Indicates if the statement has not completed. * * @note A statement is pending while it wasn't executed yet. */ bool pending_ = true; /** * @brief SQLite statement handler. */ sqlite3_stmt* statement_ = nullptr; /** * @brief SQLite database object. */ std::shared_ptr<SQLiteDatabase> database_; }; } // namespace cppdbc #endif // SQLITE_STATEMENT_HPP
30.267062
96
0.641569
[ "object" ]
da58b0d1ff62b208caa1e9c3f669193cded02091
16,725
cpp
C++
products/sgen/sgen_utils/src/SourceGen.cpp
cbtek/SourceGen
6593300c658529acb06b83982bbc9e698c270aeb
[ "MIT" ]
null
null
null
products/sgen/sgen_utils/src/SourceGen.cpp
cbtek/SourceGen
6593300c658529acb06b83982bbc9e698c270aeb
[ "MIT" ]
null
null
null
products/sgen/sgen_utils/src/SourceGen.cpp
cbtek/SourceGen
6593300c658529acb06b83982bbc9e698c270aeb
[ "MIT" ]
null
null
null
/** MIT License Copyright (c) 2016 cbtek 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 "SourceGen.h" #include "utility/inc/StringUtils.hpp" #include "utility/inc/FileUtils.hpp" #include "utility/inc/SystemUtils.hpp" #include "utility/inc/TimeUtils.hpp" #include "utility/inc/DateUtils.hpp" #include "utility/inc/StringList.h" using namespace cbtek::common::utility; namespace cbtek{ namespace products{ namespace sourcegen { //////////////////////////////////////////////////////////////////////// /// \brief SourceGen::save /// \param info /// \param log /// \param fileDataMap /// \return //////////////////////////////////////////////////////////////////////// bool SourceGen::save(const SourceGenInfo &info, StringList &log, const common::utility::StringMap &fileDataMap) { std::string className = info.getClassName(); std::string gettersSetters = info.getGetsSets(); std::string includes = info.getIncludes(); std::string inherits = info.getBaseClasses(); std::string namespaces = info.getNamespace(); std::string type = info.getClassType(); std::string outputdir = info.getOutputFolder(); std::string copyrightData = FileUtils::getFileContents(info.getCopyrightFile()); std::string srcSubFolder = info.getSrcSubFolder(); std::string uiSubFolder = info.getUiSubFolder(); std::string incSubFolder = info.getIncSubFolder(); bool overwrite = info.getCanOverwrite(); std::string hData,cppData; std::vector<std::string> namespaceList = StringUtils::split(namespaces,"."); StringUtils::clean(namespaceList); std::string beginNamespace,endNamespace; if (namespaceList.size()) { beginNamespace = StringList(namespaceList).toString("namespace "," {\n"); StringUtils::repeat("}",endNamespace,namespaceList.size()); endNamespace += "//end namespace\n"; } std::string headerguard = StringUtils::toUpperTrimmed("_"+StringList(namespaceList).toString("_")+"_"+className+"_H"); std::string timestamp = className+".cpp generated by "+ SystemUtils::getUserName()+" on "+ DateUtils::toShortDateString(DateUtils::getCurrentDate()) +" at "+TimeUtils::to12HourTimeString(TimeUtils::getCurrentTime()); std::string cppFileOut = FileUtils::buildFilePath(FileUtils::buildFilePath(outputdir,srcSubFolder),className+".cpp"); std::string hFileOut = FileUtils::buildFilePath(FileUtils::buildFilePath(outputdir,incSubFolder),className+".h"); std::string classtype = StringUtils::toUpperTrimmed(type); /// //Start constructing class output for each class type /// if (classtype=="NORMAL") { hData = fileDataMap.getValue("class_normal_template.h"); cppData = fileDataMap.getValue("class_normal_template.cpp"); } else if (classtype=="SINGLETON") { hData = fileDataMap.getValue("class_singleton_template.h"); cppData = fileDataMap.getValue("class_singleton_template.cpp"); } else if (classtype=="STATIC") { hData = fileDataMap.getValue("class_static_template.h"); cppData = fileDataMap.getValue("class_static_template.cpp"); } else if (classtype=="VIRTUAL") { hData = fileDataMap.getValue("class_virtual_template.h"); cppFileOut = ""; } else if (classtype=="QMAINWINDOW" || classtype=="QWIDGET" || classtype=="QDIALOG") { std::string qtwidget; if (classtype=="QMAINWINDOW") { qtwidget ="QMainWindow"; } else if (classtype=="QDIALOG") { qtwidget = "QDialog"; } else { qtwidget="QWidget"; } hData = fileDataMap.getValue("class_qtwidget_template.h"); cppData = fileDataMap.getValue("class_qtwidget_template.cpp"); std::string uiData = fileDataMap.getValue("class_qtwidget_template.ui"); std::string uiFileOut = FileUtils::buildFilePath(FileUtils::buildFilePath(outputdir,uiSubFolder),className+".ui"); uiData = StringUtils::replace(uiData,"$CLASS_NAME",className,true); hData = StringUtils::replace(hData,"$QT_WIDGET",qtwidget,true); cppData = StringUtils::replace(cppData,"$QT_WIDGET",qtwidget,true); uiData = StringUtils::replace(uiData,"$QT_WIDGET",qtwidget,true); if (classtype=="QMAINWINDOW") { uiData = StringUtils::replace(uiData,"$QT_MAIN_WINDOW_CHILD","<widget class=\"QWidget\" name=\"centralwidget\">\n</widget>\n"); } else { uiData = StringUtils::replace(uiData,"$QT_MAIN_WINDOW_CHILD","\n"); } SourceGen::saveGettersSetters(gettersSetters,className,hData,cppData); if (!overwrite && FileUtils::fileExists(uiFileOut)) { log.push_back("Can not overwrite file at '"); log.push_back(uiFileOut); log.push_back("'\n"); return false; } else { log.push_back("Successfully generated UI file at '"); log.push_back(uiFileOut); log.push_back("'\n"); FileUtils::writeFileContents(uiFileOut,uiData); } } if (StringUtils::trimmed(inherits).size()) { hData = StringUtils::replace(hData,"$PARENT_CLASSES",":"+inherits,true); } else { hData = StringUtils::replace(hData,"$PARENT_CLASSES","",true); } //fix for cmdline version std::string includesFixed = StringUtils::replace(includes,"*","\"",true); StringList includeList = StringUtils::split(includesFixed,","); includeList.trimmed(); includeList.remove(""); std::string yearStr = StringUtils::toString(DateUtils::getCurrentDate().getYear()); hData = StringUtils::replace(hData,"$INCLUDES_H",(includeList.size()?(includeList).toString("#include ","\n"):"")); hData = StringUtils::replace(hData,"$CLASS_NAME",className,true); cppData = StringUtils::replace(cppData,"$CLASS_NAME",className,true); hData = StringUtils::replace(hData,"$BEGIN_NAMESPACE",beginNamespace,true); cppData = StringUtils::replace(cppData,"$BEGIN_NAMESPACE",beginNamespace,true); hData = StringUtils::replace(hData,"$END_NAMESPACE",endNamespace,true); cppData = StringUtils::replace(cppData,"$END_NAMESPACE",endNamespace,true); hData = StringUtils::replace(hData,"$HEADER_GUARD",headerguard,true); cppData = StringUtils::replace(cppData,"$TIMESTAMP",timestamp,true); hData = StringUtils::replace(hData,"$YEAR",yearStr,true); cppData = StringUtils::replace(cppData,"$YEAR",yearStr,true); cppData = StringUtils::replace(cppData,"$COPYRIGHT","\n"+copyrightData,true); hData = StringUtils::replace(hData,"$COPYRIGHT","\n"+copyrightData,true); SourceGen::saveGettersSetters(gettersSetters,className,hData,cppData); if (!overwrite && FileUtils::fileExists(hFileOut)) { log << "Can not overwrite file at '"<<hFileOut<<"'!\n"; return false; } else { if (cppFileOut.size()==0) { hFileOut = hFileOut+"pp"; log << "Successfully generated .hpp file at "<<hFileOut<<"\n"; FileUtils::writeFileContents(hFileOut,hData); } else { log << "Successfully generated .h file at "<<hFileOut<<"\n"; FileUtils::writeFileContents(hFileOut,hData); } } if (!overwrite && FileUtils::fileExists(cppFileOut)) { log << "Can not overwrite file at '"<<cppFileOut<<"'!\n"; return false; } else { if (cppFileOut.size()) { log << "Successfully generated .cpp file at "<<cppFileOut<<"\n"; FileUtils::writeFileContents(cppFileOut,cppData); } } return true; } StringMap SourceGen::getValidFileList() { StringList files = StringList() <<"class_normal_template.cpp" <<"class_normal_template.h" <<"class_qtwidget_template.cpp" <<"class_qtwidget_template.h" <<"class_qtwidget_template.ui" <<"class_singleton_template.cpp" <<"class_singleton_template.h" <<"class_static_template.cpp" <<"class_static_template.h" <<"class_virtual_template.h"; std::string path = FileUtils::buildFilePath(SystemUtils::getUserHomeDirectory(),".sgen_templates"); if (!FileUtils::isDirectory(path)) { path = FileUtils::buildFilePath(SystemUtils::getApplicationDirectory(),".sgen_templates"); if (!FileUtils::isDirectory(path)) { path = FileUtils::buildFilePath(SystemUtils::getUserAppDirectory(),".sgen_templates"); #ifdef __gnu_linux__ if (!FileUtils::isDirectory(path)) { path = FileUtils::buildFilePath("/usr/local/share",".sgen_templates"); } #endif } } if (!FileUtils::isDirectory(path)) { throw FileNotFoundException(EXCEPTION_TAG+"Could not find valid path for .sgen_templates!"); } StringMap fileDataMap; for(std::string file : files) { std::string filePath = FileUtils::buildFilePath(path,file); if (FileUtils::fileExists(filePath)) { std::string fileData = FileUtils::getFileContents(filePath); if (fileData.size() == 0) { throw FileNotFoundException(EXCEPTION_TAG+"The location at \""+filePath+"\" Contains no content or can not be read.\nPlease ensure all template files are installed correctly."); } fileDataMap[file] = fileData; } else { throw FileNotFoundException(EXCEPTION_TAG+"The location at \""+filePath+"\" does not appear to be valid.\nPlease ensure all template files are installed correctly."); } } return fileDataMap; } //////////////////////////////////////////////////////////////////////// /// \brief SourceGen::saveGettersSetters /// \param gettersSetters /// \param classname /// \param hData /// \param cppData //////////////////////////////////////////////////////////////////////// void SourceGen::saveGettersSetters(const std::string &gettersSetters, const std::string &classname, std::string &hData, std::string &cppData) { std::string headerMembers,headerGetters,headerSetters; std::string sourceGetters,sourceSetters; std::vector<std::string> getsSets = StringUtils::split(gettersSetters,"\n"); for(int a1 = 0;a1<getsSets.size();++a1) { StringList items = StringUtils::split(getsSets[a1],":"); items.trimmed(); items.remove(""); if (items.size()>1) { std::string variable = items[0]; std::string type = items[1]; if (items.size()>2) { for (size_t a2=2;a2<items.size();++a2) { type+="::"+items[a2]; } } std::string func = variable; if (StringUtils::startsWith(func,"m_")) { func = func.substr(2,func.size()-2); } else if (StringUtils::startsWith(func,"_")) { func = func.substr(1,func.size()-1); } if (func.size()) { func[0]=std::toupper(func[0]); } bool useConstCorrectness=true; if (StringUtils::toLower(type)=="int" || StringUtils::toLower(type)=="long" || StringUtils::toLower(type)=="long int" || StringUtils::toLower(type)=="long long" || StringUtils::toLower(type)=="unsigned long int" || StringUtils::toLower(type)=="unsigned long long" || StringUtils::toLower(type)=="double" || StringUtils::toLower(type)=="float" || StringUtils::toLower(type)=="char" || StringUtils::toLower(type)=="size_t" || StringUtils::toLower(type)=="unsigned char" || StringUtils::toLower(type)=="unsigned int" || StringUtils::toLower(type)=="bool" || StringUtils::toLower(type)=="unsigned long" || StringUtils::toLower(type)=="boost::uint8_t" || StringUtils::toLower(type)=="boost::uint16_t" || StringUtils::toLower(type)=="boost::uint32_t" || StringUtils::toLower(type)=="boost::uint64_t" || StringUtils::toLower(type)=="boost::int8_t" || StringUtils::toLower(type)=="boost::int16_t" || StringUtils::toLower(type)=="boost::int32_t" || StringUtils::toLower(type)=="boost::int64_t" || StringUtils::toLower(type)=="std::uint8_t" || StringUtils::toLower(type)=="std::uint16_t" || StringUtils::toLower(type)=="std::uint32_t" || StringUtils::toLower(type)=="std::uint64_t" || StringUtils::toLower(type)=="std::int8_t" || StringUtils::toLower(type)=="std::int16_t" || StringUtils::toLower(type)=="std::int32_t" || StringUtils::toLower(type)=="std::int64_t" || StringUtils::toLower(type)=="uint8_t" || StringUtils::toLower(type)=="uint16_t" || StringUtils::toLower(type)=="uint32_t" || StringUtils::toLower(type)=="uint64_t" || StringUtils::toLower(type)=="int8_t" || StringUtils::toLower(type)=="int16_t" || StringUtils::toLower(type)=="int32_t" || StringUtils::toLower(type)=="int64_t") { useConstCorrectness=false; } headerMembers+=" "+type+" "+variable+";\n"; headerSetters+=" /**\n"; headerSetters+=" * @brief Setter for "+variable+"\n"; headerSetters+=" * @param Value to replace "+variable+"\n"; headerSetters+=" */\n"; headerSetters+=" void set"+func+"("+ (useConstCorrectness?"const "+type+" & value": type+" value") +");\n\n"; headerGetters+=" /**\n"; headerGetters+=" * @brief Getter for "+variable+"\n"; headerGetters+=" * @return Return copy of "+variable+"\n"; headerGetters+=" */\n"; headerGetters+=" "+(useConstCorrectness?"const "+type+" &": type)+" get"+func+"() const;\n\n"; sourceSetters+="void "+classname+"::set"+func+"("+ (useConstCorrectness?"const "+type+" & value": type+" value") +")\n{\n "+variable+"=value;\n}\n\n"; sourceGetters+=""+(useConstCorrectness?"const "+type+" &": type+" ")+classname+"::get"+func+"() const\n{\n return "+variable+";\n}\n\n"; } } hData = StringUtils::replace(hData,"$CLASS_MEMBERS_H",headerMembers); hData = StringUtils::replace(hData,"$CLASS_GETTERS_H",headerGetters); hData = StringUtils::replace(hData,"$CLASS_SETTERS_H",headerSetters); cppData = StringUtils::replace(cppData,"$CLASS_GETTERS_CPP",sourceGetters); cppData = StringUtils::replace(cppData,"$CLASS_SETTERS_CPP",sourceSetters); } }}}//namespace
41.398515
226
0.585411
[ "vector" ]
da6033e6ebbb530cf2569e919deb9f4eb559405f
2,250
hpp
C++
projects/pde1d/solver.hpp
MargotLdm/cpp_dauphine
e2b1f0a0619c99dd5b8080d780c3fe28217f04b0
[ "BSD-3-Clause" ]
null
null
null
projects/pde1d/solver.hpp
MargotLdm/cpp_dauphine
e2b1f0a0619c99dd5b8080d780c3fe28217f04b0
[ "BSD-3-Clause" ]
null
null
null
projects/pde1d/solver.hpp
MargotLdm/cpp_dauphine
e2b1f0a0619c99dd5b8080d780c3fe28217f04b0
[ "BSD-3-Clause" ]
null
null
null
// // solver.hpp // // // Created by Margot on 01/01/2019. // Copyright © 2019 Margot. All rights reserved. // #ifndef tridiagonal_solver_system_hpp #define tridiagonal_solver_system_hpp #include <string> #include "matrix.hpp" class Pde_solver { public: Pde_solver(); Pde_solver(double S0, double T, double sigma, double r, double theta, size_t Nx, size_t Nt, double dx, double dt, double (*payoff)(double), std::string boundary, std::vector<double> value_boundary); void define_matrixes(); // method to compute _A, _Aprime, _u (will be called inside the constructor) std::vector<double> vector_system(const std::vector<double> &f) const; // the vector of the right member of : A(θ)f(n) = A(θ-1)f(n+1)+u. Need to first solve f(n+1) to then obtain the vector. std::vector <double> pricing(bool display=true) const; // compute prices at t=0 void dispaly_price(const std::vector <double> &f) const; private: const double _S0; // spot at t=0 const double _T; const double _sigma; const double _r; const double _theta; double (*_payoff)(double); // pointer to function (need to define it outside the class) const size_t _Nx; // number of space points const size_t _Nt; // number of time points (T*365) const double _dx; // space step const double _dt; // time step (1/365 by default) std::vector<double> _space_mesh; std::vector<double> _time_mesh; std::string _boundary; // type of the boundary : dirichlet or neumann std::vector<double> _value_boundary; // values of f0 and fN if _boundary == 'dirichlet'; values of f'0 and f'N if _boundary == 'neumann' Tridiagonal_matrix _A; // matrix A(θ) of the linear system to solve : A(θ)f(n) = A(θ-1)f(n+1)+u Tridiagonal_matrix _Aprime; // matrix A(θ-1) of the linear system to solve : A(θ)f(n) = A(θ-1)f(n+1)+u std::vector<double> _u; // vector b of the linear system to solve : A(θ)f(n) = A(θ-1)f(n+1)+u }; double call(double S); // payoff by default std::vector<double> thomas_algorithm(const Tridiagonal_matrix &A, const std::vector<double> &y); // find x such that Ax=y when A is tridiagonal (and diagonally dominante to be preferred for stability) #endif /* solver_hpp */
40.178571
202
0.684
[ "vector" ]
da623b01e30cb2c44b134299ac463c67bce9e752
3,993
cpp
C++
examples/nbody_vec4/nbody_vec4.cpp
rcalland/hemi
2128055060160e1961c92a5192f4cb0141bb294e
[ "BSD-3-Clause" ]
286
2015-01-15T11:26:33.000Z
2022-03-31T00:48:25.000Z
examples/nbody_vec4/nbody_vec4.cpp
rcalland/hemi
2128055060160e1961c92a5192f4cb0141bb294e
[ "BSD-3-Clause" ]
17
2015-10-04T17:57:56.000Z
2022-03-29T03:04:16.000Z
examples/nbody_vec4/nbody_vec4.cpp
rcalland/hemi
2128055060160e1961c92a5192f4cb0141bb294e
[ "BSD-3-Clause" ]
52
2015-02-02T07:55:54.000Z
2022-02-20T19:00:34.000Z
/////////////////////////////////////////////////////////////////////////////// // This example implements a simple all-pairs n-body gravitational force // calculation using a 4D vector class called Vec4f. Vec4f uses the HEMI // Portable CUDA C/C++ Macros to enable all of the code for the class to be // shared between host code compiled by the host compiler and device or host // code compiled with the NVIDIA CUDA C/C++ compiler, NVCC. The example // also shares most of the all-pairs gravitationl force calculation code // between device and host, while demonstrating how optimized device // implementations can be substituted as needed. // // This sample also uses hemi::Array to simplify host/device memory allocation // and host-device data transfers. /////////////////////////////////////////////////////////////////////////////// #include <math.h> #include <stdio.h> #include <stdlib.h> #include "cuda_runtime_api.h" #include "vec4f.h" #include "nbody.h" #include "timer.h" #include "hemi/array.h" extern Vec4f centerOfMass(const Vec4f *bodies, int N); extern void allPairsForcesCuda(Vec4f *forceVectors, const Vec4f *bodies, int N, bool useShared); void allPairsForcesHost(Vec4f *forceVectors, const Vec4f *bodies, int N) { for (int i = 0; i < N; i++) forceVectors[i] = accumulateForce(bodies[i], bodies, N); } inline float randFloat(float low, float high){ float t = (float)rand() / (float)RAND_MAX; return (1.0f - t) * low + t * high; } void randomizeBodies(Vec4f *bodies, int N) { srand(437893); for (int i = 0; i < N; i++) { Vec4f &b = bodies[i]; b.x = randFloat(-1000.f, 1000.f); b.y = randFloat(-1000.f, 1000.f); b.z = randFloat(-1000.f, 1000.f); b.w = randFloat(0.1f, 1000.f); } } int main(void) { int N = 16384; Vec4f targetBody(0.5f, 0.5f, 0.5f, 10.0f); hemi::Array<Vec4f> bodies(N, true), forceVectors(N, true); randomizeBodies(bodies.writeOnlyHostPtr(), N); // Call a host function defined in a .cu compilation unit // that uses host/device shared class member functions Vec4f com = centerOfMass(bodies.readOnlyHostPtr(), N); printf("Center of mass is (%f, %f, %f)\n", com.x, com.y, com.z); // Call host function defined in a .cpp compilation unit // that uses host/device shared functions and class member functions printf("CPU: Computing all-pairs gravitational forces on %d bodies\n", N); StartTimer(); allPairsForcesHost(forceVectors.writeOnlyHostPtr(), bodies.readOnlyHostPtr(), N); printf("CPU: Force vector 0: (%0.3f, %0.3f, %0.3f)\n", forceVectors.readOnlyHostPtr()[0].x, forceVectors.readOnlyHostPtr()[0].y, forceVectors.readOnlyHostPtr()[0].z); double ms = GetTimer(); printf("CPU: %f ms\n", ms); StartTimer(); // Call device function defined in a .cu compilation unit // that uses host/device shared functions and class member functions printf("GPU: Computing all-pairs gravitational forces on %d bodies\n", N); allPairsForcesCuda(forceVectors.writeOnlyDevicePtr(), bodies.readOnlyDevicePtr(), N, false); printf("GPU: Force vector 0: (%0.3f, %0.3f, %0.3f)\n", forceVectors.readOnlyHostPtr()[0].x, forceVectors.readOnlyHostPtr()[0].y, forceVectors.readOnlyHostPtr()[0].z); ms = GetTimer(); printf("GPU: %f ms\n", ms); StartTimer(); // Call a different device function defined in a .cu compilation unit // that uses the same host/device shared functions and class member functions // as above printf("GPU: Computing optimized all-pairs gravitational forces on %d bodies\n", N); allPairsForcesCuda(forceVectors.writeOnlyDevicePtr(), bodies.readOnlyDevicePtr(), N, true); printf("GPU: Force vector 0: (%0.3f, %0.3f, %0.3f)\n", forceVectors.readOnlyHostPtr()[0].x, forceVectors.readOnlyHostPtr()[0].y, forceVectors.readOnlyHostPtr()[0].z); ms = GetTimer(); printf("GPU+shared: %f ms\n", ms); return 0; }
34.721739
96
0.653644
[ "vector" ]
da62b1ef751ce6aca93bf2ee93566548707d09ef
31,714
cpp
C++
src/routines.cpp
qalshidi/comfi
59835f0ab4f54dea0ecb44405f583c9c06ad21bb
[ "MIT" ]
1
2021-06-17T22:10:35.000Z
2021-06-17T22:10:35.000Z
src/routines.cpp
qalshidi/comfi
59835f0ab4f54dea0ecb44405f583c9c06ad21bb
[ "MIT" ]
null
null
null
src/routines.cpp
qalshidi/comfi
59835f0ab4f54dea0ecb44405f583c9c06ad21bb
[ "MIT" ]
null
null
null
#include <armadillo> #include "viennacl/vector.hpp" #include "viennacl/matrix.hpp" #include "viennacl/matrix_proxy.hpp" #include "viennacl/vector_proxy.hpp" #include "viennacl/compressed_matrix.hpp" #include "viennacl/linalg/prod.hpp" #include "viennacl/tools/timer.hpp" #include "viennacl/forwards.h" #include "comfi.hpp" using namespace viennacl::linalg; using namespace arma; /* sp_mat comfi::routines::computeRi(const vcl_vec &xn_vcl, const comfi::types::Operators &op) */ /*{*/ /* vec xn(num_of_elem);*/ /* viennacl::fast_copy(xn_vcl, xn);*/ /* const uint nnzp = 12;*/ /* umat Avi = zeros<umat>(nnzp, num_of_grid);*/ /* umat Avj = zeros<umat>(nnzp, num_of_grid);*/ /* mat Avv = zeros<mat> (nnzp, num_of_grid);*/ /* #pragma omp parallel for schedule(static)*/ /* for (uint index=0; index<num_of_grid; index++)*/ /* {*/ /* // indexing*/ /* const unsigned int i=(index)%nx; // find i and c++ index ii*/ /* const unsigned int j=(index)/nx; //find j and c++ index jj*/ /* const int ij=ind(i, j);*/ /* int ip1j=ind(i+1, j);*/ /* int im1j=ind(i-1, j);*/ /* int ijp1=ind(i, j+1);*/ /* int ijm1=ind(i, j-1);*/ /* //const double nuin = mhdsim::sol::nu_in(Nnij, 0.5*(Tpij+Tnij));*/ /* //const double nuni = mhdsim::sol::nu_in(Nnij, 0.5*(Tpij+Tnij))*Npij/Nnij;*/ /* const double nuni = collisionrate;*/ /* const double nuin = nuni*Nnij/Npij;*/ /* //const double resij = mhdsim::sol::resistivity(Npij, Nnij, Tpij, Tnij);*/ /* //const double irate = mhdsim::sol::ionization_coeff(Tnij);*/ /* //const double rrate = mhdsim::sol::recomb_coeff(Tpij);*/ /* // collect*/ /* Avi.col(index) = vi;*/ /* Avj.col(index) = vj;*/ /* Avv.col(index) = vv;*/ /* }*/ /* return comfi::util::syncSpMat(Avi, Avj, Avv);*/ /*}*/ vcl_mat comfi::routines::build_eig_matrix_z(const vcl_mat &xn, comfi::types::Context &ctx) { vcl_mat eig_matrix(ctx.num_of_grid(), ctx.num_of_eq); const vcl_mat p_fast = comfi::routines::fast_speed_z(xn, ctx); const vcl_mat GLM_eig = viennacl::scalar_matrix<double>(p_fast.size1(), p_fast.size2(), ctx.c_h()); const vcl_mat V_z = element_fabs(viennacl::linalg::element_div(ctx.v_NVz(xn), ctx.v_Np(xn))); const vcl_mat U_z = element_fabs(viennacl::linalg::element_div(ctx.v_NUz(xn), ctx.v_Nn(xn))); const vcl_mat c_a = viennacl::linalg::element_div(ctx.v_Bz(xn), viennacl::linalg::element_sqrt(ctx.v_Np(xn))); const vcl_mat c_s = comfi::routines::sound_speed_p(xn, ctx); const vcl_mat c_sn = comfi::routines::sound_speed_n(xn, ctx); //ctx.v_Np(eig_matrix) = -GLM_eig; ctx.v_Np(eig_matrix) = V_z+p_fast; ctx.v_NVx(eig_matrix) = V_z+p_fast; ctx.v_NVp(eig_matrix) = V_z+c_a; ctx.v_NVz(eig_matrix) = V_z+p_fast; ctx.v_Bx(eig_matrix) = V_z; ctx.v_Bp(eig_matrix) = V_z+c_s; ctx.v_Bz(eig_matrix) = V_z+c_a; ctx.v_Ep(eig_matrix) = V_z+p_fast; ctx.v_Nn(eig_matrix) = U_z+c_sn; ctx.v_NUx(eig_matrix) = U_z+c_sn; ctx.v_NUp(eig_matrix) = U_z+c_sn; ctx.v_NUz(eig_matrix) = U_z+c_sn; ctx.v_En(eig_matrix) = U_z+c_sn; ctx.v_GLM(eig_matrix) = GLM_eig; return eig_matrix; } vcl_mat comfi::routines::build_eig_matrix_x(const vcl_mat &xn, comfi::types::Context &ctx) { vcl_mat eig_matrix(ctx.num_of_grid(), ctx.num_of_eq); const vcl_mat p_fast = comfi::routines::fast_speed_x(xn, ctx); const vcl_mat GLM_eig = viennacl::scalar_matrix<double>(p_fast.size1(), p_fast.size2(), ctx.c_h()); const vcl_mat V_x = viennacl::linalg::element_div(ctx.v_NVx(xn), ctx.v_Np(xn)); const vcl_mat U_x = viennacl::linalg::element_div(ctx.v_NUx(xn), ctx.v_Nn(xn)); const vcl_mat c_a = viennacl::linalg::element_div(ctx.v_Bx(xn), viennacl::linalg::element_sqrt(ctx.v_Np(xn))); const vcl_mat c_s = comfi::routines::sound_speed_p(xn, ctx); const vcl_mat c_sn = comfi::routines::sound_speed_n(xn, ctx); //ctx.v_Np(eig_matrix) = -GLM_eig; ctx.v_Np(eig_matrix) = V_x+p_fast; ctx.v_NVx(eig_matrix) = V_x-p_fast; ctx.v_NVp(eig_matrix) = V_x-c_a; ctx.v_NVz(eig_matrix) = V_x-c_s; ctx.v_Bx(eig_matrix) = V_x; ctx.v_Bp(eig_matrix) = V_x+c_s; ctx.v_Bz(eig_matrix) = V_x+c_a; ctx.v_Ep(eig_matrix) = V_x+p_fast; ctx.v_Nn(eig_matrix) = U_x+c_sn; ctx.v_NUx(eig_matrix) = U_x-c_sn; ctx.v_NUp(eig_matrix) = U_x; ctx.v_NUz(eig_matrix) = U_x-c_sn; ctx.v_En(eig_matrix) = U_x+c_sn; ctx.v_GLM(eig_matrix) = GLM_eig; return eig_matrix; } vcl_mat comfi::routines::Re_MUSCL(const vcl_mat &xn, comfi::types::Context &ctx) { const vcl_mat xn_ip1 = comfi::operators::ip1(xn, ctx); const vcl_mat xn_im1 = comfi::operators::im1(xn, ctx); const vcl_mat xn_jp1 = comfi::operators::jp1(xn, ctx); const vcl_mat xn_jm1 = comfi::operators::jm1(xn, ctx); const vcl_mat dxn_iph = xn_ip1-xn; const vcl_mat dxn_imh = xn-xn_im1; const vcl_mat dxn_jph = xn_jp1-xn; const vcl_mat dxn_jmh = xn-xn_jm1; /* viennacl::ocl::program & fluxl_prog = viennacl::ocl::current_context().get_program("fluxl"); viennacl::ocl::kernel & fluxl = fluxl_prog.get_kernel("fluxl"); const vcl_mat r_i = element_div(dxn_imh, dxn_iph); const vcl_mat r_ip1 = element_div(dxn_iph, (comfi::operators::ip1(xn_ip1, ctx)-xn_ip1)); const vcl_mat r_im1 = element_div((xn_im1-comfi::operators::im1(xn_im1, ctx)), dxn_imh); const vcl_mat r_j = element_div(dxn_jmh, dxn_jph); const vcl_mat r_jp1 = element_div(dxn_jph, (comfi::operators::jp1(xn_jp1, ctx)-xn_jp1)); const vcl_mat r_jm1 = element_div((xn_jm1-comfi::operators::jm1(xn_jm1, ctx)), dxn_jmh); vcl_mat phi_i(xn.size1(), xn.size2()), phi_ip1(xn.size1(), xn.size2()), phi_im1(xn.size1(), xn.size2()), phi_j(xn.size1(), xn.size2()), phi_jp1(xn.size1(), xn.size2()), phi_jm1(xn.size1(), xn.size2()); viennacl::ocl::enqueue(fluxl(r_i, phi_i, cl_uint(r_i.size1()*r_i.size2()))); viennacl::ocl::enqueue(fluxl(r_ip1, phi_ip1, cl_uint(r_i.size1()*r_i.size2()))); viennacl::ocl::enqueue(fluxl(r_im1, phi_im1, cl_uint(r_i.size1()*r_i.size2()))); viennacl::ocl::enqueue(fluxl(r_j, phi_j, cl_uint(r_i.size1()*r_i.size2()))); viennacl::ocl::enqueue(fluxl(r_jp1, phi_jp1, cl_uint(r_i.size1()*r_i.size2()))); viennacl::ocl::enqueue(fluxl(r_jm1, phi_jm1, cl_uint(r_i.size1()*r_i.size2()))); vcl_mat Lxn_iph = xn + 0.5*element_prod(phi_i, dxn_imh); vcl_mat Lxn_imh = xn_im1 + 0.5*element_prod(phi_im1, dxn_imh); vcl_mat Rxn_iph = xn_ip1 - 0.5*element_prod(phi_ip1, dxn_iph); vcl_mat Rxn_imh = xn - 0.5*element_prod(phi_i, dxn_iph); vcl_mat Lxn_jph = xn + 0.5*element_prod(phi_j, dxn_jmh); vcl_mat Lxn_jmh = xn_jm1 + 0.5*element_prod(phi_jm1, dxn_jmh); vcl_mat Rxn_jph = xn_jp1 - 0.5*element_prod(phi_jp1, dxn_jph); vcl_mat Rxn_jmh = xn - 0.5*element_prod(phi_j, dxn_jph); */ static const vcl_mat eps = viennacl::scalar_matrix<double>(xn.size1(), xn.size2(), 1.e-100); const vcl_mat r_i = element_div(dxn_imh, dxn_iph+eps); const vcl_mat r_ip1 = element_div(dxn_iph, (comfi::operators::ip1(xn_ip1, ctx)-xn_ip1)+eps); const vcl_mat r_im1 = element_div((xn_im1-comfi::operators::im1(xn_im1, ctx)), dxn_imh+eps); const vcl_mat r_j = element_div(dxn_jmh, dxn_jph+eps); const vcl_mat r_jp1 = element_div(dxn_jph, (comfi::operators::jp1(xn_jp1, ctx)-xn_jp1)+eps); const vcl_mat r_jm1 = element_div((xn_jm1-comfi::operators::jm1(xn_jm1, ctx)), dxn_jmh+eps); //extrapolated cell edge variables vcl_mat Lxn_iph = xn + 0.5*element_prod(comfi::routines::fluxl(r_i), dxn_imh); vcl_mat Lxn_imh = xn_im1 + 0.5*element_prod(comfi::routines::fluxl(r_im1), dxn_imh); vcl_mat Rxn_iph = xn_ip1 - 0.5*element_prod(comfi::routines::fluxl(r_ip1), dxn_iph); vcl_mat Rxn_imh = xn - 0.5*element_prod(comfi::routines::fluxl(r_i), dxn_iph); vcl_mat Lxn_jph = xn + 0.5*element_prod(comfi::routines::fluxl(r_j), dxn_jmh); vcl_mat Lxn_jmh = xn_jm1 + 0.5*element_prod(comfi::routines::fluxl(r_jm1), dxn_jmh); vcl_mat Rxn_jph = xn_jp1 - 0.5*element_prod(comfi::routines::fluxl(r_jp1), dxn_jph); vcl_mat Rxn_jmh = xn - 0.5*element_prod(comfi::routines::fluxl(r_j), dxn_jph); // BOUNDARY CONDITIONS //mhdsim::routines::bottomBC(Lxn_jmh,Rxn_jmh,t,op,bg); //comfi::routines::bottombc_shock_tube(Lxn_jmh, Rxn_jmh, ctx); //comfi::routines::topbc_shock_tube(Lxn_jph, Rxn_jph, ctx); //comfi::routines::topbc_soler(Lxn_jph, Rxn_jph, op); //mhdsim::routines::topbc_driver(Lxn_jph, Rxn_jph, t, op); //comfi::routines::bottombc_soler(Lxn_jmh, Rxn_jmh, op); /* // Fast mode speed eigenvalues */ /* vcl_mat Leig_iph_p = comfi::routines::fast_speed_x_mat(Lxn_iph, ctx); */ /* vcl_mat Reig_iph_p = comfi::routines::fast_speed_x_mat(Rxn_iph, ctx); */ /* vcl_mat Leig_jph_p = comfi::routines::fast_speed_z_mat(Lxn_jph, ctx); */ /* vcl_mat Reig_jph_p = comfi::routines::fast_speed_z_mat(Rxn_jph, ctx); */ /* vcl_mat Leig_imh_p = comfi::routines::fast_speed_x_mat(Lxn_imh, ctx); */ /* vcl_mat Reig_imh_p = comfi::routines::fast_speed_x_mat(Rxn_imh, ctx); */ /* vcl_mat Leig_jmh_p = comfi::routines::fast_speed_z_mat(Lxn_jmh, ctx); */ /* vcl_mat Reig_jmh_p = comfi::routines::fast_speed_z_mat(Rxn_jmh, ctx); */ /* viennacl::ocl::program & eig_prog = viennacl::ocl::current_context().get_program("element_max"); */ /* viennacl::ocl::kernel & element_max = eig_prog.get_kernel("element_max"); */ /* vcl_mat a_imh_p(Leig_iph_p.size1(), Leig_iph_p.size2()); */ /* viennacl::ocl::enqueue(element_max(Leig_imh_p, Reig_imh_p, */ /* a_imh_p, */ /* cl_uint(Leig_imh_p.size1()))); */ /* vcl_mat a_iph_p(Leig_iph_p.size1(), Leig_iph_p.size2()); */ /* viennacl::ocl::enqueue(element_max(Leig_iph_p, Reig_iph_p, */ /* a_iph_p, */ /* cl_uint(Leig_iph_p.size1()))); */ /* vcl_mat a_jmh_p(Leig_iph_p.size1(), Leig_iph_p.size2()); */ /* viennacl::ocl::enqueue(element_max(Leig_jmh_p, Reig_jmh_p, */ /* a_jmh_p, */ /* cl_uint(Leig_jmh_p.size1()))); */ /* vcl_mat a_jph_p(Leig_iph_p.size1(), Leig_iph_p.size2()); */ /* viennacl::ocl::enqueue(element_max(Leig_jph_p, Reig_jph_p, */ /* a_jph_p, */ /* cl_uint(Leig_jph_p.size1()))); */ /* Leig_iph_p = element_fabs(element_div(ctx.v_NVx(Lxn_iph), ctx.v_Np(Lxn_iph))); */ /* viennacl::ocl::enqueue(element_max(Leig_iph_p, a_iph_p, */ /* a_iph_p, */ /* cl_uint(Leig_iph_p.size1()))); */ /* Reig_iph_p = element_fabs(element_div(ctx.v_NVx(Rxn_iph), ctx.v_Np(Rxn_iph))); */ /* viennacl::ocl::enqueue(element_max(Reig_iph_p, a_iph_p, */ /* a_iph_p, */ /* cl_uint(Reig_iph_p.size1()))); */ /* Leig_jph_p = element_fabs(element_div(ctx.v_NVz(Lxn_jph), ctx.v_Np(Lxn_jph))); */ /* viennacl::ocl::enqueue(element_max(Leig_jph_p, a_jph_p, */ /* a_jph_p, */ /* cl_uint(Leig_jph_p.size1()))); */ /* Reig_jph_p = element_fabs(element_div(ctx.v_NVz(Rxn_jph), ctx.v_Np(Rxn_jph))); */ /* viennacl::ocl::enqueue(element_max(Reig_jph_p, a_jph_p, */ /* a_jph_p, */ /* cl_uint(Reig_jph_p.size1()))); */ /* Leig_imh_p = element_fabs(element_div(ctx.v_NVx(Lxn_imh), ctx.v_Np(Lxn_imh))); */ /* viennacl::ocl::enqueue(element_max(Leig_imh_p, a_imh_p, */ /* a_imh_p, */ /* cl_uint(Leig_imh_p.size1()))); */ /* Reig_imh_p = element_fabs(element_div(ctx.v_NVx(Rxn_imh), ctx.v_Np(Rxn_imh))); */ /* viennacl::ocl::enqueue(element_max(Reig_imh_p, a_imh_p, */ /* a_imh_p, */ /* cl_uint(Reig_imh_p.size1()))); */ /* Leig_jmh_p = element_fabs(element_div(ctx.v_NVz(Lxn_jmh), ctx.v_Np(Lxn_jmh))); */ /* viennacl::ocl::enqueue(element_max(Leig_jmh_p, a_jmh_p, */ /* a_jmh_p, */ /* cl_uint(Leig_jmh_p.size1()))); */ /* Reig_jmh_p = element_fabs(element_div(ctx.v_NVz(Rxn_jmh), ctx.v_Np(Rxn_jmh))); */ /* viennacl::ocl::enqueue(element_max(Reig_jmh_p, a_jmh_p, */ /* a_jmh_p, */ /* cl_uint(Reig_jmh_p.size1()))); */ /* vcl_mat Leig_iph_n = comfi::routines::sound_speed_neutral_mat(Lxn_iph, ctx); */ /* vcl_mat Reig_iph_n = comfi::routines::sound_speed_neutral_mat(Rxn_iph, ctx); */ /* vcl_mat Leig_jph_n = comfi::routines::sound_speed_neutral_mat(Lxn_jph, ctx); */ /* vcl_mat Reig_jph_n = comfi::routines::sound_speed_neutral_mat(Rxn_jph, ctx); */ /* vcl_mat Leig_imh_n = comfi::routines::sound_speed_neutral_mat(Lxn_imh, ctx); */ /* vcl_mat Reig_imh_n = comfi::routines::sound_speed_neutral_mat(Rxn_imh, ctx); */ /* vcl_mat Leig_jmh_n = comfi::routines::sound_speed_neutral_mat(Lxn_jmh, ctx); */ /* vcl_mat Reig_jmh_n = comfi::routines::sound_speed_neutral_mat(Rxn_jmh, ctx); */ /* vcl_mat a_imh_n(Leig_iph_n.size1(), Leig_iph_n.size2()); */ /* if (ctx.bc_left != comfi::types::DIMENSIONLESS) { */ /* viennacl::ocl::enqueue(element_max(Leig_imh_n, Reig_imh_n, */ /* a_imh_n, */ /* cl_uint(Leig_imh_n.size1()))); */ /* } */ /* vcl_mat a_iph_n(Leig_iph_n.size1(), Leig_iph_n.size2()); */ /* if (ctx.bc_right != comfi::types::DIMENSIONLESS) { */ /* viennacl::ocl::enqueue(element_max(Leig_iph_n, Reig_iph_n, */ /* a_iph_n, */ /* cl_uint(Leig_iph_n.size1()))); */ /* } */ /* vcl_mat a_jmh_n(Leig_iph_n.size1(), Leig_iph_n.size2()); */ /* if (ctx.bc_down != comfi::types::DIMENSIONLESS) { */ /* viennacl::ocl::enqueue(element_max(Leig_jmh_n, Reig_jmh_n, */ /* a_jmh_n, */ /* cl_uint(Leig_jmh_n.size1()))); */ /* } */ /* vcl_mat a_jph_n(Leig_iph_n.size1(), Leig_iph_n.size2()); */ /* if (ctx.bc_up != comfi::types::DIMENSIONLESS) { */ /* viennacl::ocl::enqueue(element_max(Leig_jph_n, Reig_jph_n, */ /* a_jph_n, */ /* cl_uint(Leig_jph_n.size1()))); */ /* } */ /* Reig_jph_n = element_fabs(element_div(ctx.v_NUz(Rxn_jph), ctx.v_Nn(Rxn_jph))); */ /* viennacl::ocl::enqueue(element_max(Reig_jph_n, a_jph_n, */ /* a_jph_n, */ /* cl_uint(Reig_jph_n.size1()))); */ /* Reig_jmh_n = element_fabs(element_div(ctx.v_NUz(Rxn_jmh), ctx.v_Nn(Rxn_jmh))); */ /* viennacl::ocl::enqueue(element_max(Reig_jmh_n, a_jmh_n, */ /* a_jmh_n, */ /* cl_uint(Reig_jmh_n.size1()))); */ /* Reig_imh_n = element_fabs(element_div(ctx.v_NUx(Rxn_imh), ctx.v_Nn(Rxn_imh))); */ /* viennacl::ocl::enqueue(element_max(Reig_imh_n, a_imh_n, */ /* a_imh_n, */ /* cl_uint(Reig_imh_n.size1()))); */ /* Reig_iph_n = element_fabs(element_div(ctx.v_NUx(Rxn_iph), ctx.v_Nn(Rxn_iph))); */ /* viennacl::ocl::enqueue(element_max(Reig_iph_n, a_iph_n, */ /* a_iph_n, */ /* cl_uint(Reig_iph_n.size1()))); */ /* Leig_jph_n = element_fabs(element_div(ctx.v_NUz(Lxn_jph), ctx.v_Nn(Lxn_jph))); */ /* viennacl::ocl::enqueue(element_max(Leig_jph_n, a_jph_n, */ /* a_jph_n, */ /* cl_uint(Leig_jph_n.size1()))); */ /* Leig_jmh_n = element_fabs(element_div(ctx.v_NUz(Lxn_jmh), ctx.v_Nn(Lxn_jmh))); */ /* viennacl::ocl::enqueue(element_max(Leig_jmh_n, a_jmh_n, */ /* a_jmh_n, */ /* cl_uint(Leig_jmh_n.size1()))); */ /* Leig_imh_n = element_fabs(element_div(ctx.v_NUx(Lxn_imh), ctx.v_Nn(Lxn_imh))); */ /* viennacl::ocl::enqueue(element_max(Leig_imh_n, a_imh_n, */ /* a_imh_n, */ /* cl_uint(Leig_imh_n.size1()))); */ /* Leig_iph_n = element_fabs(element_div(ctx.v_NUx(Lxn_iph), ctx.v_Nn(Lxn_iph))); */ /* viennacl::ocl::enqueue(element_max(Leig_iph_n, a_iph_n, */ /* a_iph_n, */ /* cl_uint(Leig_iph_n.size1()))); */ const vcl_mat a_imh = element_fabs(build_eig_matrix_x(0.5*(Lxn_imh+Rxn_imh), ctx)); const vcl_mat a_iph = element_fabs(build_eig_matrix_x(0.5*(Lxn_iph+Rxn_iph), ctx)); const vcl_mat a_jmh = element_fabs(build_eig_matrix_z(0.5*(Lxn_jmh+Rxn_jmh), ctx)); const vcl_mat a_jph = element_fabs(build_eig_matrix_z(0.5*(Lxn_jph+Rxn_jph), ctx)); // LAX-FRIEDRICHS FLUX const vcl_mat Fximh = 0.5*(comfi::routines::Fx(Lxn_imh, xn, ctx)+comfi::routines::Fx(Rxn_imh, xn, ctx)) -element_prod(a_imh, (Rxn_imh-Lxn_imh)); const vcl_mat Fxiph = 0.5*(comfi::routines::Fx(Lxn_iph, xn, ctx)+comfi::routines::Fx(Rxn_iph, xn, ctx)) -element_prod(a_iph, (Rxn_iph-Lxn_iph)); const vcl_mat Fzjmh = 0.5*(comfi::routines::Fz(Lxn_jmh, xn, ctx)+comfi::routines::Fz(Rxn_jmh, xn, ctx)) -element_prod(a_jmh, (Rxn_jmh-Lxn_jmh)); const vcl_mat Fzjph = 0.5*(comfi::routines::Fz(Lxn_jph, xn, ctx)+comfi::routines::Fz(Rxn_jph, xn, ctx)) -element_prod(a_jph, (Rxn_jph-Lxn_jph)); return -1.0*(Fxiph-Fximh)/ctx.dx -1.0*(Fzjph-Fzjmh)/ctx.dz; //+ prod(op.f2V, v_collission_source) //- prod(op.f2U, v_collission_source) //+ prod(op.f2U, u_collission_source) //- prod(op.f2V, u_collission_source); //+ prod(op.f2V, me_nu_J) //+ prod(op.f2V, vsource) //- prod(op.f2U, me_nu_J) //- prod(op.f2U, vsource) //- prod(op.SG, xn) //+ boundaryconditions //+ prod(op.s2Np, isource) //- prod(op.s2Nn, isource) //+ prod(op.s2Tp, TpdivV)/3.0; //+ prod(op.s2Tn, TndivU)/3.0; //+ prod(op.s2Tp, nuin_dV2)/3.0 //+ prod(op.s2Tn, nuni_dV2)/3.0 //- two_thirds*prod(op.s2Tn, L) //+ prod(op.f2B, gNpxJxBoverN2) // Hall term source term //- prod(op.f2B,gradrescrossJ); } vcl_mat comfi::routines::computeRHS_RK4(const vcl_mat &xn, comfi::types::Context &ctx) { const double dt = ctx.dt(); // RK-4 const vcl_mat k1 = Re_MUSCL(xn, ctx)*dt; //return xn+k1; //const vcl_mat k2 = Re_MUSCL(xn+0.5*k1,t+0.5*dt,op,bg)*dt; const vcl_mat k2 = Re_MUSCL(xn+0.5*k1, ctx)*dt; //const vcl_mat k3 = Re_MUSCL(xn+0.5*k2,t+0.5*dt,op,bg)*dt; const vcl_mat k3 = Re_MUSCL(xn+0.5*k2, ctx)*dt; //const vcl_mat k4 = Re_MUSCL(xn+k3,t+dt,op,bg)*dt; const vcl_mat k4 = Re_MUSCL(xn+k3, ctx)*dt; vcl_mat result = xn + (k1+2.0*k2+2.0*k3+k4)/6.0; // GLM exact solution ctx.v_GLM(result) *= std::exp(-ctx.alpha_p*ctx.dt()*ctx.c_h()/ctx.ds); return result; } vcl_mat comfi::routines::computeRHS_Euler(const vcl_mat &xn, comfi::types::Context &ctx) { // Simple Eulerian Steps vcl_mat result = xn + comfi::routines::Re_MUSCL(xn, ctx)*ctx.dt(); // GLM exact solution ctx.v_GLM(result) *= std::exp(-ctx.alpha_p*ctx.dt()*ctx.c_h()/ctx.ds); return result; } /* vcl_vec comfi::routines::computeRHS_BDF2(const vcl_vec &xn, const vcl_vec &xn1, const vcl_sp_mat &Ri, const double alpha, const double beta, const double dt, const double t, comfi::types::Operators &op, const comfi::types::BgData &bg) { // BDF2 static double dtn1 = dt; const vcl_vec Rin = prod(Ri,xn); const vcl_vec Re = comfi::routines::Re_MUSCL(xn,t,op,bg); const vcl_vec xnpRedt = xn+Re*dt; const vcl_vec result = xnpRedt + alpha*dt*(((xn-xn1)/dtn1)-Re) + beta*dt*Rin; //GLM const double a = 0.1; vcl_vec glm = prod(op.GLMs,xnpRedt); glm *= std::exp(-a*op.ch/(ds/dt)); dtn1=dt; return prod(op.ImGLM,result) + prod(op.s2GLM,glm); } */ vcl_mat comfi::routines::Fx(const vcl_mat &xn, const vcl_mat &xn_ij, comfi::types::Context &ctx) { vcl_mat F = viennacl::zero_matrix<double>(xn.size1(), xn.size2()); const vcl_mat V_x = element_div(ctx.v_NVx(xn), ctx.v_Np(xn)); const vcl_mat U_x = element_div(ctx.v_NUx(xn), ctx.v_Nn(xn)); const vcl_mat V_z = element_div(ctx.v_NVz(xn), ctx.v_Np(xn)); const vcl_mat U_z = element_div(ctx.v_NUz(xn), ctx.v_Nn(xn)); const vcl_mat V_p = element_div(ctx.v_NVp(xn), ctx.v_Np(xn)); const vcl_mat U_p = element_div(ctx.v_NUp(xn), ctx.v_Nn(xn)); // Local speed flux -> quantity*Vz ctx.v_Np(F) = element_prod(ctx.v_Np(xn), V_x); ctx.v_Nn(F) = element_prod(ctx.v_Nn(xn), U_x); ctx.v_NVx(F) = element_prod(ctx.v_NVx(xn), V_x); ctx.v_NVz(F) = element_prod(ctx.v_NVz(xn), V_x); ctx.v_NVp(F) = element_prod(ctx.v_NVp(xn), V_x); ctx.v_NUx(F) = element_prod(ctx.v_NUx(xn), U_x); ctx.v_NUz(F) = element_prod(ctx.v_NUz(xn), U_x); ctx.v_NUp(F) = element_prod(ctx.v_NUp(xn), U_x); ctx.v_Ep(F) = element_prod(ctx.v_Ep(xn), V_x); ctx.v_En(F) = element_prod(ctx.v_En(xn), U_x); // Induction VB-BV ctx.v_Bz(F) = element_prod(V_x, ctx.v_Bz(xn)) - element_prod(ctx.v_Bx(xn), V_z); ctx.v_Bp(F) = element_prod(V_x, ctx.v_Bp(xn)) - element_prod(ctx.v_Bx(xn), V_p); // General Lagrange Multiplier ctx.v_Bx(F) = ctx.v_GLM(xn); // Thermal pressure vcl_mat Pp = comfi::routines::pressure_p(xn, ctx); ctx.v_NVx(F) += Pp; vcl_mat Pn = comfi::routines::pressure_n(xn, ctx); ctx.v_NUx(F) += Pn; // Magnetic pressure const vcl_mat pmag = 0.5*(element_prod(ctx.v_Bx(xn), ctx.v_Bx(xn)) + element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn)) + element_prod(ctx.v_Bp(xn), ctx.v_Bp(xn))); ctx.v_NVx(F) += pmag; ctx.v_NVz(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn)); ctx.v_NVx(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bx(xn)); ctx.v_NVp(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bp(xn)); // Energy flux vcl_mat bdotv = element_prod(V_x, ctx.v_Bx(xn)) + element_prod(V_z, ctx.v_Bz(xn)) + element_prod(V_p, ctx.v_Bp(xn)); ctx.v_Ep(F) += element_prod(Pp+pmag, V_x) - element_prod(ctx.v_Bx(xn), bdotv); ctx.v_En(F) += element_prod(Pn, U_x); // Flux part of GLM ctx.v_GLM(F) = ctx.c_h()*ctx.c_h()*ctx.v_Bx(xn); return F; } vcl_mat comfi::routines::Fz(const vcl_mat &xn, const vcl_mat &xn_ij, comfi::types::Context &ctx) { vcl_mat F = viennacl::zero_matrix<double>(xn.size1(), xn.size2()); const vcl_mat V_x = element_div(ctx.v_NVx(xn), ctx.v_Np(xn)); const vcl_mat U_x = element_div(ctx.v_NUx(xn), ctx.v_Nn(xn)); const vcl_mat V_z = element_div(ctx.v_NVz(xn), ctx.v_Np(xn)); const vcl_mat U_z = element_div(ctx.v_NUz(xn), ctx.v_Nn(xn)); const vcl_mat V_p = element_div(ctx.v_NVp(xn), ctx.v_Np(xn)); const vcl_mat U_p = element_div(ctx.v_NUp(xn), ctx.v_Nn(xn)); // Local speed flux -> quantity*Vz ctx.v_Np(F) = element_prod(ctx.v_Np(xn), V_z); ctx.v_Nn(F) = element_prod(ctx.v_Nn(xn), U_z); ctx.v_NVx(F) = element_prod(ctx.v_NVx(xn), V_z); ctx.v_NVz(F) = element_prod(ctx.v_NVz(xn), V_z); ctx.v_NVp(F) = element_prod(ctx.v_NVp(xn), V_z); ctx.v_NUx(F) = element_prod(ctx.v_NUx(xn), U_z); ctx.v_NUz(F) = element_prod(ctx.v_NUz(xn), U_z); ctx.v_NUp(F) = element_prod(ctx.v_NUp(xn), U_z); ctx.v_Ep(F) = element_prod(ctx.v_Ep(xn), V_z); ctx.v_En(F) = element_prod(ctx.v_En(xn), U_z); // Induction VB-BV ctx.v_Bx(F) = element_prod(V_z, ctx.v_Bx(xn)) - element_prod(ctx.v_Bz(xn), V_x); ctx.v_Bp(F) = element_prod(V_z, ctx.v_Bp(xn)) - element_prod(ctx.v_Bz(xn), V_p); // General Lagrange Multiplier ctx.v_Bz(F) = ctx.v_GLM(xn); // Thermal pressure vcl_mat Pp = comfi::routines::pressure_p(xn, ctx); ctx.v_NVz(F) += Pp; vcl_mat Pn = comfi::routines::pressure_n(xn, ctx); ctx.v_NUz(F) += Pn; // Magnetic pressure const vcl_mat pmag = 0.5*(element_prod(ctx.v_Bx(xn), ctx.v_Bx(xn)) +element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn)) +element_prod(ctx.v_Bp(xn), ctx.v_Bp(xn))); ctx.v_NVz(F) += pmag; ctx.v_NVz(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn)); ctx.v_NVx(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bx(xn)); ctx.v_NVp(F) -= element_prod(ctx.v_Bz(xn), ctx.v_Bp(xn)); // Energy flux vcl_mat bdotv = element_prod(V_x, ctx.v_Bx(xn)) + element_prod(V_z, ctx.v_Bz(xn)) + element_prod(V_p, ctx.v_Bp(xn)); ctx.v_Ep(F) += element_prod(Pp+pmag, V_z) - element_prod(ctx.v_Bz(xn), bdotv); ctx.v_En(F) += element_prod(Pn, U_z); // Flux part of GLM ctx.v_GLM(F) = ctx.c_h()*ctx.c_h()*ctx.v_Bz(xn); return F; } vcl_mat comfi::routines::pressure_n(const vcl_mat &xn, comfi::types::Context &ctx) { vcl_mat Pn = ctx.v_NUx(xn); Pn = element_prod(Pn, ctx.v_NUx(xn)); Pn = Pn + element_prod(ctx.v_NUz(xn), ctx.v_NUz(xn)); Pn = Pn + element_prod(ctx.v_NUp(xn), ctx.v_NUp(xn)); Pn = 0.5*element_div(Pn, ctx.v_Nn(xn)); Pn = element_fabs((ctx.gammamono-1.0)*(ctx.v_En(xn)-Pn)); return Pn; } vcl_mat comfi::routines::sound_speed_p(const vcl_mat &xn, comfi::types::Context &ctx) { const vcl_mat Pp = comfi::routines::pressure_p(xn, ctx); return element_sqrt(element_div(ctx.gammamono*Pp, ctx.v_Np(xn))); } vcl_mat comfi::routines::sound_speed_n(const vcl_mat &xn, comfi::types::Context &ctx) { const vcl_mat Pn = comfi::routines::pressure_n(xn, ctx); return element_sqrt(element_div(ctx.gammamono*Pn, ctx.v_Nn(xn))); } vcl_mat comfi::routines::pressure_p(const vcl_mat &xn, comfi::types::Context &ctx) { using namespace viennacl::linalg; // Calculate pressures by total energy vcl_mat Pp = ctx.v_NVx(xn); Pp = element_prod(Pp, ctx.v_NVx(xn)); Pp = Pp + element_prod(ctx.v_NVz(xn), ctx.v_NVz(xn)); Pp = Pp + element_prod(ctx.v_NVp(xn), ctx.v_NVp(xn)); Pp = 0.5*element_div(Pp, ctx.v_Np(xn)); Pp = Pp + 0.5*element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn)); Pp = Pp + 0.5*element_prod(ctx.v_Bx(xn), ctx.v_Bx(xn)); Pp = Pp + 0.5*element_prod(ctx.v_Bp(xn), ctx.v_Bp(xn)); Pp = element_fabs((ctx.gammamono-1.0)*(ctx.v_Ep(xn)-Pp)); return Pp; } vcl_mat comfi::routines::fast_speed_x(const vcl_mat &xn, comfi::types::Context &ctx) { using namespace viennacl::linalg; // Calculate pressures by total energy vcl_mat k_e = element_prod(ctx.v_NVx(xn), ctx.v_NVx(xn)); k_e = k_e + element_prod(ctx.v_NVz(xn), ctx.v_NVz(xn)); k_e = k_e + element_prod(ctx.v_NVp(xn), ctx.v_NVp(xn)); k_e = 0.5*element_div(k_e, ctx.v_Np(xn)); vcl_mat b_e = 0.5*element_prod(ctx.v_Bx(xn), ctx.v_Bx(xn)); b_e = b_e + 0.5*element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn)); b_e = b_e + 0.5*element_prod(ctx.v_Bp(xn), ctx.v_Bp(xn)); const vcl_mat Ep = element_fabs(ctx.v_Ep(xn)); const vcl_mat Pp = element_fabs((ctx.gammamono-1.0)*(Ep - k_e - b_e)); const vcl_mat cps2 = ctx.gammamono*(element_div(Pp, ctx.v_Np(xn))); const vcl_mat cps = element_sqrt(cps2); const vcl_mat ca2 = element_div(2.0*b_e, ctx.v_Np(xn)); const vcl_mat cax = element_div(ctx.v_Bx(xn), element_sqrt(ctx.v_Np(xn))); const vcl_mat cpsca = element_prod(cps, cax); const vcl_mat cpsca2 = element_prod(cpsca, cpsca); const vcl_mat cp = 0.5*(element_sqrt(2.0*(cps2 + ca2 + element_sqrt(element_prod(cps2+ca2,cps2+ca2)-4.0*cpsca2)))); return cp; } vcl_mat comfi::routines::fast_speed_z(const vcl_mat &xn, comfi::types::Context &ctx) { using namespace viennacl::linalg; // Calculate pressures by total energy vcl_mat k_e = element_prod(ctx.v_NVx(xn), ctx.v_NVx(xn)); k_e = k_e + element_prod(ctx.v_NVz(xn), ctx.v_NVz(xn)); k_e = k_e + element_prod(ctx.v_NVp(xn), ctx.v_NVp(xn)); k_e = 0.5*element_div(k_e, ctx.v_Np(xn)); vcl_mat b_e = 0.5*element_prod(ctx.v_Bx(xn), ctx.v_Bx(xn)); b_e = b_e + 0.5*element_prod(ctx.v_Bz(xn), ctx.v_Bz(xn)); b_e = b_e + 0.5*element_prod(ctx.v_Bp(xn), ctx.v_Bp(xn)); const vcl_mat Ep = element_fabs(ctx.v_Ep(xn)); const vcl_mat Pp = element_fabs((ctx.gammamono-1.0)*(Ep - k_e - b_e)); const vcl_mat cps2 = ctx.gammamono*(element_div(Pp, ctx.v_Np(xn))); const vcl_mat cps = element_sqrt(cps2); const vcl_mat ca2 = element_div(2.0*b_e, ctx.v_Np(xn)); const vcl_mat caz = element_div(ctx.v_Bz(xn), element_sqrt(ctx.v_Np(xn))); const vcl_mat cpsca = element_prod(cps, caz); const vcl_mat cpsca2 = element_prod(cpsca, cpsca); const vcl_mat cp = 0.5*(element_sqrt(2.0*(cps2 + ca2 + element_sqrt(element_prod(cps2+ca2,cps2+ca2)-4.0*cpsca2)))); return cp; } vcl_vec comfi::routines::polyval(const arma::vec &p, const vcl_vec &x) { vcl_vec b = viennacl::zero_vector<double>(x.size()); for (int i = 0; i < p.size(); i++) { const vcl_vec a = viennacl::scalar_vector<double>(x.size(), p(i)); b = a + element_prod(b, x); } return b; } vcl_mat comfi::routines::fluxl(const vcl_mat &r) { static const vcl_mat ones = viennacl::scalar_matrix<double>(r.size1(), r.size2(), 1.0); const vcl_mat r2 = element_prod(r, r); // Ospre return 1.5*element_div(r2+r, r2+r+ones); // Van Albada //return element_div(r2+r, r2+ones); // Van Leer //const vcl_mat absr = element_fabs(r); //return element_div(r+absr, ones+absr); } void comfi::routines::bottombc_shock_tube(vcl_mat &Lxn, vcl_mat &Rxn, comfi::types::Context &ctx) { uint ij = inds(0, 0, ctx); Rxn(ij, ctx.n_n) = 0.125; Rxn(ij, ctx.n_p) = 0.125; Rxn(ij, ctx.E_p) = 0.1/(ctx.gammamono-1.0); Rxn(ij, ctx.E_n) = 0.1/(ctx.gammamono-1.0); Rxn(ij, ctx.Ux) = 0.0; Rxn(ij, ctx.Uz) = 0.0; Rxn(ij, ctx.Up) = 0.0; Rxn(ij, ctx.Vx) = 0.0; Rxn(ij, ctx.Vz) = 0.0; Rxn(ij, ctx.Vp) = 0.0; Lxn(ij, ctx.n_n) = 0.125; Lxn(ij, ctx.n_p) = 0.125; Lxn(ij, ctx.E_p) = 0.1/(ctx.gammamono-1.0); Lxn(ij, ctx.E_n) = 0.1/(ctx.gammamono-1.0); Lxn(ij, ctx.Ux) = 0.0; Lxn(ij, ctx.Uz) = 0.0; Lxn(ij, ctx.Up) = 0.0; Lxn(ij, ctx.Vx) = 0.0; Lxn(ij, ctx.Vz) = 0.0; Lxn(ij, ctx.Vp) = 0.0; } void comfi::routines::topbc_shock_tube(vcl_mat &Lxn, vcl_mat &Rxn, comfi::types::Context &ctx) { uint ij = inds(0, ctx.nz-1, ctx); Rxn(ij, ctx.n_n) = 1.0; Rxn(ij, ctx.n_p) = 1.0; Rxn(ij, ctx.E_p) = 1.0/(ctx.gammamono-1.0); Rxn(ij, ctx.E_n) = 1.0/(ctx.gammamono-1.0); Rxn(ij, ctx.Ux) = 0.0; Rxn(ij, ctx.Uz) = 0.0; Rxn(ij, ctx.Up) = 0.0; Rxn(ij, ctx.Vx) = 0.0; Rxn(ij, ctx.Vz) = 0.0; Rxn(ij, ctx.Vp) = 0.0; Lxn(ij, ctx.n_n) = 1.0; Lxn(ij, ctx.n_p) = 1.0; Lxn(ij, ctx.E_p) = 1.0/(ctx.gammamono-1.0); Lxn(ij, ctx.E_n) = 1.0/(ctx.gammamono-1.0); Lxn(ij, ctx.Ux) = 0.0; Lxn(ij, ctx.Uz) = 0.0; Lxn(ij, ctx.Up) = 0.0; Lxn(ij, ctx.Vx) = 0.0; Lxn(ij, ctx.Vz) = 0.0; Lxn(ij, ctx.Vp) = 0.0; } /* vim: tabstop=2 vim: shiftwidth=2 vim: smarttab vim: expandtab */
44.667606
118
0.611087
[ "vector" ]
da6a21804e0efabb782be0acc786e722b714c133
1,850
cpp
C++
baxter_bridge/src/topic_poller.cpp
CentraleNantesRobotics/baxter_common_ros2
29079623574c383efa47b0e7e16793c44dd266b6
[ "BSD-3-Clause" ]
6
2020-06-02T17:16:29.000Z
2021-11-30T20:23:26.000Z
baxter_bridge/src/topic_poller.cpp
CentraleNantesRobotics/baxter_common_ros2
29079623574c383efa47b0e7e16793c44dd266b6
[ "BSD-3-Clause" ]
null
null
null
baxter_bridge/src/topic_poller.cpp
CentraleNantesRobotics/baxter_common_ros2
29079623574c383efa47b0e7e16793c44dd266b6
[ "BSD-3-Clause" ]
null
null
null
#include <baxter_bridge/topic_poller.h> #include <baxter_bridge/factory.h> namespace baxter_bridge { TopicPoller::TopicPoller(rclcpp::Node* node2) : node2{node2} { poller = node2->create_wall_timer(std::chrono::seconds(1), [&](){poll();}); } void TopicPoller::poll() { const auto info1{[]() {ros::master::V_TopicInfo info; ros::master::getTopics(info);return info;}()}; const auto info2{node2->get_topic_names_and_types()}; ros1_published.clear(); ros1_subscribed.clear(); ros2_published.clear(); ros2_subscribed.clear(); // only register topics that have not been bridged for(const auto &info: info1) { const auto &topic{info.name}; if(Factory::isPublishedByBaxter(topic)) ros1_published.push_back(topic); else if(Factory::isSubscribedByBaxter(topic)) ros1_subscribed.push_back(topic); } for(const auto &[topic, msg]: info2) { if(Factory::isPublishedByBaxter(topic)) ros2_subscribed.push_back(topic); else if(Factory::isSubscribedByBaxter(topic)) ros2_published.push_back(topic); } std::sort(ros1_published.begin(), ros1_published.end()); std::sort(ros1_subscribed.begin(), ros1_subscribed.end()); std::sort(ros2_published.begin(), ros2_published.end()); std::sort(ros2_subscribed.begin(), ros2_subscribed.end()); } std::vector<std::string> TopicPoller::pendingBridges() const { std::vector<std::string> pending; std::set_intersection(ros1_published.begin(),ros1_published.end(), ros2_subscribed.begin(),ros2_subscribed.end(), back_inserter(pending)); std::set_intersection(ros2_published.begin(),ros2_published.end(), ros1_subscribed.begin(),ros1_subscribed.end(), back_inserter(pending)); return pending; } }
29.365079
77
0.671351
[ "vector" ]
da6b8597d43dfe9c2a19f52c47c87b522fad7ea6
12,957
cpp
C++
darkness-engine/include/shaders/core/tools/cleartexture/ClearTexture1du4.cs.cpp
Karmiska/Darkness
c87eaf067a2707a0141909125ff461f69a3812e0
[ "MIT" ]
6
2019-10-17T11:31:55.000Z
2022-02-11T08:51:20.000Z
darkness-engine/include/shaders/core/tools/cleartexture/ClearTexture1du4.cs.cpp
Karmiska/Darkness
c87eaf067a2707a0141909125ff461f69a3812e0
[ "MIT" ]
1
2020-08-11T09:01:29.000Z
2020-08-11T09:01:29.000Z
darkness-engine/include/shaders/core/tools/cleartexture/ClearTexture1du4.cs.cpp
Karmiska/Darkness
c87eaf067a2707a0141909125ff461f69a3812e0
[ "MIT" ]
1
2020-06-02T15:48:20.000Z
2020-06-02T15:48:20.000Z
#include "ClearTexture1du4.cs.h" #include "engine/graphics/ShaderStorage.h" #include "engine/graphics/Sampler.h" #include "tools/ByteRange.h" #include "tools/Debug.h" #include <memory> namespace engine { namespace shaders { #pragma warning( push ) #pragma warning( disable : 4702 ) std::shared_ptr<const ShaderBinary> ClearTexture1du4CS::load(const Device& device, ShaderStorage& storage) const { return storage.loadShader(device, "C:/work/darkness/darkness-engine/data/shaders/vulkan/core/tools/cleartexture/ClearTexture1du4.cs.spv", "C:/work/darkness/darkness-engine/data/shaders/vulkan/core/tools/cleartexture/ClearTexture1du4.cs.support", -1, {}); ASSERT(false, "Could not load the permutation necessary. This is a bug."); return {}; } #pragma warning( pop ) ClearTexture1du4CS::ClearTexture1du4CS() : m_constantRange{ ConstantRange{ tools::ByteRange( reinterpret_cast<const uint8_t*>(static_cast<const ClearConstants*>(this)), reinterpret_cast<const uint8_t*>(static_cast<const ClearConstants*>(this)) + sizeof(ClearConstants)), nullptr, "ClearConstants" } } , m_inputParameters { ShaderInputParameter{"dispatchThreadID", "SV_DispatchThreadID", "uint3"} } {} #pragma warning( push ) #pragma warning( disable : 4100 ) ClearTexture1du4CS::ClearTexture1du4CS(const ClearTexture1du4CS& cl) : m_constantRange{ ConstantRange{ tools::ByteRange( reinterpret_cast<const uint8_t*>(static_cast<const ClearConstants*>(this)), reinterpret_cast<const uint8_t*>(static_cast<const ClearConstants*>(this)) + sizeof(ClearConstants)), nullptr, "ClearConstants" } } { for (int i = 0; i < m_constantRange.size(); ++i) { m_constantRange[i].buffer = cl.m_constantRange[i].buffer; } tex = cl.tex; } #pragma warning( pop ) #pragma warning( push ) #pragma warning( disable : 4100 ) ClearTexture1du4CS::ClearTexture1du4CS(ClearTexture1du4CS&& cl) : m_constantRange{ ConstantRange{ tools::ByteRange( reinterpret_cast<const uint8_t*>(static_cast<const ClearConstants*>(this)), reinterpret_cast<const uint8_t*>(static_cast<const ClearConstants*>(this)) + sizeof(ClearConstants)), nullptr, "ClearConstants" } } { for (int i = 0; i < m_constantRange.size(); ++i) { m_constantRange[i].buffer = std::move(cl.m_constantRange[i].buffer); } tex = std::move(cl.tex); } #pragma warning( pop ) #pragma warning( push ) #pragma warning( disable : 4100 ) ClearTexture1du4CS& ClearTexture1du4CS::operator=(const ClearTexture1du4CS& cl) { for (int i = 0; i < m_constantRange.size(); ++i) { m_constantRange[i].buffer = cl.m_constantRange[i].buffer; } tex = cl.tex; return *this; } #pragma warning( pop ) #pragma warning( push ) #pragma warning( disable : 4100 ) ClearTexture1du4CS& ClearTexture1du4CS::operator=(ClearTexture1du4CS&& cl) { for (int i = 0; i < m_constantRange.size(); ++i) { m_constantRange[i].buffer = std::move(cl.m_constantRange[i].buffer); } tex = std::move(cl.tex); return *this; } #pragma warning( pop ) std::vector<std::string> ClearTexture1du4CS::textureSrvNames() const { return { }; } std::vector<std::string> ClearTexture1du4CS::textureUavNames() const { return { "tex" }; } std::vector<std::string> ClearTexture1du4CS::bufferSrvNames() const { return { }; } std::vector<std::string> ClearTexture1du4CS::bufferUavNames() const { return { }; } std::vector<std::string> ClearTexture1du4CS::samplerNames() const { return { }; } std::vector<std::string> ClearTexture1du4CS::srvNames() const { return { }; } std::vector<std::string> ClearTexture1du4CS::uavNames() const { return { "tex" }; } #pragma warning( push ) #pragma warning( disable : 4100 ) engine::ResourceDimension ClearTexture1du4CS::textureDimension(const std::string& name) const { if("tex" == name) return engine::ResourceDimension::Texture1D; return engine::ResourceDimension::Unknown; } #pragma warning( pop ) std::vector<TextureSRV> ClearTexture1du4CS::texture_srvs() const { std::vector<TextureSRV> result; return result; } std::vector<TextureUAV> ClearTexture1du4CS::texture_uavs() const { std::vector<TextureUAV> result; result.emplace_back(tex); return result; } std::vector<BufferSRV> ClearTexture1du4CS::buffer_srvs() const { std::vector<BufferSRV> result; return result; } std::vector<BufferUAV> ClearTexture1du4CS::buffer_uavs() const { std::vector<BufferUAV> result; return result; } std::vector<TextureBindlessSRV> ClearTexture1du4CS::bindless_texture_srvs() const { std::vector<TextureBindlessSRV> result; return result; } std::vector<TextureBindlessUAV> ClearTexture1du4CS::bindless_texture_uavs() const { std::vector<TextureBindlessUAV> result; return result; } std::vector<BufferBindlessSRV> ClearTexture1du4CS::bindless_buffer_srvs() const { std::vector<BufferBindlessSRV> result; return result; } std::vector<BufferBindlessUAV> ClearTexture1du4CS::bindless_buffer_uavs() const { std::vector<BufferBindlessUAV> result; return result; } std::vector<Shader::ConstantRange>& ClearTexture1du4CS::constants() { return m_constantRange; } std::vector<Sampler> ClearTexture1du4CS::samplers() const { std::vector<Sampler> result; return result; } const std::vector<ShaderInputParameter>& ClearTexture1du4CS::inputParameters() const { return m_inputParameters; } // warning C4172: returning address of local variable or temporary // this will never happen as the name will always match the correct resource #pragma warning( push ) #pragma warning( disable : 4172 ) #pragma warning( disable : 4100 ) bool ClearTexture1du4CS::hasTextureSrv(const std::string& name) const { return false; } bool ClearTexture1du4CS::hasTextureUav(const std::string& name) const { if (name == std::string("tex")) return true; return false; } bool ClearTexture1du4CS::hasBufferSrv(const std::string& name) const { return false; } bool ClearTexture1du4CS::hasBufferUav(const std::string& name) const { return false; } bool ClearTexture1du4CS::hasBindlessTextureSrv(const std::string& name) const { return false; } bool ClearTexture1du4CS::hasBindlessTextureUav(const std::string& name) const { return false; } bool ClearTexture1du4CS::hasBindlessBufferSrv(const std::string& name) const { return false; } bool ClearTexture1du4CS::hasBindlessBufferUav(const std::string& name) const { return false; } const TextureSRV& ClearTexture1du4CS::textureSrv(const std::string& name) const { ASSERT(false, "Tried to look for non-existing resource"); return TextureSRV(); } const TextureUAV& ClearTexture1du4CS::textureUav(const std::string& name) const { if(name == std::string("tex")) return tex; ASSERT(false, "Tried to look for non-existing resource"); return TextureUAV(); } const BufferSRV& ClearTexture1du4CS::bufferSrv(const std::string& name) const { ASSERT(false, "Tried to look for non-existing resource"); return BufferSRV(); } const BufferUAV& ClearTexture1du4CS::bufferUav(const std::string& name) const { ASSERT(false, "Tried to look for non-existing resource"); return BufferUAV(); } void ClearTexture1du4CS::textureSrv(const std::string& name, TextureSRV& texture) { ASSERT(false, "Tried to set non-existing resource"); } void ClearTexture1du4CS::textureUav(const std::string& name, TextureUAV& texture) { if(name == std::string("tex")) { tex = texture; return; } ASSERT(false, "Tried to set non-existing resource"); } void ClearTexture1du4CS::bufferSrv(const std::string& name, BufferSRV& buffer) { ASSERT(false, "Tried to set non-existing resource"); } void ClearTexture1du4CS::bufferUav(const std::string& name, BufferUAV& buffer) { ASSERT(false, "Tried to set non-existing resource"); } const Sampler& ClearTexture1du4CS::sampler(const std::string& name) const { ASSERT(false, "Tried to look for non-existing resource"); return Sampler(); } const TextureBindlessSRV& ClearTexture1du4CS::bindlessTextureSrv(const std::string& name) const { ASSERT(false, "Tried to look for non-existing resource"); return TextureBindlessSRV(); } const TextureBindlessUAV& ClearTexture1du4CS::bindlessTextureUav(const std::string& name) const { ASSERT(false, "Tried to look for non-existing resource"); return TextureBindlessUAV(); } const BufferBindlessSRV& ClearTexture1du4CS::bindlessBufferSrv(const std::string& name) const { ASSERT(false, "Tried to look for non-existing resource"); return BufferBindlessSRV(); } const BufferBindlessUAV& ClearTexture1du4CS::bindlessBufferUav(const std::string& name) const { ASSERT(false, "Tried to look for non-existing resource"); return BufferBindlessUAV(); } #pragma warning( pop ) uint32_t ClearTexture1du4CS::descriptorCount() const { return 2; } } }
25.159223
266
0.498881
[ "vector" ]
da79ad085a7e2082a4e9e818eef91252b1e0c80b
14,523
cpp
C++
Testing/BlockValueComparisonTests.cpp
ncorgan/PothosArrayFire
b2ce286827cefdc45507dbae65879a943e977479
[ "BSD-3-Clause" ]
2
2021-01-19T02:21:48.000Z
2022-03-26T23:05:49.000Z
Testing/BlockValueComparisonTests.cpp
ncorgan/PothosArrayFire
b2ce286827cefdc45507dbae65879a943e977479
[ "BSD-3-Clause" ]
3
2020-07-26T18:48:21.000Z
2020-10-28T00:45:42.000Z
Testing/BlockValueComparisonTests.cpp
pothosware/PothosArrayFire
b2ce286827cefdc45507dbae65879a943e977479
[ "BSD-3-Clause" ]
1
2022-03-24T06:22:20.000Z
2022-03-24T06:22:20.000Z
// Copyright (c) 2020 Nicholas Corgan // SPDX-License-Identifier: BSD-3-Clause #include "TestUtility.hpp" #include <Pothos/Testing.hpp> #include <Pothos/Framework.hpp> #include <Pothos/Proxy.hpp> #include <Poco/Format.h> #include <complex> #include <iostream> #include <vector> struct TestBlockNames { std::string pothosBlock; std::string pothosGPUBlock; }; struct ValueCompareBlockParams { Pothos::Proxy block; std::vector<std::string> sourceChans; std::vector<std::string> sinkChans; }; struct ValueCompareParams { ValueCompareBlockParams pothosBlockParams; ValueCompareBlockParams pothosGPUBlockParams; Pothos::DType sourceDType; Pothos::DType sinkDType; }; template <typename T> static bool isClose(T t0, T t1) { return (std::abs(t0-t1) < 1e-6); } static void compareIOBlockValues(const ValueCompareParams& params) { std::cout << Poco::format( " * Testing %s vs %s (%s -> %s)...", params.pothosBlockParams.block.call<std::string>("getName"), params.pothosGPUBlockParams.block.call<std::string>("getName"), params.sourceDType.name(), params.sinkDType.name()) << std::endl; POTHOS_TEST_EQUAL( params.pothosBlockParams.sourceChans.size(), params.pothosGPUBlockParams.sourceChans.size()); POTHOS_TEST_EQUAL( params.pothosBlockParams.sinkChans.size(), params.pothosGPUBlockParams.sinkChans.size()); const auto numSourceChans = params.pothosBlockParams.sourceChans.size(); const auto numSinkChans = params.pothosBlockParams.sinkChans.size(); std::vector<Pothos::Proxy> sources(numSourceChans); std::vector<Pothos::Proxy> subBlocks(numSinkChans); std::vector<Pothos::Proxy> meanBlocks(numSinkChans); std::vector<Pothos::Proxy> stdevBlocks(numSinkChans); std::vector<Pothos::Proxy> medianBlocks(numSinkChans); std::vector<Pothos::Proxy> medAbsDevBlocks(numSinkChans); for(size_t chan = 0; chan < numSourceChans; ++chan) { sources[chan] = Pothos::BlockRegistry::make( "/blocks/feeder_source", params.sourceDType); sources[chan].call( "feedBuffer", GPUTests::getTestInputs(params.sourceDType.name())); } for(size_t chan = 0; chan < numSinkChans; ++chan) { subBlocks[chan] = Pothos::BlockRegistry::make( "/gpu/array/arithmetic", "Auto", "Subtract", params.sinkDType, 2); meanBlocks[chan] = Pothos::BlockRegistry::make( "/gpu/statistics/mean", "Auto", params.sinkDType); stdevBlocks[chan] = Pothos::BlockRegistry::make( "/gpu/statistics/stdev", "Auto", params.sinkDType); medianBlocks[chan] = Pothos::BlockRegistry::make( "/gpu/statistics/median", "Auto", params.sinkDType); medAbsDevBlocks[chan] = Pothos::BlockRegistry::make( "/gpu/statistics/medabsdev", "Auto", params.sinkDType); } { Pothos::Topology topology; for(size_t chan = 0; chan < numSourceChans; ++chan) { topology.connect( sources[chan], 0, params.pothosBlockParams.block, params.pothosBlockParams.sourceChans[chan]); topology.connect( sources[chan], 0, params.pothosGPUBlockParams.block, params.pothosGPUBlockParams.sourceChans[chan]); } for(size_t chan = 0; chan < numSinkChans; ++chan) { topology.connect( params.pothosBlockParams.block, params.pothosBlockParams.sinkChans[chan], subBlocks[chan], 0); topology.connect( params.pothosGPUBlockParams.block, params.pothosGPUBlockParams.sinkChans[chan], subBlocks[chan], 1); topology.connect( subBlocks[chan], 0, meanBlocks[chan], 0); topology.connect( subBlocks[chan], 0, stdevBlocks[chan], 0); topology.connect( subBlocks[chan], 0, medianBlocks[chan], 0); topology.connect( subBlocks[chan], 0, medAbsDevBlocks[chan], 0); } topology.commit(); POTHOS_TEST_TRUE(topology.waitInactive(0.01)); } for(size_t chan = 0; chan < numSinkChans; ++chan) { const auto mean = meanBlocks[chan].call<double>("lastValue"); const auto stdev = stdevBlocks[chan].call<double>("lastValue"); const auto median = medianBlocks[chan].call<double>("lastValue"); const auto medAbsDev = medAbsDevBlocks[chan].call<double>("lastValue"); std::string outputString; if(!isClose(mean, 0.0) || !isClose(stdev, 0.0) || !isClose(median, 0.0) || !isClose(medAbsDev, 0.0)) { outputString = Poco::format( " * %z mean difference: %f +- %f", chan, mean, stdev); std::cout << outputString << std::endl; outputString = Poco::format( " * %z median difference: %f +- %f", chan, median, medAbsDev); std::cout << outputString << std::endl; } } } static void testTrigBlock( const std::string& pothosGPUBlockPath, const std::string& pothosCommsOperation) { std::vector<Pothos::DType> dtypes = {"float32", "float64"}; for(const auto& dtype: dtypes) { ValueCompareParams params = { { Pothos::BlockRegistry::make("/comms/trigonometric", dtype, pothosCommsOperation), {"0"}, {"0"} }, { Pothos::BlockRegistry::make(pothosGPUBlockPath, "Auto", dtype), {"0"}, {"0"} }, dtype, dtype }; compareIOBlockValues(params); } } static void testConverterBlock(const Pothos::DType& inputDType) { std::vector<Pothos::DType> outputDTypes = {"int32", "int64", "uint32", "uint64", "float32", "float64"}; for(const auto& outputDType: outputDTypes) { ValueCompareParams params = { { Pothos::BlockRegistry::make("/blocks/converter", outputDType), {"0"}, {"0"} }, { Pothos::BlockRegistry::make("/gpu/array/cast", "Auto", inputDType, outputDType), {"0"}, {"0"} }, inputDType, outputDType }; compareIOBlockValues(params); } } static void testPowBlock(const Pothos::DType& dtype) { const auto powers = GPUTests::linspace<double>(0.0, 10.0, 11); for(auto power: powers) { ValueCompareParams params = { { Pothos::BlockRegistry::make("/comms/pow", dtype, power), {"0"}, {"0"} }, { Pothos::BlockRegistry::make("/gpu/arith/pow", "Auto", dtype, power), {"0"}, {"0"} }, dtype, dtype }; const auto& pothosBlock = params.pothosBlockParams.block; const auto& pothosGPUBlock = params.pothosGPUBlockParams.block; pothosBlock.call( "setName", Poco::format( "%s(%f)", pothosBlock.call<std::string>("getName"), power)); pothosGPUBlock.call( "setName", Poco::format( "%s(%f)", pothosGPUBlock.call<std::string>("getName"), power)); compareIOBlockValues(params); } } static void testRootBlock(const Pothos::DType& dtype) { const std::vector<size_t> roots{1,2,3,4}; for(auto root: roots) { ValueCompareParams params = { { Pothos::BlockRegistry::make("/comms/nth_root", dtype, root), {"0"}, {"0"} }, { Pothos::BlockRegistry::make("/gpu/arith/root", "Auto", dtype, root), {"0"}, {"0"} }, dtype, dtype }; const auto& pothosBlock = params.pothosBlockParams.block; const auto& pothosGPUBlock = params.pothosGPUBlockParams.block; pothosBlock.call( "setName", Poco::format( "%s(%z)", pothosBlock.call<std::string>("getName"), root)); pothosGPUBlock.call( "setName", Poco::format( "%s(%z)", pothosGPUBlock.call<std::string>("getName"), root)); compareIOBlockValues(params); } } static void testLogBlock(const Pothos::DType& dtype) { const std::vector<size_t> bases{2,5,10}; for(auto base: bases) { ValueCompareParams params = { { Pothos::BlockRegistry::make("/comms/logN", dtype, base), {"0"}, {"0"} }, { Pothos::BlockRegistry::make("/gpu/arith/log", "Auto", dtype, base), {"0"}, {"0"} }, dtype, dtype }; const auto& pothosBlock = params.pothosBlockParams.block; const auto& pothosGPUBlock = params.pothosGPUBlockParams.block; pothosBlock.call( "setName", Poco::format( "%s(%z)", pothosBlock.call<std::string>("getName"), base)); pothosGPUBlock.call( "setName", Poco::format( "%s(%z)", pothosGPUBlock.call<std::string>("getName"), base)); compareIOBlockValues(params); } } POTHOS_TEST_BLOCK("/gpu/tests", compare_pothos_block_outputs) { std::vector<TestBlockNames> oneChanFloatBlocks = { {"/comms/abs", "/gpu/arith/abs"}, {"/blocks/floor", "/gpu/arith/floor"}, {"/blocks/ceil", "/gpu/arith/ceil"}, {"/blocks/trunc", "/gpu/arith/trunc"}, {"/comms/gamma", "/gpu/arith/tgamma"}, {"/comms/lngamma", "/gpu/arith/lgamma"}, {"/comms/sinc", "/gpu/signal/sinc"}, {"/comms/log1p", "/gpu/arith/log1p"}, {"/comms/rsqrt", "/gpu/arith/rsqrt"}, }; for(const auto& block: oneChanFloatBlocks) { if(GPUTests::doesBlockExist(block.pothosBlock)) { std::vector<Pothos::DType> dtypes = {"float32", "float64"}; for(const auto& dtype: dtypes) { ValueCompareParams params = { { Pothos::BlockRegistry::make(block.pothosBlock, dtype), {"0"}, {"0"} }, { Pothos::BlockRegistry::make(block.pothosGPUBlock, "Auto", dtype), {"0"}, {"0"} }, dtype, dtype }; compareIOBlockValues(params); } } else std::cout << " * Could not find " << block.pothosBlock << ". Skipping." << std::endl; } if(GPUTests::doesBlockExist("/comms/trigonometric")) { testTrigBlock("/gpu/arith/cos", "COS"); testTrigBlock("/gpu/arith/sin", "SIN"); testTrigBlock("/gpu/arith/tan", "TAN"); testTrigBlock("/gpu/arith/sec", "SEC"); testTrigBlock("/gpu/arith/csc", "CSC"); testTrigBlock("/gpu/arith/cot", "COT"); testTrigBlock("/gpu/arith/acos", "ACOS"); testTrigBlock("/gpu/arith/asin", "ASIN"); testTrigBlock("/gpu/arith/atan", "ATAN"); testTrigBlock("/gpu/arith/asec", "ASEC"); testTrigBlock("/gpu/arith/acsc", "ACSC"); testTrigBlock("/gpu/arith/acot", "ACOT"); testTrigBlock("/gpu/arith/cosh", "COSH"); testTrigBlock("/gpu/arith/sinh", "SINH"); testTrigBlock("/gpu/arith/tanh", "TANH"); testTrigBlock("/gpu/arith/sech", "SECH"); testTrigBlock("/gpu/arith/csch", "CSCH"); testTrigBlock("/gpu/arith/coth", "COTH"); testTrigBlock("/gpu/arith/acosh", "ACOSH"); testTrigBlock("/gpu/arith/asinh", "ASINH"); testTrigBlock("/gpu/arith/atanh", "ATANH"); testTrigBlock("/gpu/arith/asech", "ASECH"); testTrigBlock("/gpu/arith/acsch", "ACSCH"); testTrigBlock("/gpu/arith/acoth", "ACOTH"); } else std::cout << " * Could not find /comms/trigonometric. Skipping." << std::endl; if(GPUTests::doesBlockExist("/blocks/converter")) { testConverterBlock("int16"); testConverterBlock("int32"); testConverterBlock("int64"); testConverterBlock("uint8"); testConverterBlock("uint16"); testConverterBlock("uint32"); testConverterBlock("uint64"); testConverterBlock("float32"); testConverterBlock("float64"); } else std::cout << " * Could not find /blocks/converter. Skipping." << std::endl; if(GPUTests::doesBlockExist("/comms/pow")) { testPowBlock("float32"); testPowBlock("float64"); } if(GPUTests::doesBlockExist("/comms/nth_root")) { testRootBlock("float32"); testRootBlock("float64"); } if(GPUTests::doesBlockExist("/comms/logN")) { testLogBlock("float32"); testLogBlock("float64"); } }
31.032051
108
0.502513
[ "vector" ]
da85f1080c813f9f5f0590d66def851451d8b8ed
6,430
cpp
C++
shape.cpp
txxiaobp/tiny-adams
c3cd12b350e7045f14cc42c1f43feebbe9c959a7
[ "MulanPSL-1.0" ]
null
null
null
shape.cpp
txxiaobp/tiny-adams
c3cd12b350e7045f14cc42c1f43feebbe9c959a7
[ "MulanPSL-1.0" ]
null
null
null
shape.cpp
txxiaobp/tiny-adams
c3cd12b350e7045f14cc42c1f43feebbe9c959a7
[ "MulanPSL-1.0" ]
null
null
null
#include "shape.h" #include "solid.h" #include "pub_include.h" #include <cassert> #include <QDebug> #include <map> #include <QPainter> std::unordered_map<int, Shape*> Shape::shapeMap; std::unordered_set<Shape*> Shape::chosenShapeSet; int Shape::globalShapeCount = 0; Shape* Shape::currentCapturedShape = nullptr; Shape::Shape(int solidId, QColor shapeColor, Qt::PenStyle shapeStyle, int shapeWidth, int shapeChosenWidth) : isChosen(false) , isCaptured(false) , ready(false) , shapeColor(shapeColor) , shapeStyle(shapeStyle) , shapeWidth(shapeWidth) , shapeChosenWidth(shapeChosenWidth) , shapeId(globalShapeCount++) , solidId(solidId) , currentCapturedPoint(nullptr) { assert(shapeMap.find(shapeId) == shapeMap.end()); shapeMap.insert(std::make_pair(shapeId, this)); } Shape::Shape(QColor shapeColor, Qt::PenStyle shapeStyle, int shapeWidth, int shapeChosenWidth) : isChosen(false) , isCaptured(false) , ready(false) , shapeColor(shapeColor) , shapeStyle(shapeStyle) , shapeWidth(shapeWidth) , shapeChosenWidth(shapeChosenWidth) , shapeId(globalShapeCount++) , solidId(INVALID_ID) , currentCapturedPoint(nullptr) { assert(Shape::shapeMap.find(shapeId) == Shape::shapeMap.end()); Shape::shapeMap.insert(std::make_pair(shapeId, this)); } Shape::~Shape() { assert(Shape::shapeMap.find(shapeId) != Shape::shapeMap.end()); Shape::shapeMap.erase(shapeId); // if (Shape::chosenShapeSet.find(this) != Shape::chosenShapeSet.end()) // { // Shape::chosenShapeSet.erase(this); // } } Shape* Shape::getNearestShape(QPoint& mousePoint) { std::map<double, Shape*> map; for (auto shapeMapPair : shapeMap) { double distance = shapeMapPair.second->calDistance(mousePoint); if (distance <= DISTANCE_THRESHOLD) { map.insert(std::make_pair(distance, shapeMapPair.second)); } else { shapeMapPair.second->setCaptured(false); } } if (map.empty()) { return nullptr; } return map.begin()->second; } void Shape::captureNearestShape(QPoint& mousePoint) { Shape *shape = Shape::getNearestShape(mousePoint); if (nullptr != shape) { shape->setCaptured(true); shape->capturePoint(mousePoint); } } int Shape::getShapeId() const { return shapeId; } void Shape::setChosen(bool isChosen) { this->isChosen = isChosen; } void Shape::setCaptured(bool isCaptured) { this->isCaptured = isCaptured; if (isCaptured) { Shape::currentCapturedShape = this; } else { Shape::currentCapturedShape = nullptr; currentCapturedPoint = nullptr; } } bool Shape::isChosenOrCaptured() const { return isChosen || isCaptured; } int Shape::getSolidId() const { return solidId; } void Shape::chooseShape(QPoint& mousePoint, bool isMultiple) { Shape::captureNearestShape(mousePoint); /* 如果不是多选,清空已选Set */ if (!isMultiple) { Shape::clearChosenSet(); } /* 如果是多选,继续添加 */ if (currentCapturedShape) { Solid *solid = Solid::getSolidById(currentCapturedShape->getSolidId()); if (nullptr != solid) { solid->setChosen(true); } else { Shape::pushChosenSet(currentCapturedShape); } } else { Shape::clearChosenSet(); } } void Shape::pushChosenSet(Shape *shape) { assert(shape); shape->setChosen(true); chosenShapeSet.insert(shape); } void Shape::clearChosenSet() { for (Shape *shape : chosenShapeSet) { shape->setChosen(false); } chosenShapeSet.clear(); } void Shape::setPainter(QPainter *qPainter) { if (isChosenOrCaptured()) { QPen pen(shapeColor, shapeChosenWidth); pen.setStyle(shapeStyle); qPainter->setPen(pen);//设置画笔形式 } else { QPen pen(shapeColor, shapeWidth); pen.setStyle(shapeStyle); qPainter->setPen(pen);//设置画笔形式 } } void Shape::setPointPainter(QPainter *qPainter) { QPen pen(Qt::red, 2); pen.setStyle(Qt::SolidLine); qPainter->setPen(pen);//设置画笔形式 } void Shape::deleteShapes() { for (Shape *shape : Shape::chosenShapeSet) { if (nullptr != shape) { delete shape; shape = nullptr; } } Shape::chosenShapeSet.clear(); } std::vector<Shape*> Shape::getShapes() { std::vector<Shape*> shapeVec; for (auto shapeMapPair : shapeMap) { shapeVec.push_back(shapeMapPair.second); } return shapeVec; } void Shape::showPoint(QPoint &point, QPainter *qPainter) { const int pointRecSideLength = 4; setPointPainter(qPainter); qPainter->drawRect(point.x() - pointRecSideLength, point.y() - pointRecSideLength, 2 * pointRecSideLength, 2 * pointRecSideLength); } void Shape::showPoints(QPainter *qPainter) { if (!isReady()) { return; } if (isChosen) { for (QPoint *point : pointVec) { showPoint(*point, qPainter); } } if (currentCapturedPoint) { showPoint(*currentCapturedPoint, qPainter); } } QPoint* Shape::getCapturedPoint() { return currentCapturedPoint; } Shape* Shape::getCurrentCapturedShape() { return Shape::currentCapturedShape; } QPoint* Shape::getCurrentCapturedPoint() { Shape* shape = Shape::getCurrentCapturedShape(); if (!shape) { return nullptr; } return shape->getCapturedPoint(); } Vector Shape::getUnitVec(QPoint &startPoint, QPoint &endPoint) { Vector retVec(2, 1); double length = Shape::calDistance(startPoint, endPoint); retVec[0] = (endPoint.x() - startPoint.x()) / length; retVec[1] = (endPoint.y() - startPoint.y()) / length; return retVec; } Vector Shape::getPerpendicularVec(QPoint &startPoint, QPoint &endPoint) { Matrix rotateMatrix = Shape::getRotateMatrix(M_PI / 2); Vector unitVec = Shape::getUnitVec(startPoint, endPoint); return rotateMatrix * unitVec; } Matrix Shape::getRotateMatrix(double theta) { std::vector<double> vec{ cos(theta), -sin(theta), sin(theta), cos(theta) }; return Matrix(vec, 2, 2); } void Shape::setSolid(const int solidId) { this->solidId = solidId; }
21.505017
107
0.62846
[ "shape", "vector", "solid" ]
da92b3d5eca71552e05b383295a92be5e6014cd0
45,817
cpp
C++
inetcore/setup/ieak5/ieakeng/seczones.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/setup/ieak5/ieakeng/seczones.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/setup/ieak5/ieakeng/seczones.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// // SECZONES.CPP // #include "precomp.h" #include <urlmon.h> #include <wininet.h> #ifdef WINNT #include <winineti.h> #endif // WINNT #include "SComPtr.h" #define REGSTR_PATH_SECURITY_LOCKOUT TEXT("Software\\Policies\\Microsoft\\Windows\\CurrentVersion\\Internet Settings") #define REGSTR_VAL_HKLM_ONLY TEXT("Security_HKLM_only") // prototype declarations static BOOL importZonesHelper(LPCTSTR pcszInsFile, LPCTSTR pcszZonesWorkDir, LPCTSTR pcszZonesInf, BOOL fImportZones); static BOOL importRatingsHelper(LPCTSTR pcszInsFile, LPCTSTR pcszRatingsWorkDir, LPCTSTR pcszRatingsInf, BOOL fImportRatings); static BOOL ratingsInRegistry(VOID); BOOL WINAPI ImportZonesA(LPCSTR pcszInsFile, LPCSTR pcszZonesWorkDir, LPCSTR pcszZonesInf, BOOL fImportZones) { USES_CONVERSION; return importZonesHelper(A2CT(pcszInsFile), A2CT(pcszZonesWorkDir), A2CT(pcszZonesInf), fImportZones); } BOOL WINAPI ImportZonesW(LPCWSTR pcwszInsFile, LPCWSTR pcwszZonesWorkDir, LPCWSTR pcwszZonesInf, BOOL fImportZones) { USES_CONVERSION; return importZonesHelper(W2CT(pcwszInsFile), W2CT(pcwszZonesWorkDir), W2CT(pcwszZonesInf), fImportZones); } BOOL WINAPI ModifyZones(HWND hDlg) { typedef HRESULT (WINAPI * ZONESREINIT)(DWORD); //typedef VOID (WINAPI * LAUNCHSECURITYDIALOGEX)(HWND, DWORD, DWORD); BOOL fRet; HINSTANCE hUrlmon, hInetCpl; ZONESREINIT pfnZonesReInit; //LAUNCHSECURITYDIALOGEX pfnLaunchSecurityDialogEx; HKEY hkPol; DWORD dwOldHKLM, dwOldOptEdit, dwOldZoneMap; fRet = FALSE; hUrlmon = NULL; hInetCpl = NULL; hkPol = NULL; dwOldHKLM = 0; dwOldOptEdit = 0; dwOldZoneMap = 0; if ((hUrlmon = LoadLibrary(TEXT("urlmon.dll"))) == NULL) goto Exit; if ((hInetCpl = LoadLibrary(TEXT("inetcpl.cpl"))) == NULL) goto Exit; if ((pfnZonesReInit = (ZONESREINIT) GetProcAddress(hUrlmon, "ZonesReInit")) == NULL) goto Exit; // if ((pfnLaunchSecurityDialogEx = (LAUNCHSECURITYDIALOGEX) GetProcAddress(hInetCpl, "LaunchSecurityDialogEx")) == NULL) // goto Exit; fRet = TRUE; SHOpenKeyHKLM(REG_KEY_INET_POLICIES, KEY_QUERY_VALUE | KEY_SET_VALUE, &hkPol); // if zones related restrictions are set, save the values and then delete them if (hkPol != NULL) { dwOldHKLM = RegSaveRestoreDWORD(hkPol, REG_VAL_HKLM_ONLY, 0); dwOldOptEdit = RegSaveRestoreDWORD(hkPol, REG_VAL_OPT_EDIT, 0); dwOldZoneMap = RegSaveRestoreDWORD(hkPol, REG_VAL_ZONE_MAP, 0); pfnZonesReInit(0); // call into URLMON.DLL to force it to read the current settings } // call into INETCPL.CPL to modify the zones settings //pfnLaunchSecurityDialogEx(hDlg, 1, LSDFLAG_FORCEUI); ShowInetcpl(hDlg,INET_PAGE_SECURITY|INET_PAGE_PRIVACY); // restore the original values if (hkPol != NULL) { RegSaveRestoreDWORD(hkPol, REG_VAL_HKLM_ONLY, dwOldHKLM); RegSaveRestoreDWORD(hkPol, REG_VAL_OPT_EDIT, dwOldOptEdit); RegSaveRestoreDWORD(hkPol, REG_VAL_ZONE_MAP, dwOldZoneMap); pfnZonesReInit(0); // call into URLMON.DLL to force it to read the current settings } Exit: if (hUrlmon != NULL) FreeLibrary(hUrlmon); if (hInetCpl != NULL) FreeLibrary(hInetCpl); if (hkPol != NULL) SHCloseKey(hkPol); return fRet; } BOOL WINAPI ImportRatingsA(LPCSTR pcszInsFile, LPCSTR pcszRatingsWorkDir, LPCSTR pcszRatingsInf, BOOL fImportRatings) { USES_CONVERSION; return importRatingsHelper(A2CT(pcszInsFile), A2CT(pcszRatingsWorkDir), A2CT(pcszRatingsInf), fImportRatings); } BOOL WINAPI ImportRatingsW(LPCWSTR pcwszInsFile, LPCWSTR pcwszRatingsWorkDir, LPCWSTR pcwszRatingsInf, BOOL fImportRatings) { USES_CONVERSION; return importRatingsHelper(W2CT(pcwszInsFile), W2CT(pcwszRatingsWorkDir), W2CT(pcwszRatingsInf), fImportRatings); } BOOL WINAPI ModifyRatings(HWND hDlg) { typedef HRESULT (WINAPI * RATINGSETUPUI)(HWND, LPCSTR); BOOL fRet; HINSTANCE hMSRating; RATINGSETUPUI pfnRatingSetupUI; fRet = FALSE; hMSRating = NULL; if ((hMSRating = LoadLibrary(TEXT("msrating.dll"))) == NULL) goto Exit; if ((pfnRatingSetupUI = (RATINGSETUPUI) GetProcAddress(hMSRating, "RatingSetupUI")) == NULL) goto Exit; fRet = TRUE; // call into msrating.dll to modify the ratings pfnRatingSetupUI(hDlg, NULL); Exit: if (hMSRating != NULL) FreeLibrary(hMSRating); return fRet; } ///////////////////////////////////////////////////////////////////// static void importPrivacyForRSOP(LPCTSTR szFile) { __try { BOOL fAdvanced = FALSE; DWORD dwTemplate; DWORD dwError = PrivacyGetZonePreferenceW( URLZONE_INTERNET, PRIVACY_TYPE_FIRST_PARTY, &dwTemplate, NULL, NULL); if(ERROR_SUCCESS == dwError && PRIVACY_TEMPLATE_ADVANCED == dwTemplate) fAdvanced = TRUE; // AdvancedSettings TCHAR szInt[32]; wnsprintf(szInt, countof(szInt), TEXT("%d"), fAdvanced ? 1 : 0); WritePrivateProfileString(IK_PRIVACY, IK_PRIV_ADV_SETTINGS, szInt, szFile); // // Figure out first party setting and session // dwTemplate = PRIVACY_TEMPLATE_CUSTOM; WCHAR szBuffer[MAX_PATH]; // MAX_PATH is sufficent for advanced mode setting strings, MaxPrivacySettings is overkill. DWORD dwBufferSize = ARRAYSIZE(szBuffer); dwError = PrivacyGetZonePreferenceW( URLZONE_INTERNET, PRIVACY_TYPE_FIRST_PARTY, &dwTemplate, szBuffer, &dwBufferSize); if (ERROR_SUCCESS != dwError) dwTemplate = PRIVACY_TEMPLATE_CUSTOM; // store settings in INF file // FirstPartyType wnsprintf(szInt, countof(szInt), TEXT("%lu"), dwTemplate); WritePrivateProfileString(IK_PRIVACY, IK_PRIV_1PARTY_TYPE, szInt, szFile); // FirstPartyTypeText if (ERROR_SUCCESS == dwError && fAdvanced && dwBufferSize > 0) WritePrivateProfileString(IK_PRIVACY, IK_PRIV_1PARTY_TYPE_TEXT, szBuffer, szFile); // // Figure out third party setting // dwTemplate = PRIVACY_TEMPLATE_CUSTOM; dwBufferSize = ARRAYSIZE(szBuffer); dwBufferSize = ARRAYSIZE( szBuffer); dwError = PrivacyGetZonePreferenceW( URLZONE_INTERNET, PRIVACY_TYPE_THIRD_PARTY, &dwTemplate, szBuffer, &dwBufferSize); if(dwError != ERROR_SUCCESS) dwTemplate = PRIVACY_TEMPLATE_CUSTOM; // ThirdPartyType wnsprintf(szInt, countof(szInt), TEXT("%lu"), dwTemplate); WritePrivateProfileString(IK_PRIVACY, IK_PRIV_3PARTY_TYPE, szInt, szFile); // ThirdPartyTypeText if (ERROR_SUCCESS == dwError && fAdvanced && dwBufferSize > 0) WritePrivateProfileString(IK_PRIVACY, IK_PRIV_3PARTY_TYPE_TEXT, szBuffer, szFile); } __except(TRUE) { } } ///////////////////////////////////////////////////////////////////// static void importZonesForRSOP(LPCTSTR szFile) { __try { // both the security mgr & the zone mgr must be created ComPtr<IInternetZoneManager> pZoneMgr = NULL; ComPtr<IInternetSecurityManager> pSecMan = NULL; HRESULT hr = CoCreateInstance(CLSID_InternetZoneManager, NULL, CLSCTX_INPROC_SERVER, IID_IInternetZoneManager, (void**) &pZoneMgr); if (SUCCEEDED(hr)) { hr = CoCreateInstance(CLSID_InternetSecurityManager, NULL, CLSCTX_INPROC_SERVER, IID_IInternetSecurityManager, (void**) &pSecMan); } // Write out zone mappings & attributes if (SUCCEEDED(hr)) { DWORD dwEnum = 0, dwCount = 0; hr = pZoneMgr->CreateZoneEnumerator(&dwEnum, &dwCount, 0L); if (SUCCEEDED(hr) && dwCount > 0) { TCHAR szSection[32]; TCHAR szMapping[32]; TCHAR szInt[32]; for (UINT nZone = 0; nZone < dwCount; nZone++) { for (int nHKLM = 0; nHKLM < 2; nHKLM++) { HKEY hkZones = NULL; TCHAR szZIndex[MAX_PATH]; wnsprintf(szZIndex, countof(szZIndex), REG_KEY_ZONES TEXT("\\%lu"), nZone); if (0 == nHKLM) { SHOpenKeyHKLM(szZIndex, KEY_READ, &hkZones); wnsprintf(szSection, countof(szSection), IK_ZONE_HKCU_FMT, nZone); } else { SHOpenKeyHKCU(szZIndex, KEY_READ, &hkZones); wnsprintf(szSection, countof(szSection), IK_ZONE_HKLM_FMT, nZone); } // write out zone attributes TCHAR szTemp[MAX_PATH]; // MAX_ZONE_PATH && MAX_ZONE_DESCRIPTION = MAX_PATH = 260 DWORD dwSize = sizeof(szTemp); if (NULL != hkZones) { if (ERROR_SUCCESS == RegQueryValueEx(hkZones, IK_DISPLAYNAME, NULL, NULL, (LPBYTE)szTemp, &dwSize)) { WritePrivateProfileString(szSection, IK_DISPLAYNAME, szTemp, szFile); dwSize = sizeof(szTemp); } if (ERROR_SUCCESS == RegQueryValueEx(hkZones, IK_DESCRIPTION, NULL, NULL, (LPBYTE)szTemp, &dwSize)) { WritePrivateProfileString(szSection, IK_DESCRIPTION, szTemp, szFile); dwSize = sizeof(szTemp); } if (ERROR_SUCCESS == RegQueryValueEx(hkZones, IK_ICONPATH, NULL, NULL, (LPBYTE)szTemp, &dwSize)) { WritePrivateProfileString(szSection, IK_ICONPATH, szTemp, szFile); dwSize = sizeof(szTemp); } DWORD dwTemp = 0; dwSize = sizeof(dwTemp); if (ERROR_SUCCESS == RegQueryValueEx(hkZones, IK_MINLEVEL, NULL, NULL, (LPBYTE)&dwTemp, &dwSize)) { wnsprintf(szInt, countof(szInt), TEXT("%lu"), dwTemp); WritePrivateProfileString(szSection, IK_MINLEVEL, szInt, szFile); } if (ERROR_SUCCESS == RegQueryValueEx(hkZones, IK_RECOMMENDLEVEL, NULL, NULL, (LPBYTE)&dwTemp, &dwSize)) { wnsprintf(szInt, countof(szInt), TEXT("%lu"), dwTemp); WritePrivateProfileString(szSection, IK_RECOMMENDLEVEL, szInt, szFile); } if (ERROR_SUCCESS == RegQueryValueEx(hkZones, IK_CURLEVEL, NULL, NULL, (LPBYTE)&dwTemp, &dwSize)) { wnsprintf(szInt, countof(szInt), TEXT("%lu"), dwTemp); WritePrivateProfileString(szSection, IK_CURLEVEL, szInt, szFile); } if (ERROR_SUCCESS == RegQueryValueEx(hkZones, IK_FLAGS, NULL, NULL, (LPBYTE)&dwTemp, &dwSize)) { wnsprintf(szInt, countof(szInt), TEXT("%lu"), dwTemp); WritePrivateProfileString(szSection, IK_FLAGS, szInt, szFile); } } // write out action values if (NULL != hkZones) { TCHAR szActKey[32]; TCHAR szActValue[64]; DWORD dwURLAction[] = { URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY, URLACTION_ACTIVEX_RUN, URLACTION_CHANNEL_SOFTDIST_PERMISSIONS, URLACTION_COOKIES, URLACTION_COOKIES_SESSION, URLACTION_CREDENTIALS_USE, URLACTION_CLIENT_CERT_PROMPT, URLACTION_CROSS_DOMAIN_DATA, URLACTION_DOWNLOAD_SIGNED_ACTIVEX, URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX, URLACTION_HTML_FONT_DOWNLOAD, URLACTION_HTML_SUBFRAME_NAVIGATE, URLACTION_HTML_SUBMIT_FORMS, URLACTION_HTML_JAVA_RUN, URLACTION_HTML_USERDATA_SAVE, URLACTION_JAVA_PERMISSIONS, URLACTION_SCRIPT_JAVA_USE, URLACTION_SCRIPT_PASTE, URLACTION_SCRIPT_RUN, URLACTION_SCRIPT_SAFE_ACTIVEX, URLACTION_SHELL_FILE_DOWNLOAD, URLACTION_SHELL_INSTALL_DTITEMS, URLACTION_SHELL_MOVE_OR_COPY, URLACTION_SHELL_VERB, URLACTION_SHELL_WEBVIEW_VERB, 0 }; DWORD dwSetting = 0; DWORD dwSetSize = sizeof(dwSetting); long nAction = 0; long nStoredAction = 0; while (0 != dwURLAction[nAction]) { wnsprintf(szTemp, countof(szTemp), TEXT("%lX"), dwURLAction[nAction]); if (ERROR_SUCCESS == RegQueryValueEx(hkZones, szTemp, NULL, NULL, (LPBYTE)&dwSetting, &dwSetSize)) { wnsprintf(szActKey, countof(szActKey), IK_ACTIONVALUE_FMT, nStoredAction); wnsprintf(szActValue, countof(szActValue), TEXT("%s:%lu"), szTemp, dwSetting); WritePrivateProfileString(szSection, szActKey, szActValue, szFile); nStoredAction++; } nAction++; } } // write out zone mappings DWORD dwZone = 0; hr = pZoneMgr->GetZoneAt(dwEnum, nZone, &dwZone); ComPtr<IEnumString> pEnumString = NULL; hr = pSecMan->GetZoneMappings(dwZone, &pEnumString, 0); if (SUCCEEDED(hr)) { UINT nMapping = 0; _bstr_t bstrSetting; for(int i = 0; ;i++) { TCHAR szBuffer[MAX_PATH]; wnsprintf(szMapping, countof(szMapping), IK_MAPPING_FMT, i); if(GetPrivateProfileString(szSection, szMapping, TEXT(""), szBuffer, MAX_PATH, szFile)) { WritePrivateProfileString(szSection, szMapping, NULL, szFile); } else { break; } } while (S_OK == hr) { wnsprintf(szMapping, countof(szMapping), IK_MAPPING_FMT, nMapping); nMapping++; // There should only be one object returned from this query. BSTR bstrVal = NULL; ULONG uReturned = (ULONG)-1L; hr = pEnumString->Next(1L, &bstrVal, &uReturned); if (SUCCEEDED(hr) && 1 == uReturned) { bstrSetting = bstrVal; WritePrivateProfileString(szSection, szMapping, (LPCTSTR)bstrSetting, szFile); } } } } } wnsprintf(szInt, countof(szInt), TEXT("%lu"), dwCount); WritePrivateProfileString(SECURITY_IMPORTS, IK_ZONES, szInt, szFile); if(IEHardened()) { wnsprintf(szInt, countof(szInt), TEXT("%lu"), 1); WritePrivateProfileString(SECURITY_IMPORTS, IK_IEESC, szInt, szFile); } else { wnsprintf(szInt, countof(szInt), TEXT("%lu"), 0); WritePrivateProfileString(SECURITY_IMPORTS, IK_IEESC, szInt, szFile); } } } } __except(TRUE) { } } ///////////////////////////////////////////////////////////////////// static BOOL importZonesHelper(LPCTSTR pcszInsFile, LPCTSTR pcszZonesWorkDir, LPCTSTR pcszZonesInf, BOOL fImportZones) { BOOL bRet = FALSE; HKEY hkZones = NULL, hkZoneMap = NULL; HKEY hkInetSettings = NULL, hkP3P = NULL; if (pcszInsFile == NULL || pcszZonesInf == NULL) return FALSE; // Before processing anything, first clear out the entries in the INS file and delete work dirs // clear out the entries in the INS file that correspond to importing security zones InsDeleteKey(SECURITY_IMPORTS, TEXT("ImportSecZones"), pcszInsFile); InsDeleteKey(IS_EXTREGINF, TEXT("SecZones"), pcszInsFile); InsDeleteKey(IS_EXTREGINF_HKLM, TEXT("SecZones"), pcszInsFile); InsDeleteKey(IS_EXTREGINF_HKCU, TEXT("SecZones"), pcszInsFile); InsDeleteKey(IS_EXTREGINF_ESC, TEXT("SecZones"), pcszInsFile); InsDeleteKey(IS_EXTREGINF_ESC_HKLM, TEXT("SecZones"), pcszInsFile); InsDeleteKey(IS_EXTREGINF_ESC_HKCU, TEXT("SecZones"), pcszInsFile); // blow away the pcszZonesWorkDir and pcszZonesInf if (pcszZonesWorkDir != NULL) PathRemovePath(pcszZonesWorkDir); PathRemovePath(pcszZonesInf); if (!fImportZones) return TRUE; // looks like there is some problem with setting the REG_VAL_HKLM_ONLY key; // so we'll import the settings from HKCU SHOpenKeyHKCU(REG_KEY_ZONES, KEY_DEFAULT_ACCESS, &hkZones); SHOpenKeyHKCU(REG_KEY_ZONEMAP, KEY_DEFAULT_ACCESS, &hkZoneMap); SHOpenKeyHKCU(KEY_INET_SETTINGS, KEY_DEFAULT_ACCESS, &hkInetSettings); SHOpenKeyHKCU(REG_KEY_P3P, KEY_DEFAULT_ACCESS, &hkP3P); if (hkZones != NULL && hkZoneMap != NULL) { TCHAR szFullInfName[MAX_PATH]; HANDLE hInf; if (pcszZonesWorkDir != NULL && PathIsFileSpec(pcszZonesInf)) // create SECZONES.INF under pcszZonesWorkDir PathCombine(szFullInfName, pcszZonesWorkDir, pcszZonesInf); else StrCpy(szFullInfName, pcszZonesInf); // create SECZONES.INF file if ((hInf = CreateNewFile(szFullInfName)) != INVALID_HANDLE_VALUE) { TCHAR szBuf[MAX_PATH]; // first, write the standard goo - [Version], [DefaultInstall], etc. - to SECZONES.INF WriteStringToFile(hInf, (LPCVOID) ZONES_INF_ADD, StrLen(ZONES_INF_ADD)); ExportRegTree2Inf(hkZones, TEXT("HKLM"), REG_KEY_ZONES, hInf); ExportRegTree2Inf(hkZoneMap, TEXT("HKLM"), REG_KEY_ZONEMAP, hInf); // write [AddReg.HKCU] WriteStringToFile(hInf, (LPCVOID) ZONES_INF_ADDREG_HKCU, StrLen(ZONES_INF_ADDREG_HKCU)); ExportRegTree2Inf(hkZones, TEXT("HKCU"), REG_KEY_ZONES, hInf); ExportRegTree2Inf(hkZoneMap, TEXT("HKCU"), REG_KEY_ZONEMAP, hInf); // Import P3P settings if (hkInetSettings != NULL && hkP3P != NULL) { ExportRegValue2Inf(hkInetSettings, TEXT("PrivacyAdvanced"), TEXT("HKCU"), KEY_INET_SETTINGS, hInf); ExportRegTree2Inf(hkP3P, TEXT("HKCU"), REG_KEY_P3P, hInf); } CloseHandle(hInf); BOOL fHarden = IEHardened(); // update the INS file InsWriteBool(SECURITY_IMPORTS, TEXT("ImportSecZones"), TRUE, pcszInsFile); wnsprintf(szBuf, countof(szBuf), TEXT("*,%s,") IS_DEFAULTINSTALL, PathFindFileName(pcszZonesInf)); if(fHarden) { WritePrivateProfileString(IS_EXTREGINF_ESC, TEXT("SecZones"), szBuf, pcszInsFile); } else { WritePrivateProfileString(IS_EXTREGINF, TEXT("SecZones"), szBuf, pcszInsFile); } // write to new ExtRegInf.HKLM and ExtRegInf.HKCU sections if (!InsIsSectionEmpty(IS_IEAKADDREG_HKLM, szFullInfName)) { wnsprintf(szBuf, countof(szBuf), TEXT("%s,") IS_IEAKINSTALL_HKLM, PathFindFileName(pcszZonesInf)); if(fHarden) { WritePrivateProfileString(IS_EXTREGINF_ESC_HKLM, TEXT("SecZones"), szBuf, pcszInsFile); } else { WritePrivateProfileString(IS_EXTREGINF_HKLM, TEXT("SecZones"), szBuf, pcszInsFile); } } if (!InsIsSectionEmpty(IS_IEAKADDREG_HKCU, szFullInfName)) { wnsprintf(szBuf, countof(szBuf), TEXT("%s,") IS_IEAKINSTALL_HKCU, PathFindFileName(pcszZonesInf)); if(fHarden) { WritePrivateProfileString(IS_EXTREGINF_ESC_HKCU, TEXT("SecZones"), szBuf, pcszInsFile); } else { WritePrivateProfileString(IS_EXTREGINF_HKCU, TEXT("SecZones"), szBuf, pcszInsFile); } } bRet = TRUE; } // create SECZRSOP.INF file TCHAR szZRSOPInfFile[MAX_PATH]; StrCpy(szZRSOPInfFile, szFullInfName); PathRemoveFileSpec(szZRSOPInfFile); StrCat(szZRSOPInfFile, TEXT("\\seczrsop.inf")); importZonesForRSOP(szZRSOPInfFile); importPrivacyForRSOP(szZRSOPInfFile); } SHCloseKey(hkZones); SHCloseKey(hkZoneMap); SHCloseKey(hkInetSettings); SHCloseKey(hkP3P); return bRet; } #define PICSRULES_APPROVEDSITES 0 #define PICSRULES_ALWAYS 1 #define PICSRULES_NEVER 0 //This indicates which member is valid in a PICSRulesPolicy //Class enum PICSRulesPolicyAttribute { PR_POLICY_NONEVALID, PR_POLICY_REJECTBYURL, PR_POLICY_ACCEPTBYURL, PR_POLICY_REJECTIF, PR_POLICY_ACCEPTIF, PR_POLICY_REJECTUNLESS, PR_POLICY_ACCEPTUNLESS }; ///////////////////////////////////////////////////////////////////// static void importRatingsForRSOP(HKEY hkRat, LPCTSTR szFile) { __try { TCHAR szSection[32] = IK_FF_GENERAL; TCHAR szKey[32]; TCHAR szInt[32]; // write out ratings system filenames // not sure why, but code below only loops through 10 TCHAR szTemp[MAX_PATH]; DWORD cbSize = 0; for (int nFile = 0; nFile < 10; nFile++) { wnsprintf(szKey, countof(szKey), IK_FILENAME_FMT, nFile); cbSize = sizeof(szTemp); if (RegQueryValueEx(hkRat, szKey, NULL, NULL, (LPBYTE) szTemp, &cbSize) != ERROR_SUCCESS) break; WritePrivateProfileString(szSection, szKey, szTemp, szFile); } // write out checked values from General tab HKEY hkDef = NULL; DWORD dwTemp = 0; if (ERROR_SUCCESS == SHOpenKey(hkRat, TEXT(".Default"), KEY_DEFAULT_ACCESS, &hkDef)) { cbSize = sizeof(dwTemp); if (ERROR_SUCCESS == RegQueryValueEx(hkDef, VIEW_UNKNOWN_RATED_SITES, NULL, NULL, (LPBYTE)&dwTemp, &cbSize)) { wnsprintf(szInt, countof(szInt), TEXT("%lu"), dwTemp); WritePrivateProfileString(szSection, VIEW_UNKNOWN_RATED_SITES, szInt, szFile); } cbSize = sizeof(dwTemp); if (ERROR_SUCCESS == RegQueryValueEx(hkDef, PASSWORD_OVERRIDE_ENABLED, NULL, NULL, (LPBYTE)&dwTemp, &cbSize)) { wnsprintf(szInt, countof(szInt), TEXT("%lu"), dwTemp); WritePrivateProfileString(szSection, PASSWORD_OVERRIDE_ENABLED, szInt, szFile); } } // write out always viewable & never viewable sites from the approved sites tab // See msrating.dll for src HKEY hkUser = NULL; HKEY hkPRPolicy = NULL; DWORD nPolicies = 0; cbSize = sizeof(dwTemp); HRESULT hr = SHOpenKey(hkRat, TEXT("PICSRules\\.Default"), KEY_DEFAULT_ACCESS, &hkUser); if (ERROR_SUCCESS == hr) { hr = SHOpenKey(hkUser, TEXT("0\\PRPolicy"), KEY_DEFAULT_ACCESS, &hkPRPolicy); if (ERROR_SUCCESS == hr) { hr = RegQueryValueEx(hkPRPolicy, TEXT("PRNumPolicy"), NULL, NULL, (LPBYTE)&nPolicies, &cbSize); } } if (ERROR_SUCCESS == hr) { TCHAR szNumber[MAX_PATH]; HKEY hkItem = NULL; HKEY hkPolicySub = NULL; DWORD dwAttrib = PR_POLICY_NONEVALID; DWORD nExpressions = 0; long nApproved = 0; long nDisapproved = 0; for (DWORD nItem = 0; nItem < nPolicies; nItem++) { wnsprintf(szNumber, countof(szNumber), TEXT("%d"), nItem); hr = SHOpenKey(hkPRPolicy, szNumber, KEY_DEFAULT_ACCESS, &hkItem); if (ERROR_SUCCESS == hr) { cbSize = sizeof(dwAttrib); hr = RegQueryValueEx(hkItem, TEXT("PRPPolicyAttribute"), NULL, NULL, (LPBYTE)&dwAttrib, &cbSize); } if (ERROR_SUCCESS == hr) hr = SHOpenKey(hkItem, TEXT("PRPPolicySub"), KEY_DEFAULT_ACCESS, &hkPolicySub); if (ERROR_SUCCESS == hr) { cbSize = sizeof(nExpressions); hr = RegQueryValueEx(hkPolicySub, TEXT("PRNumURLExpressions"), NULL, NULL, (LPBYTE)&nExpressions, &cbSize); } if (ERROR_SUCCESS == hr) { HKEY hByURLKey = NULL; TCHAR szURL[INTERNET_MAX_URL_LENGTH]; for (DWORD nExp = 0; nExp < nExpressions; nExp++) { wnsprintf(szNumber, countof(szNumber), TEXT("%d"), nExp); hr = SHOpenKey(hkPolicySub, szNumber, KEY_DEFAULT_ACCESS, &hByURLKey); cbSize = sizeof(szURL); if (ERROR_SUCCESS == hr) { hr = RegQueryValueEx(hByURLKey, TEXT("PRBUUrl"), NULL, NULL, (LPBYTE)szURL, &cbSize); } if (ERROR_SUCCESS == hr) { if (PR_POLICY_REJECTBYURL == dwAttrib) { wnsprintf(szKey, countof(szKey), IK_DISAPPROVED_FMT, nDisapproved++); WritePrivateProfileString(szSection, szKey, szURL, szFile); } else if (PR_POLICY_ACCEPTBYURL == dwAttrib) { wnsprintf(szKey, countof(szKey), IK_APPROVED_FMT, nApproved++); WritePrivateProfileString(szSection, szKey, szURL, szFile); } } } } } } // write out select ratings bureau cbSize = sizeof(szTemp); if (ERROR_SUCCESS == RegQueryValueEx(hkRat, IK_BUREAU, NULL, NULL, (LPBYTE)szTemp, &cbSize)) { WritePrivateProfileString(szSection, IK_BUREAU, szTemp, szFile); } } __except(TRUE) { } } ///////////////////////////////////////////////////////////////////// static BOOL importRatingsHelper(LPCTSTR pcszInsFile, LPCTSTR pcszRatingsWorkDir, LPCTSTR pcszRatingsInf, BOOL fImportRatings) { BOOL bRet = FALSE; HKEY hkRat = NULL; BOOL bRatLoadedAsHive = FALSE; if (pcszInsFile == NULL || pcszRatingsInf == NULL) return FALSE; // Before processing anything, first clear out the entries in the INS file and delete work dirs // clear out the entries in the INS file that correspond to importing ratings InsDeleteKey(SECURITY_IMPORTS, TEXT("ImportRatings"), pcszInsFile); InsDeleteKey(IS_EXTREGINF, TEXT("Ratings"), pcszInsFile); InsDeleteKey(IS_EXTREGINF_HKLM, TEXT("Ratings"), pcszInsFile); // blow away the pcszRatingsWorkDir and pcszRatingsInf if (pcszRatingsWorkDir != NULL) PathRemovePath(pcszRatingsWorkDir); PathRemovePath(pcszRatingsInf); if (!fImportRatings) return TRUE; if (ratingsInRegistry()) { SHOpenKeyHKLM(REG_KEY_RATINGS, KEY_DEFAULT_ACCESS, &hkRat); } else { TCHAR szRatFile[MAX_PATH]; GetSystemDirectory(szRatFile, countof(szRatFile)); PathAppend(szRatFile, TEXT("ratings.pol")); if (RegLoadKey(HKEY_LOCAL_MACHINE, POLICYDATA, szRatFile) == ERROR_SUCCESS) { bRatLoadedAsHive = TRUE; SHOpenKeyHKLM(REG_KEY_POLICY_DATA, KEY_DEFAULT_ACCESS, &hkRat); } } if (hkRat != NULL) { TCHAR szFullInfName[MAX_PATH]; HANDLE hInf; if (pcszRatingsWorkDir != NULL && PathIsFileSpec(pcszRatingsInf)) // create RATINGS.INF under pcszRatingsWorkDir PathCombine(szFullInfName, pcszRatingsWorkDir, pcszRatingsInf); else StrCpy(szFullInfName, pcszRatingsInf); // create RATINGS.INF file if ((hInf = CreateNewFile(szFullInfName)) != INVALID_HANDLE_VALUE) { INT i; HKEY hkDef; TCHAR szSysDir[MAX_PATH]; WriteStringToFile(hInf, RATINGS_INF_ADD, StrLen(RATINGS_INF_ADD)); // convert the system path to %11% ldid for (i = 0; i < 10; i++) { TCHAR szNameParm[16]; TCHAR szFileName[MAX_PATH]; DWORD cbSize; wnsprintf(szNameParm, countof(szNameParm), TEXT("FileName%i"), i); cbSize = sizeof(szFileName); if (RegQueryValueEx(hkRat, szNameParm, NULL, NULL, (LPBYTE) szFileName, &cbSize) != ERROR_SUCCESS) break; if (PathIsFullPath(szFileName)) { TCHAR szEncFileName[MAX_PATH]; // BUBBUG: Should we check if the path is really the system dir? wnsprintf(szEncFileName, countof(szEncFileName), TEXT("%%11%%\\%s"), PathFindFileName(szFileName)); RegSetValueEx(hkRat, szNameParm, 0, REG_SZ, (CONST BYTE *)szEncFileName, (DWORD)StrCbFromSz(szEncFileName)); } } RegFlushKey(hkRat); ExportRegKey2Inf(hkRat, TEXT("HKLM"), REG_KEY_RATINGS, hInf); WriteStringToFile(hInf, (LPCVOID) TEXT("\r\n"), 2); if (SHOpenKey(hkRat, TEXT(".Default"), KEY_DEFAULT_ACCESS, &hkDef) == ERROR_SUCCESS) { TCHAR szDefault[MAX_PATH]; wnsprintf(szDefault, countof(szDefault), TEXT("%s\\.Default"), REG_KEY_RATINGS); ExportRegTree2Inf(hkDef, TEXT("HKLM"), szDefault, hInf); SHCloseKey(hkDef); } // new IE5 specific key if (SHOpenKey(hkRat, TEXT("PICSRules"), KEY_DEFAULT_ACCESS, &hkDef) == ERROR_SUCCESS) { TCHAR szRules[MAX_PATH]; wnsprintf(szRules, countof(szRules), TEXT("%s\\PICSRules"), REG_KEY_RATINGS); ExportRegTree2Inf(hkDef, TEXT("HKLM"), szRules, hInf); SHCloseKey(hkDef); } if (bRatLoadedAsHive) { HKEY hkRatsInReg; // eventhough ratings has been loaded as a hive, the password is still in the registry if (SHOpenKeyHKLM(REG_KEY_RATINGS, KEY_DEFAULT_ACCESS, &hkRatsInReg) == ERROR_SUCCESS) { ExportRegKey2Inf(hkRatsInReg, TEXT("HKLM"), REG_KEY_RATINGS, hInf); SHCloseKey(hkRatsInReg); } // browser ratings code does some weird stuff with their hive, so we have to go to // the right level to get the new IE5 PICSRules key if (SHOpenKey(hkRat, REG_KEY_RATINGS TEXT("\\PICSRules"), KEY_DEFAULT_ACCESS, &hkRatsInReg) == ERROR_SUCCESS) { TCHAR szRules[MAX_PATH]; wnsprintf(szRules, countof(szRules), TEXT("%s\\PICSRules"), REG_KEY_RATINGS); ExportRegTree2Inf(hkDef, TEXT("HKLM"), szRules, hInf); SHCloseKey(hkDef); } } CloseHandle(hInf); // update the INS file InsWriteBool(SECURITY_IMPORTS, TEXT("ImportRatings"), TRUE, pcszInsFile); wnsprintf(szSysDir, countof(szSysDir), TEXT("*,%s,") IS_DEFAULTINSTALL, PathFindFileName(pcszRatingsInf)); WritePrivateProfileString(IS_EXTREGINF, TEXT("Ratings"), szSysDir, pcszInsFile); // write to new ExtRegInf.HKLM section if (!InsIsSectionEmpty(TEXT("AddReg.HKLM"), szFullInfName)) { wnsprintf(szSysDir, countof(szSysDir), TEXT("%s,IEAKInstall.HKLM"), PathFindFileName(pcszRatingsInf)); WritePrivateProfileString(IS_EXTREGINF_HKLM, TEXT("Ratings"), szSysDir, pcszInsFile); } bRet = TRUE; // restore the %11% ldid paths to the system dir GetSystemDirectory(szSysDir, countof(szSysDir)); for (i = 0; i < 10; i++) { TCHAR szNameParm[16]; TCHAR szEncFileName[MAX_PATH]; DWORD cbSize; wnsprintf(szNameParm, countof(szNameParm), TEXT("FileName%i"), i); cbSize = sizeof(szEncFileName); if (RegQueryValueEx(hkRat, szNameParm, NULL, NULL, (LPBYTE) szEncFileName, &cbSize) != ERROR_SUCCESS) break; if (PathIsFullPath(szEncFileName)) { TCHAR szFileName[MAX_PATH]; PathCombine(szFileName, szSysDir, PathFindFileName(szEncFileName)); RegSetValueEx(hkRat, szNameParm, 0, REG_SZ, (CONST BYTE *)szFileName, (DWORD)StrCbFromSz(szFileName)); } } RegFlushKey(hkRat); } // create RATRSOP.INF file TCHAR szRRSOPInfFile[MAX_PATH]; StrCpy(szRRSOPInfFile, szFullInfName); PathRemoveFileSpec(szRRSOPInfFile); StrCat(szRRSOPInfFile, TEXT("\\ratrsop.inf")); importRatingsForRSOP(hkRat, szRRSOPInfFile); SHCloseKey(hkRat); } if (bRatLoadedAsHive) RegUnLoadKey(HKEY_LOCAL_MACHINE, POLICYDATA); return bRet; } static BOOL ratingsInRegistry(VOID) { BOOL fRet = TRUE; if (g_fRunningOnNT) return fRet; if (fRet) { HKEY hk; fRet = FALSE; if (SHOpenKeyHKLM(TEXT("System\\CurrentControlSet\\Control\\Update"), KEY_DEFAULT_ACCESS, &hk) == ERROR_SUCCESS) { DWORD dwData, cbSize; cbSize = sizeof(dwData); if (RegQueryValueEx(hk, TEXT("UpdateMode"), 0, NULL, (LPBYTE) &dwData, &cbSize) == ERROR_SUCCESS && dwData) fRet = TRUE; SHCloseKey(hk); } } if (fRet) { HKEY hk; fRet = FALSE; if (SHOpenKeyHKLM(TEXT("Network\\Logon"), KEY_DEFAULT_ACCESS, &hk) == ERROR_SUCCESS) { DWORD dwData, cbSize; cbSize = sizeof(dwData); if (RegQueryValueEx(hk, TEXT("UserProfiles"), 0, NULL, (LPBYTE) &dwData, &cbSize) == ERROR_SUCCESS && dwData) fRet = TRUE; SHCloseKey(hk); } } if (fRet) { HKEY hk; fRet = FALSE; if (SHOpenKeyHKLM(REG_KEY_RATINGS, KEY_DEFAULT_ACCESS, &hk) == ERROR_SUCCESS) { HKEY hkRatDef; if (SHOpenKey(hk, TEXT(".Default"), KEY_DEFAULT_ACCESS, &hkRatDef) == ERROR_SUCCESS) { fRet = TRUE; SHCloseKey(hkRatDef); } SHCloseKey(hk); } } return fRet; }
45.408325
169
0.446996
[ "object" ]
dab8f7bbcb7f0651b4a7e0b3bf94371071193701
4,485
cpp
C++
src/bindings/bnd_polycurve.cpp
lukegehron/rhino3dm
0e124084f7397f72aa82e499124a9232497573f0
[ "MIT" ]
343
2018-10-17T07:36:55.000Z
2022-03-31T08:18:36.000Z
src/bindings/bnd_polycurve.cpp
iintrigued/rhino3dm
aa3cffaf66a22883de64b4bc096d554341c1ce39
[ "MIT" ]
187
2018-10-18T23:07:44.000Z
2022-03-24T02:05:00.000Z
src/bindings/bnd_polycurve.cpp
iintrigued/rhino3dm
aa3cffaf66a22883de64b4bc096d554341c1ce39
[ "MIT" ]
115
2018-10-18T01:17:20.000Z
2022-03-31T16:43:58.000Z
#include "bindings.h" BND_PolyCurve::BND_PolyCurve() { SetTrackedPointer(new ON_PolyCurve(), nullptr); } BND_PolyCurve::BND_PolyCurve(ON_PolyCurve* polycurve, const ON_ModelComponentReference* compref) { SetTrackedPointer(polycurve, compref); } void BND_PolyCurve::SetTrackedPointer(ON_PolyCurve* polycurve, const ON_ModelComponentReference* compref) { m_polycurve = polycurve; BND_Curve::SetTrackedPointer(polycurve, compref); } BND_Curve* BND_PolyCurve::SegmentCurve(int index) const { ON_Curve* curve = m_polycurve->SegmentCurve(index); BND_Curve* rc = dynamic_cast<BND_Curve*>(BND_CommonObject::CreateWrapper(curve, &m_component_ref)); return rc; } std::vector<BND_Curve*> BND_PolyCurve::Explode() const { int count = SegmentCount(); std::vector<BND_Curve*> rc; for (int i = 0; i < count; i++) { BND_Curve* curve = SegmentCurve(i); if (curve) { ON_Curve* crv = curve->m_curve->DuplicateCurve(); rc.push_back(dynamic_cast<BND_Curve*>(BND_CommonObject::CreateWrapper(crv, nullptr))); } } return rc; } bool BND_PolyCurve::Append1(const ON_Line& line) { return m_polycurve->AppendAndMatch(new ON_LineCurve(line)); } bool BND_PolyCurve::Append2(BND_Arc& arc) { return m_polycurve->AppendAndMatch(new ON_ArcCurve(arc.m_arc)); } bool BND_PolyCurve::Append3(const BND_Curve& curve) { ON_Curve* crv = curve.m_curve->DuplicateCurve(); return m_polycurve->AppendAndMatch(crv); } bool BND_PolyCurve::AppendSegment(const BND_Curve& curve) { ON_Curve* crv = curve.m_curve->DuplicateCurve(); return m_polycurve->Append(crv); } double BND_PolyCurve::SegmentCurveParameter(double t) const { return m_polycurve->SegmentCurveParameter(t); } double BND_PolyCurve::PolyCurveParameter(int segmentIndex, double segmentCurveParameter) const { return m_polycurve->PolyCurveParameter(segmentIndex, segmentCurveParameter); } BND_Interval BND_PolyCurve::SegmentDomain(int segmentIndex) const { ON_Interval rc = m_polycurve->SegmentDomain(segmentIndex); return BND_Interval(rc); } int BND_PolyCurve::SegmentIndex(double polycurveParameter) const { return m_polycurve->SegmentIndex(polycurveParameter); } ///////////////////////////////////////////////////////////////// #if defined(ON_PYTHON_COMPILE) namespace py = pybind11; void initPolyCurveBindings(pybind11::module& m) { py::class_<BND_PolyCurve, BND_Curve>(m, "PolyCurve") .def(py::init<>()) .def_property_readonly("SegmentCount", &BND_PolyCurve::SegmentCount) .def("SegmentCurve", &BND_PolyCurve::SegmentCurve, py::arg("index")) .def_property_readonly("IsNested", &BND_PolyCurve::IsNested) .def_property_readonly("HasGap", &BND_PolyCurve::HasGap) .def("RemoveNesting", &BND_PolyCurve::RemoveNesting) .def("Explode", &BND_PolyCurve::Explode) .def("Append", &BND_PolyCurve::Append1, py::arg("line")) .def("Append", &BND_PolyCurve::Append2, py::arg("arc")) .def("Append", &BND_PolyCurve::Append3, py::arg("curve")) .def("AppendSegment", &BND_PolyCurve::AppendSegment, py::arg("curve")) .def("SegmentCurveParameter", &BND_PolyCurve::SegmentCurveParameter, py::arg("polycurveParameter")) .def("PolyCurveParameter", &BND_PolyCurve::PolyCurveParameter, py::arg("segmentIndex"), py::arg("segmentCurveParameter")) .def("SegmentDomain", &BND_PolyCurve::SegmentDomain, py::arg("segmentIndex")) .def("SegmentIndex", &BND_PolyCurve::SegmentIndex, py::arg("polycurveParameter")) ; } #endif #if defined(ON_WASM_COMPILE) using namespace emscripten; void initPolyCurveBindings(void*) { class_<BND_PolyCurve, base<BND_Curve>>("PolyCurve") .constructor<>() .property("segmentCount", &BND_PolyCurve::SegmentCount) .function("segmentCurve", &BND_PolyCurve::SegmentCurve, allow_raw_pointers()) .property("isNested", &BND_PolyCurve::IsNested) .property("hasGap", &BND_PolyCurve::HasGap) .function("removeNesting", &BND_PolyCurve::RemoveNesting) .function("explode", &BND_PolyCurve::Explode) .function("append", &BND_PolyCurve::Append1) .function("append", &BND_PolyCurve::Append2) .function("append", &BND_PolyCurve::Append3) .function("appendSegment", &BND_PolyCurve::AppendSegment) .function("segmentCurveParameter", &BND_PolyCurve::SegmentCurveParameter) .function("polyCurveParameter", &BND_PolyCurve::PolyCurveParameter) .function("segmentDomain", &BND_PolyCurve::SegmentDomain) .function("segmentIndex", &BND_PolyCurve::SegmentIndex) ; } #endif
32.737226
125
0.733556
[ "vector" ]
dabba4f2e58a814fa69c030cbd1f66feb2ce4048
2,197
cpp
C++
UVA/10258.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
UVA/10258.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
UVA/10258.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define f first #define s second #define vi vector<int> #define pii pair<int, int> #define ll long long using namespace std; struct Problem{ int team; int problem; int time; string status; }; struct Team{ int team; int problems; int time; bool hasSubmissions=false; }; int main(){ //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); //ios_base::sync_with_stdio(false); //cin.tie(NULL); int cases; string str; cin >> cases; cin.ignore(); getline(cin, str); while(cases--){ vector<vi> points(101, vi(10, 0)); vector<vi> solved(101, vi(10, 0)); vector<Team> teams(101); for(int i=1; i<teams.size(); i++){ teams[i].team=i; teams[i].problems=0; teams[i].time=0; } Problem p; while(getline(cin, str) && str!=""){ stringstream ss(str); ss >> p.team >> p.problem >> p.time >> p.status; if(p.status[0]=='I'){ points[p.team][p.problem]+=20; } if(p.status[0]=='C' && !solved[p.team][p.problem]){ points[p.team][p.problem]+=p.time; solved[p.team][p.problem]=true; teams[p.team].problems++; teams[p.team].time+=points[p.team][p.problem]; } teams[p.team].hasSubmissions=true; } sort(teams.begin(), teams.end(), [](const Team &t1, const Team &t2){ if(t1.problems>t2.problems) return true; else if(t1.problems==t2.problems){ if(t1.time!=t2.time){ return t1.time<t2.time; } else if(t1.time==t2.time){ return t1.team<t2.team; } } else if(t1.problems<t2.problems) return false; }); for(int i=0; i<teams.size(); i++){ if(teams[i].hasSubmissions){ cout << teams[i].team << " " << teams[i].problems << " " << teams[i].time << "\n"; } } if(cases>0){ cout << "\n"; } } return 0; }
28.532468
98
0.474738
[ "vector" ]
dabba6716f6a59fec43ef7d31b2492a32ff2f85c
868
hpp
C++
src/core/lib/core_python27/type_converters/default_converter.hpp
wgsyd/wgtf
d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed
[ "BSD-3-Clause" ]
28
2016-06-03T05:28:25.000Z
2019-02-14T12:04:31.000Z
src/core/lib/core_python27/type_converters/default_converter.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
null
null
null
src/core/lib/core_python27/type_converters/default_converter.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
14
2016-06-03T05:52:27.000Z
2019-03-21T09:56:03.000Z
#pragma once #include "core_dependency_system/depends.hpp" #include "../interfaces/i_python_obj_manager.hpp" #include "i_parent_type_converter.hpp" namespace wgt { namespace PyScript { class ScriptObject; } // namespace PyScript class Variant; namespace PythonType { /** * Attempts to convert ScriptObject<->Variant. * This is for any Python type that inherits from "object". */ class DefaultConverter : public IParentConverter, public Depends<IPythonObjManager> { public: virtual bool toVariant(const PyScript::ScriptObject& inObject, Variant& outVariant, const ObjectHandle& parentHandle, const std::string& childPath) override; virtual bool toScriptType(const Variant& inVariant, PyScript::ScriptObject& outObject, void* userData = nullptr) override; }; } // namespace PythonType } // end namespace wgt
25.529412
97
0.736175
[ "object" ]
dabcd2ab11349b461f863e959c61efeacb40e120
2,554
hpp
C++
Donut Maker/Source Files/D-NSpace/my_nspace.hpp
RoDoRiTos/Archives
1addb6fba9b941818c5e24e26cb0475e9cbec2db
[ "BSD-Source-Code" ]
null
null
null
Donut Maker/Source Files/D-NSpace/my_nspace.hpp
RoDoRiTos/Archives
1addb6fba9b941818c5e24e26cb0475e9cbec2db
[ "BSD-Source-Code" ]
null
null
null
Donut Maker/Source Files/D-NSpace/my_nspace.hpp
RoDoRiTos/Archives
1addb6fba9b941818c5e24e26cb0475e9cbec2db
[ "BSD-Source-Code" ]
null
null
null
#pragma once #include "cinder/app/AppNative.h" #include "cinder/gl/Texture.h" #include "cinder/TriMesh.h" #include "cinder/CinderMath.h" namespace doritos{ enum Window{ WIDTH = 640, HEIGHT = 640 }; struct Object{ ci::Vec3f pos; ci::Vec3f rotation; }; class Plane{ private: ci::TriMesh plane; public: void init(){ ci::Vec3f plane_vertices[] = { { -1, 1, 0 }, { 1, 1, 0 }, { 1, -1, 0 }, { -1, -1, 0 }, }; plane.appendVertices(plane_vertices, sizeof(plane_vertices) / sizeof(plane_vertices[0])); ci::ColorA plane_colors[]{ {1, 1, 1, 1}, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, }; plane.appendColorsRgba(plane_colors, sizeof(plane_colors) / sizeof(plane_colors[0])); uint32_t plane_indices[] = { 0, 1, 2, 2, 3, 0 }; plane.appendIndices(plane_indices, sizeof(plane_indices) / sizeof(plane_indices[0])); ci::Vec2f plane_tex_coords[] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }; plane.appendTexCoords(plane_tex_coords, sizeof(plane_tex_coords) / sizeof(plane_tex_coords[0])); } ci::TriMesh getMesh(){ return plane; } }; class Func{ public: static std::string getNumberSize(unsigned short counter){ unsigned short size = counter / 3; switch (size){ case 1: return "K"; case 2: return "M"; case 3: return "B"; case 4: return "T"; case 5: return "Qa"; } return ""; } static std::string filterValue(unsigned __int64 value){ unsigned __int64 init_val = value; if (value > 1000){ short counter = -1; std::vector<unsigned short> temp; while (value > 0){ temp.push_back(value % 10); value /= 10; counter++; } unsigned short size = counter / 3; unsigned short disp_val = static_cast<unsigned short>(init_val / ci::math<unsigned __int64>::pow(10, size * 3)); unsigned short dec = static_cast<unsigned short>((init_val / ci::math<int>::pow(10, size * 3 - 3)) % 1000); std::stringstream disp_dec; if (dec < 10){ disp_dec << "00" << dec; } else if (dec < 100){ disp_dec << "0" << dec; } else{ disp_dec << dec; } return std::to_string(disp_val) + "." + disp_dec.str() + " " + getNumberSize(counter); } return std::to_string(value); } }; }
24.32381
120
0.53054
[ "object", "vector" ]
dace25b3cc871cb043dda9dc054edc85bdd7f6f0
2,061
cpp
C++
Threads Synchronization/Philosophers/main.cpp
Maxikq/Algorithms
cd76ca2f02ccd1d4e5b014373f6da5deb054ee93
[ "MIT" ]
2
2015-02-21T13:31:05.000Z
2016-04-05T07:54:04.000Z
Threads Synchronization/Philosophers/main.cpp
wojciech-kulik/Algorithms
cd76ca2f02ccd1d4e5b014373f6da5deb054ee93
[ "MIT" ]
null
null
null
Threads Synchronization/Philosophers/main.cpp
wojciech-kulik/Algorithms
cd76ca2f02ccd1d4e5b014373f6da5deb054ee93
[ "MIT" ]
1
2018-05-19T12:33:37.000Z
2018-05-19T12:33:37.000Z
#include <string> #include <iostream> #include <thread> #include <Windows.h> #include <random> #include <functional> #include <atomic> #include <mutex> #include <chrono> #include <array> using namespace std; mutex m; array<mutex, 5> forks; int random() { std::array<int, std::mt19937::state_size> seed_data; std::random_device r; std::generate_n(seed_data.data(), seed_data.size(), std::ref(r)); std::seed_seq seq(std::begin(seed_data), std::end(seed_data)); std::uniform_int_distribution<int> distribiuton(500, 2000); std::mt19937 engine; engine.seed(seq); auto generator = std::bind(distribiuton, engine); return generator(); } void philosopher(int id, int rightFork, int leftFork) { //http://en.wikipedia.org/wiki/Dining_philosophers_problem //Each philosopher eats only once, so algorithm will finish. //It bases on philosophers problem, but it doesn't solve starvation case (if you replace "while (hungry)" with "while (true)"). //It's just an example of synchronization. bool hungry = true; while (hungry) { forks[rightFork].lock(); m.lock(); cout << "Philosopher " << id + 1 << " picks up the right fork." << endl; m.unlock(); if (forks[leftFork].try_lock()) { m.lock(); cout << "Philosopher " << id + 1 << " picks up the left fork and eats." << endl; m.unlock(); this_thread::sleep_for(chrono::milliseconds(random())); m.lock(); cout << "Philosopher " << id + 1 << " puts down both forks." << endl; m.unlock(); forks[leftFork].unlock(); forks[rightFork].unlock(); hungry = false; } else { m.lock(); cout << "Philosopher " << id + 1 << " puts down the right fork and thinks." << endl; m.unlock(); forks[rightFork].unlock(); this_thread::sleep_for(chrono::milliseconds(random())); } } } int main() { vector<thread> philosophers; for (int i = 0; i < 5; i++) philosophers.push_back(thread(philosopher, i, i, (i + 1) % 5)); for (int i = 0; i < 5; i++) philosophers[i].join(); cout << "No more spaghetti..." << endl; system("pause"); return 0; }
22.9
128
0.649685
[ "vector" ]
dad42a4a0f7ace1ecb995391d1c623aa5529a833
1,364
cpp
C++
leetcode/problems/medium/1833-maximum-ice-cream-bars.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/medium/1833-maximum-ice-cream-bars.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/medium/1833-maximum-ice-cream-bars.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Maximum Ice Cream Bars https://leetcode.com/problems/maximum-ice-cream-bars/ It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. Return the maximum number of ice cream bars the boy can buy with coins coins. Note: The boy can buy the ice cream bars in any order. Example 1: Input: costs = [1,3,2,4,1], coins = 7 Output: 4 Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7. Example 2: Input: costs = [10,6,8,7,7,8], coins = 5 Output: 0 Explanation: The boy cannot afford any of the ice cream bars. Example 3: Input: costs = [1,6,3,1,2,5], coins = 20 Output: 6 Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18. Constraints: costs.length == n 1 <= n <= 105 1 <= costs[i] <= 105 1 <= coins <= 108 */ class Solution { public: int maxIceCream(vector<int>& costs, int coins) { int ans =0; sort(costs.begin(), costs.end()); for(auto c : costs) { if(coins - c < 0) break; ans++, coins -= c; } return ans; } };
26.745098
247
0.645894
[ "vector" ]
dad93a499678d6efb14107028edfaad338f986e9
10,095
cpp
C++
src/ImageTextureImpl.cpp
fuchsteufelswild/Ray-Tracer
d83553db691543b7925a31ca57139490547279c0
[ "MIT" ]
null
null
null
src/ImageTextureImpl.cpp
fuchsteufelswild/Ray-Tracer
d83553db691543b7925a31ca57139490547279c0
[ "MIT" ]
null
null
null
src/ImageTextureImpl.cpp
fuchsteufelswild/Ray-Tracer
d83553db691543b7925a31ca57139490547279c0
[ "MIT" ]
null
null
null
#include "ImageTextureImpl.h" #include "TextureReader.h" #include "Triangle.h" #include "Sphere.h" namespace actracer { static float GetAverageValue(const Vector3f& color); static void AssignRowsFromMatrix(const glm::mat3x2& matrix, glm::vec2& row1, glm::vec2& row2, glm::vec2& row3); ImageTextureImpl::~ImageTextureImpl() { if(mTextureReader) delete mTextureReader; } Vector3f ImageTextureImpl::GetBaseTextureColorForColorChange(const SurfaceIntersection &intersection) const { return RetrieveRGBFromUV(intersection.uv.x, intersection.uv.y) / mNormalizer; } ImageTextureImpl::ImageTextureImpl(const std::string& imagePath, float bumpFactor, int normalizer, ImageType imageType, InterpolationMethodCode interpolationMethodeCode) : TextureImpl(bumpFactor), mNormalizer(normalizer) { mTextureReader = TextureReader::CreateTextureReader(imagePath, imageType, interpolationMethodeCode); } Vector3f ImageTextureImpl::RetrieveRGBFromUV(float u, float v, float w) const { return mTextureReader->ComputeRGBValueOn(u, v); } Vector3f ImageTextureImpl::GetReplacedNormal(const SurfaceIntersection &intersectedSurfaceInformation, const Triangle *triangle) const { if(!triangle) return {}; glm::mat3x2 edgeMatrix = ComputePositionEdgeMatrixInObjectSpace(*triangle); glm::mat2x2 uvEdgeMatrix = glm::inverse(-ComputeUVEdgeMatrix(*triangle)); glm::mat3x2 combinedMatrix = uvEdgeMatrix * edgeMatrix; glm::vec2 row1, row2, row3; AssignRowsFromMatrix(combinedMatrix, row1, row2, row3); glm::vec3 tangent = Normalize(Vector3f(row1.x, row2.x, row3.x)); glm::vec3 bitangent = Normalize(Vector3f(row1.y, row2.y, row3.y)); glm::mat3x3 TBNMatrix(tangent, bitangent, triangle->GetNormal()); Vector3f textureNormal = ComputeNormalValueOn(intersectedSurfaceInformation.uv.x, intersectedSurfaceInformation.uv.y); return (TBNMatrix * textureNormal); } glm::mat3x2 ImageTextureImpl::ComputePositionEdgeMatrixInObjectSpace(const Triangle &triangle) const { const Vector3f &p0p1 = triangle.GetEdgeVectorFromFirstToSecondVertex(); const Vector3f &p0p2 = triangle.GetEdgeVectorFromFirstToThirdVertex(); return glm::mat3x2(glm::vec2(p0p1.x, p0p2.x), glm::vec2(p0p1.y, p0p2.y), glm::vec2(p0p1.z, p0p2.z)); } glm::mat2x2 ImageTextureImpl::ComputeUVEdgeMatrix(const Triangle &triangle) const { const Vertex *v0 = triangle.GetFirstVertex(); const Vertex *v1 = triangle.GetSecondVertex(); const Vertex *v2 = triangle.GetThirdVertex(); glm::vec2 v0v1UVEdgeVector = -glm::vec2(v0->uv.u - v1->uv.u, v0->uv.v - v1->uv.v); glm::vec2 v0v2UVEdgeVector = -glm::vec2(v0->uv.u - v2->uv.u, v0->uv.v - v2->uv.v); glm::mat2x2 uvEdgeMatrix(glm::vec2(v0v1UVEdgeVector.x, v0v2UVEdgeVector.x), glm::vec2(v0v1UVEdgeVector.y, v0v2UVEdgeVector.y)); return uvEdgeMatrix; } static void AssignRowsFromMatrix(const glm::mat3x2 &matrix, glm::vec2 &row1, glm::vec2 &row2, glm::vec2 &row3) { row1 = matrix[0]; row2 = matrix[1]; row3 = matrix[2]; } Vector3f ImageTextureImpl::ComputeNormalValueOn(float u, float v) const { Vector3f normal = mTextureReader->ComputeRGBValueOn(u, v) / 255.0f; normal = Normalize((normal - 0.5f) * 2.0f); // [0,1] -> [-1, 1] return normal; } Vector3f ImageTextureImpl::GetBumpedNormal(const SurfaceIntersection &intersectedSurfaceInformation, const Triangle *triangle) const { if(!triangle) return {}; glm::vec3 tangent, bitangent, normal; ComputeTBNVectors(*triangle, tangent, bitangent, normal); float standardColor, horizontalOffsetColor, verticalOffsetColor; ComputeTextureColorValues(intersectedSurfaceInformation.uv, standardColor, horizontalOffsetColor, verticalOffsetColor); // dpdu, dpdv // Tangents are tweaked using how much Color values are changed with very small u and v change glm::vec3 tweakedTangent = tangent + (horizontalOffsetColor - standardColor) * normal; glm::vec3 tweakedBitangent = bitangent + (verticalOffsetColor - standardColor) * normal; glm::vec3 bumpedNormal = glm::cross(tweakedTangent, tweakedBitangent); return Vector3f{bumpedNormal}; } void ImageTextureImpl::ComputeTBNVectors(const Triangle &triangle, glm::vec3 &tangent, glm::vec3 &bitangent, glm::vec3 &normal) const { glm::vec2 combinedMatrixRow1; glm::vec2 combinedMatrixRow2; glm::vec2 combinedMatrixRow3; AssignCombinedMatrixRows(triangle, combinedMatrixRow1, combinedMatrixRow2, combinedMatrixRow3); tangent = Normalize(Vector3f(combinedMatrixRow1.x, combinedMatrixRow2.x, combinedMatrixRow3.x)); bitangent = Normalize(Vector3f(combinedMatrixRow1.y, combinedMatrixRow2.y, combinedMatrixRow3.y)); normal = glm::cross(tangent, bitangent); tangent = tangent - normal * glm::dot(tangent, normal); bitangent = bitangent - glm::dot(bitangent, normal) * normal - glm::dot(tangent, bitangent) * tangent; } void ImageTextureImpl::AssignCombinedMatrixRows(const Triangle &triangle, glm::vec2 &row1, glm::vec2 &row2, glm::vec2 &row3) const { glm::mat3x2 edgeMatrix = ComputePositionEdgeMatrixInWorldSpace(triangle); glm::mat2x2 uvEdgeMatrix = glm::inverse(ComputeUVEdgeMatrix(triangle)); glm::mat3x2 combinedMatrix = uvEdgeMatrix * edgeMatrix; row1 = combinedMatrix[0]; row2 = combinedMatrix[1]; row3 = combinedMatrix[2]; } glm::mat3x2 ImageTextureImpl::ComputePositionEdgeMatrixInWorldSpace(const Triangle &triangle) const { // Transform into world space Vector3f p0p1t = (*triangle.GetObjectTransform())(-triangle.GetEdgeVectorFromFirstToSecondVertex(), true); Vector3f p0p2t = (*triangle.GetObjectTransform())(-triangle.GetEdgeVectorFromFirstToThirdVertex(), true); glm::vec3 firstEdgeVectorWorldSpace = p0p1t; glm::vec3 secondEdgeVectorWorldSpace = p0p2t; return glm::mat3x2(glm::vec2(firstEdgeVectorWorldSpace.x, secondEdgeVectorWorldSpace.x), glm::vec2(firstEdgeVectorWorldSpace.y, secondEdgeVectorWorldSpace.y), glm::vec2(firstEdgeVectorWorldSpace.z, secondEdgeVectorWorldSpace.z)); } void ImageTextureImpl::ComputeTextureColorValues(const Vector2f &intersectionPointUV, float &standardColor, float &horizontalColor, float &verticalColor, float uvOffsetEpsilon) const { float u = intersectionPointUV.x - std::floor(intersectionPointUV.x); float v = intersectionPointUV.y - std::floor(intersectionPointUV.y); float multiplier = mBumpFactor / 255; Vector3f uvColor = mTextureReader->ComputeRGBValueOn(u, v) * multiplier; Vector3f horizontalOffsetUVColor = mTextureReader->ComputeRGBValueOn(u + uvOffsetEpsilon, v) * multiplier; Vector3f verticalOffsetUVColor = mTextureReader->ComputeRGBValueOn(u, v + uvOffsetEpsilon) * multiplier; standardColor = GetAverageValue(uvColor); horizontalColor = GetAverageValue(horizontalOffsetUVColor); verticalColor = GetAverageValue(verticalOffsetUVColor); } static float GetAverageValue(const Vector3f &color) { return (color.x + color.y + color.z) / 3; } Vector3f ImageTextureImpl::GetReplacedNormal(const SurfaceIntersection &intersectedSurfaceInformation, const Sphere *sphere) const { if(!sphere) return {}; glm::vec3 tangent, bitangent, normal; ComputeTBNVectors(*sphere, intersectedSurfaceInformation, tangent, bitangent, normal); glm::mat3x3 TBNMatrix(tangent, bitangent, normal); Vector3f replacedNormal = TBNMatrix * ComputeNormalValueOn(intersectedSurfaceInformation.uv.x, intersectedSurfaceInformation.uv.y); return Normalize(replacedNormal); } Vector3f ImageTextureImpl::GetBumpedNormal(const SurfaceIntersection &intersectedSurfaceInformation, const Sphere *sphere) const { if(!sphere) return {}; glm::vec3 tangent, bitangent, normal; ComputeTBNVectors(*sphere, intersectedSurfaceInformation, tangent, bitangent, normal); float standardColor, horizontalOffsetColor, verticalOffsetColor; ComputeTextureColorValues(intersectedSurfaceInformation.uv, standardColor, horizontalOffsetColor, verticalOffsetColor, 0.002f); return ComputeSphereBumpedNormalFromTBN(tangent, bitangent, normal, standardColor, horizontalOffsetColor, verticalOffsetColor); } void ImageTextureImpl::ComputeTBNVectors(const Sphere &sphere, const SurfaceIntersection& intersection, glm::vec3 &tangent, glm::vec3 &bitangent, glm::vec3 &normal) const { Vector3f T, B; GetTangentValues(sphere, intersection, T, B); tangent = Normalize(T); bitangent = Normalize(B); normal = intersection.n; tangent = tangent - normal * glm::dot(tangent, normal); bitangent = bitangent - glm::dot(bitangent, normal) * normal - glm::dot(tangent, bitangent) * tangent; } void ImageTextureImpl::GetTangentValues(const Sphere &sphere, const SurfaceIntersection &intersection, Vector3f &tangent, Vector3f &bitangent) const { float phi = intersection.lip.y, theta = intersection.lip.x; float u = intersection.uv.u; float v = intersection.uv.v; float x = sphere.GetRadius() * std::sin(v * PI) * std::cos(PI - 2*u*PI); float y = sphere.GetRadius() * std::cos(v * PI); float z = sphere.GetRadius() * std::sin(v * PI) * std::sin(PI - 2*u*PI); tangent = Vector3f(2*z*PI, .0f, -2*x*PI); bitangent = Vector3f(y * std::cos(phi) * PI, -sphere.GetRadius() * std::sin(theta) * PI, y * std::sin(phi) * PI); } Vector3f ImageTextureImpl::ComputeSphereBumpedNormalFromTBN(const glm::vec3 &tangent, const glm::vec3 &bitangent, const glm::vec3 &normal, const float standardColor, const float horizontalOffsetColor, const float verticalOffsetColor) const { float horizontalDifference = (horizontalOffsetColor - standardColor); float verticalDifference = (verticalOffsetColor - standardColor); glm::vec3 bumpedNormal = normal - tangent*horizontalDifference - bitangent*verticalDifference; bumpedNormal = glm::normalize(bumpedNormal); if (glm::dot(bumpedNormal, normal) < 0) bumpedNormal *= -1; return bumpedNormal; } }
41.204082
182
0.741753
[ "transform" ]
daed278a94cca8bd3a9927b8883d988e04a4da36
1,394
cpp
C++
aws-cpp-sdk-databrew/source/model/CreateScheduleRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-databrew/source/model/CreateScheduleRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-databrew/source/model/CreateScheduleRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/databrew/model/CreateScheduleRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::GlueDataBrew::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateScheduleRequest::CreateScheduleRequest() : m_jobNamesHasBeenSet(false), m_cronExpressionHasBeenSet(false), m_tagsHasBeenSet(false), m_nameHasBeenSet(false) { } Aws::String CreateScheduleRequest::SerializePayload() const { JsonValue payload; if(m_jobNamesHasBeenSet) { Array<JsonValue> jobNamesJsonList(m_jobNames.size()); for(unsigned jobNamesIndex = 0; jobNamesIndex < jobNamesJsonList.GetLength(); ++jobNamesIndex) { jobNamesJsonList[jobNamesIndex].AsString(m_jobNames[jobNamesIndex]); } payload.WithArray("JobNames", std::move(jobNamesJsonList)); } if(m_cronExpressionHasBeenSet) { payload.WithString("CronExpression", m_cronExpression); } if(m_tagsHasBeenSet) { JsonValue tagsJsonMap; for(auto& tagsItem : m_tags) { tagsJsonMap.WithString(tagsItem.first, tagsItem.second); } payload.WithObject("Tags", std::move(tagsJsonMap)); } if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } return payload.View().WriteReadable(); }
20.80597
97
0.726686
[ "model" ]
8ccbb38e1d34e63417d6aa77a904a33c39c440ff
55,265
cpp
C++
sp/src/game/server/Human_Error/vehicle_drivable_apc.cpp
atp-tha/source-sdk-2013
8adf94f37107ce9e7a2678d75b91deb51243c8cb
[ "Unlicense" ]
12
2019-03-26T21:15:57.000Z
2022-03-16T14:53:14.000Z
sp/src/game/server/Human_Error/vehicle_drivable_apc.cpp
atp-tha/source-sdk-2013
8adf94f37107ce9e7a2678d75b91deb51243c8cb
[ "Unlicense" ]
8
2019-10-07T01:21:13.000Z
2022-03-26T16:53:42.000Z
sp/src/game/server/Human_Error/vehicle_drivable_apc.cpp
atp-tha/source-sdk-2013
8adf94f37107ce9e7a2678d75b91deb51243c8cb
[ "Unlicense" ]
4
2019-10-03T14:09:14.000Z
2020-12-30T12:03:38.000Z
//=================== Half-Life 2: Short Stories Mod 2007 =====================// // // Purpose: Drivable APC // //=============================================================================// #include "cbase.h" #include "engine/IEngineSound.h" #include "in_buttons.h" #include "ammodef.h" #include "IEffects.h" #include "beam_shared.h" #include "soundenvelope.h" #include "decals.h" #include "soundent.h" #include "grenade_ar2.h" #include "te_effect_dispatch.h" //for the stuff that kills NPCs from the way of the APC #include "vphysics/friction.h" #include "vphysicsupdateai.h" #include "physics_npc_solver.h" #include "hl2_player.h" #include "ndebugoverlay.h" #include "movevars_shared.h" #include "bone_setup.h" #include "ai_basenpc.h" #include "ai_hint.h" #include "npc_crow.h" #include "globalstate.h" #include "vehicle_drivable_apc.h" #include "weapon_rpg.h" #include "rumble_shared.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define VEHICLE_HITBOX_DRIVER 1 #define LOCK_SPEED 10 #define APC_GUN_YAW "vehicle_weapon_yaw" #define APC_GUN_PITCH "vehicle_weapon_pitch" #define APC_LOWER_VIEW "vehicle_lower_view" #define CANNON_MAX_UP_PITCH 45 #define CANNON_MAX_DOWN_PITCH 11 #define CANNON_MAX_LEFT_YAW 90 #define CANNON_MAX_RIGHT_YAW 90 #define OVERTURNED_EXIT_WAITTIME 2.0f #define APC_STEERING_SLOW_ANGLE 50.0f #define APC_STEERING_FAST_ANGLE 15.0f #define APC_DELTA_LENGTH_MAX 12.0f // 1 foot #define APC_FRAMETIME_MIN 1e-6 //APC defines: #define MACHINE_GUN_BURST_SIZE 100 #define MACHINE_GUN_BURST_TIME 0.075f #define MACHINE_GUN_RELOAD_TIME 0.15f #define ROCKET_SALVO_SIZE 3 #define ROCKET_DELAY_TIME 0.75 #define ROCKET_MIN_BURST_PAUSE_TIME 3 #define ROCKET_MAX_BURST_PAUSE_TIME 4 #define ROCKET_SPEED 1500 //Originally 800 #define DEATH_VOLLEY_ROCKET_COUNT 4 #define DEATH_VOLLEY_MIN_FIRE_TIME 0.333 #define DEATH_VOLLEY_MAX_FIRE_TIME 0.166 ConVar hud_apchint_numentries( "hud_apchint_numentries", "10", FCVAR_NONE ); ConVar g_apcexitspeed( "g_apcexitspeed", "100", FCVAR_CHEAT ); extern ConVar autoaim_max_dist; extern ConVar phys_upimpactforcescale; //ConVar apc_pitch_fix("hlss_apc_pitch_fix", "0" ); #define HLSS_APC_PITCH_FIX -1.5f ConVar apc_zoomed_pitch_fix("hlss_apc_zoomed_pitch_fix", "0" ); ConVar apc_zoomed_yaw_fix("hlss_apc_zoomed_yaw_fix", "0" ); ConVar apc_no_rpg_while_moving( "hlss_apc_no_rpg_while_moving", "0", FCVAR_CHEAT ); //ConVar apc_hull_trace_attack(" hlss_apc_hull_trace_attack", "1", FCVAR_CHEAT ); #ifdef EZ ConVar sk_apc_damage_normal( "sk_apc_damage_normal", "0.15" ); ConVar sk_apc_damage_blast( "sk_apc_damage_blast", "0.1" ); ConVar sk_apc_damage_vort( "sk_apc_damage_vort", "0.75" ); #endif static void SolveBlockingProps( bool bBreakProps, CPropDrivableAPC *pVehicleEntity, IPhysicsObject *pVehiclePhysics ); static void SimpleCollisionResponse( Vector velocityIn, const Vector &normal, float coefficientOfRestitution, Vector *pVelocityOut ); static void KillBlockingEnemyNPCs( CBasePlayer *pPlayer, CBaseEntity *pVehicleEntity, IPhysicsObject *pVehiclePhysics ); int HLSS_SelectTargetType(CBaseEntity *pEntity); BEGIN_DATADESC( CPropDrivableAPC ) DEFINE_FIELD( m_flDangerSoundTime, FIELD_TIME ), DEFINE_FIELD( m_vecGunOrigin, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_aimYaw, FIELD_FLOAT ), DEFINE_FIELD( m_aimPitch, FIELD_FLOAT ), DEFINE_FIELD( m_throttleDisableTime, FIELD_TIME ), DEFINE_FIELD( m_flHandbrakeTime, FIELD_TIME ), DEFINE_FIELD( m_bInitialHandbrake, FIELD_BOOLEAN ), DEFINE_FIELD( m_flOverturnedTime, FIELD_TIME ), DEFINE_FIELD( m_vecLastEyePos, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_vecLastEyeTarget, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_vecEyeSpeed, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_vecTargetSpeed, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_bHeadlightIsOn, FIELD_BOOLEAN ), DEFINE_FIELD( m_iNumberOfEntries, FIELD_INTEGER ), DEFINE_FIELD( m_flPlayerExitedTime, FIELD_TIME ), DEFINE_FIELD( m_flLastSawPlayerAt, FIELD_TIME ), DEFINE_FIELD( m_hLastPlayerInVehicle, FIELD_EHANDLE ), DEFINE_FIELD( m_bIsMounted, FIELD_BOOLEAN ), DEFINE_FIELD( m_hTarget, FIELD_EHANDLE ), DEFINE_FIELD( m_iTargetType, FIELD_INTEGER ), DEFINE_FIELD( m_flTargetSelectTime, FIELD_TIME ), DEFINE_FIELD( m_flLaserTargetTime, FIELD_TIME ), DEFINE_FIELD( m_flMachineGunTime, FIELD_TIME ), DEFINE_FIELD( m_flMachineGunReloadTime, FIELD_TIME), DEFINE_FIELD( m_iMachineGunBurstLeft, FIELD_INTEGER ), DEFINE_FIELD( m_nMachineGunMuzzleAttachment, FIELD_INTEGER ), DEFINE_FIELD( m_nMachineGunBaseAttachment, FIELD_INTEGER ), DEFINE_FIELD( m_hRocketTarget, FIELD_EHANDLE ), DEFINE_FIELD( m_iRocketSalvoLeft, FIELD_INTEGER ), DEFINE_FIELD( m_flRocketTime, FIELD_TIME ), DEFINE_FIELD( m_flRocketReloadTime, FIELD_TIME ), DEFINE_FIELD( m_flNextPropAttackTime, FIELD_TIME ), DEFINE_FIELD( m_flStopBreakTime, FIELD_TIME ), DEFINE_FIELD( m_bShouldAttackProps, FIELD_BOOLEAN ), DEFINE_KEYFIELD( m_bCannotMove, FIELD_BOOLEAN, "cannotmove" ), DEFINE_FIELD( m_nRocketSide, FIELD_INTEGER ), DEFINE_FIELD( m_flViewLowered, FIELD_FLOAT ), // DEFINE_FIELD( m_bForcePlayerOut, FIELD_BOOLEAN ), DEFINE_INPUTFUNC( FIELD_VOID, "ForcePlayerOut", InputForcePlayerOut ), DEFINE_INPUTFUNC( FIELD_VOID, "EnableMove", InputEnableMove ), DEFINE_INPUTFUNC( FIELD_VOID, "DisableMove", InputDisableMove ), #ifdef EZ DEFINE_OUTPUT( m_onOverturned, "OnOverturned" ) #endif END_DATADESC() IMPLEMENT_SERVERCLASS_ST( CPropDrivableAPC, DT_PropDrivableAPC ) SendPropBool( SENDINFO( m_bHeadlightIsOn ) ), SendPropInt( SENDINFO( m_iMachineGunBurstLeft ) ), SendPropInt( SENDINFO( m_iRocketSalvoLeft ) ), SendPropBool( SENDINFO( m_bIsMounted ) ), SendPropEHandle(SENDINFO(m_hTarget)), SendPropInt( SENDINFO( m_iTargetType ) ), // SendPropBool( SENDINFO( m_bHasTarget ) ), END_SEND_TABLE(); LINK_ENTITY_TO_CLASS( prop_vehicle_drivable_apc, CPropDrivableAPC ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CPropDrivableAPC::CPropDrivableAPC( void ) { m_flOverturnedTime = 0.0f; m_iNumberOfEntries = 0; m_vecEyeSpeed.Init(); m_bUnableToFire = true; m_bCannotMove = false; //TERO: lets start with full ammo m_iMachineGunBurstLeft = MACHINE_GUN_BURST_SIZE; m_iRocketSalvoLeft = ROCKET_SALVO_SIZE; m_flNextPropAttackTime = 0 ; m_flStopBreakTime = 0; m_bShouldAttackProps = false; } void CPropDrivableAPC::InputDisableMove( inputdata_t &inputdata ) { m_bCannotMove = true; } void CPropDrivableAPC::InputEnableMove( inputdata_t &inputdata ) { m_bCannotMove = false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::CreateServerVehicle( void ) { // Create our armed server vehicle m_pServerVehicle = new CDrivableAPCFourWheelServerVehicle(); m_pServerVehicle->SetVehicle( this ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::Precache( void ) { PrecacheScriptSound( "Weapon_AR2.Single" ); PrecacheScriptSound( "PropAPC.FireRocket" ); PrecacheScriptSound( "combine.door_lock" ); PrecacheScriptSound( "Airboat_headlight_on" ); PrecacheScriptSound( "Airboat_headlight_off" ); PrecacheModel( "sprites/redglow1.vmt" ); BaseClass::Precache(); } //------------------------------------------------ // Spawn //------------------------------------------------ void CPropDrivableAPC::Spawn( void ) { // Setup vehicle as a real-wheels car. SetVehicleType( VEHICLE_TYPE_CAR_WHEELS ); SetCollisionGroup( COLLISION_GROUP_VEHICLE ); BaseClass::Spawn(); m_flHandbrakeTime = gpGlobals->curtime + 0.1; m_bInitialHandbrake = false; m_flMinimumSpeedToEnterExit = LOCK_SPEED; // Initialize pose parameters SetPoseParameter( APC_GUN_YAW, 0 ); SetPoseParameter( APC_GUN_PITCH, 0 ); m_aimYaw = 0; m_aimPitch = 0; m_flViewLowered = 0; SetPoseParameter( APC_LOWER_VIEW, 0 ); m_flTargetSelectTime = 0; m_hTarget = NULL; CreateAPCLaserDot(); AddSolidFlags( FSOLID_NOT_STANDABLE ); // m_bForcePlayerOut = false; } //----------------------------------------------------------------------------- // Purpose: Create a laser //----------------------------------------------------------------------------- void CPropDrivableAPC::CreateAPCLaserDot( void ) { // Create a laser if we don't have one if ( m_hLaserDot == NULL ) { m_hLaserDot = CreateLaserDot( GetAbsOrigin(), this, false ); } } //----------------------------------------------------------------------------- // Aims the secondary weapon at a target //----------------------------------------------------------------------------- void CPropDrivableAPC::AimSecondaryWeaponAt( CBaseEntity *pTarget ) { m_hRocketTarget = pTarget; // Update the rocket target CreateAPCLaserDot(); if ( m_hRocketTarget ) { m_hLaserDot->SetAbsOrigin( m_hRocketTarget->BodyTarget( WorldSpaceCenter(), false ) ); } if (m_hLaserDot) { SetLaserDotTarget( m_hLaserDot, m_hRocketTarget ); EnableLaserDot( m_hLaserDot, m_hRocketTarget != NULL ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::UpdateOnRemove( void ) { if ( m_hLaserDot ) { UTIL_Remove( m_hLaserDot ); m_hLaserDot = NULL; } BaseClass::UpdateOnRemove(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CPropDrivableAPC::Activate() { BaseClass::Activate(); CBaseServerVehicle *pServerVehicle = dynamic_cast<CBaseServerVehicle *>(GetServerVehicle()); if ( pServerVehicle ) { if( pServerVehicle->GetPassenger() ) { // If a jeep comes back from a save game with a driver, make sure the engine rumble starts up. pServerVehicle->StartEngineRumble(); } } m_nRocketAttachment = LookupAttachment( "cannon_muzzle" ); m_nMachineGunMuzzleAttachment = LookupAttachment( "Muzzle" ); m_nMachineGunBaseAttachment = LookupAttachment( "gun_base" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::TraceAttack( const CTakeDamageInfo &inputInfo, const Vector &vecDir, trace_t *ptr ) { CTakeDamageInfo info = inputInfo; if (info.GetAttacker() && info.GetAttacker()->MyNPCPointer() && info.GetAttacker()->IsAlive() && CBaseCombatCharacter::GetDefaultRelationshipDispositionBetweenClasses( CLASS_PLAYER, info.GetAttacker()->Classify() ) != D_LI ) { if (!m_hTarget || m_flTargetSelectTime < gpGlobals->curtime) { #ifdef EZ if ( m_hTarget != NULL && m_hTarget->MyNPCPointer() != NULL ) { m_hTarget->MyNPCPointer()->RemoveGlowEffect(); } if ( info.GetAttacker()->MyNPCPointer() != NULL ) { info.GetAttacker()->MyNPCPointer()->AddGlowEffect(); } #endif m_hTarget = info.GetAttacker(); m_iTargetType = HLSS_SelectTargetType(m_hTarget); } } if ( ptr->hitbox != VEHICLE_HITBOX_DRIVER ) { if ( inputInfo.GetDamageType() & DMG_BULLET ) { info.ScaleDamage( 0.0001 ); } } BaseClass::TraceAttack( info, vecDir, ptr, NULL ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CPropDrivableAPC::OnTakeDamage( const CTakeDamageInfo &inputInfo ) { //Do scaled up physics damage to the car CTakeDamageInfo info = inputInfo; /*info.ScaleDamage( 5 ); //25 // HACKHACK: Scale up grenades until we get a better explosion/pressure damage system if ( inputInfo.GetDamageType() & DMG_BLAST ) { info.SetDamageForce( inputInfo.GetDamageForce() * 10 ); } VPhysicsTakeDamage( info ); // reset the damage info.SetDamage( inputInfo.GetDamage() );*/ // small amounts of shock damage disrupt the car, but aren't transferred to the player /*if ( info.GetDamageType() == DMG_SHOCK ) { if ( info.GetDamage() <= 10 ) { // take 10% damage and make the engine stall info.ScaleDamage( 0.1 ); m_throttleDisableTime = gpGlobals->curtime + 2; } }*/ //Check to do damage to driver if ( GetDriver() ) { float flNormalDamageModifier = sk_apc_damage_normal.GetFloat(); #ifdef EZ // In Human Error, the view hide damage reduce percent modifier was half of the normal damage modifier divided by the maximum flViewLowered distance, 10 // 0.15 / 2 / 10 = 0.0075 // In Entropy : Zero, we want it to have half of the normal damage modifier divided by 10 float flViewHideDamageReduce = flNormalDamageModifier / 20.0f; #else float flViewHideDamageReduce = (float)(m_flViewLowered * 0.0075); #endif //Take no damage from physics damages if ( info.GetDamageType() & DMG_CRUSH ) return 0; //We want to get more damage from vortigaunts if ( info.GetDamageType() == DMG_SHOCK ) { #ifdef EZ info.ScaleDamage( sk_apc_damage_vort.GetFloat() ); #else info.ScaleDamage( 0.75f ); #endif } else if (!m_bExitAnimOn && !m_bEnterAnimOn) { #ifdef EZ if (info.GetDamageType() & DMG_BLAST) info.ScaleDamage( MAX( sk_apc_damage_blast.GetFloat() + flViewHideDamageReduce, 0.0f) ); else info.ScaleDamage( MAX( flNormalDamageModifier + flViewHideDamageReduce, 0.0f) ); #else if ( info.GetDamageType() & DMG_BLAST ) info.ScaleDamage( 0.1 + flViewHideDamageReduce ); else info.ScaleDamage( 0.15 + flViewHideDamageReduce ); #endif } // Take the damage (strip out the DMG_BLAST) info.SetDamageType( info.GetDamageType() & (~DMG_BLAST) ); GetDriver()->TakeDamage( info ); } return 0; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- Vector CPropDrivableAPC::BodyTarget( const Vector &posSrc, bool bNoisy ) { Vector shotPos; matrix3x4_t matrix; int eyeAttachmentIndex = LookupAttachment("vehicle_driver_eyes"); GetAttachment( eyeAttachmentIndex, matrix ); MatrixGetColumn( matrix, 3, shotPos ); if ( bNoisy ) { shotPos[0] += random->RandomFloat( -8.0f, 8.0f ); shotPos[1] += random->RandomFloat( -8.0f, 8.0f ); shotPos[2] += random->RandomFloat( -8.0f, 8.0f ); } return shotPos; } //----------------------------------------------------------------------------- // Purpose: Aim Gun at a target //----------------------------------------------------------------------------- void CPropDrivableAPC::AimGunAt( Vector *endPos, float flInterval ) { Vector aimPos = *endPos; // See if the gun should be allowed to aim if ( IsOverturned() || m_bEngineLocked ) { SetPoseParameter( APC_GUN_YAW, 0 ); SetPoseParameter( APC_GUN_PITCH, 0 ); return; // Make the gun go limp and look "down" Vector v_forward, v_up; AngleVectors( GetLocalAngles(), NULL, &v_forward, &v_up ); aimPos = WorldSpaceCenter() + ( v_forward * -32.0f ) - Vector( 0, 0, 128.0f ); } matrix3x4_t gunMatrix; GetAttachment( LookupAttachment("gun_ref"), gunMatrix ); // transform the enemy into gun space Vector localEnemyPosition; VectorITransform( aimPos, gunMatrix, localEnemyPosition ); // do a look at in gun space (essentially a delta-lookat) QAngle localEnemyAngles; VectorAngles( localEnemyPosition, localEnemyAngles ); // convert to +/- 180 degrees localEnemyAngles.x = UTIL_AngleDiff( localEnemyAngles.x, 0 ); localEnemyAngles.y = UTIL_AngleDiff( localEnemyAngles.y, 0 ); float targetYaw = m_aimYaw + localEnemyAngles.y; float targetPitch = m_aimPitch + localEnemyAngles.x; //TERO: a silly trick to able different pose parameters float max_down_pitch = 4; float yaw = GetPoseParameter( APC_GUN_YAW ); if (yaw < 0) { yaw = -yaw; float yaw_fix = ((yaw - 90)/90); max_down_pitch += ((1 - (yaw_fix * yaw_fix)) * 37); //this sets the pitch down max to 45 if yaw is -90 } max_down_pitch += (8 - (yaw / 22.5)); //from 0 to 8, this sets the original pitch down max of 4 to 12 if yaw is -180 or 180 // Constrain our angles float newTargetYaw = targetYaw; float newTargetPitch = HLSS_APC_PITCH_FIX + clamp( targetPitch, -CANNON_MAX_UP_PITCH, max_down_pitch ); //newTargetYaw += apc_zoomed_yaw_fix.GetFloat(); //newTargetPitch += apc_zoomed_pitch_fix.GetFloat(); //DevMsg("newTargetPitch: %f\n", newTargetPitch); // If the angles have been clamped, we're looking outside of our valid range if ( fabs(newTargetYaw-targetYaw) > 1e-4 || fabs(newTargetPitch-targetPitch) > 1e-4 ) { m_bUnableToFire = true; } targetYaw = newTargetYaw; targetPitch = newTargetPitch; // Exponentially approach the target float yawSpeed = 8; float pitchSpeed = 8; m_aimYaw = UTIL_Approach( targetYaw, m_aimYaw, yawSpeed ); m_aimPitch = UTIL_Approach( targetPitch, m_aimPitch, pitchSpeed ); SetPoseParameter( APC_GUN_YAW, -m_aimYaw); SetPoseParameter( APC_GUN_PITCH, -m_aimPitch ); InvalidateBoneCache(); // read back to avoid drift when hitting limits // as long as the velocity is less than the delta between the limit and 180, this is fine. m_aimPitch = -GetPoseParameter( APC_GUN_PITCH ); m_aimYaw = -GetPoseParameter( APC_GUN_YAW ); // Now draw crosshair for actual aiming point Vector vecMuzzle, vecMuzzleDir; QAngle vecMuzzleAng; GetAttachment( "Muzzle", vecMuzzle, vecMuzzleAng ); AngleVectors( vecMuzzleAng, &vecMuzzleDir ); trace_t tr; UTIL_TraceLine( vecMuzzle, vecMuzzle + (vecMuzzleDir * MAX_TRACE_LENGTH), MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); // see if we hit something, if so, adjust endPos to hit location if ( m_hLaserDot && tr.fraction < 1.0 ) { m_vecGunCrosshair = vecMuzzle + ( vecMuzzleDir * MAX_TRACE_LENGTH * tr.fraction ); m_hLaserDot->SetAbsOrigin( tr.endpos ); EnableLaserDot( m_hLaserDot, true ); /*if ( tr.m_pEnt && tr.m_pEnt->IsNPC() && tr.m_pEnt->MyNPCPointer() && m_hPlayer && tr.m_pEnt->MyNPCPointer()->IsValidEnemy(m_hPlayer) ) { SetLaserDotTarget( m_hLaserDot, tr.m_pEnt ); m_bHasTarget = true; } else { SetLaserDotTarget( m_hLaserDot, NULL ); }*/ if (tr.m_pEnt && tr.m_pEnt->MyNPCPointer() && CBaseCombatCharacter::GetDefaultRelationshipDispositionBetweenClasses( CLASS_PLAYER, tr.m_pEnt->Classify() ) == D_HT ) { SetLaserDotTarget( m_hLaserDot, tr.m_pEnt ); m_flLaserTargetTime = gpGlobals->curtime + 0.6f; if (tr.m_pEnt->IsAlive()) { #ifdef EZ if ( m_hTarget != NULL && m_hTarget->MyNPCPointer() != NULL ) { m_hTarget->MyNPCPointer()->RemoveGlowEffect( ); } if ( tr.m_pEnt->MyNPCPointer() != NULL ) { tr.m_pEnt->MyNPCPointer()->AddGlowEffect(); } #endif m_hTarget = tr.m_pEnt; //TERO: don't change from this target for a moment m_flTargetSelectTime = gpGlobals->curtime + 0.6f; m_iTargetType = HLSS_SelectTargetType(m_hTarget); } } else if (m_flLaserTargetTime < gpGlobals->curtime) { SetLaserDotTarget( m_hLaserDot, NULL ); } //m_hLaserDot->SetLaserPosition( tr.endpos, tr.plane.normal ); } // Update the rocket target CreateAPCLaserDot(); if (!DoesLaserDotHaveTarget( m_hLaserDot )) { m_hLaserDot->SetAbsOrigin( *endPos ); } if (m_hLaserDot) EnableLaserDot( m_hLaserDot, true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::Think(void) { BaseClass::Think(); CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if ( m_bEngineLocked ) { m_bUnableToFire = true; if ( pPlayer != NULL ) { pPlayer->m_Local.m_iHideHUD |= HIDEHUD_VEHICLE_CROSSHAIR; } } else { // Start this as false and update it again each frame m_bUnableToFire = false; if ( pPlayer != NULL ) { pPlayer->m_Local.m_iHideHUD &= ~HIDEHUD_VEHICLE_CROSSHAIR; } } SetSimulationTime( gpGlobals->curtime ); SetNextThink( gpGlobals->curtime ); SetAnimatedEveryTick( true ); if ( !m_bInitialHandbrake ) // after initial timer expires, set the handbrake { m_bInitialHandbrake = true; m_VehiclePhysics.SetHandbrake( true ); m_VehiclePhysics.Think(); } // Check overturned status. if ( !IsOverturned() ) { m_flOverturnedTime = 0.0f; } else { #ifdef EZ if (m_flOverturnedTime == 0.0f ) { // Fire an output m_onOverturned.FireOutput( this, this, 0 ); } #endif m_flOverturnedTime += gpGlobals->frametime; } // Aim gun based on the player view direction. if ( m_hPlayer && !m_bExitAnimOn && !m_bEnterAnimOn ) { if (m_flMachineGunReloadTime < gpGlobals->curtime && m_iMachineGunBurstLeft < MACHINE_GUN_BURST_SIZE) { m_iMachineGunBurstLeft++; m_flMachineGunReloadTime = gpGlobals->curtime + MACHINE_GUN_RELOAD_TIME; } if (m_flRocketReloadTime < gpGlobals->curtime && m_iRocketSalvoLeft < ROCKET_SALVO_SIZE) { m_iRocketSalvoLeft++; m_flRocketReloadTime = gpGlobals->curtime + random->RandomFloat( ROCKET_MIN_BURST_PAUSE_TIME + 1, ROCKET_MAX_BURST_PAUSE_TIME + 1 ); } /*Vector vecEyeDir, vecEyePos; m_hPlayer->EyePositionAndVectors( &vecEyePos, NULL, NULL, NULL ); //second one used to be &vecEyeDir QAngle angEyeDir = m_hPlayer->EyeAngles(); //TERO: attempt to fix the zoom aiming float angleFix = (m_hPlayer->GetDefaultFOV() / m_hPlayer->GetFOV()) - 1; angEyeDir.x -= angleFix; // * 0.5; AngleVectors(angEyeDir, &vecEyeDir); // Trace out from the player's eye point. Vector vecEndPos = vecEyePos + ( vecEyeDir * MAX_TRACE_LENGTH ); trace_t trace; UTIL_TraceLine( vecEyePos, vecEndPos, MASK_SHOT, this, COLLISION_GROUP_NONE, &trace );*/ Vector vecEndPos, vecEyePos, vecEyeDirection; m_hPlayer->EyePositionAndVectors( &vecEyePos, &vecEyeDirection, NULL, NULL ); vecEndPos = vecEyePos + ( vecEyeDirection * MAX_TRACE_LENGTH ); trace_t trace; UTIL_TraceLine( vecEyePos, vecEndPos, MASK_SHOT, this, COLLISION_GROUP_NONE, &trace ); vecEndPos = trace.endpos; // See if we hit something, if so, adjust end position to hit location. /*if ( trace.fraction < 1.0 ) { vecEndPos = vecEyePos + ( vecEyeDir * MAX_TRACE_LENGTH * trace.fraction ); }*/ if ( m_hTarget && !m_hTarget->IsAlive() ) { #ifdef EZ if ( m_hTarget->MyNPCPointer() != NULL ) { m_hTarget->MyNPCPointer()->RemoveGlowEffect(); } #endif m_hTarget = NULL; } //NDebugOverlay::Box(vecEndPos, Vector(-1,-1,-1),Vector(1,1,1), 255, 0, 255, 0, 0.1); //m_vecLookCrosshair = vecEndPos; AimGunAt( &vecEndPos, 0.1f ); // AimSecondaryWeaponAt( &vecEndPos, 0.1f); } StudioFrameAdvance(); // If the enter or exit animation has finished, tell the server vehicle if ( IsSequenceFinished() && (m_bExitAnimOn || m_bEnterAnimOn) ) { if ( m_bEnterAnimOn ) { m_VehiclePhysics.ReleaseHandbrake(); StartEngine(); // HACKHACK: This forces the jeep to play a sound when it gets entered underwater if ( m_VehiclePhysics.IsEngineDisabled() ) { CBaseServerVehicle *pServerVehicle = dynamic_cast<CBaseServerVehicle *>(GetServerVehicle()); if ( pServerVehicle ) { pServerVehicle->SoundStartDisabled(); } } // The first few time we get into the jeep, print the jeep help if ( m_iNumberOfEntries < hud_apchint_numentries.GetInt() ) { UTIL_HudHintText( m_hPlayer, "#HLSS_Hint_APC" ); m_iNumberOfEntries++; } } // If we're exiting and have had the tau cannon removed, we don't want to reset the animation GetServerVehicle()->HandleEntryExitFinish( m_bExitAnimOn, !m_bExitAnimOn ); } /*if (m_bForcePlayerOut) { GetServerVehicle()->HandlePassengerExit( m_hPlayer ); }*/ } //----------------------------------------------------------------------------- // Purpose: If the player uses the jeep while at the back, he gets ammo from the crate instead //----------------------------------------------------------------------------- void CPropDrivableAPC::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { /*CBasePlayer *pPlayer = ToBasePlayer( pActivator ); if ( pPlayer == NULL) return; // Find out if the player's looking at our ammocrate hitbox Vector vecForward; pPlayer->EyeVectors( &vecForward, NULL, NULL ); trace_t tr; Vector vecStart = pPlayer->EyePosition(); UTIL_TraceLine( vecStart, vecStart + vecForward * 1024, MASK_SOLID | CONTENTS_DEBRIS | CONTENTS_HITBOX, pPlayer, COLLISION_GROUP_NONE, &tr ); if ( tr.m_pEnt == this && tr.hitgroup == JEEP_AMMOCRATE_HITGROUP ) { // Player's using the crate. // Fill up his SMG ammo. pPlayer->GiveAmmo( 300, "SMG1"); if ( ( GetSequence() != LookupSequence( "ammo_open" ) ) && ( GetSequence() != LookupSequence( "ammo_close" ) ) ) { // Open the crate m_flAnimTime = gpGlobals->curtime; m_flPlaybackRate = 0.0; SetCycle( 0 ); ResetSequence( LookupSequence( "ammo_open" ) ); CPASAttenuationFilter sndFilter( this, "PropJeep.AmmoOpen" ); EmitSound( sndFilter, entindex(), "PropJeep.AmmoOpen" ); } m_flAmmoCrateCloseTime = gpGlobals->curtime + JEEP_AMMO_CRATE_CLOSE_DELAY; return; }*/ // Fall back and get in the vehicle instead BaseClass::Use( pActivator, pCaller, useType, value ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CPropDrivableAPC::CanExitVehicle( CBaseEntity *pEntity ) { return ( !m_bEnterAnimOn && !m_bExitAnimOn && !m_bLocked && (m_nSpeed <= g_apcexitspeed.GetFloat() ) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::DampenEyePosition( Vector &vecVehicleEyePos, QAngle &vecVehicleEyeAngles ) { // Get the frametime. (Check to see if enough time has passed to warrent dampening). float flFrameTime = gpGlobals->frametime; if ( flFrameTime < APC_FRAMETIME_MIN ) { vecVehicleEyePos = m_vecLastEyePos; DampenUpMotion( vecVehicleEyePos, vecVehicleEyeAngles, 0.0f ); return; } // Keep static the sideways motion. // Dampen forward/backward motion. DampenForwardMotion( vecVehicleEyePos, vecVehicleEyeAngles, flFrameTime ); // Blend up/down motion. DampenUpMotion( vecVehicleEyePos, vecVehicleEyeAngles, flFrameTime ); } //----------------------------------------------------------------------------- // Use the controller as follows: // speed += ( pCoefficientsOut[0] * ( targetPos - currentPos ) + pCoefficientsOut[1] * ( targetSpeed - currentSpeed ) ) * flDeltaTime; //----------------------------------------------------------------------------- void CPropDrivableAPC::ComputePDControllerCoefficients( float *pCoefficientsOut, float flFrequency, float flDampening, float flDeltaTime ) { float flKs = 9.0f * flFrequency * flFrequency; float flKd = 4.5f * flFrequency * flDampening; float flScale = 1.0f / ( 1.0f + flKd * flDeltaTime + flKs * flDeltaTime * flDeltaTime ); pCoefficientsOut[0] = flKs * flScale; pCoefficientsOut[1] = ( flKd + flKs * flDeltaTime ) * flScale; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::DampenForwardMotion( Vector &vecVehicleEyePos, QAngle &vecVehicleEyeAngles, float flFrameTime ) { // Get forward vector. Vector vecForward; AngleVectors( vecVehicleEyeAngles, &vecForward); // Simulate the eye position forward based on the data from last frame // (assumes no acceleration - it will get that from the "spring"). Vector vecCurrentEyePos = m_vecLastEyePos + m_vecEyeSpeed * flFrameTime; // Calculate target speed based on the current vehicle eye position and the last vehicle eye position and frametime. Vector vecVehicleEyeSpeed = ( vecVehicleEyePos - m_vecLastEyeTarget ) / flFrameTime; m_vecLastEyeTarget = vecVehicleEyePos; // Calculate the speed and position deltas. Vector vecDeltaSpeed = vecVehicleEyeSpeed - m_vecEyeSpeed; Vector vecDeltaPos = vecVehicleEyePos - vecCurrentEyePos; // Clamp. if ( vecDeltaPos.Length() > APC_DELTA_LENGTH_MAX ) { float flSign = vecForward.Dot( vecVehicleEyeSpeed ) >= 0.0f ? -1.0f : 1.0f; vecVehicleEyePos += flSign * ( vecForward * APC_DELTA_LENGTH_MAX ); m_vecLastEyePos = vecVehicleEyePos; m_vecEyeSpeed = vecVehicleEyeSpeed; return; } // Generate an updated (dampening) speed for use in next frames position extrapolation. float flCoefficients[2]; ComputePDControllerCoefficients( flCoefficients, r_JeepViewDampenFreq.GetFloat(), r_JeepViewDampenDamp.GetFloat(), flFrameTime ); m_vecEyeSpeed += ( ( flCoefficients[0] * vecDeltaPos + flCoefficients[1] * vecDeltaSpeed ) * flFrameTime ); // Save off data for next frame. m_vecLastEyePos = vecCurrentEyePos; // Move eye forward/backward. Vector vecForwardOffset = vecForward * ( vecForward.Dot( vecDeltaPos ) ); vecVehicleEyePos -= vecForwardOffset; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::DampenUpMotion( Vector &vecVehicleEyePos, QAngle &vecVehicleEyeAngles, float flFrameTime ) { // Get up vector. Vector vecUp; AngleVectors( vecVehicleEyeAngles, NULL, NULL, &vecUp ); vecUp.z = clamp( vecUp.z, 0.0f, vecUp.z ); vecVehicleEyePos.z += r_JeepViewZHeight.GetFloat() * vecUp.z; // NOTE: Should probably use some damped equation here. } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::SetupMove( CBasePlayer *player, CUserCmd *ucmd, IMoveHelper *pHelper, CMoveData *move ) { // If we are overturned and hit any key - leave the vehicle (IN_USE is already handled!). if ( m_flOverturnedTime > OVERTURNED_EXIT_WAITTIME ) { if ( (ucmd->buttons & (IN_FORWARD|IN_BACK|IN_MOVELEFT|IN_MOVERIGHT|IN_SPEED|IN_JUMP|IN_ATTACK|IN_ATTACK2) ) && !m_bExitAnimOn ) { // Can't exit yet? We're probably still moving. Swallow the keys. if ( !CanExitVehicle(player) ) return; if ( !GetServerVehicle()->HandlePassengerExit( m_hPlayer ) && ( m_hPlayer != NULL ) ) { m_hPlayer->PlayUseDenySound(); } return; } } // If the throttle is disabled or we're upside-down, don't allow throttling (including turbo) CUserCmd tmp; if ( ( m_throttleDisableTime > gpGlobals->curtime ) || ( IsOverturned() ) ) { m_bUnableToFire = true; tmp = (*ucmd); tmp.buttons &= ~(IN_FORWARD|IN_BACK|IN_SPEED); ucmd = &tmp; } //TERO: if we are pressing use, stop the vehicle first if ( ucmd->buttons & IN_USE ) //|| m_bForcePlayerOut ) { ucmd->buttons |= IN_JUMP; } if (m_bCannotMove) { ucmd->forwardmove = 0; tmp = (*ucmd); tmp.buttons &= ~(IN_FORWARD|IN_BACK|IN_SPEED|IN_MOVELEFT|IN_MOVERIGHT); ucmd = &tmp; } BaseClass::SetupMove( player, ucmd, pHelper, move ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::HeadlightTurnOn( void ) { EmitSound( "Airboat_headlight_on" ); m_bHeadlightIsOn = true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::HeadlightTurnOff( void ) { EmitSound( "Airboat_headlight_off" ); m_bHeadlightIsOn = false; } float CPropDrivableAPC::GetUprightStrength( void ) { // Lesser if overturned if ( IsOverturned() ) return 4.0f; return 2.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::DriveVehicle( float flFrameTime, CUserCmd *ucmd, int iButtonsDown, int iButtonsReleased ) { int iButtons = ucmd->buttons; if ( ucmd->impulse == 100 ) { if (HeadlightIsOn()) { HeadlightTurnOff(); } else { HeadlightTurnOn(); } } //int iDangerRadius = 200; if ( ucmd->forwardmove != 0.0f ) { //iDangerRadius = 300; //Msg("Push V: %.2f, %.2f, %.2f\n", ucmd->forwardmove, carState->engineRPM, carState->speed ); CBasePlayer *pPlayer = ToBasePlayer(GetDriver()); if ( pPlayer && VPhysicsGetObject() ) { bool bBreakProps = false; Vector velocity; VPhysicsGetObject()->GetVelocity( &velocity, NULL ); float flAttackScale = velocity.Length() / 100.0f; //DevMsg("velocity %f, scale %f\n", velocity.Length(), flAttackScale); if (flAttackScale >= 2.0f) { m_bShouldAttackProps = true; } else if (flAttackScale < 1.0f) { if (m_bShouldAttackProps) { m_flNextPropAttackTime = gpGlobals->curtime; } m_bShouldAttackProps = false; } if (flAttackScale >= 1.0f) { m_flStopBreakTime = gpGlobals->curtime + 0.6f; } if ((m_flStopBreakTime > gpGlobals->curtime && m_flNextPropAttackTime < gpGlobals->curtime) ) { m_flNextPropAttackTime = gpGlobals->curtime + 0.3f; bBreakProps = true; } KillBlockingEnemyNPCs( pPlayer, this, VPhysicsGetObject() ); SolveBlockingProps( bBreakProps, this, VPhysicsGetObject() ); /*if (true) //apc_hull_trace_attack.GetBool()) { QAngle angHeadlight; Vector vecHeadlight, vecDir; GetAttachment( "headlight", vecHeadlight, angHeadlight ); AngleVectors( angHeadlight, &vecDir ); vecDir = vecHeadlight + (vecDir); //TERO: only stepping one //CheckTraceHullAttack(vecHeadlight, vecDir, Vector(-10,-10,-10), Vector(10,10,10), 100.0f, DMG_CLUB ); this->Get NDebugOverlay::Box( vecHeadlight, -Vector(10,10,10), Vector(10,10,10), 255,0,0, 8, 0.1 ); NDebugOverlay::Box( vecDir, -Vector(10,10,10), Vector(10,10,10), 0,255,0, 8, 0.1 ); }*/ } m_bIsMounted = false; //Disable LaserDot if (m_hLaserDot && apc_no_rpg_while_moving.GetBool() ) EnableLaserDot( m_hLaserDot, false ); } else { m_bIsMounted = true; if (m_hLaserDot) EnableLaserDot( m_hLaserDot, true ); } //CSoundEnt::InsertSound( SOUND_DANGER, GetAbsOrigin(), iDangerRadius, flFrameTime, NULL ); if ( iButtons & IN_ATTACK ) { FireMachineGun(); } else if ( (m_bIsMounted || !apc_no_rpg_while_moving.GetBool() ) && iButtons & IN_ATTACK2 ) { FireRocket(); } //TERO: lowering the view - ability m_flViewLowered = GetPoseParameter( APC_LOWER_VIEW ); if ( iButtons & IN_DUCK ) { m_flViewLowered = UTIL_Approach( -10.0, m_flViewLowered, 1.0); } else { m_flViewLowered = UTIL_Approach( 0, m_flViewLowered, 2.0); } //DevMsg("vehicle_drivable_apc, m_flViewLowered: %f\n", m_flViewLowered); SetPoseParameter( APC_LOWER_VIEW, m_flViewLowered ); BaseClass::DriveVehicle( flFrameTime, ucmd, iButtonsDown, iButtonsReleased ); } //----------------------------------------------------------------------------- // Purpose: // Input : *pPlayer - // *pMoveData - //----------------------------------------------------------------------------- void CPropDrivableAPC::ProcessMovement( CBasePlayer *pPlayer, CMoveData *pMoveData ) { BaseClass::ProcessMovement( pPlayer, pMoveData ); // Update the steering angles based on speed. UpdateSteeringAngle(); // Create dangers sounds in front of the vehicle. CreateDangerSounds(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::UpdateSteeringAngle( void ) { float flMaxSpeed = m_VehiclePhysics.GetMaxSpeed(); float flSpeed = m_VehiclePhysics.GetSpeed(); float flRatio = 1.0f - ( flSpeed / flMaxSpeed ); float flSteeringDegrees = APC_STEERING_FAST_ANGLE + ( ( APC_STEERING_SLOW_ANGLE - APC_STEERING_FAST_ANGLE ) * flRatio ); flSteeringDegrees = clamp( flSteeringDegrees, APC_STEERING_FAST_ANGLE, APC_STEERING_SLOW_ANGLE ); m_VehiclePhysics.SetSteeringDegrees( flSteeringDegrees ); } //----------------------------------------------------------------------------- // Purpose: Create danger sounds in front of the vehicle. //----------------------------------------------------------------------------- void CPropDrivableAPC::CreateDangerSounds( void ) { // QAngle dummy; // GetAttachment( "Muzzle", m_vecGunOrigin, dummy ); if ( m_flDangerSoundTime > gpGlobals->curtime ) return; QAngle vehicleAngles = GetLocalAngles(); Vector vecStart = GetAbsOrigin(); Vector vecDir, vecRight; GetVectors( &vecDir, &vecRight, NULL ); const float soundDuration = 0.25; float speed = m_VehiclePhysics.GetHLSpeed(); // Make danger sounds ahead of the jeep if ( fabs(speed) > 120 ) { Vector vecSpot; float steering = m_VehiclePhysics.GetSteering(); if ( steering != 0 ) { if ( speed > 0 ) { vecDir += vecRight * steering * 0.5; } else { vecDir -= vecRight * steering * 0.5; } VectorNormalize(vecDir); } const float radius = speed * 1.1; // 0.3 seconds ahead of the jeep vecSpot = vecStart + vecDir * (speed * 0.3f); CSoundEnt::InsertSound( SOUND_DANGER, vecSpot, radius, soundDuration, NULL, 0 ); CSoundEnt::InsertSound( SOUND_PHYSICS_DANGER, vecSpot, radius, soundDuration, NULL, 1 ); //NDebugOverlay::Box(vecSpot, Vector(-radius,-radius,-radius),Vector(radius,radius,radius), 255, 0, 255, 0, soundDuration); #if 0 trace_t tr; // put sounds a bit to left and right but slightly closer to Jeep to make a "cone" of sound // in front of it vecSpot = vecStart + vecDir * (speed * 0.5f) - vecRight * speed * 0.5; UTIL_TraceLine( vecStart, vecSpot, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); CSoundEnt::InsertSound( SOUND_DANGER, vecSpot, 400, soundDuration, NULL, 1 ); vecSpot = vecStart + vecDir * (speed * 0.5f) + vecRight * speed * 0.5; UTIL_TraceLine( vecStart, vecSpot, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); CSoundEnt::InsertSound( SOUND_DANGER, vecSpot, 400, soundDuration, NULL, 2); #endif } else { //TERO: added by me CSoundEnt::InsertSound( SOUND_MOVE_AWAY, GetAbsOrigin(), 250, soundDuration, NULL ); } m_flDangerSoundTime = gpGlobals->curtime + 0.1; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::EnterVehicle( CBasePlayer *pPlayer ) { if ( !pPlayer ) return; BaseClass::EnterVehicle( pPlayer ); //TERO: m_flViewLowered = 0; SetPoseParameter( APC_LOWER_VIEW, 0 ); // Start looking for seagulls to land m_hLastPlayerInVehicle = m_hPlayer; // SetContextThink( NULL, 0, g_pApcThinkContext ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::ExitVehicle( int nRole ) { HeadlightTurnOff(); //m_bForcePlayerOut = false; #ifdef EZ // If we have a target, remove the glow effect on that target // and reset to NULL if (m_hTarget != NULL && m_hTarget->MyNPCPointer() != NULL) { m_hTarget->MyNPCPointer()->RemoveGlowEffect(); m_hTarget = NULL; } #endif BaseClass::ExitVehicle( nRole ); m_flViewLowered = 0; SetPoseParameter( APC_LOWER_VIEW, 0 ); // Remember when we last saw the player m_flPlayerExitedTime = gpGlobals->curtime; m_flLastSawPlayerAt = gpGlobals->curtime; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const char *CPropDrivableAPC::GetTracerType( void ) { return "HelicopterTracer"; } //----------------------------------------------------------------------------- // Allows the shooter to change the impact effect of his bullets //----------------------------------------------------------------------------- void CPropDrivableAPC::DoImpactEffect( trace_t &tr, int nDamageType ) { UTIL_ImpactTrace( &tr, nDamageType, "HelicopterImpact" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::DoMuzzleFlash( void ) { CEffectData data; data.m_nEntIndex = entindex(); data.m_nAttachmentIndex = m_nMachineGunMuzzleAttachment; data.m_flScale = 1.0f; DispatchEffect( "AirboatMuzzleFlash", data ); //used to be ChopperMuzzleFlash BaseClass::DoMuzzleFlash(); } /*Class_T CPropDrivableAPC::Classify() { if (GetDriver()) return CLASS_METROPOLICE; return CLASS_NONE; }*/ //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::FireMachineGun( void ) { if ( m_flMachineGunTime > gpGlobals->curtime ) return; // If we're still firing the salvo, fire quickly m_iMachineGunBurstLeft--; if ( m_iMachineGunBurstLeft > 0 ) { m_flMachineGunTime = gpGlobals->curtime + MACHINE_GUN_BURST_TIME; m_flMachineGunReloadTime = gpGlobals->curtime + MACHINE_GUN_RELOAD_TIME; } else { // Reload the salvo m_iMachineGunBurstLeft = 0; m_flMachineGunTime = gpGlobals->curtime + MACHINE_GUN_RELOAD_TIME * 2; } Vector vecMachineGunShootPos; Vector vecMachineGunDir; GetAttachment( m_nMachineGunMuzzleAttachment, vecMachineGunShootPos, &vecMachineGunDir ); // Fire the round //int bulletType = GetAmmoDef()->Index("AR2"); //FireBullets( 1, vecMachineGunShootPos, vecMachineGunDir, VECTOR_CONE_5DEGREES, MAX_TRACE_LENGTH, bulletType, 1 ); FireBulletsInfo_t BulletInfo; BulletInfo.m_iShots = 1; BulletInfo.m_vecSrc = vecMachineGunShootPos; BulletInfo.m_vecDirShooting = vecMachineGunDir; BulletInfo.m_vecSpread = VECTOR_CONE_1DEGREES; //vec3_origin; BulletInfo.m_flDistance = MAX_TRACE_LENGTH; BulletInfo.m_iAmmoType = GetAmmoDef()->Index("AirboatGun"); //BulletInfo.m_iTracerFreq = info.m_iTracerFreq; //BulletInfo.m_iDamage = info.m_iDamage; BulletInfo.m_pAttacker = UTIL_GetLocalPlayer(); FireBullets( BulletInfo ); Classify(); DoMuzzleFlash(); EmitSound( "Weapon_AR2.Single" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::GetRocketShootPosition( Vector *pPosition ) { GetAttachment( m_nRocketAttachment, *pPosition ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::OnRestore( void ) { IServerVehicle *pServerVehicle = GetServerVehicle(); if ( pServerVehicle != NULL ) { // Restore the passenger information we're holding on to pServerVehicle->RestorePassengerInfo(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPropDrivableAPC::FireRocket( void ) { if ( m_flRocketTime > gpGlobals->curtime ) return; // If we're still firing the salvo, fire quickly m_iRocketSalvoLeft--; if ( m_iRocketSalvoLeft > 0 ) { m_flRocketTime = gpGlobals->curtime + ROCKET_DELAY_TIME; m_flRocketReloadTime = gpGlobals->curtime + random->RandomFloat( ROCKET_MIN_BURST_PAUSE_TIME, ROCKET_MAX_BURST_PAUSE_TIME ); } else { // Reload the salvo m_iRocketSalvoLeft = 0; m_flRocketReloadTime = gpGlobals->curtime + random->RandomFloat( ROCKET_MIN_BURST_PAUSE_TIME, ROCKET_MAX_BURST_PAUSE_TIME ); m_flRocketTime = m_flRocketReloadTime + 0.1f; } Vector vecRocketOrigin; GetRocketShootPosition( &vecRocketOrigin ); //static float s_pSide[] = { 0.966, 0.866, 0.5, -0.5, -0.866, -0.966 }; /*static float s_pSide[] = { 0.5, 0.3, 0, -0.3, -0.5 }; Vector forward, right; GetVectors( &forward, &right, NULL ); float flZ = GetPoseParameter( APC_GUN_YAW ); flZ = clamp( flZ * 0.02f, 0, 1); // 1/45 * 0.7 = 0.02 (approx) Vector vecDir; //CrossProduct( Vector( 0, 0, 1 ), forward, vecDir ); vecDir = forward + (right * s_pSide[m_nRocketSide]); vecDir.z = 0.3f + flZ; if ( ++m_nRocketSide >= 5 ) { m_nRocketSide = 0; } //TERO: if you want the Side thing to work uncomment the above and comment the following //Vector vecDir = forward; VectorNormalize( vecDir );*/ //start new way of shooting rocket Vector vecMuzzle, vecDir; QAngle vecMuzzleAng; GetAttachment( "Muzzle", vecMuzzle, vecMuzzleAng ); AngleVectors( vecMuzzleAng, &vecDir ); //end new way of shooting rocket Vector vecVelocity; VectorMultiply( vecDir, ROCKET_SPEED, vecVelocity ); QAngle angles; VectorAngles( vecDir, angles ); CAPCMissile *pRocket = (CAPCMissile *)CAPCMissile::Create( vecRocketOrigin, angles, vecVelocity, this ); pRocket->IgniteDelay(); #ifdef EZ // If the APC has a target, disable guiding and aim at that target instead if ( m_hTarget != NULL ) { pRocket->AimAtSpecificTarget( m_hTarget ); } else { // If there is no target, disable guiding pRocket->DisableGuiding(); } #endif EmitSound( "PropAPC.FireRocket" ); /* Vector vecMuzzle, vecMuzzleDir; QAngle vecMuzzleAng; GetAttachment( "Muzzle", vecMuzzle, vecMuzzleAng ); AngleVectors( vecMuzzleAng, &vecMuzzleDir );*/ } void CPropDrivableAPC::InputForcePlayerOut( inputdata_t &inputdata ) { if ( !m_hPlayer) return; //m_bForcePlayerOut = true; m_VehiclePhysics.SetHandbrake( true ); GetServerVehicle()->HandlePassengerExit( m_hPlayer ); } //======================================================================================================================================== // JEEP FOUR WHEEL PHYSICS VEHICLE SERVER VEHICLE //======================================================================================================================================== //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CDrivableAPCFourWheelServerVehicle::NPC_AimPrimaryWeapon( Vector vecTarget ) { ((CPropDrivableAPC*)m_pVehicle)->AimGunAt( &vecTarget, 0.1f ); } //----------------------------------------------------------------------------- // Purpose: // Input : &vecEyeExitEndpoint - // Output : int //----------------------------------------------------------------------------- int CDrivableAPCFourWheelServerVehicle::GetExitAnimToUse( Vector &vecEyeExitEndpoint, bool &bAllPointsBlocked ) { bAllPointsBlocked = false; if ( !m_bParsedAnimations ) { // Load the entry/exit animations from the vehicle ParseEntryExitAnims(); m_bParsedAnimations = true; } // CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle); return BaseClass::GetExitAnimToUse( vecEyeExitEndpoint, bAllPointsBlocked ); } // Moved here from vehicle_manhack.cpp int HLSS_SelectTargetType( CBaseEntity *pEntity ) { if (pEntity) { switch (pEntity->Classify()) { case CLASS_CITIZEN_REBEL: return 1; break; //case CLASS_ALIENCONTROLLER: //case CLASS_ALIENGRUNT: case CLASS_VORTIGAUNT: //case CLASS_MANTARAY_TELEPORTER: return 2; break; case CLASS_HEADCRAB: case CLASS_ZOMBIE: case CLASS_ANTLION: return 3; break; //case CLASS_MILITARY_HACKED: //case CLASS_COMBINE_HACKED: //case CLASS_AIR_DEFENSE_HACKED: case CLASS_HACKED_ROLLERMINE: return 4; break; default: return 0; break; } } return 0; } // adds a collision solver for any small props that are stuck under the vehicle static void SolveBlockingProps( bool bBreakProps, CPropDrivableAPC *pVehicleEntity, IPhysicsObject *pVehiclePhysics ) { //TERO: added Vector velocity; pVehiclePhysics->GetVelocity( &velocity, NULL ); CUtlVector<CBaseEntity *> solveList; float vehicleMass = pVehiclePhysics->GetMass(); Vector vehicleUp; pVehicleEntity->GetVectors( NULL, NULL, &vehicleUp ); IPhysicsFrictionSnapshot *pSnapshot = pVehiclePhysics->CreateFrictionSnapshot(); while ( pSnapshot->IsValid() ) { IPhysicsObject *pOther = pSnapshot->GetObject(1); float otherMass = pOther->GetMass(); CBaseEntity *pOtherEntity = static_cast<CBaseEntity *>(pOther->GetGameData()); Assert(pOtherEntity); if ( pOtherEntity && pOtherEntity->GetMoveType() == MOVETYPE_VPHYSICS && pOther->IsMoveable() && (otherMass*2.0f) < vehicleMass ) { Vector normal; pSnapshot->GetSurfaceNormal(normal); // this points down in the car's reference frame, then it's probably trapped under the car if ( DotProduct(normal, vehicleUp) < -0.9f ) { Vector point, pointLocal; pSnapshot->GetContactPoint(point); VectorITransform( point, pVehicleEntity->EntityToWorldTransform(), pointLocal ); Vector bottomPoint = physcollision->CollideGetExtent( pVehiclePhysics->GetCollide(), vec3_origin, vec3_angle, Vector(0,0,-1) ); // make sure it's under the bottom of the car float bottomPlane = DotProduct(bottomPoint,vehicleUp)+8; // 8 inches above bottom if ( DotProduct( pointLocal, vehicleUp ) <= bottomPlane ) { //Msg("Solved %s\n", pOtherEntity->GetClassname()); if ( solveList.Find(pOtherEntity) < 0 ) { solveList.AddToTail(pOtherEntity); } } } } //TERO: added if ( bBreakProps && pOtherEntity && ( (pOtherEntity->GetMoveType() == MOVETYPE_VPHYSICS && ((otherMass*2.0f) < vehicleMass )) || pOtherEntity->GetMoveType() == MOVETYPE_PUSH)) { //TERO: it's okay to have pVehicleEntity as the attacker instead of player, since dey arr props CTakeDamageInfo dmgInfo( pVehicleEntity, pVehicleEntity, velocity, pOtherEntity->WorldSpaceCenter(), 25.0f, DMG_CLUB ); pOtherEntity->TakeDamage( dmgInfo ); } //DevMsg("other mass %f, vehicleMass %f\n", otherMass, vehicleMass); pSnapshot->NextFrictionData(); } pVehiclePhysics->DestroyFrictionSnapshot( pSnapshot ); if ( solveList.Count() ) { for ( int i = 0; i < solveList.Count(); i++ ) { EntityPhysics_CreateSolver( pVehicleEntity, solveList[i], true, 6.0f ); } pVehiclePhysics->RecheckContactPoints(); } } static void SimpleCollisionResponse( Vector velocityIn, const Vector &normal, float coefficientOfRestitution, Vector *pVelocityOut ) { Vector Vn = DotProduct(velocityIn,normal) * normal; Vector Vt = velocityIn - Vn; *pVelocityOut = Vt - coefficientOfRestitution * Vn; } static void KillBlockingEnemyNPCs( CBasePlayer *pPlayer, CBaseEntity *pVehicleEntity, IPhysicsObject *pVehiclePhysics ) { Vector velocity; pVehiclePhysics->GetVelocity( &velocity, NULL ); float vehicleMass = pVehiclePhysics->GetMass(); // loop through the contacts and look for enemy NPCs that we're pushing on CUtlVector<CAI_BaseNPC *> npcList; CUtlVector<Vector> forceList; CUtlVector<Vector> contactList; IPhysicsFrictionSnapshot *pSnapshot = pVehiclePhysics->CreateFrictionSnapshot(); while ( pSnapshot->IsValid() ) { IPhysicsObject *pOther = pSnapshot->GetObject(1); float otherMass = pOther->GetMass(); CBaseEntity *pOtherEntity = static_cast<CBaseEntity *>(pOther->GetGameData()); CAI_BaseNPC *pNPC = pOtherEntity ? pOtherEntity->MyNPCPointer() : NULL; // Is this an enemy NPC with a small enough mass? if ( pNPC && pPlayer->IRelationType(pNPC) != D_LI && ((otherMass*2.0f) < vehicleMass) ) { // accumulate the stress force for this NPC in the lsit float force = pSnapshot->GetNormalForce(); Vector normal; pSnapshot->GetSurfaceNormal(normal); normal *= force; int index = npcList.Find(pNPC); if ( index < 0 ) { vphysicsupdateai_t *pUpdate = NULL; if ( pNPC->VPhysicsGetObject() && pNPC->VPhysicsGetObject()->GetShadowController() && pNPC->GetMoveType() == MOVETYPE_STEP ) { if ( pNPC->HasDataObjectType(VPHYSICSUPDATEAI) ) { pUpdate = static_cast<vphysicsupdateai_t *>(pNPC->GetDataObject(VPHYSICSUPDATEAI)); // kill this guy if I've been pushing him for more than half a second and I'm // still pushing in his direction if ( (gpGlobals->curtime - pUpdate->startUpdateTime) > 0.5f && DotProduct(velocity,normal) > 0) { index = npcList.AddToTail(pNPC); forceList.AddToTail( normal ); Vector pos; pSnapshot->GetContactPoint(pos); contactList.AddToTail(pos); } } else { pUpdate = static_cast<vphysicsupdateai_t *>(pNPC->CreateDataObject( VPHYSICSUPDATEAI )); pUpdate->startUpdateTime = gpGlobals->curtime; } // update based on vphysics for the next second // this allows the car to push the NPC pUpdate->stopUpdateTime = gpGlobals->curtime + 1.0f; float maxAngular; pNPC->VPhysicsGetObject()->GetShadowController()->GetMaxSpeed( &pUpdate->savedShadowControllerMaxSpeed, &maxAngular ); pNPC->VPhysicsGetObject()->GetShadowController()->MaxSpeed( 1.0f, maxAngular ); } } else { forceList[index] += normal; } } pSnapshot->NextFrictionData(); } pVehiclePhysics->DestroyFrictionSnapshot( pSnapshot ); // now iterate the list and check each cumulative force against the threshold if ( npcList.Count() ) { for ( int i = npcList.Count(); --i >= 0; ) { Vector damageForce; if (npcList[i]->VPhysicsGetObject() == NULL) { DevMsg( "APC tried to access NULL physics object\n" ); continue; } npcList[i]->VPhysicsGetObject()->GetVelocity( &damageForce, NULL ); Vector vel; pVehiclePhysics->GetVelocityAtPoint( contactList[i], &vel ); vel *= 12; //TERO: added by because the APC is generally slow damageForce -= vel; Vector normal = forceList[i]; VectorNormalize(normal); SimpleCollisionResponse( damageForce, normal, 1.0, &damageForce ); damageForce += (normal * 10.0f); damageForce *= npcList[i]->VPhysicsGetObject()->GetMass(); float len = damageForce.Length(); damageForce.z += len*phys_upimpactforcescale.GetFloat(); Vector vehicleForce = -damageForce; //TERO: next bit added by me //damageForce *= 10.0f; //DevMsg("KillBlockingEnemyNPCs %f\n", len ); CTakeDamageInfo dmgInfo( pVehicleEntity, pPlayer, damageForce, contactList[i], 600.0f, DMG_CRUSH|DMG_VEHICLE ); npcList[i]->TakeDamage( dmgInfo ); pVehiclePhysics->ApplyForceOffset( vehicleForce, contactList[i] ); if (npcList[i]->VPhysicsGetObject() == NULL) { DevMsg( "APC tried to access NULL physics object\n" ); continue; } PhysCollisionSound( pVehicleEntity, npcList[i]->VPhysicsGetObject(), CHAN_BODY, pVehiclePhysics->GetMaterialIndex(), npcList[i]->VPhysicsGetObject()->GetMaterialIndex(), gpGlobals->frametime, 200.0f ); } } }
31.012907
204
0.64093
[ "object", "vector", "transform" ]
8cd1b47e4271ec0c1e1943e603ce15f2f6e00df3
14,418
cpp
C++
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/listview.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/listview.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/listview.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
// // listview.cpp // MDStudio // // Created by Daniel Cliche on 2014-06-26. // Copyright (c) 2014-2021 Daniel Cliche. All rights reserved. // #include "listview.h" #include <algorithm> #include "draw.h" #include "responderchain.h" using namespace MDStudio; // --------------------------------------------------------------------------------------------------------------------- ListView::ListView(const std::string& name, void* owner, float rowHeight, bool isMultipleSelectionsAllowed) : _rowHeight(rowHeight), _isMultipleSelectionsAllowed(isMultipleSelectionsAllowed), Control(name, owner) { _nbRowsFn = nullptr; _viewForRowFn = nullptr; _didSelectRowFn = nullptr; _didDeselectRowFn = nullptr; _didHoverRowFn = nullptr; _didConfirmRowSelectionFn = nullptr; _didSetFocusStateFn = nullptr; _didPressUnhandledKeyFn = nullptr; _selectedRow = -1; _hasFocus = false; _isWaitingMouseUp = false; _isDeselectingRow = false; _nbRows = 0; _isPassThrough = false; } // --------------------------------------------------------------------------------------------------------------------- ListView::~ListView() { removeAllSubviews(); } // --------------------------------------------------------------------------------------------------------------------- void ListView::reload() { setSelectedRow(-1); removeAllSubviews(); _items.clear(); _nbRows = _nbRowsFn(this); for (unsigned int row = 0; row < _nbRows; row++) { std::shared_ptr<View> rowView = _viewForRowFn(this, row); addSubview(rowView); _items[row] = rowView; } layoutList(); } // --------------------------------------------------------------------------------------------------------------------- void ListView::layoutList() { for (auto item : _items) { auto row = item.first; auto rowView = item.second; auto y = rect().size.height - (_rowHeight) * (row + 1); rowView->setFrame(makeRect(0.0f, y, rect().size.width, _rowHeight)); } } // --------------------------------------------------------------------------------------------------------------------- void ListView::reloadWindow(bool isDelayed, bool isRefreshOnly) { if (isDelayed) { _isReloadWindowPending = true; } else { float endPosY = resolvedClippedRect().size.height - resolvedOffset().y; float startPosY = endPosY - resolvedClippedRect().size.height - _rowHeight; if (!isRefreshOnly) { removeAllSubviews(); _items.clear(); } _nbRows = _nbRowsFn(this); float y = rect().size.height - _rowHeight; unsigned int minRow = 0, maxRow = 0; bool isMinRowSet = false; for (unsigned int row = 0; row < _nbRows; row++) { if (y >= startPosY && y <= endPosY) { if (!isMinRowSet) { minRow = row; isMinRowSet = true; } maxRow = row; bool isFetchRequired = true; if (isRefreshOnly) isFetchRequired = _items.find(row) == _items.end(); if (isFetchRequired) { std::shared_ptr<View> rowView = _viewForRowFn(this, row); addSubview(rowView); _items[row] = rowView; } } if (y < startPosY) break; y -= _rowHeight; } if (isRefreshOnly) { // Remove subviews no longer visible for (auto it = _items.begin(); it != _items.end();) if (it->first < minRow || it->first > maxRow) { removeSubview(it->second); it = _items.erase(it); } else { ++it; } } layoutList(); } setDirty(); } // --------------------------------------------------------------------------------------------------------------------- float ListView::contentHeight() { return _nbRowsFn(this) * _rowHeight; } // --------------------------------------------------------------------------------------------------------------------- Rect ListView::viewRectAtRow(int row) { auto r = rect(); auto y = r.size.height - (_rowHeight) * (row + 1); return makeRect(r.origin.x, r.origin.y + y, r.size.width, _rowHeight); } // --------------------------------------------------------------------------------------------------------------------- void ListView::setFrame(Rect aRect) { View::setFrame(aRect); layoutList(); } // --------------------------------------------------------------------------------------------------------------------- void ListView::didResolveClippedRect() { if (_isReloadWindowPending) { _isReloadWindowPending = false; Platform::sharedInstance()->invoke([=] { reloadWindow(false, false); }); } } // --------------------------------------------------------------------------------------------------------------------- void ListView::setSelectedRow(int row, bool isDelegateNotified, bool isExclusive) { if (!_isMultipleSelectionsAllowed) { // Deselect all rows except the selected one std::vector<int> selectedRows = _selectedRows; _selectedRows.clear(); for (auto r : selectedRows) { if ((r != row) && isDelegateNotified && _didDeselectRowFn != nullptr) _didDeselectRowFn(this, r); } if (row >= 0) _selectedRows.push_back(row); } else { // Multiple selections are allowed if (isExclusive) { std::vector<int> selectedRows = _selectedRows; _selectedRows.clear(); if (isDelegateNotified && _didDeselectRowFn != nullptr) { for (auto row : selectedRows) _didDeselectRowFn(this, row); } } if (row >= 0 && std::find(_selectedRows.begin(), _selectedRows.end(), row) == _selectedRows.end()) _selectedRows.push_back(row); } _selectedRow = row; if ((row >= 0) && isDelegateNotified && _didSelectRowFn != nullptr) _didSelectRowFn(this, row); } // --------------------------------------------------------------------------------------------------------------------- void ListView::setSelectedRangeRows(int firstRow, int lastRow) { for (int row = firstRow; row <= lastRow; ++row) { // If the row is not already selected if (std::find(_selectedRows.begin(), _selectedRows.end(), row) == _selectedRows.end()) setSelectedRow(row, true, false); } } // --------------------------------------------------------------------------------------------------------------------- bool ListView::isRowSelected(int row) { if (row < 0) return false; if (!_isMultipleSelectionsAllowed) { return _selectedRow == row; } else { return std::find(_selectedRows.begin(), _selectedRows.end(), row) != _selectedRows.end(); } } // --------------------------------------------------------------------------------------------------------------------- void ListView::deselectRow(int row) { if (_isMultipleSelectionsAllowed) { _selectedRows.erase(std::find(_selectedRows.begin(), _selectedRows.end(), row)); } if (row == _selectedRow) _selectedRow = -1; if (_didSelectRowFn != nullptr) _didDeselectRowFn(this, row); } // --------------------------------------------------------------------------------------------------------------------- bool ListView::handleEvent(const UIEvent* event) { if (_isStatic) return false; if (View::handleEvent(event)) return true; if (!isVisible()) return false; bool hadFocus = _hasFocus; if ((_hasFocus && (event->type == KEY_UIEVENT)) || ((event->type == MOUSE_DOWN_UIEVENT || event->type == MOUSE_UP_UIEVENT || event->type == MOUSE_MOVED_UIEVENT) && (isPointInRect(event->pt, resolvedClippedRect())))) { if (event->type == MOUSE_DOWN_UIEVENT && !_hasFocus) { responderChain()->makeFirstResponder(this); if (_isCapturing) responderChain()->captureResponder(this); _hasFocus = true; _isWaitingMouseUp = _hasFocus; if (_didSetFocusStateFn) _didSetFocusStateFn(this, _hasFocus); } if (event->type == KEY_UIEVENT) { if (event->key == KEY_UP) { if (_selectedRow > 0) { if (event->modifierFlags & MODIFIER_FLAG_SHIFT) { int row = _selectedRow - 1; if (_selectedRow > _selectedRowRef) deselectRow(_selectedRow); setSelectedRow(row, true, false); } else { setSelectedRow(_selectedRow - 1); _selectedRowRef = _selectedRow; } } } else if (event->key == KEY_DOWN) { if (_selectedRow < _nbRows - 1) { if (event->modifierFlags & MODIFIER_FLAG_SHIFT) { int row = _selectedRow + 1; if (_selectedRow < _selectedRowRef) deselectRow(_selectedRow); setSelectedRow(row, true, false); } else { setSelectedRow(_selectedRow + 1); _selectedRowRef = _selectedRow; } } } else if (_didConfirmRowSelectionFn && (event->key == KEY_ENTER)) { _didConfirmRowSelectionFn(this, _selectedRow); } else { if (_didPressUnhandledKeyFn) { return _didPressUnhandledKeyFn(this, event->key); } else { return false; } } } else { int row = (rect().origin.y + rect().size.height + resolvedOffset().y - event->pt.y) / _rowHeight; if (row >= _nbRows) return false; if (event->type == MOUSE_DOWN_UIEVENT || event->type == MOUSE_UP_UIEVENT) { if (event->modifierFlags & MODIFIER_FLAG_SHIFT) { if (_selectedRow >= 0) { int firstRow = _selectedRow; int lastRow = row; if (firstRow > lastRow) { int r = firstRow; firstRow = lastRow; lastRow = r; } setSelectedRangeRows(firstRow, lastRow); } } else if (!isRowSelected(row)) { if (!_isDeselectingRow && (event->type == MOUSE_UP_UIEVENT)) { setSelectedRow(row, true, !(event->modifierFlags & MODIFIER_FLAG_COMMAND)); _selectedRowRef = _selectedRow; } } else { // The row is already selected if (event->modifierFlags & MODIFIER_FLAG_COMMAND) { if (event->type == MOUSE_DOWN_UIEVENT) { deselectRow(row); _isDeselectingRow = true; } } else { if (event->type == MOUSE_UP_UIEVENT && _selectedRows.size() > 1) { setSelectedRow(row); _selectedRowRef = _selectedRow; } else { // If we have the focus, we do not intercept the event if we allow pass through if (_isPassThrough && hadFocus && _hasFocus) { if (!(_isWaitingMouseUp && (event->type == MOUSE_UP_UIEVENT))) { _isWaitingMouseUp = false; return false; } } } } } if (event->type == MOUSE_UP_UIEVENT) { _isWaitingMouseUp = false; _isDeselectingRow = false; } if ((event->type == MOUSE_UP_UIEVENT) && _didConfirmRowSelectionFn) _didConfirmRowSelectionFn(this, row); } else { // Mouse move if (_didHoverRowFn != nullptr) _didHoverRowFn(this, row); if (_isPassThrough && _hasFocus) return false; } } return true; } else if (_hasFocus && (event->type == MOUSE_DOWN_UIEVENT) && !isPointInRect(event->pt, resolvedClippedRect())) { responderChain()->makeFirstResponder(nullptr); _isWaitingMouseUp = false; responderChain()->sendEvent(event); return true; } return false; } // --------------------------------------------------------------------------------------------------------------------- void ListView::captureFocus() { if (!_hasFocus) { _hasFocus = true; responderChain()->makeFirstResponder(this); if (_isCapturing) responderChain()->captureResponder(this); if (_didSetFocusStateFn) _didSetFocusStateFn(this, _hasFocus); } } // --------------------------------------------------------------------------------------------------------------------- void ListView::releaseFocus() { if (_hasFocus) { responderChain()->makeFirstResponder(nullptr); } } // --------------------------------------------------------------------------------------------------------------------- void ListView::resignFirstResponder() { if (_hasFocus) { if (_isCapturing) responderChain()->releaseResponder(this); _hasFocus = false; if (_didSetFocusStateFn) _didSetFocusStateFn(this, _hasFocus); } } // --------------------------------------------------------------------------------------------------------------------- std::shared_ptr<View> ListView::viewAtRow(int row) { // If the view is available, return it directly if (_items.find(row) != _items.end()) return _items[row]; // The view is not available return nullptr; } // --------------------------------------------------------------------------------------------------------------------- void ListView::selectAll() { if (_isMultipleSelectionsAllowed) setSelectedRangeRows(0, _nbRows - 1); }
38.758065
120
0.456721
[ "vector" ]
8cd2337c8870fd55565ef3288e0684a0d9d30676
3,819
hpp
C++
src/kernels/rotationkernel/FSpherical.hpp
berenger-eu/tbfmm
6a86a0cb28615d8e7d11afc3e4428da6fc398f43
[ "MIT" ]
4
2020-12-04T09:24:52.000Z
2021-06-14T13:56:35.000Z
src/kernels/rotationkernel/FSpherical.hpp
berenger-eu/tbfmm
6a86a0cb28615d8e7d11afc3e4428da6fc398f43
[ "MIT" ]
2
2020-08-24T08:46:08.000Z
2021-06-15T08:57:55.000Z
src/kernels/rotationkernel/FSpherical.hpp
berenger-eu/tbfmm
6a86a0cb28615d8e7d11afc3e4428da6fc398f43
[ "MIT" ]
2
2020-11-21T01:22:13.000Z
2020-12-23T02:08:45.000Z
// See LICENCE file at project root #ifndef FSPHERICAL_HPP #define FSPHERICAL_HPP #include <cmath> /** * This class is a Spherical position * * @brief Spherical coordinate system * * We consider the spherical coordinate system \f$(r, \theta, \varphi)\f$ commonly used in physics. r is the radial distance, \f$\theta\f$ the polar/inclination angle and \f$\varphi\f$ the azimuthal angle.<br> * The <b>radial distance</b> is the Euclidean distance from the origin O to P.<br> * The <b>inclination (or polar angle) </b>is the angle between the zenith direction and the line segment OP.<br> * The <b>azimuth (or azimuthal angle)</b> is the signed angle measured from the azimuth reference direction to the orthogonal projection of the line segment OP on the reference plane.<br> * * The spherical coordinates of a point can be obtained from its Cartesian coordinates (x, y, z) by the formulae * \f$ \displaystyle r = \sqrt{x^2 + y^2 + z^2}\f$<br> * \f$ \displaystyle \theta = \displaystyle\arccos\left(\frac{z}{r}\right) \f$<br> * \f$ \displaystyle \varphi = \displaystyle\arctan\left(\frac{y}{x}\right) \f$<br> *and \f$\varphi\in[0,2\pi[ \f$ \f$ \theta\in[0,\pi]\f$<br> * * The spherical coordinate system is retrieved from the the spherical coordinates by <br> * \f$x = r \sin(\theta) \cos(\varphi)\f$ <br> * \f$y = r \sin(\theta) \sin(\varphi)\f$ <br> * \f$z = r \cos(\theta) \f$<br> * with \f$\varphi\in[-\pi,\pi[ \f$ \f$ \theta\in[0,\pi]\f$<br> * * This system is defined in p 872 of the paper of Epton and Dembart, SIAM J Sci Comput 1995.<br> * * Even if it can look different from usual expression (where theta and phi are inversed), * such expression is used to match the SH expression. * See http://en.wikipedia.org/wiki/Spherical_coordinate_system */ template <class FReal> class FSpherical { const FReal PI = FReal(3.14159265358979323846264338327950288419716939937510582097494459230781640628620899863L); const FReal PI2 = FReal(3.14159265358979323846264338327950288419716939937510582097494459230781640628620899863L*2); // The attributes of a sphere FReal r; //!< the radial distance FReal theta; //!< the inclination angle [0, pi] - colatitude, polar angle FReal phi; //!< the azimuth angle [-pi,pi] - longitude - around z axis FReal cosTheta; FReal sinTheta; public: /** Default Constructor, set attributes to 0 */ FSpherical() : r(0.0), theta(0.0), phi(0.0), cosTheta(0.0), sinTheta(0.0) { } /** From now, we just need a constructor based on a 3D position */ explicit FSpherical(const std::array<FReal, 3>& inVector){ const FReal x2y2 = (inVector[0] * inVector[0]) + (inVector[1] * inVector[1]); this->r = std::sqrt( x2y2 + (inVector[2] * inVector[2])); this->phi = std::atan2(inVector[1],inVector[0]); this->cosTheta = inVector[2] / r; this->sinTheta = std::sqrt(x2y2) / r; this->theta = std::acos(this->cosTheta); } /** Get the radius */ FReal getR() const{ return r; } /** Get the inclination angle theta = acos(z/r) [0, pi] */ FReal getTheta() const{ return theta; } /** Get the azimuth angle phi = atan2(y,x) [-pi,pi] */ FReal getPhi() const{ return phi; } /** Get the inclination angle [0, pi] */ FReal getInclination() const{ return theta; } /** Get the azimuth angle [0,2pi]. You should use this method in order to obtain (x,y,z)*/ FReal getPhiZero2Pi() const{ return (phi < 0 ? PI2 + phi : phi); } /** Get the cos of theta = z / r */ FReal getCosTheta() const{ return cosTheta; } /** Get the sin of theta = sqrt(x2y2) / r */ FReal getSinTheta() const{ return sinTheta; } }; #endif // FSPHERICAL_HPP
38.969388
208
0.645981
[ "3d" ]
8ce5db4f4b65e70ad57503d3fea98c142942e8cc
1,855
cpp
C++
InsertionSortGeneric.cpp
rlama7/InsertionSort
745d48b1b7855f55fef9854da15bdc3103e55d46
[ "MIT" ]
null
null
null
InsertionSortGeneric.cpp
rlama7/InsertionSort
745d48b1b7855f55fef9854da15bdc3103e55d46
[ "MIT" ]
null
null
null
InsertionSortGeneric.cpp
rlama7/InsertionSort
745d48b1b7855f55fef9854da15bdc3103e55d46
[ "MIT" ]
null
null
null
/** * @file InsertionSortGeneric.cpp * @brief A program to implement Insert Sort for generic data * @param Array Array to be sorted * @param size size of the Array to be sorted * * @algorithm: * KeyWord: Sorted Sublist * Steps: * 1) Consider the first element in the array to be a sorted sublist of length 1 * 2) Introduc the second element into the sorted sublist, shifting the first element if needed * 3) Introduce the third element into the sorted sublist, shifting the other elements as needed * 4) Repeat until all values have been sorted into their proper positions in the Array. * */ #include <iostream> #include <string> // c++ style string #include <vector> // vector using namespace std; template<typename ItemType> void InsertionSort(ItemType Array[], int size); int main() { string my_Array[7] = {"T", "K", "P", "A", "R", "L", "F"}; InsertionSort(my_Array, 6); for (auto s : my_Array) { cout << s << " "; } cout << "\n--------------------------------------------\n" << endl; int num[] = {3,5,8,0,9,3,4,2,1,7,6,2}; InsertionSort(num, 12); for (auto n : num) { cout << n << " "; } cout << "\n--------------------------------------------\n" << endl; string flowers[] = {"Rose", "Jasmine", "Tulip","Lily", "Rhododendron", "Daffodil", "Heather", "Limonium", "Ranunculus", "Dahlia"}; InsertionSort(flowers, 10); for(auto f : flowers) { cout << f << " "; } cout << "\n--------------------------------------------\n" << endl; return 0; } // end main template<typename ItemType> void InsertionSort(ItemType Array[], int size) { for (int unsorted = 1; unsorted < size; unsorted++) { ItemType nextItem = Array[unsorted]; int loc = unsorted; while ((loc > 0) && (Array[loc-1] > nextItem)) { Array[loc] = Array[loc-1]; loc--; } Array[loc] = nextItem; } } // end InsertionSort
29.919355
131
0.591914
[ "vector" ]
8ce63f8a2923e3466f8be08fdfc554c0f62c8f7d
7,791
hpp
C++
src/SyncLoop.hpp
afalchetti/slidesync
a3764f42cc8f95ec3a788c0b7ed81563e48924d9
[ "Apache-2.0" ]
null
null
null
src/SyncLoop.hpp
afalchetti/slidesync
a3764f42cc8f95ec3a788c0b7ed81563e48924d9
[ "Apache-2.0" ]
null
null
null
src/SyncLoop.hpp
afalchetti/slidesync
a3764f42cc8f95ec3a788c0b7ed81563e48924d9
[ "Apache-2.0" ]
null
null
null
/// @file SyncLoop.hpp /// @brief Synchronization processing loop header file // // Part of SlideSync // // Copyright 2017 Angelo Falchetti Pareja // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SYNCLOOP_HPP #define SYNCLOOP_HPP 1 #include <opencv2/opencv.hpp> #include "ProcessLoop.hpp" #include "CVCanvas.hpp" #include "Quad.hpp" #include "SyncInstructions.hpp" using std::string; using cv::Mat; namespace slidesync { class SyncLoop; /// @brief Internal synchronization processor function pointer typedef void (SyncLoop::*SyncProcessorFn)(); /// @brief Generate a synchronization file from a footage file and a slides file. Core loop /// /// Match the slides in the slides file to the frames in the footage file and discover /// which slides have been used at which times. Then, generate a synchronization file /// describing such matches through "instructions" to the slideshow, such as "go to slide 3 /// at time 00:17:23.146" or "after 5 seconds go the next slide". class SyncLoop : public ProcessLoop { private: /// @brief Number of frames to skip between keyframes /// /// Presentation are very static so processing them at 30 fps would be incredibly wasteful. /// Hence, the video is subsampled, i.e. the effective framecount is framecount / (frameskip + 1). static const unsigned int frameskip = 7; /// @brief Maximum ratio between best match and second match's distance to consider /// a keypoint pair a good match static constexpr float max_matchratio = 0.8; /// @brief RANSAC threshold to decide a point is within the inlier group static constexpr float RANSAC_threshold = 2.5; /// @brief Name of the cache file for the synchronization instructions string cachefname; /// @brief OpenGL canvas observer reference CVCanvas* canvas; /// @brief Video input observer reference cv::VideoCapture* footage; /// @brief Frame index for the next Notify() call unsigned int frame_index; /// @brief Coarse frame index for the next Notify() call /// /// The canvas will skip frames; this index represents the effective /// frame as seen by the user, but not the real one in the video file. unsigned int coarse_index; /// @brief Footage length unsigned int length; /// @brief Slides image array observer reference std::vector<Mat>* slides; /// @brief Slide index unsigned int slide_index; /// @brief Keypoint detector cv::Ptr<cv::Feature2D> detector; /// @brief Keypoint matcher cv::Ptr<cv::DescriptorMatcher> matcher; /// @brief Precomputed keypoints for each slide std::vector<std::vector<cv::KeyPoint>> slide_keypoints; /// @brief Precomputed keypoint descriptors for each slide std::vector<Mat> slide_descriptors; /// @brief Reference frame (for differential processing) Mat ref_frame; /// @brief Previously computed keypoints for the reference frame std::vector<cv::KeyPoint> ref_frame_keypoints; /// @brief Previously computed keypoint descriptors for the reference frame Mat ref_frame_descriptors; /// @brief Subset of ref_frame_keypoints but only containing the keypoints inside the ref_slidepose Quad std::vector<cv::KeyPoint> ref_quad_keypoints; /// @brief Subset of ref_frame_descriptors but only containing the keypoints inside the ref_slidepose Quad Mat ref_quad_descriptors; /// @brief Index lookup table, indicating the index in ref_quad_keypoints for every element /// in ref_frame_keypoints /// /// A value of -1 indicates the particular keypoint is not inside the presentation Quad. std::vector<int> ref_quad_indices; /// @brief Description of the slide pose in the reference frame /// /// The quad's vertices can be outside the frame region, since the slides /// could be out-of-frame. Quad ref_slidepose; /// @brief Description of the slide pose in the previous frame /// /// This quad will be used as a auxiliar reference in case the tracker gets lost. Quad prev_slidepose; /// @brief Count of consecutive frames where the presentation Quad has been closed to where it was /// int the previous slide (indicator of a robust match) unsigned int nearcount; /// @brief Count of consecutive frames the tracker hasn't been able to find anything decent (indicator /// of being totally lost and requiring a full scan through the slides) unsigned int badcount; /// @brief Synchronization instructions to match the slides with the footage SyncInstructions sync_instructions; /// @brief Frame-slide processor /// /// References the main routine which will be called periodically. /// Since the processing consists of several stages which do very /// different operations, it makes sense to separate their implementations /// (and function delegates are nicer than big switches). SyncProcessorFn processor; /// @brief Flag indicating if the loop is currently processing a frame or not bool processing; public: /// @brief Construct a SyncLoop /// /// @param[in] canvas OpenGL canvas to draw user interactive interface. /// @param[in] footage Recording of the presentation. /// @param[in] slides Array of slide images. /// @param[in] cachefname Name of the SyncInstructions cache file. SyncLoop(CVCanvas* canvas, cv::VideoCapture* footage, std::vector<Mat>* slides, const string& cachefname); /// @brief Set the internal canvas void SetCanvas(CVCanvas* canvas); /// @brief Set the internal footage void SetFootage(cv::VideoCapture* footage); /// @brief Recurrent action. Updates the canvas virtual void Notify(); /// @brief Get the internal synchronization instructions SyncInstructions GetSyncInstructions(); private: /// @brief Get the next frame on the footage Mat next_frame(); /// @brief Compute a matching between two images given their keypoints /// /// @param[in] descriptors1 Corresponding descriptors in the first image. /// @param[in] descriptors2 Corresponding descriptors in the second image. /// @returns Matching keypoints std::vector<cv::DMatch> match(const Mat& descriptors1, const Mat& descriptors2); /// @brief Refine a matching using RANSAC and get an appropriate homography matrix /// /// @param[in] keypoints1 Matching keypoints in the first image. /// @param[in] keypoints2 Corresponding matching keypoints in the second image. /// @param[in] matches Original matching keypoints. /// @param[out] inliers Filtered matching keypoints, after RANSAC. /// @returns Homography matrix. Mat refineHomography(const std::vector<cv::KeyPoint>& keypoints1, const std::vector<cv::KeyPoint>& keypoints2, const std::vector<cv::DMatch>& matches, std::vector<cv::DMatch>& inliers); /// @brief First processing stage. Initializes the required internal resources /// /// Pre-processes the slide images and matches them to the first frame. void initialize(); /// @brief Main processing stage. Follows the slide projection in the frame /// /// As the processor detects slide changes in the footage, it will update /// the sync instructions, which can be retrieved later with GetSyncInstructions(). void track(); /// @brief Idle processing stage. Do nothing /// /// Usually entered when the work has finished or /// an error won't allow further processing. void idle(); }; } #endif
35.413636
111
0.736748
[ "vector" ]
8ced3a87ca69111b1103754a90bafba9147d991b
7,314
hpp
C++
include/Node.hpp
pasqenr/modern-cpp-course-project
9d0e8ea1106db2e157e30061a83fb8aab3fd43c6
[ "MIT" ]
null
null
null
include/Node.hpp
pasqenr/modern-cpp-course-project
9d0e8ea1106db2e157e30061a83fb8aab3fd43c6
[ "MIT" ]
null
null
null
include/Node.hpp
pasqenr/modern-cpp-course-project
9d0e8ea1106db2e157e30061a83fb8aab3fd43c6
[ "MIT" ]
null
null
null
/** * @copyright Copyright 2018 SimpleList * * <blockquote> * 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. * </blockquote> * * @author Enrico Pasquali <br> * Univerity of Verona, Dept. of Computer Science <br> * enrico.pasquali@studenti.univr.it * @date June, 2018 * @version v0.1 * * @file */ #pragma once #include "SentinelNode.hpp" #include <iostream> namespace simple_list { template<typename T> class SentinelNode; /** * @brief A node with pointer to the next and previous node. * @tparam T The type of the node. */ template<typename T> class Node { public: /** * @brief Create a node with value set to zero. */ explicit Node(); /** * @brief Create a node with value. * @param[in] value The value of the node. */ explicit Node(T value); /** * @brief Default copy constructor * @param[in] obj The other object. */ Node(const Node &obj) = default; /** * @brief Writes the node value to the stream. * @tparam R The type of the node. * @param[in] stream The stream. * @param[in] node The node to output. * @return The modified stream. */ template<typename R> friend std::ostream &operator<<(std::ostream &stream, const Node<R> &node); /** * @brief Compare the address of the Node b with the current. * @param[in] b The other node. * @return True if the nodes have the same address, false otherwise. */ bool operator==(const Node<T> &b) const; /** * @brief Compare the address of the SentinelNode b with the current. * @param[in] b The other node. * @return True if the nodes have the same address, false otherwise. */ bool operator==(const SentinelNode<T> &b) const; /** * @brief Compare the address of the Node b with the current. * @param[in] b The other node. * @return True if the nodes have different address, false otherwise. */ bool operator!=(const Node<T> &b) const; /** * @brief Compare the value of the current node and b. * @param[in] b The other node. * @return True if the value of the current node is less than the value of * node b. */ bool operator<(const Node<T> &b) const; /** * @brief Compare the value of the current node and b. * @param[in] b The other node. * @return True if the value of the current node is less or equal than the * value of node b. */ bool operator<=(const Node<T> &b) const; /** * @brief Compare the value of the current node and b. * @param[in] b The other node. * @return True if the value of the current node is greater than the value * of node b. */ bool operator>(const Node<T> &b) const; /** * @brief Compare the value of the current node and b. * @param[in] b The other node. * @return True if the value of the current node is greater or equal than * the value of node b. */ bool operator>=(const Node<T> &b) const; /** * @brief Copy the content of obj to the current Node. * @param obj The other node. * @return The current node with the values of obj. */ Node<T> &operator=(const Node<T> &obj); /** * @brief Return the value of the node. * @return The value of the node. */ T value() const; /** * Set the value of the node to val. * @param[in] val The new value. */ void value(T val); /** * @brief Unset the pointers to the next and previous node. */ void clear(); /** * @brief Unset the pointer to the previous node. */ void clear_prev(); /** * @brief Unset the pointer to the next node. */ void clear_next(); /** * @brief Check if the node has a next node. * @return True if the node has a valid next node, false otherwise. */ bool has_next() const; /** * @brief Check if the node has a previous node. * @return True if the node has a valid previous node, false otherwise. */ bool has_prev() const; /** * @brief Return the next node. If the next node is invalid an error occurs. * @return The next node. */ Node<T> &next(); /** * @brief Set the next Node to node. * @param[in] node The node to set. */ void next(Node<T> &node); /** * @brief Add node between the current and the next node. * @param[in] node The node to insert. */ void append_next(Node<T> &node); /** * @brief Return the previous node. If the previous node is invalid an error * occurs. * @return The previous node. */ Node<T> &prev(); /** * @brief Set the previous Node to node. * @param[in] node The node to set. */ void prev(Node<T> &node); /** * @brief Add node between the current and the previous node. * @param[in] node The node to insert. */ void append_prev(Node<T> &node); protected: T _value{0}; /**< The value of the node. */ Node<T> *_next{nullptr}; /**< The next node. */ Node<T> *_prev{nullptr}; /**< The previous node. */ bool _has_next{false}; /**< True if the next node is valid. */ bool _has_prev{false}; /**< True if the previous node is valid. */ private: /** * @brief Check if a node is assigned to himself. If so a warning occurs. * @param[in] node The other node. */ void check_self_assignment(const Node<T> &node); }; } // namespace simple_list namespace sl = simple_list; #include "impl/Node.i.hpp"
31.525862
84
0.564397
[ "object" ]
8cedfe32ceba5ea3ac88df8a05ad8fddfbec9ef3
1,779
hh
C++
src/memo/cli/Object.hh
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
[ "Apache-2.0" ]
124
2017-06-22T19:20:54.000Z
2021-12-23T21:36:37.000Z
src/memo/cli/Object.hh
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
[ "Apache-2.0" ]
4
2017-08-21T15:57:29.000Z
2019-01-10T02:52:35.000Z
src/memo/cli/Object.hh
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
[ "Apache-2.0" ]
12
2017-06-29T09:15:35.000Z
2020-12-31T12:39:52.000Z
#pragma once #include <elle/attribute.hh> #include <elle/das/bound-method.hh> #include <elle/das/cli.hh> #include <memo/cli/fwd.hh> #include <memo/cli/symbols.hh> namespace memo { namespace cli { template <typename Self, typename Owner = Memo, typename Cli = Memo> class Object; template <typename Self, typename Owner, typename Cli> class Object : public elle::das::named::Function<void (decltype(help = false))> { public: Object(Cli& memo); void help(std::ostream& s); void call(bool help); void apply(Cli& cli, std::vector<std::string>& args); template <typename Symbol, typename ... Args> static auto binding(Symbol const&, Args&& ... args) -> decltype(elle::das::named::function( elle::das::bind_method<Symbol, Self>(std::declval<Self&>()), std::forward<Args>(args)...)); template <typename Symbol, typename ... Args> auto bind(Symbol const& s, Args&& ... args) -> decltype(binding(s, std::forward<Args>(args)...)); ELLE_ATTRIBUTE_R(Cli&, cli); ELLE_ATTRIBUTE_R(elle::das::cli::Options, options, protected); }; template <typename Symbol, typename Object, typename Cli = Memo> struct mode_call { using type = bool; static bool value(Cli& memo, Object& o, std::vector<std::string>& args, bool& found) { if (!found && elle::das::cli::option_name_from_c(Symbol::name()) == args[0]) { found = true; args.erase(args.begin()); Symbol::attr_get(o).apply(memo, args); return true; } else return false; } }; } }
25.782609
84
0.559303
[ "object", "vector" ]
ea0233d3a478495615f6707389ba1ade6d3c2ada
1,230
hpp
C++
include/wex/presets/GameObject.hpp
cpp-gamedev/wex
247b470e8ea33293aab9b323f57ec23c6af6b779
[ "MIT" ]
1
2021-06-16T14:20:05.000Z
2021-06-16T14:20:05.000Z
include/wex/presets/GameObject.hpp
cpp-gamedev/wex
247b470e8ea33293aab9b323f57ec23c6af6b779
[ "MIT" ]
null
null
null
include/wex/presets/GameObject.hpp
cpp-gamedev/wex
247b470e8ea33293aab9b323f57ec23c6af6b779
[ "MIT" ]
null
null
null
#include "../Common.hpp" #include "../Engine.hpp" #include "../util.hpp" #include "Component.hpp" #include <cstddef> #include <vector> namespace wex { /// \brief The game game object class. A game object is a bag of components with an /// `onUpdate` method that is called once per iteration of the game loop. class GameObject { std::vector<std::unique_ptr<Component>> mComponents; public: GameObject() = default; /// \brief called on every 'update' call to the parent engine virtual void onUpdate([[maybe_unused]] double dt) {} template <typename T> [[nodiscard]] T* get() const noexcept { static_assert(std::is_base_of_v<Component, T>); /// TODO: optimize this O(n) lookup for (auto const& compPtr : mComponents) { auto comp = dynamic_cast<T*>(compPtr.get()); if (comp != nullptr) return comp; } return nullptr; } template <typename T, typename... Args> T* give(Args&&... args) { static_assert(std::is_base_of_v<Component, T>, "T does not derive from wex::Component"); auto compPtr = std::make_unique<T>(std::forward<Args>(args)...); mComponents.push_back(std::move(compPtr)); return static_cast<T*>(mComponents.back().get()); } virtual ~GameObject() = default; }; } // namespace wex
27.954545
90
0.688618
[ "object", "vector" ]
ea056af5e750cfd591842f65bf44dd0788e595ad
3,277
cpp
C++
src/things/mesh.cpp
jkrueger/phosphorus
e36d3c4b81b4327a983469116f066fdeefc9104e
[ "MIT" ]
null
null
null
src/things/mesh.cpp
jkrueger/phosphorus
e36d3c4b81b4327a983469116f066fdeefc9104e
[ "MIT" ]
null
null
null
src/things/mesh.cpp
jkrueger/phosphorus
e36d3c4b81b4327a983469116f066fdeefc9104e
[ "MIT" ]
null
null
null
#include "mesh.hpp" #include "shading.hpp" std::vector<vector_t> mesh_t::vertices; std::vector<vector_t> mesh_t::normals; std::vector<float_t> mesh_t::u; std::vector<float_t> mesh_t::v; std::vector<uint32_t> mesh_t::faces; mesh_t::mesh_t(const material_t::p& m) : index_vertices(vertices.size()) , index_faces(faces.size()) , material(m) {} mesh_t::mesh_t( const material_t::p& m, const vector_t* v, const vector_t* n, const uint32_t* f, uint32_t nv, uint32_t nf) : index_vertices(vertices.size()) , index_faces(faces.size()) , material(m) { num_vertices = nv; num_faces = nf / 3; std::copy(v, v + nv, std::back_insert_iterator<decltype(vertices)>(vertices)); std::copy(n, n + nv, std::back_insert_iterator<decltype(normals)>(normals)); std::transform( f, f + nf, std::back_insert_iterator<decltype(faces)>(faces), [=](uint32_t f){ return f; }); } void mesh_t::tesselate(std::vector<triangle_t::p>& out) const { for (auto i=index_faces; i<index_faces+(num_faces*3); i+=3) { out.emplace_back(new triangle_t(this, i)); } } void mesh_t::compute_normals() { normals.resize(normals.size()+num_vertices); for (auto i=0; i<num_faces*3; i+=3) { auto index = index_faces+i; uint32_t face[3] = {faces[index], faces[index+1], faces[index+2]}; vector_t v0v1 = vertex(face[1]) - vertex(face[0]); vector_t v0v2 = vertex(face[2]) - vertex(face[0]); vector_t n = normalize(cross(v0v2,v0v1)); for (auto j=0; j<3; ++j) { normals[index_vertices+face[j]] += n; } } for (auto i=index_vertices; i<index_vertices+num_vertices; ++i) { normals[i].normalize(); } } triangle_t::triangle_t(const mesh_t* m, int id) : mesh(m), id(id) {} // bool triangle_t::intersect(const ray_t& ray, shading_info_t& info) const { // vector_t v0v1 = mesh->vertex(b) - mesh->vertex(a); // vector_t v0v2 = mesh->vertex(c) - mesh->vertex(a); // vector_t p = cross(ray.direction, v0v2); // auto det = dot(v0v1, p); // if (std::abs(det) < 0.00000001) { // return false; // } // auto ood = 1.0 / det; // vector_t t = ray.origin - mesh->vertices[a]; // auto u = dot(t, p) * ood; // if (u < 0.0 || u > 1.0) { // return false; // } // vector_t q = cross(t, v0v1); // auto v = dot(ray.direction, q) * ood; // if (v < 0.0 || (u + v) > 1.0) { // return false; // } // auto d = dot(v0v2, q) * ood; // if (d < 0.0) { // return false; // } // return info.update(ray, d, this, u, v); // } // void triangle_t::shading_parameters(shading_info_t& info, const vector_t&, float_t u, float_t v) const { // auto w = (1 - u - v); // info.n = w * mesh->normal(a) + u * mesh->normal(b) + v * mesh->normal(c); // info.n.normalize(); // info.material = mesh->material; // } aabb_t triangle_t::bounds() const { aabb_t out; bounds::merge(out, mesh->vertex(mesh_t::faces[id ])); bounds::merge(out, mesh->vertex(mesh_t::faces[id+1])); bounds::merge(out, mesh->vertex(mesh_t::faces[id+2])); return out; } vector_t triangle_t::v0() const { return mesh->vertex(mesh_t::faces[id]); } vector_t triangle_t::v1() const { return mesh->vertex(mesh_t::faces[id+1]); } vector_t triangle_t::v2() const { return mesh->vertex(mesh_t::faces[id+2]); }
26.216
107
0.617638
[ "mesh", "vector", "transform" ]
ea06978c243c9074b7fffed5c067b6eea27cc54f
4,227
cpp
C++
src/shogun/structure/MulticlassModel.cpp
ShankarNara/shogun
8ab196de16b8d8917e5c84770924c8d0f5a3d17c
[ "BSD-3-Clause" ]
2,753
2015-01-02T11:34:13.000Z
2022-03-25T07:04:27.000Z
src/shogun/structure/MulticlassModel.cpp
ShankarNara/shogun
8ab196de16b8d8917e5c84770924c8d0f5a3d17c
[ "BSD-3-Clause" ]
2,404
2015-01-02T19:31:41.000Z
2022-03-09T10:58:22.000Z
src/shogun/structure/MulticlassModel.cpp
ShankarNara/shogun
8ab196de16b8d8917e5c84770924c8d0f5a3d17c
[ "BSD-3-Clause" ]
1,156
2015-01-03T01:57:21.000Z
2022-03-26T01:06:28.000Z
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Fernando Iglesias, Abinash Panda, Viktor Gal, Soeren Sonnenburg, * Shell Hu, Thoralf Klein, Michal Uricar, Sanuj Sharma */ #include <shogun/features/DotFeatures.h> #include <shogun/mathematics/Math.h> #include <shogun/mathematics/linalg/LinalgNamespace.h> #include <shogun/structure/MulticlassModel.h> #include <shogun/structure/MulticlassSOLabels.h> #include <utility> using namespace shogun; MulticlassModel::MulticlassModel() : StructuredModel() { init(); } MulticlassModel::MulticlassModel(std::shared_ptr<Features> features, std::shared_ptr<StructuredLabels> labels) : StructuredModel(std::move(features), std::move(labels)) { init(); } MulticlassModel::~MulticlassModel() { } std::shared_ptr<StructuredLabels> MulticlassModel::structured_labels_factory(int32_t num_labels) { return std::make_shared<MulticlassSOLabels>(num_labels); } int32_t MulticlassModel::get_dim() const { // TODO make the casts safe! int32_t num_classes = m_labels->as<MulticlassSOLabels>()->get_num_classes(); int32_t feats_dim = m_features->as<DotFeatures>()->get_dim_feature_space(); return feats_dim*num_classes; } SGVector< float64_t > MulticlassModel::get_joint_feature_vector(int32_t feat_idx, std::shared_ptr<StructuredData> y) { SGVector< float64_t > psi( get_dim() ); psi.zero(); SGVector< float64_t > x = m_features->as<DotFeatures>()-> get_computed_dot_feature_vector(feat_idx); auto r = y->as<RealNumber>(); ASSERT(r != NULL) float64_t label_value = r->value; for ( index_t i = 0, j = label_value*x.vlen ; i < x.vlen ; ++i, ++j ) psi[j] = x[i]; return psi; } std::shared_ptr<ResultSet> MulticlassModel::argmax( SGVector< float64_t > w, int32_t feat_idx, bool const training) { auto df = m_features->as<DotFeatures>(); int32_t feats_dim = df->get_dim_feature_space(); if ( training ) { auto ml = m_labels->as<MulticlassSOLabels>(); m_num_classes = ml->get_num_classes(); } else { require(m_num_classes > 0, "The model needs to be trained before " "using it for prediction"); } int32_t dim = get_dim(); ASSERT(dim == w.vlen) // Find the class that gives the maximum score float64_t score = 0, ypred = 0; float64_t max_score = -Math::INFTY; for ( int32_t c = 0 ; c < m_num_classes ; ++c ) { score = df->dot(feat_idx, w.slice(c*feats_dim, c*feats_dim + feats_dim)); if ( training ) score += delta_loss(feat_idx, c); if ( score > max_score ) { max_score = score; ypred = c; } } // Build the ResultSet object to return auto ret = std::make_shared<ResultSet>(); ret->psi_computed = true; auto y = std::make_shared<RealNumber>(ypred); ret->psi_pred = get_joint_feature_vector(feat_idx, y); ret->score = max_score; ret->argmax = y; if ( training ) { ret->delta = StructuredModel::delta_loss(feat_idx, y); ret->psi_truth = StructuredModel::get_joint_feature_vector( feat_idx, feat_idx); ret->score -= linalg::dot(w, ret->psi_truth); } return ret; } float64_t MulticlassModel::delta_loss(std::shared_ptr<StructuredData> y1, std::shared_ptr<StructuredData> y2) { auto rn1 = y1->as<RealNumber>(); auto rn2 = y2->as<RealNumber>(); ASSERT(rn1 != NULL) ASSERT(rn2 != NULL) return delta_loss(rn1->value, rn2->value); } float64_t MulticlassModel::delta_loss(int32_t y1_idx, float64_t y2) { require(y1_idx >= 0 || y1_idx < m_labels->get_num_labels(), "The label index must be inside [0, num_labels-1]"); auto rn1 = m_labels->get_label(y1_idx)->as<RealNumber>(); float64_t ret = delta_loss(rn1->value, y2); return ret; } float64_t MulticlassModel::delta_loss(float64_t y1, float64_t y2) { return (y1 == y2) ? 0 : 1; } void MulticlassModel::init_primal_opt( float64_t regularization, SGMatrix< float64_t > & A, SGVector< float64_t > a, SGMatrix< float64_t > B, SGVector< float64_t > & b, SGVector< float64_t > & lb, SGVector< float64_t > & ub, SGMatrix< float64_t > & C) { C = SGMatrix< float64_t >::create_identity_matrix(get_dim(), regularization); } void MulticlassModel::init() { SG_ADD(&m_num_classes, "m_num_classes", "The number of classes"); m_num_classes = 0; }
24.433526
116
0.707357
[ "object", "model" ]
ea0a97f1cf3e8c9d9518586f74936d50c1dd92f2
4,419
cpp
C++
dali-extension/vector-image-renderer/tizen-vector-image-renderer.cpp
dalihub/dali-extension
9bd20cbbf588828621acc1467c61c5168d7e1772
[ "Apache-2.0" ]
null
null
null
dali-extension/vector-image-renderer/tizen-vector-image-renderer.cpp
dalihub/dali-extension
9bd20cbbf588828621acc1467c61c5168d7e1772
[ "Apache-2.0" ]
null
null
null
dali-extension/vector-image-renderer/tizen-vector-image-renderer.cpp
dalihub/dali-extension
9bd20cbbf588828621acc1467c61c5168d7e1772
[ "Apache-2.0" ]
2
2020-08-29T01:26:29.000Z
2021-05-24T07:35:51.000Z
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali-extension/vector-image-renderer/tizen-vector-image-renderer.h> // EXTERNAL INCLUDES #include <dali/integration-api/debug.h> // The plugin factories extern "C" DALI_EXPORT_API Dali::VectorImageRendererPlugin* CreateVectorImageRendererPlugin( void ) { return new Dali::Plugin::TizenVectorImageRenderer; } namespace Dali { namespace Plugin { TizenVectorImageRenderer::TizenVectorImageRenderer() : mPicture(nullptr), mDefaultWidth(0), mDefaultHeight(0) { tvg::Initializer::init(tvg::CanvasEngine::Sw, 0); mSwCanvas = tvg::SwCanvas::gen(); mSwCanvas->mempool(tvg::SwCanvas::MempoolPolicy::Individual); mSwCanvas->reserve(1); //has one picture } TizenVectorImageRenderer::~TizenVectorImageRenderer() { mSwCanvas->clear(false); if(mPicture) { delete(mPicture); } tvg::Initializer::term(tvg::CanvasEngine::Sw); } bool TizenVectorImageRenderer::Load(const Vector<uint8_t>& data) { if(!mSwCanvas) { DALI_LOG_ERROR("TizenVectorImageRenderer::Load Canvas Object is null [%p]\n", this); return false; } if(!mPicture) { mPicture = tvg::Picture::gen().release(); if(!mPicture) { DALI_LOG_ERROR("TizenVectorImageRenderer::Load: Picture gen Fail [%p]\n", this); return false; } } tvg::Result ret = mPicture->load(reinterpret_cast<char*>(data.Begin()), data.Size(), false); if(ret != tvg::Result::Success) { switch (ret) { case tvg::Result::InvalidArguments: { DALI_LOG_ERROR("TizenVectorImageRenderer::Load Load fail(Invalid arguments) Size:%d [%p]\n", data.Size(), this); break; } case tvg::Result::NonSupport: { DALI_LOG_ERROR("TizenVectorImageRenderer::Load Load fail(Invalid SVG) Size:%d [%p]\n", data.Size(), this); break; } case tvg::Result::Unknown: { DALI_LOG_ERROR("TizenVectorImageRenderer::Load Load fail(Parse fail) Size:%d [%p]\n", data.Size(), this); break; } default: { DALI_LOG_ERROR("TizenVectorImageRenderer::Load Load fail / Size:%d [%p]\n", data.Size(), this); break; } } return false; } float w, h; mPicture->size(&w, &h); mDefaultWidth = static_cast<uint32_t>(w); mDefaultHeight = static_cast<uint32_t>(h); return true; } bool TizenVectorImageRenderer::Rasterize(Dali::Devel::PixelBuffer& buffer) { if(!mSwCanvas || !mPicture) { DALI_LOG_ERROR("TizenVectorImageRenderer::Rasterize: either Canvas[%p] or Picture[%p] is invalid [%p]\n", mSwCanvas.get(), mPicture, this); return false; } mSwCanvas->clear(false); auto pBuffer = buffer.GetBuffer(); if(!pBuffer) { DALI_LOG_ERROR("TizenVectorImageRenderer::Rasterize: pixel buffer is null [%p]\n", this); return false; } auto width = buffer.GetWidth(); auto height = buffer.GetHeight(); mSwCanvas->target(reinterpret_cast<uint32_t*>(pBuffer), width, width, height, tvg::SwCanvas::ABGR8888); DALI_LOG_RELEASE_INFO("TizenVectorImageRenderer::Rasterize: Buffer[%p] size[%d x %d]! [%p]\n", pBuffer, width, height, this); mPicture->size(width, height); /* We can push everytime since we cleared the canvas just before. */ if(mSwCanvas->push(std::unique_ptr<tvg::Picture>(mPicture)) != tvg::Result::Success) { DALI_LOG_ERROR("TizenVectorImageRenderer::Rasterize: Picture push fail [%p]\n", this); return false; } if(mSwCanvas->draw() != tvg::Result::Success) { DALI_LOG_ERROR("TizenVectorImageRenderer::Rasterize: Draw fail [%p]\n", this); return false; } mSwCanvas->sync(); return true; } void TizenVectorImageRenderer::GetDefaultSize(uint32_t &width, uint32_t &height) const { width = mDefaultWidth; height = mDefaultHeight; } } // namespace Plugin } // namespace Dali;
26.303571
143
0.683413
[ "object", "vector" ]
ea0bb8178841314138a7fbb0b01df8f61c8996cb
1,925
cpp
C++
binary-search/easy/349.IntersectionOfTwoArrays.cpp
XiaotaoGuo/Leetcode-Solution-In-Cpp
8e01e35c742a7afb0c8cdd228a6a5e564375434e
[ "Apache-2.0" ]
null
null
null
binary-search/easy/349.IntersectionOfTwoArrays.cpp
XiaotaoGuo/Leetcode-Solution-In-Cpp
8e01e35c742a7afb0c8cdd228a6a5e564375434e
[ "Apache-2.0" ]
null
null
null
binary-search/easy/349.IntersectionOfTwoArrays.cpp
XiaotaoGuo/Leetcode-Solution-In-Cpp
8e01e35c742a7afb0c8cdd228a6a5e564375434e
[ "Apache-2.0" ]
null
null
null
/* * @lc app=leetcode id=349 lang=cpp * * [349] Intersection of Two Arrays * * https://leetcode.com/problems/intersection-of-two-arrays/description/ * * algorithms * Easy (64.69%) * Likes: 1296 * Dislikes: 1496 * Total Accepted: 458.3K * Total Submissions: 705K * Testcase Example: '[1,2,2,1]\n[2,2]' * * Given two integer arrays nums1 and nums2, return an array of their * intersection. Each element in the result must be unique and you may return * the result in any order. * * * Example 1: * * * Input: nums1 = [1,2,2,1], nums2 = [2,2] * Output: [2] * * * Example 2: * * * Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] * Output: [9,4] * Explanation: [4,9] is also accepted. * * * * Constraints: * * * 1 <= nums1.length, nums2.length <= 1000 * 0 <= nums1[i], nums2[i] <= 1000 * * */ // @lc code=start #include <algorithm> #include <vector> class Solution { public: std::vector<int> intersection(std::vector<int>& nums1, std::vector<int>& nums2) { std::sort(nums1.begin(), nums1.end()); std::sort(nums2.begin(), nums2.end()); std::vector<int> intersection; for (size_t i = 0; i < nums1.size(); ++i) { if (i > 0 && nums1[i] == nums1[i - 1]) continue; if (binary_search(nums2, nums1[i])) { intersection.push_back(nums1[i]); } } return intersection; } private: bool binary_search(const std::vector<int>& nums, int target) { int left = 0; int right = nums.size() - 1; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] == target) { return true; } else if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return false; } }; // @lc code=end
22.126437
77
0.520519
[ "vector" ]
ea0f2fba64a730ac41bed5f42fb1b307fdee8fa1
937
cpp
C++
443.string-compression.156829728.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
443.string-compression.156829728.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
443.string-compression.156829728.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
class Solution { public: int compress(vector<char>& chars) { int pos =0; int start = 0; char ch = chars[start]; int count =0; if(chars.size()==1)return 1; while(start<chars.size()) { if(chars[start]==ch) { start++; count++; } else if(chars[start]!=ch) { chars[pos++]=ch; ch = chars[start]; string ct = to_string(count); if(count!=1)for(int i=0;i<ct.length();i++)chars[pos++]=ct[i]; count =0; } } chars[pos++]=ch; ch = chars[start]; string ct = to_string(count); if(count!=1)for(int i=0;i<ct.length();i++)chars[pos++]=ct[i]; count =0; return pos; } };
26.027778
77
0.372465
[ "vector" ]
ea2c8577a68663dae57c9aa8636a5e2cdff3a147
4,914
cc
C++
samples/dpc_gemm/main.cc
ivorobts/pti-gpu
d846e1b428a5280ab0fd065d5ae68e0a2308fa9b
[ "MIT" ]
1
2021-11-23T19:00:27.000Z
2021-11-23T19:00:27.000Z
samples/dpc_gemm/main.cc
inteI-cloud/pti-gpu
df968c95687f15f871c9323d9325211669487bd2
[ "MIT" ]
null
null
null
samples/dpc_gemm/main.cc
inteI-cloud/pti-gpu
df968c95687f15f871c9323d9325211669487bd2
[ "MIT" ]
null
null
null
//============================================================== // Copyright (C) Intel Corporation // // SPDX-License-Identifier: MIT // ============================================================= #include <string.h> #include <memory> #include "utils.h" #include <CL/sycl.hpp> #define A_VALUE 0.128f #define B_VALUE 0.256f #define MAX_EPS 1.0e-4f static float Check(const std::vector<float>& a, float value) { PTI_ASSERT(value > MAX_EPS); float eps = 0.0f; for (size_t i = 0; i < a.size(); ++i) { eps += fabs((a[i] - value) / value); } return eps / a.size(); } void GEMM(const float* a, const float* b, float* c, unsigned size, sycl::id<2> id) { int i = id.get(0); int j = id.get(1); float sum = 0.0f; for (unsigned k = 0; k < size; ++k) { sum += a[i * size + k] * b[k * size + j]; } c[i * size + j] = sum; } static float RunAndCheck(sycl::queue queue, const std::vector<float>& a, const std::vector<float>& b, std::vector<float>& c, unsigned size, float expected_result) { PTI_ASSERT(size > 0); PTI_ASSERT(a.size() == size * size); PTI_ASSERT(b.size() == size * size); PTI_ASSERT(c.size() == size * size); double time = 0.0; try { sycl::buffer<float, 1> a_buf(a.data(), a.size()); sycl::buffer<float, 1> b_buf(b.data(), b.size()); sycl::buffer<float, 1> c_buf(c.data(), c.size()); sycl::event event = queue.submit([&](sycl::handler& cgh) { auto a_acc = a_buf.get_access<sycl::access::mode::read>(cgh); auto b_acc = b_buf.get_access<sycl::access::mode::read>(cgh); auto c_acc = c_buf.get_access<sycl::access::mode::write>(cgh); cgh.parallel_for<class __GEMM>(sycl::range<2>(size, size), [=](sycl::id<2> id) { GEMM(a_acc.get_pointer(), b_acc.get_pointer(), c_acc.get_pointer(), size, id); }); }); queue.wait_and_throw(); auto start = event.get_profiling_info<sycl::info::event_profiling::command_start>(); auto end = event.get_profiling_info<sycl::info::event_profiling::command_end>(); time = static_cast<double>(end - start) / NSEC_IN_SEC; } catch (sycl::exception e) { std::cout << "[ERROR] " << e.what() << std::endl; } std::cout << "Matrix multiplication time: " << time << " sec" << std::endl; return Check(c, expected_result); } static void Compute(sycl::queue queue, const std::vector<float>& a, const std::vector<float>& b, std::vector<float>& c, unsigned size, unsigned repeat_count, float expected_result) { for (unsigned i = 0; i < repeat_count; ++i) { float eps = RunAndCheck(queue, a, b, c, size, expected_result); std::cout << "Results are " << ((eps < MAX_EPS) ? "" : "IN") << "CORRECT with accuracy: " << eps << std::endl; } } int main(int argc, char* argv[]) { sycl::info::device_type device_type = sycl::info::device_type::gpu; if (argc > 1 && strcmp(argv[1], "cpu") == 0) { device_type = sycl::info::device_type::cpu; } else if (argc > 1 && strcmp(argv[1], "host") == 0) { device_type = sycl::info::device_type::host; } unsigned size = 1024; if (argc > 2) { size = std::stoul(argv[2]); } unsigned repeat_count = 4; if (argc > 3) { repeat_count = std::stoul(argv[3]); } std::unique_ptr<sycl::device_selector> selector(nullptr); if (device_type == sycl::info::device_type::cpu) { selector.reset(new sycl::cpu_selector); } else if (device_type == sycl::info::device_type::gpu) { selector.reset(new sycl::gpu_selector); } else if (device_type == sycl::info::device_type::host) { selector.reset(new sycl::host_selector); } sycl::property_list prop_list{sycl::property::queue::enable_profiling()}; sycl::queue queue(*selector.get(), sycl::async_handler{}, prop_list); std::cout << "DPC++ Matrix Multiplication (matrix size: " << size << " x " << size << ", repeats " << repeat_count << " times)" << std::endl; std::cout << "Target device: " << queue.get_info<sycl::info::queue::device>().get_info< sycl::info::device::name>() << std::endl; std::vector<float> a(size * size, A_VALUE); std::vector<float> b(size * size, B_VALUE); std::vector<float> c(size * size, 0.0f); auto start = std::chrono::steady_clock::now(); float expected_result = A_VALUE * B_VALUE * size; Compute(queue, a, b, c, size, repeat_count, expected_result); auto end = std::chrono::steady_clock::now(); std::chrono::duration<float> time = end - start; std::cout << "Total execution time: " << time.count() << " sec" << std::endl; return 0; }
32.543046
79
0.55637
[ "vector" ]
ea2dd1167abc8d95833332642a377b28d0b295bf
515
cpp
C++
Array/80_RemoveDuplicatesFromSortedArrayII.cpp
trierbo/OJCode
327f78b12d3461f64c42375d611b6b65e71f4f78
[ "MIT" ]
null
null
null
Array/80_RemoveDuplicatesFromSortedArrayII.cpp
trierbo/OJCode
327f78b12d3461f64c42375d611b6b65e71f4f78
[ "MIT" ]
null
null
null
Array/80_RemoveDuplicatesFromSortedArrayII.cpp
trierbo/OJCode
327f78b12d3461f64c42375d611b6b65e71f4f78
[ "MIT" ]
null
null
null
#include <vector> using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.size() == 0) return 0; int res = 1, count = 1, tmp=nums[0]; for (int i = 1; i < nums.size(); ++i) { if (nums[i] != tmp) { tmp = nums[res++] = nums[i]; count = 1; } else if (count == 1) { nums[res++] = nums[i]; ++count; } } return res; } };
24.52381
47
0.401942
[ "vector" ]
ea3b970a029318555d8541d1030cf5ec0befb598
3,133
cpp
C++
restore-ip-addresses.cpp
cfriedt/leetcode
ad15031b407b895f12704897eb81042d7d56d07d
[ "MIT" ]
1
2021-01-20T16:04:54.000Z
2021-01-20T16:04:54.000Z
restore-ip-addresses.cpp
cfriedt/leetcode
ad15031b407b895f12704897eb81042d7d56d07d
[ "MIT" ]
293
2018-11-29T14:54:29.000Z
2021-01-29T16:07:26.000Z
restore-ip-addresses.cpp
cfriedt/leetcode
ad15031b407b895f12704897eb81042d7d56d07d
[ "MIT" ]
1
2020-11-10T10:49:12.000Z
2020-11-10T10:49:12.000Z
/* * Copyright (c) 2018 Christopher Friedt * * SPDX-License-Identifier: MIT */ #include <array> #include <numeric> #include <regex> #include <vector> using namespace std; class Solution { public: // https://leetcode.com/problems/restore-ip-addresses/ vector<string> restoreIpAddresses(string s) { // Assumptions // - all zeros ip address is OK // - all ones ip address is ok // - no rules like netmask, etc // // Observations // - octet pattern is "^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$" // - each octet in an IP address (in string format) is 1-3 characters // - I can brute-force the entire range of octet lengths in 81 tries :-) // 1.1.1.1 // 1.1.1.2 // ... // 3.3.3.3 // - really, those numbers are base 3, so the counting will be 0,1,2 // - 3^4 = 81 possibilities // - Only some of the 81 possibilities will match up exactly to the length // of the given string. // - only some so the algorithm is really O( 1 ) in the worst // case scenario :-) // - only some of the some of the 81 possibilities will actually make it // through the regex comparison. // - need to write toBase3PlusOne() // // Can we do better? Probably, but it's late, and this took me all of 5 // minutes to come up with. // // I suppose it would be possible to play the game of "pick where the // dot goes". Could probably be done recursively. I'm just not sure // if it's faster. // // Also, cannot simply use sscanf to parse the integer value, because // it will (for some reason), accept leading zeros. // // Analysis: // O(1) in time, or possibly O( M ) where M is the length of the // internal automata used to parse the IP address string. // O(1) in space. Very little extra storage is used, but it's constant, // in any case. vector<string> r; if (s.length() < 4 || s.length() > 12) { return r; } for (uint8_t i = 0; i < 81; i++) { array<uint8_t, 4> substring_lengths = toBase3PlusOne(i); if (accumulate(substring_lengths.begin(), substring_lengths.end(), size_t(0)) != s.size()) { continue; } string ipstr; for (size_t offs = 0, i = 0; i < 4; offs += substring_lengths[i], i++) { string sub = s.substr(offs, substring_lengths[i]); if (!regex_search(sub, octet_regex)) { break; } ipstr += sub; if (i + 1 < 4) { ipstr += "."; } if (3 == i) { r.push_back(ipstr); } } } return r; } protected: static const string octet_pattern; static const regex octet_regex; array<uint8_t, 4> toBase3PlusOne(uint8_t x) { array<uint8_t, 4> r; for (size_t i = 0; i < r.size(); i++) { r[i] = x % 3 + 1; x /= 3; } return r; } }; const string Solution::octet_pattern("^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"); const regex Solution::octet_regex(Solution::octet_pattern, std::regex_constants::ECMAScript);
28.743119
79
0.571976
[ "vector" ]
ea3d9a00ff6223ed17299cea0880bfe2970751c1
5,216
cpp
C++
mobot/traj_builder/src/traj_builder_example_main.cpp
xpharry/mobot_driving_in_gazebo
b3d25a242a177f6d466d7a00a6f91b882820b6ed
[ "MIT" ]
null
null
null
mobot/traj_builder/src/traj_builder_example_main.cpp
xpharry/mobot_driving_in_gazebo
b3d25a242a177f6d466d7a00a6f91b882820b6ed
[ "MIT" ]
null
null
null
mobot/traj_builder/src/traj_builder_example_main.cpp
xpharry/mobot_driving_in_gazebo
b3d25a242a177f6d466d7a00a6f91b882820b6ed
[ "MIT" ]
null
null
null
#include <traj_builder/traj_builder.h> //has almost all the headers we need #include <std_msgs/Float64.h> #include <nav_msgs/Odometry.h> //global vars, equivalent to member vars of class geometry_msgs::Twist g_halt_twist; nav_msgs::Odometry g_end_state; nav_msgs::Odometry g_start_state; geometry_msgs::PoseStamped g_start_pose; geometry_msgs::PoseStamped g_end_pose; void do_inits() { //similar to a constructor //define a halt state; zero speed and spin, and fill with viable coords g_halt_twist.linear.x = 0.0; g_halt_twist.linear.y = 0.0; g_halt_twist.linear.z = 0.0; g_halt_twist.angular.x = 0.0; g_halt_twist.angular.y = 0.0; g_halt_twist.angular.z = 0.0; //default values; can be overridden g_start_state.twist.twist = g_halt_twist; g_start_state.pose.pose.position.x = 0; g_start_state.pose.pose.position.y = 0; g_start_state.pose.pose.position.z = 0; } int main(int argc, char **argv) { ros::init(argc, argv, "des_state_publisher"); ros::NodeHandle n; double dt = 0.02; //will stream (publish) desired states to this topic with this message type: ros::Publisher des_state_publisher = n.advertise<nav_msgs::Odometry>("/desState", 1); ros::Publisher des_psi_publisher = n.advertise<std_msgs::Float64>("/desPsi", 1); //can use this to drive a robot around, open loop: ros::Publisher twist_commander = n.advertise<geometry_msgs::Twist>("cmd_vel", 1); ros::Rate looprate(1 / dt); //timer for fixed publication rate TrajBuilder trajBuilder; //instantiate one of these trajBuilder.set_dt(dt); //make sure trajectory builder and main use the same time step trajBuilder.set_alpha_max(1.0); //hard code two poses; more generally, would get poses from a nav_msgs/Path message. double psi_start = 0.0; double psi_end = 0.0; //3.0; g_start_state.pose.pose.orientation = trajBuilder.convertPlanarPsi2Quaternion(psi_start); g_end_state = g_start_state; g_end_state.pose.pose.orientation = trajBuilder.convertPlanarPsi2Quaternion(psi_end); g_start_pose.pose.position.x = 0.0; g_start_pose.pose.position.y = 0.0; g_start_pose.pose.position.z = 0.0; g_start_pose.pose.orientation = trajBuilder.convertPlanarPsi2Quaternion(psi_start); g_end_pose = g_start_pose; //includes copying over twist with all zeros //don't really care about orientation, since this will follow from // point-and-go trajectory; g_end_pose.pose.orientation = trajBuilder.convertPlanarPsi2Quaternion(psi_end); g_end_pose.pose.position.x = 5.0; //set goal coordinates g_end_pose.pose.position.y = 0.0; //-4.0; double des_psi; std_msgs::Float64 psi_msg; std::vector<nav_msgs::Odometry> vec_of_states; //trajBuilder.build_triangular_spin_traj(g_start_pose,g_end_pose,vec_of_states); //trajBuilder.build_point_and_go_traj(g_start_pose, g_end_pose, vec_of_states); nav_msgs::Odometry des_state; nav_msgs::Odometry last_state; geometry_msgs::PoseStamped last_pose; /*timing test: takes about 1.3 msec to compute a point-and-go trajectory ROS_INFO("timing test: constructing 10000 point-and-go trajectories"); for (int ipaths=0;ipaths<10000;ipaths++) { trajBuilder.build_point_and_go_traj(g_start_pose, g_end_pose, vec_of_states); } ROS_INFO("done computing trajectories"); * */ // main loop; publish a desired state every iteration while (ros::ok()) { ROS_INFO("building traj from start to end"); trajBuilder.build_point_and_go_traj(g_start_pose, g_end_pose, vec_of_states); ROS_INFO("publishing desired states and open-loop cmd_vel"); for (int i = 0; i < vec_of_states.size(); i++) { des_state = vec_of_states[i]; des_state.header.stamp = ros::Time::now(); des_state_publisher.publish(des_state); des_psi = trajBuilder.convertPlanarQuat2Psi(des_state.pose.pose.orientation); psi_msg.data = des_psi; des_psi_publisher.publish(psi_msg); twist_commander.publish(des_state.twist.twist); //FOR OPEN-LOOP CTL ONLY! looprate.sleep(); //sleep for defined sample period, then do loop again } ROS_INFO("building traj from end to start"); last_state = vec_of_states.back(); last_pose.header = last_state.header; last_pose.pose = last_state.pose.pose; trajBuilder.build_point_and_go_traj(last_pose, g_start_pose, vec_of_states); for (int i = 0; i < vec_of_states.size(); i++) { des_state = vec_of_states[i]; des_state.header.stamp = ros::Time::now(); des_state_publisher.publish(des_state); des_psi = trajBuilder.convertPlanarQuat2Psi(des_state.pose.pose.orientation); psi_msg.data = des_psi; des_psi_publisher.publish(psi_msg); twist_commander.publish(des_state.twist.twist); //FOR OPEN-LOOP CTL ONLY! looprate.sleep(); //sleep for defined sample period, then do loop again } last_state = vec_of_states.back(); g_start_pose.header = last_state.header; g_start_pose.pose = last_state.pose.pose; } }
45.356522
93
0.700537
[ "vector" ]
ea3ef636f54441d8114b074bcfbb54eca1b4d33b
14,864
cxx
C++
painty/sbr/src/PictureTargetSbrPainter.cxx
lindemeier/painty
792cac6655b3707805ffc68d902f0e675a7770b8
[ "MIT" ]
15
2020-04-22T15:18:28.000Z
2022-03-24T07:48:28.000Z
painty/sbr/src/PictureTargetSbrPainter.cxx
lindemeier/painty
792cac6655b3707805ffc68d902f0e675a7770b8
[ "MIT" ]
25
2020-04-18T18:55:50.000Z
2021-05-30T21:26:39.000Z
painty/sbr/src/PictureTargetSbrPainter.cxx
lindemeier/painty
792cac6655b3707805ffc68d902f0e675a7770b8
[ "MIT" ]
2
2020-09-16T05:55:54.000Z
2021-01-09T12:09:43.000Z
/** * @file PictureTargetSbrPainter.cxx * @author Thomas Lindemeier * @brief * @date 2020-09-11 * */ #include "painty/sbr/PictureTargetSbrPainter.hxx" #include <future> #include <random> #include "painty/core/Color.hxx" #include "painty/image/Convolution.hxx" #include "painty/image/EdgeTangentFlow.hxx" #include "painty/io/ImageIO.hxx" #include "painty/mixer/Serialization.hxx" #include "painty/renderer/Renderer.hxx" #include "painty/sbr/PathTracer.hxx" namespace painty { PictureTargetSbrPainter::PictureTargetSbrPainter( const std::shared_ptr<GpuTaskQueue>& gpuTaskQueue, const Size& rendererSize, const std::shared_ptr<PaintMixer>& basePigmentsMixerPtr) : _renderThread(gpuTaskQueue, rendererSize), _basePigmentsMixerPtr(basePigmentsMixerPtr) {} void PictureTargetSbrPainter::enableCoatCanvas(bool enable) { _coatCanvas = enable; } void PictureTargetSbrPainter::enableSmudge(bool enable) { _renderThread.enableSmudge(enable); } auto PictureTargetSbrPainter::extractRegions(const Mat3d& target_Lab, const Mat1d& difference, double brushSize) const -> std::pair<Mat<int32_t>, std::map<int32_t, ImageRegion>> { Mat3d segImage = _paramsInput.inputSRGB.clone(); Mat3d segDiffImage(segImage.size()); std::map<int32_t, ImageRegion> regions; Mat<int32_t> labels; SuperpixelSegmentation seg; seg.setUseDiffWeight(_paramsRegionExtraction.useDiffWeights); seg.setExtractionStrategy(_paramsRegionExtraction.extractionStrategy); seg.extractWithDiff(target_Lab, difference, _paramsInput.mask, static_cast<int32_t>(brushSize)); labels = seg.getRegions(regions); for (auto j = 0; j < static_cast<int32_t>(segDiffImage.total()); ++j) { segDiffImage(j)[0] = difference(j); segDiffImage(j)[1] = difference(j); segDiffImage(j)[2] = difference(j); } seg.getSegmentationOutlined(segImage); seg.getSegmentationOutlined(segDiffImage); painty::io::imSave("/tmp/superpixelsTarget.jpg", segImage, false); painty::io::imSave("/tmp/superpixelsDifference.jpg", segDiffImage, false); return {labels, regions}; } auto PictureTargetSbrPainter::checkConvergence( const Mat1d& difference, std::map<int32_t, ImageRegion>& regions, Mat<int32_t>& labels, const double epsFac) const -> bool { auto globalRMS = 0.0; std::cout << "filtering evaluation regions for finished regions" << std::endl; auto nrActiveRegions = 0UL; const auto localRms = epsFac * _paramsConvergence.rms_local; for (auto iter = regions.begin(); iter != regions.end(); iter++) { auto rms = iter->second.computeRms(difference); if (rms >= localRms) { iter->second.setActive(true); globalRMS += rms; nrActiveRegions++; } else { iter->second.setActive(false); iter->second.fill(labels, -1); std::cout << "Region " << iter->first << " set inactive with rms " << rms << " < " << localRms << std::endl; } } globalRMS /= static_cast<double>(nrActiveRegions); if (globalRMS < _paramsConvergence.rms_global) { std::cout << "Converged globally..." << std::endl; return true; } return false; } auto PictureTargetSbrPainter::generateBrushStrokes( std::map<int32_t, ImageRegion>& regions, const Mat3d& target_Lab, const Mat3d& canvasCurrentLab, const Mat1d& /*difference*/, const double brushRadius, const Palette& palette, const Mat<int32_t>& labels, const Mat1d& mask, const Mat3d& tensors) const -> PictureTargetSbrPainter::ColorIndexBrushStrokeMap { PathTracer tracer(tensors); tracer.setMinLen(_paramsStroke.minLen); tracer.setMaxLen(_paramsStroke.maxLen); tracer.setStep((_paramsStroke.stepSize <= 0.0) ? (brushRadius * 0.25) : _paramsStroke.stepSize); tracer.setFrame(cv::Rect2i(0, 0, target_Lab.cols, target_Lab.rows)); tracer.setFc(_paramsStroke.curvatureAlpha); ColorIndexBrushStrokeMap brushStrokes; std::cout << "Iterating through all active regions" << std::endl; for (auto reg : regions) { auto& region = reg.second; if (!region.isActive()) { continue; } vec2 incenter = {100, 100}; auto usedRadius = region.getInscribedCircle(incenter); const auto width = usedRadius * 2.0; // TODO clamp is bad for strokes whose minsize is larger than inscribed circle radius. if (_paramsStroke.clampBrushRadius) { usedRadius = clamp(width, BrushMinSize, BrushMaxSize) / 2.; } else { if (width < BrushMinSize) { region.setActive(false); continue; } if (width > BrushMaxSize) { usedRadius = std::min(width, BrushMaxSize) / 2.0; } } vec3 Rt = region.computeMean(target_Lab); vec3 R0 = region.computeMean(canvasCurrentLab); ColorConverter<double> con; con.lab2rgb(R0, R0); con.lab2rgb(Rt, Rt); const auto closestPaint = PaintMixer(palette).mixClosestFit(R0, Rt); auto currentPaintIndex = findBestPaintIndex(Rt, R0, palette); if (!currentPaintIndex) { currentPaintIndex = 0; } tracer.setEvaluatePositionFun([&](const vec2& p) -> PathTracer::NextAction { if ((static_cast<int32_t>(p[0U]) < 0) || (static_cast<int32_t>(p[1U]) < 0) || (static_cast<int32_t>(p[0U]) >= labels.cols) || (static_cast<int32_t>(p[1U]) >= labels.rows)) { return PathTracer::NextAction::PATH_STOP_NOW; } const auto clabel = labels(static_cast<int32_t>(p[1U]), static_cast<int32_t>(p[0U])); if ((clabel < 0) || ((!mask.empty()) && (mask(static_cast<int32_t>(p[1U]), static_cast<int32_t>(p[0U])) < 1.0)) || (regions.count(clabel) == 0u)) { return PathTracer::NextAction::PATH_STOP_NOW; } vec3 LabCanvas = regions[clabel].computeMean(canvasCurrentLab); vec3 LabSource = regions[clabel].computeMean(target_Lab); ColorConverter<double> converter; vec3 R0_test; converter.lab2rgb(LabCanvas, R0_test); const auto R1 = ComputeReflectance( closestPaint.K, closestPaint.S, R0_test, AssumedAvgThickness * _renderThread.getBrushThicknessScale()); vec3 Lab1; converter.rgb2lab(R1, Lab1); if ((Lab1 - LabSource).squaredNorm() < (LabSource - LabCanvas).squaredNorm()) { return PathTracer::NextAction::PATH_CONTINUE; } return PathTracer::NextAction::PATH_STOP_NEXT; }); // std::cout << "Generating path at: " << incenter.transpose() << std::endl; auto path = tracer.trace(incenter); // std::cout << "Adding valid strokes and sort by paint" << std::endl; if (_paramsStroke.blockVisitedRegions) { for (const auto& p : path) { if ((static_cast<int32_t>(p[0U]) < 0) || (static_cast<int32_t>(p[1U]) < 0) || (static_cast<int32_t>(p[0U]) >= labels.cols) || (static_cast<int32_t>(p[1U]) >= labels.rows)) { continue; } // block this cell from painting for future visits regions[labels(static_cast<int32_t>(p[1]), static_cast<int32_t>(p[0]))] .setActive(false); } } if (!path.empty()) { PaintMixer mixer(palette); brushStrokes[currentPaintIndex.value()].push_back( {path, usedRadius, closestPaint}); } } return brushStrokes; } auto PictureTargetSbrPainter::findBestPaintIndex(const vec3& R_target, const vec3& R0, const Palette& palette) const -> std::optional<size_t> { ColorConverter<double> con; vec3 R_target_Lab; vec3 R0_Lab; con.rgb2lab(R_target, R_target_Lab); con.rgb2lab(R0, R0_Lab); auto d = (R0_Lab - R_target_Lab).squaredNorm(); size_t bestIndex = std::numeric_limits<size_t>::max(); for (size_t i = 0UL; (i < palette.size()); i++) { vec3 R_Lab; con.rgb2lab(ComputeReflectance( palette[i].K, palette[i].S, R0, AssumedAvgThickness * _renderThread.getBrushThicknessScale()), R_Lab); const auto ld = (R_Lab - R_target_Lab).squaredNorm(); if (ld < d) { d = ld; bestIndex = i; } } return (bestIndex == std::numeric_limits<size_t>::max()) ? std::nullopt : std::optional<size_t>(bestIndex); } auto PictureTargetSbrPainter::computeDifference(const Mat3d& target_Lab, const Mat3d& canvasCurrentLab, const double brushRadius) const -> Mat1d { const auto derivTarget = differencesOfGaussians(target_Lab, brushRadius); const auto derivCanvas = differencesOfGaussians(canvasCurrentLab, brushRadius); constexpr auto derivMaxNorm = 20.0; auto difference = Mat1d(target_Lab.size()); for (auto i = 0; i < static_cast<int32_t>(target_Lab.total()); i++) { difference(i) = _paramsInput.alphaDiff * ColorConverter<double>::ColorDifference( target_Lab(i), canvasCurrentLab(i)) + (1.0 - _paramsInput.alphaDiff) * ((derivTarget(i) - derivCanvas(i)).norm() / derivMaxNorm); } painty::io::imSave("/tmp/difference.jpg", difference, false); return difference; } auto PictureTargetSbrPainter::paint() -> Mat3d { if (_paramsInput.inputSRGB.empty()) { throw std::runtime_error("_paramsInput.inputSRGB.empty()"); } std::cout << "Converting input to Lab and apply smoothing" << std::endl; // convert to CIELab and blur the image using a bilateral filter const auto target_Lab = smoothOABF( convertColor(_paramsInput.inputSRGB, ColorConverter<double>::Conversion::srgb_2_CIELab), Mat1d(), _paramsInput.sigmaSpatial, _paramsInput.sigmaColor, _paramsOrientations.outerBlurScale, _paramsInput.smoothIterations); painty::io::imSave( "/tmp/targetImage.jpg", convertColor(target_Lab, ColorConverter<double>::Conversion::CIELab_2_srgb), false); std::cout << "Extract color palette from image using base pigments" << std::endl; // mix palette for the image from the painters base pigments auto palette = _basePigmentsMixerPtr->mixFromInputPicture( _paramsInput.inputSRGB, _paramsInput.nrColors); // make the paints thinner { const auto thinner = getThinningMedium(); for (auto& paint : palette) { paint = _basePigmentsMixerPtr->mixed(paint, 1.0, thinner, _paramsInput.thinningVolume); } } painty::io::imSave("/tmp/targetImagePalette.jpg", VisualizePalette(palette, 1.0), false); std::cout << "coating canvas" << std::endl; if (_coatCanvas) { paintCoatCanvas(palette[1U]); } // for every brush auto itBrush = 1; for (const auto brushSize : _paramsStroke.brushSizes) { std::cout << "Switching to brush size: " << brushSize << std::endl; const double brushRadius = brushSize / 2.0; _renderThread.setBrushThicknessScale(_paramsStroke.thicknessScale); std::cout << "Computing structure tensor field" << std::endl; // compute structure tensor field const auto tensors = tensor::ComputeTensors(target_Lab, _paramsInput.mask, brushRadius * _paramsOrientations.innerBlurScale, brushRadius * _paramsOrientations.outerBlurScale); const auto future = std::async(std::launch::async, [tensors]() { painty::io::imSave("/tmp/targetImageOrientation.jpg", lineIntegralConv(ComputeEdgeTangentFlow(tensors), 10.), false); }); std::cout << "Iterating layers" << std::endl; for (uint32_t iteration = 0U; iteration < _paramsConvergence.maxIterations; iteration++) { std::cout << "Iteration: " << iteration << std::endl; const double epsFac = (itBrush++ / static_cast<double>(_paramsConvergence.maxIterations * _paramsStroke.brushSizes.size())); std::cout << "Getting current state of the canvas" << std::endl; const Mat3d canvasCurrentRGBLinear = _renderThread.getLinearRgbImage().get(); painty::io::imSave("/tmp/canvasCurrent.jpg", canvasCurrentRGBLinear, true); const auto canvasCurrentLab = ScaledMat( convertColor(canvasCurrentRGBLinear, ColorConverter<double>::Conversion::rgb_2_CIELab), target_Lab.rows, target_Lab.cols); std::cout << "Compute difference of target and canvas" << std::endl; auto difference = computeDifference(target_Lab, canvasCurrentLab, brushRadius); std::cout << "Extracting superpixels" << std::endl; std::map<int32_t, ImageRegion> regions; Mat<int32_t> labels; std::tie(labels, regions) = extractRegions(target_Lab, difference, brushSize); // discard already close enough regions if (checkConvergence(difference, regions, labels, epsFac)) { return _renderThread.getLinearRgbImage().get(); } auto brushStrokeMap = generateBrushStrokes( regions, target_Lab, canvasCurrentLab, difference, brushRadius, palette, labels, _paramsInput.mask, tensors); std::cout << "Rendering strokes" << std::endl; const auto xs = static_cast<double>(_renderThread.getSize().width) / static_cast<double>(target_Lab.cols); const auto ys = static_cast<double>(_renderThread.getSize().height) / static_cast<double>(target_Lab.rows); for (auto& element : brushStrokeMap) { const auto paint = palette[element.first]; // std::cout << "Changing paint to: " << element.first << std::endl; for (auto& brushStroke : element.second) { for (auto& vertex : brushStroke.path) { vertex[0U] *= xs; vertex[1U] *= ys; } _renderThread.render(brushStroke.path, ((xs + ys) * 0.5) * brushStroke.radius, {brushStroke.paint.K, brushStroke.paint.S}); } } } future.wait(); } _renderThread.dryCanvas().wait(); return _renderThread.getLinearRgbImage().get(); } void PictureTargetSbrPainter::paintCoatCanvas(const PaintCoeff& paint) { const auto step = static_cast<double>(_renderThread.getSize().height) / 10.0; for (auto u = step * 0.5; u < static_cast<double>(_renderThread.getSize().height); u += step) { std::vector<vec2> path = { {-2.0 * step, u}, {static_cast<double>(_renderThread.getSize().width) + 2.0 * step, u}}; _renderThread.render(path, step * 0.8, {paint.K, paint.S}); } } } // namespace painty
36.975124
90
0.639195
[ "render", "vector" ]
ea3f56556ac61a2096843c67bcce4106762ddfa8
640
cpp
C++
something-learned/Algorithms and Data-Structures/Competitive-programming-library/CP/codechef/December Challenge 16/KIRLAB-naive.cpp
gopala-kr/CR-101
dd27b767cdc0c667655ab8e32e020ed4248bd112
[ "MIT" ]
5
2018-05-09T04:02:04.000Z
2021-02-21T19:27:56.000Z
something-learned/Algorithms and Data-Structures/Competitive-programming-library/CP/codechef/December Challenge 16/KIRLAB-naive.cpp
gopala-kr/CR-101
dd27b767cdc0c667655ab8e32e020ed4248bd112
[ "MIT" ]
null
null
null
something-learned/Algorithms and Data-Structures/Competitive-programming-library/CP/codechef/December Challenge 16/KIRLAB-naive.cpp
gopala-kr/CR-101
dd27b767cdc0c667655ab8e32e020ed4248bd112
[ "MIT" ]
5
2018-02-23T22:08:28.000Z
2020-08-19T08:31:47.000Z
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return (b == 0)?a:gcd(b,a%b); } int main(){ int t; cin>>t; while(t--) { long n; cin>>n; vector<long long > arr(n); for(long i=0;i<n;i++) cin>>arr[i]; vector<vector<long long> > mat(n); long mv = 0; for(long i=0;i<arr.size();i++){ long cur = mv; while(cur != -1) { long j; for(j=0;j<mat[cur].size();j++) { if(gcd(mat[cur][j],arr[i])!=1) break; } if(j!=mat[cur].size()) break; cur--; } cur++; mv = max(mv,cur); mat[cur].push_back(arr[i]); } cout<<mv+1<<endl; } return 0; }
17.777778
41
0.509375
[ "vector" ]
ea41648dbd0d115952e837e5102e0f20f2261471
958
cc
C++
Code/0111-minimum-depth-of-binary-tree.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
2
2019-12-06T14:08:57.000Z
2020-01-15T15:25:32.000Z
Code/0111-minimum-depth-of-binary-tree.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
1
2020-01-15T16:29:16.000Z
2020-01-26T12:40:13.000Z
Code/0111-minimum-depth-of-binary-tree.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
null
null
null
/** * 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: int minDepth(TreeNode* root) { if (!root) { return 0; } vector<TreeNode *> parent; vector<TreeNode *> child; parent.push_back(root); int result = 1; while (true) { child.clear(); for (int i = 0; i < parent.size(); i++) { if (parent[i]->left) { child.push_back(parent[i]->left); } if (parent[i]->right) { child.push_back(parent[i]->right); } if (!parent[i]->left && !parent[i]->right) { return result; } } parent = child; result++; } } };
25.891892
60
0.417537
[ "vector" ]
ea478e91fbe87b4e73f6d72011d3ebe54db8a0cb
7,216
cpp
C++
Redline_CLI/RenderApplication.cpp
64-bit/Redline
c3f5ebd24da8ac437aee5429b2eeea7a14cc93b0
[ "MIT" ]
1
2019-02-03T04:47:21.000Z
2019-02-03T04:47:21.000Z
Redline_CLI/RenderApplication.cpp
64-bit/Redline
c3f5ebd24da8ac437aee5429b2eeea7a14cc93b0
[ "MIT" ]
null
null
null
Redline_CLI/RenderApplication.cpp
64-bit/Redline
c3f5ebd24da8ac437aee5429b2eeea7a14cc93b0
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "RenderApplication.h" #include "CLIErrorCodes.h" #include "CommandLineArguments.h" #include "CameraFlightController.h" #include "Renderer/BRDF/CookTorrence/Functions/GGX_Distribution.h" #include "Renderer/BRDF/CookTorrence/Functions/GGX_Geometry.h" #include "Renderer/BRDF/CookTorrence/Functions/Schlick_Fresnel.h" using namespace Redline; int RenderApplication::Run(const CommandLineArguments* const arguments) { _threadpool = new Threadpool(arguments->Threads, Normal); const auto loadSceneResult = LoadScene(arguments); if(loadSceneResult != CLI_ERRORCODE___OK) { return loadSceneResult; } SDL_Init(SDL_INIT_EVERYTHING); SetupFeatures(arguments); RunWholeApplication(arguments); return CLI_ERRORCODE___OK; } void RenderApplication::RestartRender() { //If we have no preview window, render mip level 1, else 16 _currentRenderMipLevel = _previewWindow == nullptr ? 1 : 16; //_currentRenderMipLevel = 1; if (_frameResultPromis != nullptr) { _frameRenderer->StopRendering(); _frameResultPromis->Getvalue(); } _frameRenderer->ResetRenderer(); _frameResultPromis = _frameRenderer->RenderFrameAsync(_currentRenderMipLevel); } RenderApplication::~RenderApplication() { delete _threadpool; } //Temp #include "Scene/Scene.h" #include "Renderer/Raytracer.h" #include <ostream> #include <iostream> #include "SDL.h" #undef main #include "Scene/Components/Renderable/SphereRenderer.h" #include "Scene/Components/CameraComponent.h" #include "Renderer/FrameRenderer.h" #include "GraphicalResources/CubemapTexture.h" #include "Utilities/Stopwatch.h" #include "Renderer/BRDF/CookTorrence/CookTorrence.h" #include "FileFormats/GLTFSceneLoader.h" using namespace std; using namespace mathfu; void RenderApplication::RunWholeApplication(const CommandLineArguments* const arguments) { //Start SDL //Main loop flag bool quit = false; int lastTick = SDL_GetTicks(); //Render frame async printf("\n---Raytracing Starting---\n"); Stopwatch watch; RestartRender(); while (!quit) { const int thisTick = SDL_GetTicks(); const int ticksPassed = thisTick - lastTick; lastTick = thisTick; const float deltaT = static_cast<float>(ticksPassed) / 1000.0f;//Convert miliseconds to seconds //Check if the user has pressed escape or click the X on the preview window if(_previewWindow != nullptr) { quit = quit || _previewWindow->ShouldQuitThisFrame(); } //Update this value to true if OnSDLUpdate returns that we moved //This lets us move the camera with percisoin, but only restart the render every so often if (_flightController != nullptr) { const bool shouldUpdatePreview = _flightController->OnSDLUpdate(deltaT); if(shouldUpdatePreview) { watch = Stopwatch(); RestartRender(); } } //Check promis for updates and update screen if we are done if (_frameResultPromis != nullptr) { if (_frameResultPromis->IsFufilled()) { if (_previewWindow != nullptr) { _previewWindow->UpdateWindowFromBitmap(_frameResultPromis->Getvalue()); } printf("\n---Raytracing finished---\n"); //printf("Raytracing scene took %.1f1 mS\n", raytraceTime.GetMiliseconds()); if (_currentRenderMipLevel != 1) { _frameResultPromis = nullptr; _currentRenderMipLevel /= 2; _frameRenderer->ResetRenderer(); _frameResultPromis = _frameRenderer->RenderFrameAsync(_currentRenderMipLevel); } else { //Stop timer watch.Stop(); auto ms = watch.GetMiliseconds(); printf("\n---Raytracing finished in %f mS---\n", ms); //Write out to disk if enabled. //TODO:Better name for multiple preview renders, or don't write this if the camera moved if(arguments->WriteImageOnRenderFinish) { auto bitmap = _frameResultPromis->Getvalue(); stbi_write_png(arguments->OutputFilename.c_str(), bitmap->Width, bitmap->Height, 4, bitmap->Pixels, bitmap->Width * 4); _frameResultPromis = nullptr; } } } else { if(_previewWindow != nullptr) { _previewWindow->UpdateWindowFromBitmap(_frameRenderer->GetCurrentFrameState()); } } } //Wiat a minimum of 5 miliseconds between iterations of this loop if (ticksPassed < 50) { int delay = 50 - ticksPassed; SDL_Delay(delay); } } //Quit SDL SDL_Quit(); return; } int RenderApplication::LoadScene(const CommandLineArguments* const arguments) { GLTFSceneLoader gltfSceneLoader; _scene = gltfSceneLoader.LoadSceneFromGLTFFile(arguments->SceneFilename); if(_scene == nullptr) { printf("Error: Invalid scene\n"); return CLI_ERRORCODE___INVALID_SCENE; } #ifdef NDEBUG //TODO: Read from scene file extension //_scene->EnvironmentCubemap = LoadCubemap(); _scene->BackgroundColor = mathfu::vec3(1.0f, 1.0f, 1.0f); _scene->EnvironmentPower = 1.0; #endif //_scene->BackgroundColor = mathfu::vec3(0.369f, 0.438f, 0.5f); _scene->BackgroundColor = mathfu::vec3(0.0f, 0.0f, 0.0f); _scene->EnvironmentPower = 0.0f; _camera = _scene->FindComponentByType<CameraComponent>(); if(_camera == nullptr) { printf("Error: No camera found in scene\n"); return CLI_ERRORCODE___NO_CAMERA_IN_SCENE; } return CLI_ERRORCODE___OK; } int RenderApplication::SetupFeatures(const CommandLineArguments* const arguments) { if(arguments->EnableFlightCamera) { if(arguments->EnableRenderPreview) { _flightController = make_shared<CameraFlightController>(*this, _camera); } else { printf("Warning: flight camera cannot be enabled without render preview\n"); } } if(arguments->EnableRenderPreview) { _previewWindow = make_shared<RenderPreviewWindow>(); const int createwWindowResult = _previewWindow->CreateWindow(arguments); if(createwWindowResult != CLI_ERRORCODE___OK) { return createwWindowResult; } } //Create functions for Cook-Torrence auto distributionFunction = std::make_shared<CookTorrenceBRDF::GGX_Distribution>(); auto geometryFunction = std::make_shared<CookTorrenceBRDF::GGX_Geometry>(); auto fresnelFunction = std::make_shared<CookTorrenceBRDF::Schlick_Fresnel>(); _brdf = std::make_shared<CookTorrence>( distributionFunction, geometryFunction, fresnelFunction); _pathTracer = std::make_shared<PathTracer>( arguments->OutputSettings, arguments->QuailtySettings, _brdf); _frameRenderer = make_shared<FrameRenderer>( _scene, _camera, arguments->OutputSettings, arguments->QuailtySettings, _threadpool, _brdf, _pathTracer); return CLI_ERRORCODE___OK; } shared_ptr<CubemapTexture> RenderApplication::LoadCubemap() //TODO:Make this driven by a command line argument and or scene extension { auto cubemap = std::make_shared<CubemapTexture>(); cubemap->Faces[0] = Bitmap2D::LoadFromFile("TestFiles/cubemap/rightImage.png"); cubemap->Faces[1] = Bitmap2D::LoadFromFile("TestFiles/cubemap/leftImage.png"); cubemap->Faces[2] = Bitmap2D::LoadFromFile("TestFiles/cubemap/downImage.png"); cubemap->Faces[3] = Bitmap2D::LoadFromFile("TestFiles/cubemap/upImage.png"); cubemap->Faces[4] = Bitmap2D::LoadFromFile("TestFiles/cubemap/backImage.png"); cubemap->Faces[5] = Bitmap2D::LoadFromFile("TestFiles/cubemap/frontImage.png"); return cubemap; }
25.956835
133
0.738498
[ "render" ]
35689dcbec3b0ff800e384c863d286626ecee4fa
1,168
cpp
C++
examples/example-05-vacant-surface/vacant.cpp
edisonslightbulbs/dbscan-cpp
48b2e38726761cda1533aff68de6882e0fb441a7
[ "MIT" ]
1
2021-06-27T21:46:33.000Z
2021-06-27T21:46:33.000Z
examples/example-05-vacant-surface/vacant.cpp
researchers-anonymous/test
3a802254d53aca8635131b5b35f7f07d6eee0737
[ "MIT" ]
null
null
null
examples/example-05-vacant-surface/vacant.cpp
researchers-anonymous/test
3a802254d53aca8635131b5b35f7f07d6eee0737
[ "MIT" ]
1
2022-01-27T19:36:58.000Z
2022-01-27T19:36:58.000Z
#include <thread> #include "i3d.h" #include "i3dpcl.h" #include "i3dscene.h" #include "kinect.h" #include "usage.h" int main(int argc, char* argv[]) { // init logger, kinect, and i3d logger(argc, argv); usage::prompt(ABOUT); std::shared_ptr<kinect> sptr_kinect(new kinect); std::shared_ptr<i3d> sptr_i3d(new i3d()); std::thread work( i3dscene::context, std::ref(sptr_kinect), std::ref(sptr_i3d)); WAIT_FOR_CLUSTERS auto clusters = sptr_i3d->getPCloudClusters(); auto clusteredPoints = clusters->first; auto clusteredPointIndexes = clusters->second; // initialize random color uint8_t rgba[4] = { 69, 117, 180, 1 }; // clusters are sorted in descending order of size // in this example, to extract the tabletop surface // we assume that the vacant space corresponds to // the largest cluster std::vector<Point> vacant; for (auto& index : clusteredPointIndexes[0]) { clusteredPoints[index].setRGBA(rgba); vacant.emplace_back(clusteredPoints[index]); } i3dpcl::write(vacant, "./output/vacant-surface.ply"); sptr_i3d->stop(); work.join(); return 0; }
28.487805
70
0.663527
[ "vector" ]
3568d3b9a28107e11740bf621bc8ae97ea01815b
9,513
cpp
C++
modules/io/src/png_image.cpp
ChristopheEcabert/OGLKit
909e25d833ed5338dd627f71f89064b8cb4ed36f
[ "Apache-2.0" ]
null
null
null
modules/io/src/png_image.cpp
ChristopheEcabert/OGLKit
909e25d833ed5338dd627f71f89064b8cb4ed36f
[ "Apache-2.0" ]
null
null
null
modules/io/src/png_image.cpp
ChristopheEcabert/OGLKit
909e25d833ed5338dd627f71f89064b8cb4ed36f
[ "Apache-2.0" ]
null
null
null
/** * @file png_image.cpp * @brief PNG Image object * * @author Christophe Ecabert * @date 06.03.17 * Copyright © 2017 Christophe Ecabert. All rights reserved. */ #include <fstream> #include <setjmp.h> #include <vector> #include <iostream> #include "png.h" #include "oglkit/core/string_util.hpp" #include "oglkit/io/png_image.hpp" /** * @namespace OGLKit * @brief OpenGL development space */ namespace OGLKit { /** * @name * @brief Read data from stream * @param[in,out] png_ptr Png decoder instance * @param[in.out] out_byte Buffer where to place data laoded * @param[in] byte_to_read Number of byte to be read */ void ReadData(png_structp png_ptr, png_bytep out_byte, png_size_t byte_to_read) { // Get io_ptr png_voidp io_ptr = png_get_io_ptr(png_ptr); if (io_ptr) { // Get stream std::istream* stream = reinterpret_cast<std::istream*>(io_ptr); // Read stream->read(reinterpret_cast<char*>(out_byte), byte_to_read); } } /** * @name WriteData * @brief Write data into custom stream * @param[in] png_str Png decoder instance * @param[in] in_byte Pointer to data to write * @param[in] byte_to_write Number of byte to write */ void WriteData(png_structp png_ptr, png_bytep in_byte, png_size_t byte_to_write) { // Get io_ptr png_voidp io_ptr = png_get_io_ptr(png_ptr); if (io_ptr) { // Get stream std::ostream* stream = reinterpret_cast<std::ostream*>(io_ptr); // Write stream->write(reinterpret_cast<const char*>(in_byte), byte_to_write); } } /** * @name FlushData * @brief Flush stream * @param[in] png_str Png decoder instance */ void FlushData(png_structp png_ptr) { // Get io_ptr png_voidp io_ptr = png_get_io_ptr(png_ptr); if (io_ptr) { // Get stream std::ostream* stream = reinterpret_cast<std::ostream*>(io_ptr); // Flush stream->flush(); } } Image::Format PNGFormatConverter(int type) { if (type == PNG_COLOR_TYPE_GRAY) { return Image::Format::kGrayscale; } else if (type == PNG_COLOR_TYPE_RGB || type == PNG_COLOR_TYPE_PALETTE) { return Image::Format::kRGB; } else if (type == PNG_COLOR_TYPE_RGBA) { return Image::Format::kRGBA; } return static_cast<Image::Format>(-1); } int PNGColorTypeConverter(const Image::Format& format) { if (format == Image::Format::kGrayscale ) { return PNG_COLOR_TYPE_GRAY; } else if (format == Image::Format::kRGB) { return PNG_COLOR_TYPE_RGB; } else if (format == Image::Format::kRGBA) { return PNG_COLOR_TYPE_RGBA; } return -1; } /* * @name PNGImage * @fn PNGImage(void) * @brief Constructor */ PNGImage::PNGImage(void) {} /* * @name ~PNGImage * @fn ~PNGImage(void) * @brief Destructor */ PNGImage::~PNGImage(void) { if (this->data_) { delete[] this->data_; this->data_ = nullptr; } } /* * @name Load * @fn int Load(const std::string& filename) * @brief Load image from dist * @param[in] filename Path to ressource on the disk * @return -1 if error, 0 otherwise */ int PNGImage::Load(const std::string& filename) { int err = -1; // Open stream std::ifstream stream(filename.c_str()); if (stream.is_open()) { // Load err = this->Load(stream); } return err; } /* * @name Load * @fn virtual int Load(std::istream& stream) = 0 * @brief Load image from dist * @param[in] stream Binary stream from where to load the ressource * @return -1 if error, 0 otherwise */ int PNGImage::Load(std::istream& stream) { int err = -1; if (stream.good()) { png_structp png_ptr = nullptr; png_infop info_ptr = nullptr; enum {kPngSignatureLength = 8}; // Read signature + Check unsigned char signature[kPngSignatureLength]; stream.read(reinterpret_cast<char*>(&signature[0]), kPngSignatureLength); if (png_check_sig(signature, kPngSignatureLength)) { // get PNG file info struct (memory is allocated by libpng) png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (png_ptr) { // get PNG image data info struct (memory is allocated by libpng) info_ptr = png_create_info_struct(png_ptr); if (info_ptr) { // Register custom callback to read data from stream png_set_read_fn(png_ptr, &stream, ReadData); // tell libpng we already read the signature png_set_sig_bytes(png_ptr, kPngSignatureLength); // Read header png_read_info(png_ptr, info_ptr); png_uint_32 width = 0; png_uint_32 height = 0; int bitDepth = 0; int colorType = -1; png_uint_32 retval = png_get_IHDR(png_ptr, info_ptr, &width, &height, &bitDepth, &colorType, nullptr, nullptr, nullptr); if (retval == 1) { // Fix palettetype if (colorType == PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); } // Update info png_read_update_info(png_ptr, info_ptr); // Set prop this->width_ = static_cast<size_t>(width); this->height_ = static_cast<size_t>(height); this->format_ = PNGFormatConverter(colorType); // Allocate if (this->data_) { delete[] this->data_; } const size_t sz = this->width_ * this->height_ * this->format_; this->data_ = new unsigned char[sz]; // Read info + one line at a time const size_t bytesPerRow = png_get_rowbytes(png_ptr, info_ptr); for (size_t r = 0; r < this->height_; ++r) { png_read_row(png_ptr, &this->data_[r * bytesPerRow], nullptr); } err = 0; } } } } // release reading struct png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); } return err; } /* * @name Save * @fn int Save(const std::string& filename) * @brief Save image to dist * @param[in] filename Path to ressource on the disk * @return -1 if error, 0 otherwise */ int PNGImage::Save(const std::string& filename) const { int err = -1; // Check filename std::string dir, file, ext, f; StringUtil::ExtractDirectory(filename, &dir, &file, &ext); if (ext != ".png") { if (dir.empty()) { f = file + ".png"; } else { f = dir + "/" + file + ".png"; } } else { f = filename; } // Open stream std::fstream stream(f.c_str(), std::ios_base::binary|std::ios_base::out); if (stream.is_open()) { // Load err = this->Save(stream); } return err; } /* * @name Save * @fn int Save(std::ostream& stream) * @brief Load image to dist * @param[in] stream Binary stream to where to save the ressource * @return -1 if error, 0 otherwise */ int PNGImage::Save(std::ostream& stream) const { int err = -1; if (stream.good() && this->data_) { png_structp png_ptr = nullptr; png_infop info_ptr = nullptr; // get PNG file info struct (memory is allocated by libpng) png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (png_ptr) { // Info info_ptr = png_create_info_struct(png_ptr); if (info_ptr) { // Register custom callback png_set_write_fn(png_ptr, &stream, WriteData, FlushData); // Write header (8 bit colour depth) png_uint_32 w = static_cast<png_uint_32>(this->width_); png_uint_32 h = static_cast<png_uint_32>(this->height_); int colorType = PNGColorTypeConverter(this->format_); png_set_IHDR(png_ptr, info_ptr, w, h, 8, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(png_ptr, info_ptr); // Write image data, one row at a time size_t byte_per_row = this->width_ * this->format_; for (size_t r = 0; r < this->height_; ++r) { png_write_row(png_ptr, &(this->data_[r * byte_per_row])); } // End write png_write_end(png_ptr, nullptr); err = 0; } } // Release png_destroy_write_struct(&png_ptr, &info_ptr); } return err; } #pragma mark - #pragma mark Registration /* * @name PNGProxy * @fn PNGProxy(void) * @brief Constructor */ PNGProxy::PNGProxy(void) : OGLKit::ImageProxy() {} /* * @name ~PNGProxy * @fn ~PNGProxy(void) * @brief Destructor */ PNGProxy::~PNGProxy(void) {} /* * @name Create * @fn Image* Create(void) const * @brief Create an instance of image with proper type */ Image* PNGProxy::Create(void) const { return new PNGImage(); } /* * @name Extension * @fn const char* Extension(void) const * @brief Return the extension for a given type of image * @return extension type */ const char* PNGProxy::Extension(void) const { return "png"; } // Explicit registration PNGProxy png_proxy; } // namespace OGLKit
28.653614
82
0.591296
[ "object", "vector" ]
357135aa2737d3bba0d19f5ef25971a5356826cc
884
cpp
C++
solutions/Easy/257. Binary Tree Paths/solution.cpp
BASARANOMO/leetcode-cpp
f779ec46e672f01cec69077e854d6ba15e451d27
[ "MIT" ]
null
null
null
solutions/Easy/257. Binary Tree Paths/solution.cpp
BASARANOMO/leetcode-cpp
f779ec46e672f01cec69077e854d6ba15e451d27
[ "MIT" ]
null
null
null
solutions/Easy/257. Binary Tree Paths/solution.cpp
BASARANOMO/leetcode-cpp
f779ec46e672f01cec69077e854d6ba15e451d27
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; dfs(root, res, ""); return res; } void dfs(TreeNode* T, vector<string>& res, string curr) { if (T != nullptr) { curr += to_string(T->val); if (!T->left && !T->right) { res.push_back(curr); } else { dfs(T->left, res, curr+"->"); dfs(T->right, res, curr+"->"); } } } };
26.787879
93
0.486425
[ "vector" ]
3579c6dfc015ee9616fb6195d1d659e64bd7751b
3,448
cpp
C++
vegastrike/src/gfx/radar/track.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/gfx/radar/track.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/gfx/radar/track.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
// -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- #include <algorithm> #include "gfxlib.h" #include "cmd/unit_generic.h" #include "cmd/planet_generic.h" #include "cmd/unit_util.h" #include "track.h" namespace Radar { Track::Track(Unit *player, Unit *target) : player(player), target(target), distance(0.0) { position = player->LocalCoordinates(target); distance = UnitUtil::getDistance(player, target); type = IdentifyType(); } Track::Track(Unit *player, Unit *target, const Vector& position) : player(player), target(target), position(position) { distance = UnitUtil::getDistance(player, target); type = IdentifyType(); } Track::Track(Unit *player, Unit *target, const Vector& position, float distance) : player(player), target(target), position(position), distance(distance) { type = IdentifyType(); } const Vector& Track::GetPosition() const { return position; } float Track::GetDistance() const { return distance; } Track::Type::Value Track::GetType() const { return type; } float Track::GetSize() const { assert(target); return target->rSize(); } bool Track::IsExploding() const { assert(target); return target->IsExploding(); } float Track::ExplodingProgress() const { assert(IsExploding()); return target->ExplodingProgress(); } bool Track::HasWeapons() const { assert(target); return (target->GetNumMounts() > 0); } bool Track::HasTurrets() const { assert(target); return !(target->SubUnits.empty()); } bool Track::HasActiveECM() const { assert(target); return (UnitUtil::getECM(target) > 0); } bool Track::HasLock() const { assert(player); assert(target); return (player == target->Target()); } bool Track::HasWeaponLock() const { assert(target); return (HasLock() && target->TargetLocked()); } Track::Type::Value Track::IdentifyType() const { assert(target); switch (target->isUnit()) { case NEBULAPTR: return Type::Nebula; case PLANETPTR: { Planet *planet = static_cast<Planet *>(target); if (planet->isJumppoint()) return Type::JumpPoint; if (planet->hasLights()) return Type::Star; if (planet->isAtmospheric()) return Type::Planet; return Type::DeadPlanet; } break; case ASTEROIDPTR: return Type::Asteroid; case BUILDINGPTR: // FIXME: Can this ever happen? return Type::Unknown; case UNITPTR: { if (target->IsBase()) return Type::Base; if (UnitUtil::isCapitalShip(target)) return Type::CapitalShip; return Type::Ship; } case ENHANCEMENTPTR: return Type::Cargo; case MISSILEPTR: // FIXME: Is this correct? if (target->faction == FactionUtil::GetUpgradeFaction()) return Type::Cargo; return Type::Missile; default: assert(false); return Type::Unknown; } } Track::Relation::Value Track::GetRelation() const { assert(player); assert(target); const float relation = player->getRelation(target); if (relation > 0) return Relation::Friend; if (relation < 0) return Relation::Enemy; return Relation::Neutral; } } // namespace Radar
18.340426
80
0.601508
[ "vector" ]
358c017b2468a0250222877d448a1c1fdb2b23ea
36,492
cpp
C++
LuaDecompiler/decompiler.cpp
sebyval93/LuaDecompiler
13349f2595a88227d0526301997d0ed7122b7fb4
[ "MIT", "BSD-3-Clause" ]
2
2018-05-16T12:46:33.000Z
2018-08-30T15:31:30.000Z
LuaDecompiler/decompiler.cpp
sebyval93/LuaDecompiler
13349f2595a88227d0526301997d0ed7122b7fb4
[ "MIT", "BSD-3-Clause" ]
5
2017-10-10T20:29:29.000Z
2017-10-19T18:58:48.000Z
LuaDecompiler/decompiler.cpp
sebyval93/LuaDecompiler
13349f2595a88227d0526301997d0ed7122b7fb4
[ "MIT", "BSD-3-Clause" ]
null
null
null
#include "decompiler.h" #include <filesystem> #include <iostream> #include <fstream> #include <stack> #include "lex.yy.h" #include "luac\luac.h" // function that loads binary lua scripts extern "C" Proto* loadproto(const char* filename); // TODO: test settable and getindexed extensively Decompiler::Decompiler() : m_format(Formatter::getInstance()), m_success(true) {} std::string Decompiler::decompileFunction() { FuncInfo &funcInfo = m_funcInfos.back(); const Instruction* code = funcInfo.tf->code; const Instruction* p = code; funcInfo.nForLoops = 0; funcInfo.nForLoopLevel = 0; funcInfo.nLocals = 0; std::string funcStr; funcInfo.codeStack.clear(); if (!funcInfo.isMain) { funcStr = "function ("; // add arguments if we have any for (int i = 0; i < funcInfo.tf->numparams; ++i) { std::string argName = "arg" + std::to_string(i + 1); funcInfo.locals.insert(std::make_pair(i, argName)); funcStr += funcInfo.locals.at(i); StackValue local; local.type = ValueType::STRING_LOCAL; local.str = argName; funcInfo.codeStack.push_back(local); // if this is not the last elem, put a delimiter if (i != (funcInfo.tf->numparams - 1)) funcStr += ", "; } funcStr += ")\n"; } for (;;) { int line = p - code + 1; Instruction instr = *p; std::string tempStr; FuncInfo &currInfo = m_funcInfos.back(); if (!currInfo.context.empty() && currInfo.context.back().dest == line) { Context cont = currInfo.context.back(); // eval conditions // this is currently a test std::string condition; condition = "testCOND"; std::string condPrologue, condEpilogue; if (cont.type == Context::IF) { condPrologue = "if "; condEpilogue = " then\n"; } else { condPrologue = "while "; condEpilogue = " do\n"; } // assemble and insert cond std::string finalCond = condPrologue + condition + condEpilogue; funcStr.insert(cont.strIndex, finalCond); funcStr += "end\n"; currInfo.context.pop_back(); } switch (GET_OPCODE(instr)) { case OP_END: break; case OP_RETURN: funcStr += opReturn(GETARG_U(instr)); break; case OP_CALL: funcStr += opCall(GETARG_A(instr), GETARG_B(instr), false); break; case OP_TAILCALL: funcStr += opTailCall(GETARG_A(instr), GETARG_B(instr)); break; case OP_PUSHNIL: opPushNil(GETARG_U(instr)); break; case OP_POP: opPop(GETARG_U(instr)); break; case OP_PUSHINT: opPushInt(GETARG_S(instr)); break; case OP_PUSHSTRING: opPushString(currInfo.tf->kstr[GETARG_U(instr)]->str); break; case OP_PUSHNUM: opPushNum(std::to_string(currInfo.tf->knum[GETARG_U(instr)])); break; case OP_PUSHNEGNUM: opPushNegNum(std::to_string(currInfo.tf->knum[GETARG_U(instr)])); break; case OP_PUSHUPVALUE: opPushUpvalue(GETARG_U(instr)); break; case OP_GETLOCAL: opGetLocal(GETARG_U(instr)); break; case OP_GETGLOBAL: opGetGlobal(GETARG_U(instr)); break; case OP_GETTABLE: opGetTable(); break; case OP_GETDOTTED: opGetDotted(GETARG_U(instr)); break; case OP_GETINDEXED: opGetIndexed(GETARG_U(instr)); break; case OP_PUSHSELF: opPushSelf(GETARG_U(instr)); break; case OP_CREATETABLE: opCreateTable(GETARG_U(instr)); break; case OP_SETLOCAL: funcStr += opSetLocal(GETARG_U(instr)); break; case OP_SETGLOBAL: funcStr += opSetGlobal(GETARG_U(instr)); break; case OP_SETTABLE: funcStr += opSetTable(GETARG_A(instr), GETARG_B(instr)); break; case OP_SETLIST: opSetList(GETARG_A(instr), GETARG_B(instr)); break; case OP_SETMAP: opSetMap(GETARG_U(instr)); break; case OP_ADD: opAdd(); break; case OP_ADDI: opAddI(GETARG_S(instr)); break; case OP_SUB: opSub(); break; case OP_MULT: opMult(); break; case OP_DIV: opDiv(); break; case OP_POW: opPow(); break; case OP_CONCAT: opConcat(GETARG_U(instr)); break; case OP_MINUS: opMinus(); break; case OP_NOT: opNot(); break; case OP_JMPNE: { //showErrorMessage("Unimplemented opcode JMPNE! exiting!", true); std::string arg1 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); std::string arg0 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); int destLine = GETARG_S(instr) + line + 1; CondElem elem; elem.args.push_back(arg0); elem.args.push_back(arg1); elem.dest = destLine; elem.lineNum = line; elem.jmpType = OP_JMPNE; elem.nextCond = CondElem::NONE; if (currInfo.context.empty() || currInfo.context.back().dest > destLine) { Context cont; cont.conds.push_back(elem); cont.dest = destLine; cont.type = Context::IF; cont.strIndex = funcStr.size(); currInfo.context.push_back(cont); } else { currInfo.context.back().conds.push_back(elem); currInfo.context.back().dest = elem.dest; } } break; case OP_JMPEQ: { //showErrorMessage("Unimplemented opcode JMPEQ! exiting!", true); std::string arg1 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); std::string arg0 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); int destLine = GETARG_S(instr) + line + 1; CondElem elem; elem.args.push_back(arg0); elem.args.push_back(arg1); elem.dest = destLine; elem.lineNum = line; elem.jmpType = OP_JMPEQ; elem.nextCond = CondElem::NONE; if (currInfo.context.empty() || currInfo.context.back().dest > destLine) { Context cont; cont.conds.push_back(elem); cont.dest = destLine; cont.type = Context::IF; cont.strIndex = funcStr.size(); currInfo.context.push_back(cont); } else { currInfo.context.back().conds.push_back(elem); currInfo.context.back().dest = elem.dest; } } break; case OP_JMPLT: { //showErrorMessage("Unimplemented opcode JMPLT! exiting!", true); std::string arg1 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); std::string arg0 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); int destLine = GETARG_S(instr) + line + 1; CondElem elem; elem.args.push_back(arg0); elem.args.push_back(arg1); elem.dest = destLine; elem.lineNum = line; elem.jmpType = OP_JMPLT; elem.nextCond = CondElem::NONE; if (currInfo.context.empty() || currInfo.context.back().dest > destLine) { Context cont; cont.conds.push_back(elem); cont.dest = destLine; cont.type = Context::IF; cont.strIndex = funcStr.size(); currInfo.context.push_back(cont); } else { currInfo.context.back().conds.push_back(elem); currInfo.context.back().dest = elem.dest; } } break; case OP_JMPLE: { //showErrorMessage("Unimplemented opcode JMPLE! exiting!", true); std::string arg1 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); std::string arg0 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); int destLine = GETARG_S(instr) + line + 1; CondElem elem; elem.args.push_back(arg0); elem.args.push_back(arg1); elem.dest = destLine; elem.lineNum = line; elem.jmpType = OP_JMPLE; elem.nextCond = CondElem::NONE; if (currInfo.context.empty() || currInfo.context.back().dest > destLine) { Context cont; cont.conds.push_back(elem); cont.dest = destLine; cont.type = Context::IF; cont.strIndex = funcStr.size(); currInfo.context.push_back(cont); } else { currInfo.context.back().conds.push_back(elem); currInfo.context.back().dest = elem.dest; } } break; case OP_JMPGT: { //showErrorMessage("Unimplemented opcode JMPLE! exiting!", true); std::string arg1 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); std::string arg0 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); int destLine = GETARG_S(instr) + line + 1; CondElem elem; elem.args.push_back(arg0); elem.args.push_back(arg1); elem.dest = destLine; elem.lineNum = line; elem.jmpType = OP_JMPGT; elem.nextCond = CondElem::NONE; if (currInfo.context.empty() || currInfo.context.back().dest > destLine) { Context cont; cont.conds.push_back(elem); cont.dest = destLine; cont.type = Context::IF; cont.strIndex = funcStr.size(); currInfo.context.push_back(cont); } else { currInfo.context.back().conds.push_back(elem); currInfo.context.back().dest = elem.dest; } } break; case OP_JMPGE: { //showErrorMessage("Unimplemented opcode JMPLE! exiting!", true); std::string arg1 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); std::string arg0 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); int destLine = GETARG_S(instr) + line + 1; CondElem elem; elem.args.push_back(arg0); elem.args.push_back(arg1); elem.dest = destLine; elem.lineNum = line; elem.jmpType = OP_JMPGE; elem.nextCond = CondElem::NONE; if (currInfo.context.empty() || currInfo.context.back().dest > destLine) { Context cont; cont.conds.push_back(elem); cont.dest = destLine; cont.type = Context::IF; cont.strIndex = funcStr.size(); currInfo.context.push_back(cont); } else { currInfo.context.back().conds.push_back(elem); currInfo.context.back().dest = elem.dest; } } break; case OP_JMPT: { //showErrorMessage("Unimplemented opcode JMPLE! exiting!", true); std::string arg0 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); int destLine = GETARG_S(instr) + line + 1; CondElem elem; elem.args.push_back(arg0); elem.dest = destLine; elem.lineNum = line; elem.jmpType = OP_JMPT; elem.nextCond = CondElem::NONE; if (currInfo.context.empty() || currInfo.context.back().dest > destLine) { Context cont; cont.conds.push_back(elem); cont.dest = destLine; cont.type = Context::IF; cont.strIndex = funcStr.size(); currInfo.context.push_back(cont); } else { currInfo.context.back().conds.push_back(elem); currInfo.context.back().dest = elem.dest; } } break; case OP_JMPF: { //showErrorMessage("Unimplemented opcode JMPLE! exiting!", true); std::string arg0 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); int destLine = GETARG_S(instr) + line + 1; CondElem elem; elem.args.push_back(arg0); elem.dest = destLine; elem.lineNum = line; elem.jmpType = OP_JMPF; elem.nextCond = CondElem::NONE; if (currInfo.context.empty() || currInfo.context.back().dest > destLine) { Context cont; cont.conds.push_back(elem); cont.dest = destLine; cont.type = Context::IF; cont.strIndex = funcStr.size(); currInfo.context.push_back(cont); } else { currInfo.context.back().conds.push_back(elem); currInfo.context.back().dest = elem.dest; } } break; case OP_JMPONT: { // IDK YET //showErrorMessage("Unimplemented opcode JMPONT! exiting!", true); std::string arg0 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); int destLine = GETARG_S(instr) + line + 1; CondElem elem; elem.args.push_back(arg0); elem.dest = destLine; elem.lineNum = line; elem.jmpType = OP_JMPONT; elem.nextCond = CondElem::NONE; if (currInfo.context.empty() || currInfo.context.back().dest > destLine) { Context cont; cont.conds.push_back(elem); cont.dest = destLine; cont.type = Context::IF; cont.strIndex = funcStr.size(); currInfo.context.push_back(cont); } else { currInfo.context.back().conds.push_back(elem); currInfo.context.back().dest = elem.dest; } } break; case OP_JMPONF: { // IDK YET //showErrorMessage("Unimplemented opcode JMPONF! exiting!", true); std::string arg0 = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); int destLine = GETARG_S(instr) + line + 1; CondElem elem; elem.args.push_back(arg0); elem.dest = destLine; elem.lineNum = line; elem.jmpType = OP_JMPONF; elem.nextCond = CondElem::NONE; if (currInfo.context.empty() || currInfo.context.back().dest > destLine) { Context cont; cont.conds.push_back(elem); cont.dest = destLine; cont.type = Context::IF; cont.strIndex = funcStr.size(); currInfo.context.push_back(cont); } else { currInfo.context.back().conds.push_back(elem); currInfo.context.back().dest = elem.dest; } } break; case OP_JMP: opJmp(GETARG_S(instr)); break; case OP_PUSHNILJMP: opPushNilJmp(); break; case OP_FORPREP: funcStr += opForPrep(); break; case OP_FORLOOP: funcStr += opForLoop(); break; case OP_LFORPREP: funcStr += opLForPrep(); break; case OP_LFORLOOP: funcStr += opLForLoop(); break; case OP_CLOSURE: opClosure(GETARG_A(instr), GETARG_B(instr)); break; } if (instr == OP_END) { if (!currInfo.isMain) funcStr += "end\n"; break; } p++; } return funcStr; } void Decompiler::processPath(std::string pathStr) { // update to c++17 soon, microsoft?? using namespace std::experimental; filesystem::path path(pathStr); std::string sourceStr; if (!filesystem::exists(path)) { std::cerr << "Path " << pathStr << " does not exist!" << '\n'; } if (filesystem::is_regular_file(path)) { sourceStr = decompileFile(path.string().c_str()); if (!sourceStr.empty()) { saveFile(sourceStr, path.parent_path().string() + "\\" + path.stem().string() + "_d" + path.extension().string()); if (m_success) std::cout << "File " << path.filename() << " successfully decompiled!\n"; else std::cout << "File " << path.filename() << " decompiled with errors!\n"; sourceStr.clear(); m_format.reset(); m_success = true; } } else { filesystem::recursive_directory_iterator dir(path), end; filesystem::path rootOutputPath = path.parent_path(); rootOutputPath.append(path.filename().string() + "_d"); filesystem::create_directory(rootOutputPath); while (dir != end) { if (filesystem::is_regular_file(dir->path())) { sourceStr = decompileFile(dir->path().string().c_str()); if (!sourceStr.empty()) { filesystem::path newPath = rootOutputPath / dir->path().string().substr(rootOutputPath.string().length() - 2); if (!filesystem::exists(newPath.parent_path())) filesystem::create_directory(newPath.parent_path()); saveFile(sourceStr, newPath.string()); if (m_success) std::cout << "File " << dir->path().filename() << " successfully decompiled!\n"; else std::cout << "File " << dir->path().filename() << " decompiled with errors!\n"; m_format.reset(); sourceStr.clear(); m_success = true; } } ++dir; } } } std::string Decompiler::evalCondition(CondElem currentCond) { return ""; } int Decompiler::invertCond(int cnd) { OpCode cond = (OpCode)cnd; switch (cond) { case OP_JMPNE: return OP_JMPEQ; case OP_JMPEQ: return OP_JMPNE; case OP_JMPLT: return OP_JMPGE; case OP_JMPLE: return OP_JMPGT; case OP_JMPGT: return OP_JMPLE; case OP_JMPGE: return OP_JMPLT; case OP_JMPT: return OP_JMPF; case OP_JMPF: return OP_JMPT; case OP_JMPONT: return OP_JMPONF; case OP_JMPONF: return OP_JMPONT; default: return -1; } } std::string Decompiler::decompileFile(const char* fileName) { Proto* tf = loadLuaStructure(fileName); std::string sourceStr; std::experimental::filesystem::path path(fileName); if (tf == NULL) { std::cout << "Error: file " << path.filename() << " is not a compiled lua file!\n"; return sourceStr; } //std::cout << "File " << path.filename() << " opened successfully!\n"; FuncInfo mainInfo; mainInfo.isMain = true; mainInfo.tf = tf; m_funcInfos.push_back(mainInfo); sourceStr = decompileFunction(); m_funcInfos.pop_back(); return formatCode(sourceStr); } std::string Decompiler::formatCode(std::string &sourceStr) { const reflex::Input strInput(sourceStr); yyFlexLexer lexer(strInput, &std::cout); lexer.yylex(); //std::cout << *m_formattedStr; return m_format.getFormattedStr(); } void Decompiler::saveFile(const std::string &src, const std::string &path) { std::ofstream file; file.open(path, std::ios::trunc); file << src; } Proto* Decompiler::loadLuaStructure(const char* fileName) { return loadproto(fileName); } void Decompiler::showErrorMessage(std::string message, bool exitError) { std::cerr << "Error: " << message << '\n'; m_success = false; if (exitError) { // pause char f; std::cin >> f; std::exit(1); } } void Decompiler::opEnd() { } std::string Decompiler::opReturn(int returnBase) { //int returnBase = GETARG_U(instr); std::vector<StackValue> args; std::string tempStr; FuncInfo &currInfo = m_funcInfos.back(); // pop size - base int items = currInfo.codeStack.size() - returnBase; for (int i = 0; i < items; ++i) { args.push_back(currInfo.codeStack.back()); currInfo.codeStack.pop_back(); } tempStr = "return "; // insert arguments in the right order for (auto it = args.rbegin(); it != args.rend(); ++it) { tempStr += (*it).str; if (--args.rend() != it) tempStr += ", "; } return (tempStr + '\n'); } std::string Decompiler::opCall(int callBase, int numResults, bool isTailCall) { std::vector<StackValue> args; std::string funcName; std::string tempStr; FuncInfo &currInfo = m_funcInfos.back(); funcName = currInfo.codeStack[callBase].str; int items = currInfo.codeStack.size() - callBase; for (int i = 0; i < items - 1; ++i) { if (currInfo.codeStack.back().type == ValueType::STRING_PUSHSELF) { std::string str = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); str = currInfo.codeStack.back().str + str; currInfo.codeStack.pop_back(); StackValue result; result.str = str; result.type = ValueType::STRING_GLOBAL; currInfo.codeStack.push_back(result); } else { args.push_back(currInfo.codeStack.back()); currInfo.codeStack.pop_back(); } } // get funcName funcName = currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); tempStr = funcName + "("; // insert arguments in the right order for (auto it = args.rbegin(); it != args.rend(); ++it) { tempStr += (*it).str; if (--args.rend() != it) tempStr += ", "; } tempStr += ")"; if (numResults > 0) { StackValue result; result.str = tempStr; result.type = ValueType::STRING; if (isTailCall) result.str = "return " + result.str; if (numResults != 255) { for (int i = 0; i < numResults; ++i) { currInfo.codeStack.push_back(result); } } else currInfo.codeStack.push_back(result); if (isTailCall) { // assume argb to be 1?? // HACK maybe working currInfo.codeStack.pop_back(); return (result.str + '\n'); //funcStr += (result.str + '\n'); } return ""; } else { //funcStr += (tempStr + '\n'); return (tempStr + '\n'); } } std::string Decompiler::opTailCall(int callBase, int numResults) { return opCall(callBase, numResults, true); } void Decompiler::opPushNil(int numNil) { StackValue result; result.str = "nil"; result.type = ValueType::NIL; for (int i = 0; i < numNil; ++i) m_funcInfos.back().codeStack.push_back(result); } void Decompiler::opPop(int numPop) { for (int i = 0; i < numPop; ++i) { m_funcInfos.back().codeStack.pop_back(); } } void Decompiler::opPushInt(int num) { StackValue stackValue; stackValue.str = std::to_string(num); stackValue.type = ValueType::INT; m_funcInfos.back().codeStack.push_back(stackValue); } void Decompiler::opPushString(std::string str) { StackValue result; if (str.find('\n') != std::string::npos || str.find('\t') != std::string::npos) { str.insert(0, "[["); str.insert(str.size(), "]]"); } else { str.insert(0, "\""); str.insert(str.size(), "\""); } result.str = str; result.type = ValueType::STRING; m_funcInfos.back().codeStack.push_back(result); } void Decompiler::opPushNum(std::string numStr) { StackValue stackValue; stackValue.str = numStr; // trim trailing zeros, if is a fp number // don't have to check for .0 or 1.0, thx lua! // it is guaranteed to have something beyond the . if fp size_t dotPos = stackValue.str.find('.'); if (dotPos != std::string::npos) { for (size_t i = stackValue.str.size() - 1; i > dotPos; --i) { if (stackValue.str[i] == '0') stackValue.str.erase(i); else break; } } stackValue.type = ValueType::INT; m_funcInfos.back().codeStack.push_back(stackValue); } void Decompiler::opPushNegNum(std::string numStr) { StackValue stackValue; stackValue.str = numStr; // trim trailing zeros, if is a fp number // don't have to check for .0 or 1.0, thx lua! // it is guaranteed to have something beyond the . if fp size_t dotPos = stackValue.str.find('.'); if (dotPos != std::string::npos) { for (size_t i = stackValue.str.size() - 1; i > dotPos; --i) { if (stackValue.str[i] == '0') stackValue.str.erase(i); else break; } } stackValue.str.insert(0, "-"); stackValue.type = ValueType::INT; m_funcInfos.back().codeStack.push_back(stackValue); } void Decompiler::opPushUpvalue(int upvalueIndex) { StackValue result; FuncInfo &currInfo = m_funcInfos.back(); result.str = '%' + currInfo.upvalues.at(upvalueIndex); result.type = ValueType::STRING; currInfo.codeStack.push_back(result); } std::string Decompiler::opGetLocal(int localIndex) { StackValue stackValue; std::string tempStr; FuncInfo &currInfo = m_funcInfos.back(); if (currInfo.locals.find(localIndex) == currInfo.locals.end()) { // local is not present in the list // name it. std::string localName = "loc" + std::to_string(localIndex - currInfo.tf->numparams + 1); currInfo.locals.insert(std::make_pair(localIndex, localName)); ++currInfo.nLocals; tempStr += "local " + localName + " = " + currInfo.codeStack[localIndex].str + "\n"; } stackValue.str = currInfo.locals.find(localIndex)->second; stackValue.type = ValueType::STRING_LOCAL; m_funcInfos.back().codeStack.push_back(stackValue); return tempStr; } void Decompiler::opGetGlobal(int globalIndex) { StackValue stackValue; FuncInfo &currInfo = m_funcInfos.back(); stackValue.index = globalIndex; stackValue.str = std::string(currInfo.tf->kstr[stackValue.index]->str); stackValue.type = ValueType::STRING_GLOBAL; currInfo.codeStack.push_back(stackValue); } void Decompiler::opGetTable() { std::vector<StackValue> args; StackValue result; FuncInfo &currInfo = m_funcInfos.back(); args.push_back(currInfo.codeStack.back()); currInfo.codeStack.pop_back(); args.push_back(currInfo.codeStack.back()); currInfo.codeStack.pop_back(); result.str = args[1].str + '[' + args[0].str + ']'; currInfo.codeStack.push_back(result); } void Decompiler::opGetDotted(int stringIndex) { FuncInfo &currInfo = m_funcInfos.back(); std::string str = currInfo.tf->kstr[stringIndex]->str; StackValue target, result; target = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); result.str = target.str + "." + str; result.type = ValueType::STRING; currInfo.codeStack.push_back(result); } void Decompiler::opGetIndexed(int localIndex) { FuncInfo &currInfo = m_funcInfos.back(); std::string local = currInfo.locals.at(localIndex); StackValue target, result; target = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); result.str = target.str + "[" + local + "]"; result.type = target.type; currInfo.codeStack.push_back(result); } void Decompiler::opPushSelf(int stringIndex) { FuncInfo currInfo = m_funcInfos.back(); std::string str = currInfo.tf->kstr[stringIndex]->str; StackValue target, result; result.str = ":" + str; result.type = ValueType::STRING_PUSHSELF; currInfo.codeStack.push_back(result); } void Decompiler::opCreateTable(int numElems) { StackValue result; if (numElems > 0) { result.str += "{ "; result.type = ValueType::TABLE_BRACE; result.index = numElems; } else { result.str = "{}"; result.type = ValueType::STRING_GLOBAL; } m_funcInfos.back().codeStack.push_back(result); } std::string Decompiler::opSetLocal(int localIndex) { StackValue val; std::string local, result; FuncInfo &currInfo = m_funcInfos.back(); val = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); if (currInfo.locals.size() <= localIndex) { std::cout << "WARNING!! SETLOCAL out of bounds!!! ignoring"; return result; } local = currInfo.locals.at(localIndex); result = local + " = " + val.str + "\n"; return result; } std::string Decompiler::opSetGlobal(int globalIndex) { StackValue val; std::string global, result; FuncInfo &currInfo = m_funcInfos.back(); val = currInfo.codeStack.back(); global = currInfo.tf->kstr[globalIndex]->str; if (val.type == ValueType::CLOSURE_STRING) { // we have a closure on the stack // insert after "function ", which is 9 chars currInfo.codeStack.pop_back(); val.str.insert(9, global); return val.str; } else { currInfo.codeStack.pop_back(); result = global + " = " + val.str + '\n'; return result; } } std::string Decompiler::opSetTable(int targetIndex, int numElems) { std::vector<StackValue> args; std::string result; FuncInfo &currInfo = m_funcInfos.back(); if (targetIndex == numElems && numElems == 3) { for (int i = 0; i < numElems; ++i) { args.push_back(currInfo.codeStack.back()); currInfo.codeStack.pop_back(); } if (args[1].type == ValueType::STRING_GLOBAL) { args[1].str.erase(0, 1); args[1].str.erase(args[1].str.size() - 1); } result = args[2].str + "[" + args[1].str + "] = " + args[0].str; return (result + '\n'); } else { // unimplemented yet showErrorMessage("SETTABLE " + std::to_string(targetIndex) + " " + std::to_string(numElems) + " not implemented!!!", false); return result; } } void Decompiler::opSetList(int targetIndex, int numElems) { std::vector<StackValue> args; StackValue target, tableBrace, result; FuncInfo &currInfo = m_funcInfos.back(); if (targetIndex != 0) { showErrorMessage("SETLIST not fully implemented!, first arg is nonzero!", false); } for (int i = 0; i < numElems; ++i) { args.push_back(currInfo.codeStack.back()); currInfo.codeStack.pop_back(); } tableBrace = currInfo.codeStack.back(); if (currInfo.codeStack.back().type == ValueType::TABLE_BRACE) { if (tableBrace.index > numElems) { currInfo.codeStack.pop_back(); for (auto it = args.rbegin(); it != args.rend(); ++it) { result.str += (*it).str; if (--args.rend() != it) result.str += ", "; } result.str += ";"; tableBrace.str += result.str; tableBrace.index -= numElems; currInfo.codeStack.push_back(tableBrace); return; } currInfo.codeStack.pop_back(); } result.str = "{ "; for (auto it = args.rbegin(); it != args.rend(); ++it) { result.str += (*it).str; if (--args.rend() != it) result.str += ", "; } result.str += " }"; result.type = ValueType::STRING; currInfo.codeStack.push_back(result); } void Decompiler::opSetMap(int numElems) { StackValue identifier, mapValue, tableBrace, result; std::vector<std::string> args; FuncInfo &currInfo = m_funcInfos.back(); // TODO: nicer name bool hasRemainingElems = false; for (int i = 0; i < numElems; ++i) { mapValue = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); identifier = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); //remove quotes from identifier if (identifier.type == ValueType::STRING) { identifier.str.erase(0, 1); identifier.str.erase(identifier.str.size() - 1); } else if (identifier.type == ValueType::INT) { identifier.str.insert(0, "["); identifier.str.insert(identifier.str.size(), "]"); } args.push_back(identifier.str + " = " + mapValue.str); } // pop until we find a brace while (currInfo.codeStack.back().type != ValueType::TABLE_BRACE) { args.push_back(currInfo.codeStack.back().str); currInfo.codeStack.pop_back(); } tableBrace = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); tableBrace.index -= numElems; if (tableBrace.index > 0) hasRemainingElems = true; result.type = ValueType::STRING_GLOBAL; for (int i = args.size() - 1; i >= 0; --i) { result.str += args[i]; if ((i - 1) >= 0) result.str += ", "; } if (hasRemainingElems) { currInfo.codeStack.push_back(tableBrace); } else { result.str.insert(0, tableBrace.str); result.str += " }"; } currInfo.codeStack.push_back(result); } void Decompiler::opConcat(int numElems) { StackValue result; std::vector<StackValue> args; FuncInfo &currInfo = m_funcInfos.back(); for (int i = 0; i < numElems; ++i) { args.push_back(currInfo.codeStack.back()); currInfo.codeStack.pop_back(); } for (int i = numElems - 1; i >= 0; --i) { result.str += args[i].str; if ((i - 1) >= 0) result.str += ".."; } result.type = ValueType::STRING_GLOBAL; currInfo.codeStack.push_back(result); } void Decompiler::opAdd() { StackValue y, x, result; FuncInfo &currInfo = m_funcInfos.back(); y = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); x = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); result.str = x.str + " + " + y.str; result.type = ValueType::STRING_GLOBAL; currInfo.codeStack.push_back(result); } void Decompiler::opAddI(int value) { StackValue stackValue; FuncInfo &currInfo = m_funcInfos.back(); stackValue = currInfo.codeStack.back(); StackValue newValue; currInfo.codeStack.pop_back(); std::string op; if (value >= 0) op = " + "; else op = ""; newValue.str = stackValue.str + op + std::to_string(value); newValue.type = ValueType::STRING_GLOBAL; currInfo.codeStack.push_back(newValue); } void Decompiler::opSub() { StackValue y, x, result; FuncInfo &currInfo = m_funcInfos.back(); y = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); x = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); result.str = x.str + " - " + y.str; result.type = ValueType::STRING_GLOBAL; currInfo.codeStack.push_back(result); } void Decompiler::opMult() { StackValue y, x, result; FuncInfo &currInfo = m_funcInfos.back(); y = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); x = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); result.str = "( " + x.str + " * " + y.str + " )"; result.type = ValueType::STRING_GLOBAL; currInfo.codeStack.push_back(result); } void Decompiler::opDiv() { StackValue y, x, result; FuncInfo &currInfo = m_funcInfos.back(); y = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); x = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); result.str = "( " + x.str + " / " + y.str + " )"; result.type = ValueType::STRING_GLOBAL; currInfo.codeStack.push_back(result); } void Decompiler::opPow() { StackValue y, x, result; FuncInfo &currInfo = m_funcInfos.back(); y = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); x = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); result.str = "( " + x.str + " ^ " + y.str + " )"; result.type = ValueType::STRING_GLOBAL; currInfo.codeStack.push_back(result); } void Decompiler::opMinus() { StackValue x, result; FuncInfo &currInfo = m_funcInfos.back(); x = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); result.str = "-" + x.str; result.type = ValueType::STRING_GLOBAL; currInfo.codeStack.push_back(result); } void Decompiler::opNot() { // showErrorMessage("Unimplemented opcode NOT! exiting!", true); FuncInfo &currInfo = m_funcInfos.back(); std::string arg = "not " + currInfo.codeStack.back().str; currInfo.codeStack.pop_back(); StackValue result; result.type = ValueType::STRING_GLOBAL; result.str = arg; currInfo.codeStack.push_back(result); } std::string Decompiler::opForPrep() { StackValue val1, val2, val3; std::string result; FuncInfo &currInfo = m_funcInfos.back(); val3 = currInfo.codeStack[currInfo.codeStack.size() - 1]; val2 = currInfo.codeStack[currInfo.codeStack.size() - 2]; val1 = currInfo.codeStack[currInfo.codeStack.size() - 3]; std::string locName = "for" + std::to_string(currInfo.nForLoops); ++currInfo.nForLoops; ++currInfo.nForLoopLevel; int locIndex = currInfo.nLocals; ++currInfo.nLocals; currInfo.locals.insert(std::make_pair(locIndex, locName)); result += "for " + locName + " = " + val1.str + ", " + val2.str + ", " + val3.str + " do\n"; return result; } std::string Decompiler::opForLoop() { std::string result; FuncInfo &currInfo = m_funcInfos.back(); // the last local should be the forloop var --currInfo.nLocals; --currInfo.nForLoopLevel; currInfo.locals.erase(currInfo.nLocals); // clear control vars currInfo.codeStack.pop_back(); currInfo.codeStack.pop_back(); currInfo.codeStack.pop_back(); result = "end\n"; return result; } std::string Decompiler::opLForPrep() { //showErrorMessage("Unimplemented opcode LFORPREP! exiting!", true); FuncInfo &currInfo = m_funcInfos.back(); StackValue tableName = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); StackValue invisTable, index, value; invisTable.type = ValueType::STRING_LOCAL; invisTable.str = "_t"; index.type = ValueType::STRING_LOCAL; index.str = "index"; value.type = ValueType::STRING_LOCAL; value.str = "value"; currInfo.codeStack.push_back(invisTable); currInfo.codeStack.push_back(index); currInfo.codeStack.push_back(value); currInfo.locals.insert(std::make_pair(currInfo.nLocals++, "_t")); currInfo.locals.insert(std::make_pair(currInfo.nLocals++, "index")); currInfo.locals.insert(std::make_pair(currInfo.nLocals++, "value")); return ("for index, value in " + tableName.str + " do\n"); } std::string Decompiler::opLForLoop() { std::string result; FuncInfo &currInfo = m_funcInfos.back(); //showErrorMessage("Unimplemented opcode LFORLOOP! exiting!", true); currInfo.locals.erase(--currInfo.nLocals); currInfo.locals.erase(--currInfo.nLocals); currInfo.locals.erase(--currInfo.nLocals); currInfo.codeStack.pop_back(); currInfo.codeStack.pop_back(); currInfo.codeStack.pop_back(); result = "end\n"; return result; } void Decompiler::opClosure(int closureIndex, int numUpvalues) { FuncInfo &currInfo = m_funcInfos.back(); FuncInfo funcInfo; StackValue stackValue; std::string closureSrc; // pop all upvalues if any are found // and register them into funcInfo for (int i = 0; i < numUpvalues; ++i) { StackValue upvalue; upvalue = currInfo.codeStack.back(); currInfo.codeStack.pop_back(); currInfo.upvalues.insert(std::make_pair(numUpvalues - (i + 1), upvalue.str)); } // decompile closure funcInfo.isMain = false; funcInfo.tf = currInfo.tf->kproto[closureIndex]; m_funcInfos.push_back(funcInfo); closureSrc = decompileFunction(); m_funcInfos.pop_back(); stackValue.str = closureSrc; stackValue.type = ValueType::CLOSURE_STRING; // closureSrc += "end\n"; m_funcInfos.back().codeStack.push_back(stackValue); } void Decompiler::opJmpne(int destLine, int currLine) { } void Decompiler::opJmpeq(int destLine, int currLine) { } void Decompiler::opJmplt(int destLine, int currLine) { } void Decompiler::opJmple(int destLine, int currLine) { } void Decompiler::opJmpgt(int destLine, int currLine) { } void Decompiler::opJmpge(int destLine, int currLine) { } void Decompiler::opJmpt(int destLine, int currLine) { } void Decompiler::opJmpf(int destLine, int currLine) { } void Decompiler::opJmpont(int destLine, int currLine) { } void Decompiler::opJmponf(int destLine, int currLine) { } void Decompiler::opJmp(int destLine) { showErrorMessage("Unimplemented opcode JMP! continuing!", false); FuncInfo &currInfo = m_funcInfos.back(); if (!currInfo.context.empty() && destLine < 0) { currInfo.context.back().type = Context::WHILE; } } void Decompiler::opPushNilJmp() { //showErrorMessage("Unimplemented opcode PUSHNILJMP! exiting!", true); StackValue result; FuncInfo &currInfo = m_funcInfos.back(); result.str = "nil"; result.type = ValueType::NIL; currInfo.codeStack.push_back(result); }
22.183587
126
0.665434
[ "vector" ]
35917f7b77e04f194a5069aa86ae794f6cf0c4a4
1,687
cpp
C++
src/cpp/media-stream-audio-source-node.cpp
node-3d/waa-raub
e458d76f290b1e12ef2a0adc063b521816337f04
[ "MIT" ]
17
2018-10-03T00:44:33.000Z
2022-03-17T06:40:15.000Z
src/cpp/media-stream-audio-source-node.cpp
raub/node-waa
e458d76f290b1e12ef2a0adc063b521816337f04
[ "MIT" ]
7
2019-07-16T08:22:31.000Z
2021-11-29T21:45:06.000Z
src/cpp/media-stream-audio-source-node.cpp
raub/node-waa
e458d76f290b1e12ef2a0adc063b521816337f04
[ "MIT" ]
2
2019-08-05T20:00:42.000Z
2020-03-15T13:25:41.000Z
#include "media-stream-audio-source-node.hpp" MediaStreamAudioSourceNode::MediaStreamAudioSourceNode() : AudioNode() { _isDestroyed = false; } MediaStreamAudioSourceNode::~MediaStreamAudioSourceNode() { _destroy(); } void MediaStreamAudioSourceNode::_destroy() { DES_CHECK; _isDestroyed = true; AudioNode::_destroy(); } // ------ Methods and props JS_IMPLEMENT_GETTER(MediaStreamAudioSourceNode, mediaStream) { THIS_CHECK; RET_VALUE(_mediaStream.Value()); } // ------ System methods and props for Napi::ObjectWrap IMPLEMENT_ES5_CLASS(MediaStreamAudioSourceNode); void MediaStreamAudioSourceNode::init(Napi::Env env, Napi::Object exports) { Napi::Function ctor = wrap(env); JS_ASSIGN_METHOD(destroy); JS_ASSIGN_GETTER(mediaStream); JS_ASSIGN_GETTER(isDestroyed); exports.Set("MediaStreamAudioSourceNode", ctor); } bool MediaStreamAudioSourceNode::isMediaStreamAudioSourceNode(Napi::Object obj) { return obj.InstanceOf(_ctorEs5.Value()); } Napi::Object MediaStreamAudioSourceNode::getNew() { Napi::Function ctor = Nan::New(_constructor); // Napi::Value argv[] = { /* arg1, arg2, ... */ }; return Nan::NewInstance(ctor, 0/*argc*/, nullptr/*argv*/).ToLocalChecked(); } MediaStreamAudioSourceNode::MediaStreamAudioSourceNode(const Napi::CallbackInfo &info): Napi::ObjectWrap<MediaStreamAudioSourceNode>(info) { MediaStreamAudioSourceNode *mediaStreamAudioSourceNode = new MediaStreamAudioSourceNode(); } JS_IMPLEMENT_METHOD(MediaStreamAudioSourceNode, destroy) { THIS_CHECK; emit("destroy"); _destroy(); } JS_IMPLEMENT_GETTER(MediaStreamAudioSourceNode, isDestroyed) { NAPI_ENV; RET_BOOL(_isDestroyed); }
18.139785
91
0.750445
[ "object" ]