hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
82c372258db90a8bb6ad993843f33ed140153e3a
1,560
cc
C++
pb/protobuf_dump.cc
corrupt-stack/protobuf-super-lite
c9c0c90721756b9208f6bfccfdc40838316edf2c
[ "BSD-3-Clause" ]
null
null
null
pb/protobuf_dump.cc
corrupt-stack/protobuf-super-lite
c9c0c90721756b9208f6bfccfdc40838316edf2c
[ "BSD-3-Clause" ]
null
null
null
pb/protobuf_dump.cc
corrupt-stack/protobuf-super-lite
c9c0c90721756b9208f6bfccfdc40838316edf2c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2022 Yuri Wiitala. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cstdint> #include <fstream> #include <iostream> #include <limits> #include <vector> #include "pb/codec/limits.h" #include "pb/inspection.h" int main(int argc, char* argv[]) { // If a path was provided on the command line, open a file. Else, read from // stdin. std::istream* in; std::fstream fs; if (argc > 1) { fs.open(argv[1], std::fstream::in); in = &fs; } else { in = &std::cin; } if (!*in) { std::cerr << "Failed to open file.\n"; return 1; } // Read the whole file into memory. static constexpr int32_t kChunkSize = 4096; std::vector<uint8_t> buffer; while (static_cast<int64_t>(buffer.size()) < pb::codec::kMaxSerializedSize) { buffer.resize(buffer.size() + kChunkSize); in->read( reinterpret_cast<char*>(buffer.data() + buffer.size() - kChunkSize), kChunkSize); if (!*in) { const auto num_read = static_cast<std::size_t>(in->gcount()); buffer.resize(buffer.size() - kChunkSize + num_read); break; } } // Interpret and print the results to stdout. pb::InspectionRenderingContext(buffer.data(), static_cast<std::ptrdiff_t>(buffer.size())) .Print(pb::ScanForMessageFields(buffer.data(), buffer.data() + buffer.size(), true), std::cout); if (argc > 1) { fs.close(); } return 0; }
26.896552
79
0.605128
corrupt-stack
82c45ea309c8a36f6dda9ef3cdc760ea092e1a67
54
cc
C++
tests/data/test-diff-filter/test19-enum-v0.cc
insilications/libabigail-clr
1eb5d367686626660d3cc987b473f296b0a59152
[ "Apache-2.0" ]
3
2021-01-29T20:26:44.000Z
2021-04-28T07:49:48.000Z
tests/data/test-diff-filter/test19-enum-v0.cc
insilications/libabigail-clr
1eb5d367686626660d3cc987b473f296b0a59152
[ "Apache-2.0" ]
2
2021-03-07T19:31:56.000Z
2021-03-07T23:26:13.000Z
tests/data/test-diff-filter/test19-enum-v0.cc
insilications/libabigail-clr
1eb5d367686626660d3cc987b473f296b0a59152
[ "Apache-2.0" ]
1
2021-03-07T19:14:08.000Z
2021-03-07T19:14:08.000Z
typedef enum { v0, v1, v2 } E; void foo(E) { }
4.909091
14
0.481481
insilications
82c851fe3f10a27336cd8670fcb72b466a71e0f1
647
hpp
C++
include/chesham/cppext/functional.hpp
Chesham/cppext
9fb0326fcfcb737797ed9ece4a88688d996ec615
[ "MIT" ]
3
2020-05-25T03:39:05.000Z
2022-01-11T16:55:18.000Z
include/chesham/cppext/functional.hpp
Chesham/cppext
9fb0326fcfcb737797ed9ece4a88688d996ec615
[ "MIT" ]
null
null
null
include/chesham/cppext/functional.hpp
Chesham/cppext
9fb0326fcfcb737797ed9ece4a88688d996ec615
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <cctype> #include <functional> namespace chesham { template<class T> struct string_no_case_comparer { T& to_lower(T& s) const { transform(s.begin(), s.end(), s.begin(), [](const auto& i) { return ::tolower(i); }); return s; } std::size_t operator()(T s) const { using namespace std; return std::hash<T>()(to_lower(s)); } bool operator()(T x, T y) const { using namespace std; return to_lower(x) == to_lower(y); } }; }
23.962963
98
0.483771
Chesham
82c931d036489bb1edf04731319c35afa727d4b3
1,805
cpp
C++
CardGame/Classes/Social/SocialJNI.cpp
GuruDev0807/CardGame
e14c71b9833b38d97266678810d1800cb7880ea6
[ "MIT" ]
2
2022-03-10T00:18:44.000Z
2022-03-26T12:26:19.000Z
CardGame/Classes/Social/SocialJNI.cpp
GuruDev0807/CardGame
e14c71b9833b38d97266678810d1800cb7880ea6
[ "MIT" ]
null
null
null
CardGame/Classes/Social/SocialJNI.cpp
GuruDev0807/CardGame
e14c71b9833b38d97266678810d1800cb7880ea6
[ "MIT" ]
2
2019-12-18T15:55:48.000Z
2020-02-16T15:02:10.000Z
#include "../Common/Common.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include <jni.h> #include "platform/android/jni/JniHelper.h" #include <android/log.h> #endif #include "SocialJni.h" #include "../Layer/SettingLayer.h" #define CLASS_NAME "com/mcmahon/cardgame/AppActivity" extern "C" { std::string getIMEI() { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) JniMethodInfo methodInfo; #ifdef ANDROID_AMAZON #else if(! JniHelper::getStaticMethodInfo(methodInfo, CLASS_NAME, "getIMEI", "()Ljava/lang/String;")) #endif return ""; jstring device_id = (jstring)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID); std::string result = JniHelper::jstring2string(device_id); methodInfo.env->DeleteLocalRef(methodInfo.classID); return result; #endif } void captureAvatar(std::string user_id) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) JniMethodInfo methodInfo; #ifdef ANDROID_AMAZON #else if(! JniHelper::getStaticMethodInfo(methodInfo, CLASS_NAME, "captureAvatar", "(Ljava/lang/String;)V")) #endif return; jstring param = methodInfo.env->NewStringUTF(user_id.c_str()); methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, param); methodInfo.env->DeleteLocalRef(param); methodInfo.env->DeleteLocalRef(methodInfo.classID); #endif } void nativeCompletedCaptureAvatar(JNIEnv *env, jobject obj, jstring file_path) { jboolean isCopy; const char* path; path = env->GetStringUTFChars(file_path, &isCopy); if(g_pCurrentLayer != NULL && g_pCurrentLayer->m_nType == LAYER_SETTING) ((SettingLayer*)g_pCurrentLayer)->updateProfile(path); } }
27.769231
117
0.693075
GuruDev0807
82cb697fa829ffbb50bf5892b434d01a7efef170
116
hh
C++
src/Environment.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
src/Environment.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
src/Environment.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
#pragma once #include <glow/fwd.hh> #include <typed-geometry/tg.hh> namespace gamedev { class Environment { }; }
8.923077
31
0.706897
rovedit
82cc6a56b7b9256e3173193140429ab1d6d4272f
1,335
cpp
C++
src/cmd/ActivateLayer.cpp
felipemanga/Dotto
61be3e7be083cca5ba16fc8c181799830f6f7d47
[ "MIT" ]
151
2021-12-28T21:22:42.000Z
2022-03-30T13:53:28.000Z
src/cmd/ActivateLayer.cpp
felipemanga/Dotto
61be3e7be083cca5ba16fc8c181799830f6f7d47
[ "MIT" ]
9
2021-12-29T13:20:00.000Z
2022-03-18T12:47:19.000Z
src/cmd/ActivateLayer.cpp
felipemanga/Dotto
61be3e7be083cca5ba16fc8c181799830f6f7d47
[ "MIT" ]
18
2021-12-28T19:58:49.000Z
2022-03-31T16:38:14.000Z
// Copyright (c) 2021 LibreSprite Authors (cf. AUTHORS.md) // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #include <cmd/Command.hpp> #include <common/Messages.hpp> #include <common/PubSub.hpp> #include <doc/Document.hpp> #include <doc/Timeline.hpp> #include <doc/Cell.hpp> #include <gui/Node.hpp> #include <log/Log.hpp> class ActivateLayer : public Command { inject<ui::Node> editor{"activeeditor"}; Property<U32> layer{this, "layer", ~U32{}}; Property<S32> navigate{this, "navigate", 0}; U32 prevLayer = -1; public: void undo() override { editor->set("layer", prevLayer); } void run() override { if (!doc()) return; auto timeline = doc()->currentTimeline(); if (!timeline) return; auto& ps = editor->getPropertySet(); if (prevLayer == -1) prevLayer = ps.get<U32>("layer"); U32 layer = *this->layer; auto layerCount = timeline->layerCount(); if (navigate) layer = prevLayer + navigate; if (layer >= layerCount) layer = prevLayer; if (layer != prevLayer) { editor->set("layer", layer); commit(); } } }; static Command::Shared<ActivateLayer> cmd{"activatelayer"};
27.8125
60
0.592509
felipemanga
82ce374c5d2af4739797f042689a752c146e0e4d
694
cpp
C++
main.cpp
vvroul/Graphics_Solar_System
a6c35c73fa708faea1caf07648c609aa0acef6fc
[ "MIT" ]
null
null
null
main.cpp
vvroul/Graphics_Solar_System
a6c35c73fa708faea1caf07648c609aa0acef6fc
[ "MIT" ]
null
null
null
main.cpp
vvroul/Graphics_Solar_System
a6c35c73fa708faea1caf07648c609aa0acef6fc
[ "MIT" ]
null
null
null
#include "visuals.h" //********** STATE VARIABLES ********** float t = 0.0; //********** MAIN PROGRAM ********** int main(int argc, char* argv[]) { //Initialize GLUT library state glutInit(&argc, argv); cout << "GLUT library initialized successfully!" << endl; //Setup display glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE); //Setup window glutInitWindowSize(1280, 720); glutInitWindowPosition(50, 50); glutCreateWindow("Solar System"); //Configure rendering properties Setup(); Init_Structs(); glutDisplayFunc(Render); glutReshapeFunc(Resize); glutIdleFunc(Idle); glutKeyboardFunc(Keyboard); //Main event handling loop glutMainLoop(); return 0; }
19.828571
59
0.678674
vvroul
82d38d5722252f23dcd2c1cfd3ecebcf36cb67b1
1,239
cpp
C++
leetcode/binarytreepostordertravesal.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2016-01-20T08:26:34.000Z
2016-01-20T08:26:34.000Z
leetcode/binarytreepostordertravesal.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2015-10-21T05:38:17.000Z
2015-11-02T07:42:55.000Z
leetcode/binarytreepostordertravesal.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
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: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; //p is the current visiting pointer,q is just visited poointer TreeNode *p,*q; stack<TreeNode*> ss; p=root; do{ while(p!=NULL){ //go left; ss.push(p); p=p->left; } q=NULL; while(!ss.empty()){ p=ss.top(); ss.pop(); if(p->right==q){ //right child is visited or no exist //add to res res.push_back(p->val); q=p; }else{ //not ready yet.push it back ss.push(p); p=p->right; break; } } }while(!ss.empty()); return res; } };
23.377358
70
0.357546
WIZARD-CXY
82d3ac8d867034cc2cb7d3130b467bad0970d0bb
130
inl
C++
Blob_Lib/Include/glm/gtx/euler_angles.inl
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/Include/glm/gtx/euler_angles.inl
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/Include/glm/gtx/euler_angles.inl
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:a9d9bdd6e8fa3b6aa17d8364d2ef16a76950b06feadea874cc740f3ade5e1601 size 23652
32.5
75
0.884615
antholuo
82d3bc212ad95a120c275f453620497077efc0ec
100,172
cpp
C++
B2G/gecko/widget/windows/nsTextStore.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/widget/windows/nsTextStore.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/widget/windows/nsTextStore.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <olectl.h> #ifdef MOZ_LOGGING #define FORCE_PR_LOG /* Allow logging in the release build */ #endif // MOZ_LOGGING #include "prlog.h" #include "nscore.h" #include "nsTextStore.h" #include "nsWindow.h" #include "nsPrintfCString.h" #include "WinUtils.h" #include "mozilla/Preferences.h" using namespace mozilla; using namespace mozilla::widget; /******************************************************************/ /* nsTextStore */ /******************************************************************/ ITfThreadMgr* nsTextStore::sTsfThreadMgr = NULL; ITfDisplayAttributeMgr* nsTextStore::sDisplayAttrMgr = NULL; ITfCategoryMgr* nsTextStore::sCategoryMgr = NULL; DWORD nsTextStore::sTsfClientId = 0; nsTextStore* nsTextStore::sTsfTextStore = NULL; UINT nsTextStore::sFlushTIPInputMessage = 0; #ifdef PR_LOGGING /** * TSF related code should log its behavior even on release build especially * in the interface methods. * * In interface methods, use PR_LOG_ALWAYS. * In internal methods, use PR_LOG_DEBUG for logging normal behavior. * For logging error, use PR_LOG_ERROR. * * When an instance method is called, start with following text: * "TSF: 0x%p nsFoo::Bar(", the 0x%p should be the "this" of the nsFoo. * after that, start with: * "TSF: 0x%p nsFoo::Bar(" * In an internal method, start with following text: * "TSF: 0x%p nsFoo::Bar(" * When a static method is called, start with following text: * "TSF: nsFoo::Bar(" */ PRLogModuleInfo* sTextStoreLog = nullptr; static const char* GetBoolName(bool aBool) { return aBool ? "true" : "false"; } static const char* GetIMEEnabledName(IMEState::Enabled aIMEEnabled) { switch (aIMEEnabled) { case IMEState::DISABLED: return "DISABLED"; case IMEState::ENABLED: return "ENABLED"; case IMEState::PASSWORD: return "PASSWORD"; case IMEState::PLUGIN: return "PLUGIN"; default: return "Invalid"; } } static nsCString GetRIIDNameStr(REFIID aRIID) { LPOLESTR str = nullptr; HRESULT hr = ::StringFromIID(aRIID, &str); if (FAILED(hr) || !str || !str[0]) { return EmptyCString(); } nsAutoString key(L"Interface\\"); key += str; nsAutoCString result; PRUnichar buf[256]; if (WinUtils::GetRegistryKey(HKEY_CLASSES_ROOT, key.get(), nullptr, buf, sizeof(buf))) { result = NS_ConvertUTF16toUTF8(buf); } else { result = NS_ConvertUTF16toUTF8(str); } ::CoTaskMemFree(str); return result; } static const char* GetCommonReturnValueName(HRESULT aResult) { switch (aResult) { case S_OK: return "S_OK"; case E_ABORT: return "E_ABORT"; case E_ACCESSDENIED: return "E_ACCESSDENIED"; case E_FAIL: return "E_FAIL"; case E_HANDLE: return "E_HANDLE"; case E_INVALIDARG: return "E_INVALIDARG"; case E_NOINTERFACE: return "E_NOINTERFACE"; case E_NOTIMPL: return "E_NOTIMPL"; case E_OUTOFMEMORY: return "E_OUTOFMEMORY"; case E_POINTER: return "E_POINTER"; case E_UNEXPECTED: return "E_UNEXPECTED"; default: return SUCCEEDED(aResult) ? "Succeeded" : "Failed"; } } static const char* GetTextStoreReturnValueName(HRESULT aResult) { switch (aResult) { case TS_E_FORMAT: return "TS_E_FORMAT"; case TS_E_INVALIDPOINT: return "TS_E_INVALIDPOINT"; case TS_E_INVALIDPOS: return "TS_E_INVALIDPOS"; case TS_E_NOINTERFACE: return "TS_E_NOINTERFACE"; case TS_E_NOLAYOUT: return "TS_E_NOLAYOUT"; case TS_E_NOLOCK: return "TS_E_NOLOCK"; case TS_E_NOOBJECT: return "TS_E_NOOBJECT"; case TS_E_NOSELECTION: return "TS_E_NOSELECTION"; case TS_E_NOSERVICE: return "TS_E_NOSERVICE"; case TS_E_READONLY: return "TS_E_READONLY"; case TS_E_SYNCHRONOUS: return "TS_E_SYNCHRONOUS"; case TS_S_ASYNC: return "TS_S_ASYNC"; default: return GetCommonReturnValueName(aResult); } } static const nsCString GetSinkMaskNameStr(DWORD aSinkMask) { nsAutoCString description; if (aSinkMask & TS_AS_TEXT_CHANGE) { description.AppendLiteral("TS_AS_TEXT_CHANGE"); } if (aSinkMask & TS_AS_SEL_CHANGE) { if (!description.IsEmpty()) { description.AppendLiteral(" | "); } description.AppendLiteral("TS_AS_SEL_CHANGE"); } if (aSinkMask & TS_AS_LAYOUT_CHANGE) { if (!description.IsEmpty()) { description.AppendLiteral(" | "); } description.AppendLiteral("TS_AS_LAYOUT_CHANGE"); } if (aSinkMask & TS_AS_ATTR_CHANGE) { if (!description.IsEmpty()) { description.AppendLiteral(" | "); } description.AppendLiteral("TS_AS_ATTR_CHANGE"); } if (aSinkMask & TS_AS_STATUS_CHANGE) { if (!description.IsEmpty()) { description.AppendLiteral(" | "); } description.AppendLiteral("TS_AS_STATUS_CHANGE"); } if (description.IsEmpty()) { description.AppendLiteral("not-specified"); } return description; } static const char* GetActiveSelEndName(TsActiveSelEnd aSelEnd) { return aSelEnd == TS_AE_NONE ? "TS_AE_NONE" : aSelEnd == TS_AE_START ? "TS_AE_START" : aSelEnd == TS_AE_END ? "TS_AE_END" : "Unknown"; } static const nsCString GetLockFlagNameStr(DWORD aLockFlags) { nsAutoCString description; if ((aLockFlags & TS_LF_READWRITE) == TS_LF_READWRITE) { description.AppendLiteral("TS_LF_READWRITE"); } else if (aLockFlags & TS_LF_READ) { description.AppendLiteral("TS_LF_READ"); } if (aLockFlags & TS_LF_SYNC) { if (!description.IsEmpty()) { description.AppendLiteral(" | "); } description.AppendLiteral("TS_LF_SYNC"); } if (description.IsEmpty()) { description.AppendLiteral("not-specified"); } return description; } static const char* GetTextRunTypeName(TsRunType aRunType) { switch (aRunType) { case TS_RT_PLAIN: return "TS_RT_PLAIN"; case TS_RT_HIDDEN: return "TS_RT_HIDDEN"; case TS_RT_OPAQUE: return "TS_RT_OPAQUE"; default: return "Unknown"; } } static nsCString GetColorName(const TF_DA_COLOR &aColor) { switch (aColor.type) { case TF_CT_NONE: return NS_LITERAL_CSTRING("TF_CT_NONE"); case TF_CT_SYSCOLOR: return nsPrintfCString("TF_CT_SYSCOLOR, nIndex:0x%08X", static_cast<int32_t>(aColor.nIndex)); case TF_CT_COLORREF: return nsPrintfCString("TF_CT_COLORREF, cr:0x%08X", static_cast<int32_t>(aColor.cr)); break; default: return nsPrintfCString("Unknown(%08X)", static_cast<int32_t>(aColor.type)); } } static nsCString GetLineStyleName(TF_DA_LINESTYLE aLineStyle) { switch (aLineStyle) { case TF_LS_NONE: return NS_LITERAL_CSTRING("TF_LS_NONE"); case TF_LS_SOLID: return NS_LITERAL_CSTRING("TF_LS_SOLID"); case TF_LS_DOT: return NS_LITERAL_CSTRING("TF_LS_DOT"); case TF_LS_DASH: return NS_LITERAL_CSTRING("TF_LS_DASH"); case TF_LS_SQUIGGLE: return NS_LITERAL_CSTRING("TF_LS_SQUIGGLE"); default: { return nsPrintfCString("Unknown(%08X)", static_cast<int32_t>(aLineStyle)); } } } static nsCString GetClauseAttrName(TF_DA_ATTR_INFO aAttr) { switch (aAttr) { case TF_ATTR_INPUT: return NS_LITERAL_CSTRING("TF_ATTR_INPUT"); case TF_ATTR_TARGET_CONVERTED: return NS_LITERAL_CSTRING("TF_ATTR_TARGET_CONVERTED"); case TF_ATTR_CONVERTED: return NS_LITERAL_CSTRING("TF_ATTR_CONVERTED"); case TF_ATTR_TARGET_NOTCONVERTED: return NS_LITERAL_CSTRING("TF_ATTR_TARGET_NOTCONVERTED"); case TF_ATTR_INPUT_ERROR: return NS_LITERAL_CSTRING("TF_ATTR_INPUT_ERROR"); case TF_ATTR_FIXEDCONVERTED: return NS_LITERAL_CSTRING("TF_ATTR_FIXEDCONVERTED"); case TF_ATTR_OTHER: return NS_LITERAL_CSTRING("TF_ATTR_OTHER"); default: { return nsPrintfCString("Unknown(%08X)", static_cast<int32_t>(aAttr)); } } } static nsCString GetDisplayAttrStr(const TF_DISPLAYATTRIBUTE &aDispAttr) { nsAutoCString str; str = "crText:{ "; str += GetColorName(aDispAttr.crText); str += " }, crBk:{ "; str += GetColorName(aDispAttr.crBk); str += " }, lsStyle: "; str += GetLineStyleName(aDispAttr.lsStyle); str += ", fBoldLine: "; str += GetBoolName(aDispAttr.fBoldLine); str += ", crLine:{ "; str += GetColorName(aDispAttr.crLine); str += " }, bAttr: "; str += GetClauseAttrName(aDispAttr.bAttr); return str; } #endif // #ifdef PR_LOGGING nsTextStore::nsTextStore() { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::nsTestStore(): instance is created", this)); mRefCnt = 1; mEditCookie = 0; mSinkMask = 0; mWindow = nullptr; mLock = 0; mLockQueued = 0; mTextChange.acpStart = INT32_MAX; mTextChange.acpOldEnd = mTextChange.acpNewEnd = 0; mLastDispatchedTextEvent = nullptr; } nsTextStore::~nsTextStore() { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore instance is destroyed, " "mWindow=0x%p, mDocumentMgr=0x%p, mContext=0x%p", this, mWindow, mDocumentMgr.get(), mContext.get())); if (mCompositionTimer) { mCompositionTimer->Cancel(); mCompositionTimer = nullptr; } SaveTextEvent(nullptr); } bool nsTextStore::Create(nsWindow* aWindow, IMEState::Enabled aIMEEnabled) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::Create(aWindow=0x%p, aIMEEnabled=%s)", this, aWindow, GetIMEEnabledName(aIMEEnabled))); if (mDocumentMgr) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::Create() FAILED due to already initialized", this)); return false; } // Create document manager HRESULT hr = sTsfThreadMgr->CreateDocumentMgr( getter_AddRefs(mDocumentMgr)); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::Create() FAILED to create DocumentMgr " "(0x%08X)", this, hr)); return false; } mWindow = aWindow; // Create context and add it to document manager hr = mDocumentMgr->CreateContext(sTsfClientId, 0, static_cast<ITextStoreACP*>(this), getter_AddRefs(mContext), &mEditCookie); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::Create() FAILED to create the context " "(0x%08X)", this, hr)); mDocumentMgr = NULL; return false; } SetInputContextInternal(aIMEEnabled); hr = mDocumentMgr->Push(mContext); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::Create() FAILED to push the context (0x%08X)", this, hr)); // XXX Why don't we use NS_IF_RELEASE() here?? mContext = NULL; mDocumentMgr = NULL; return false; } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::Create() succeeded: " "mDocumentMgr=0x%p, mContext=0x%p, mEditCookie=0x%08X", this, mDocumentMgr.get(), mContext.get(), mEditCookie)); return true; } bool nsTextStore::Destroy(void) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::Destroy()", this)); if (mWindow) { // When blurred, Tablet Input Panel posts "blur" messages // and try to insert text when the message is retrieved later. // But by that time the text store is already destroyed, // so try to get the message early MSG msg; if (::PeekMessageW(&msg, mWindow->GetWindowHandle(), sFlushTIPInputMessage, sFlushTIPInputMessage, PM_REMOVE)) { ::DispatchMessageW(&msg); } } mContext = NULL; if (mDocumentMgr) { mDocumentMgr->Pop(TF_POPF_ALL); mDocumentMgr = NULL; } mSink = NULL; mWindow = NULL; PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::Destroy() succeeded", this)); return true; } STDMETHODIMP nsTextStore::QueryInterface(REFIID riid, void** ppv) { *ppv=NULL; if ( (IID_IUnknown == riid) || (IID_ITextStoreACP == riid) ) { *ppv = static_cast<ITextStoreACP*>(this); } else if (IID_ITfContextOwnerCompositionSink == riid) { *ppv = static_cast<ITfContextOwnerCompositionSink*>(this); } if (*ppv) { AddRef(); return S_OK; } PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::QueryInterface() FAILED, riid=%s", this, GetRIIDNameStr(riid).get())); return E_NOINTERFACE; } STDMETHODIMP_(ULONG) nsTextStore::AddRef() { return ++mRefCnt; } STDMETHODIMP_(ULONG) nsTextStore::Release() { --mRefCnt; if (0 != mRefCnt) return mRefCnt; delete this; return 0; } STDMETHODIMP nsTextStore::AdviseSink(REFIID riid, IUnknown *punk, DWORD dwMask) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::AdviseSink(riid=%s, punk=0x%p, dwMask=%s), " "mSink=0x%p, mSinkMask=%s", this, GetRIIDNameStr(riid).get(), punk, GetSinkMaskNameStr(dwMask).get(), mSink.get(), GetSinkMaskNameStr(mSinkMask).get())); if (!punk) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::AdviseSink() FAILED due to the null punk", this)); return E_UNEXPECTED; } if (IID_ITextStoreACPSink != riid) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::AdviseSink() FAILED due to " "unsupported interface", this)); return E_INVALIDARG; // means unsupported interface. } if (!mSink) { // Install sink punk->QueryInterface(IID_ITextStoreACPSink, getter_AddRefs(mSink)); if (!mSink) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::AdviseSink() FAILED due to " "punk not having the interface", this)); return E_UNEXPECTED; } } else { // If sink is already installed we check to see if they are the same // Get IUnknown from both sides for comparison nsRefPtr<IUnknown> comparison1, comparison2; punk->QueryInterface(IID_IUnknown, getter_AddRefs(comparison1)); mSink->QueryInterface(IID_IUnknown, getter_AddRefs(comparison2)); if (comparison1 != comparison2) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::AdviseSink() FAILED due to " "the sink being different from the stored sink", this)); return CONNECT_E_ADVISELIMIT; } } // Update mask either for a new sink or an existing sink mSinkMask = dwMask; return S_OK; } STDMETHODIMP nsTextStore::UnadviseSink(IUnknown *punk) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::UnadviseSink(punk=0x%p), mSink=0x%p", this, punk, mSink.get())); if (!punk) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::UnadviseSink() FAILED due to the null punk", this)); return E_INVALIDARG; } if (!mSink) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::UnadviseSink() FAILED due to " "any sink not stored", this)); return CONNECT_E_NOCONNECTION; } // Get IUnknown from both sides for comparison nsRefPtr<IUnknown> comparison1, comparison2; punk->QueryInterface(IID_IUnknown, getter_AddRefs(comparison1)); mSink->QueryInterface(IID_IUnknown, getter_AddRefs(comparison2)); // Unadvise only if sinks are the same if (comparison1 != comparison2) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::UnadviseSink() FAILED due to " "the sink being different from the stored sink", this)); return CONNECT_E_NOCONNECTION; } mSink = NULL; mSinkMask = 0; return S_OK; } STDMETHODIMP nsTextStore::RequestLock(DWORD dwLockFlags, HRESULT *phrSession) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::RequestLock(dwLockFlags=%s, phrSession=0x%p), " "mLock=%s", this, GetLockFlagNameStr(dwLockFlags).get(), phrSession, GetLockFlagNameStr(mLock).get())); if (!mSink) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::RequestLock() FAILED due to " "any sink not stored", this)); return E_FAIL; } if (!phrSession) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::RequestLock() FAILED due to " "null phrSession", this)); return E_INVALIDARG; } if (!mLock) { // put on lock mLock = dwLockFlags & (~TS_LF_SYNC); PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::RequestLock() notifying OnLockGranted()...", this)); *phrSession = mSink->OnLockGranted(mLock); while (mLockQueued) { mLock = mLockQueued; mLockQueued = 0; PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::RequestLock() notifying OnLockGranted() " "with mLockQueued (%s)...", this, GetLockFlagNameStr(mLock).get())); mSink->OnLockGranted(mLock); } mLock = 0; PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::RequestLock() succeeded: *phrSession=%s", this, GetTextStoreReturnValueName(*phrSession))); return S_OK; } // only time when reentrant lock is allowed is when caller holds a // read-only lock and is requesting an async write lock if (IsReadLocked() && !IsReadWriteLocked() && IsReadWriteLock(dwLockFlags) && !(dwLockFlags & TS_LF_SYNC)) { *phrSession = TS_S_ASYNC; mLockQueued = dwLockFlags & (~TS_LF_SYNC); PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::RequestLock() stores the request in the " "queue, *phrSession=TS_S_ASYNC", this)); return S_OK; } // no more locks allowed PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::RequestLock() didn't allow to lock, " "*phrSession=TS_E_SYNCHRONOUS", this)); *phrSession = TS_E_SYNCHRONOUS; return E_FAIL; } STDMETHODIMP nsTextStore::GetStatus(TS_STATUS *pdcs) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetStatus(pdcs=0x%p)", this, pdcs)); if (!pdcs) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetStatus() FAILED due to null pdcs", this)); return E_INVALIDARG; } pdcs->dwDynamicFlags = 0; // we use a "flat" text model for TSF support so no hidden text pdcs->dwStaticFlags = TS_SS_NOHIDDENTEXT; return S_OK; } STDMETHODIMP nsTextStore::QueryInsert(LONG acpTestStart, LONG acpTestEnd, ULONG cch, LONG *pacpResultStart, LONG *pacpResultEnd) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::QueryInsert(acpTestStart=%ld, " "acpTestEnd=%ld, cch=%lu, pacpResultStart=0x%p, pacpResultEnd=0x%p)", this, acpTestStart, acpTestEnd, cch, acpTestStart, acpTestEnd)); if (!pacpResultStart || !pacpResultEnd) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::QueryInsert() FAILED due to " "the null argument", this)); return E_INVALIDARG; } if (acpTestStart < 0 || acpTestStart > acpTestEnd) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::QueryInsert() FAILED due to " "wrong argument", this)); return E_INVALIDARG; } // XXX need to adjust to cluster boundary // Assume we are given good offsets for now *pacpResultStart = acpTestStart; *pacpResultEnd = acpTestStart + cch; PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::QueryInsert() succeeded: " "*pacpResultStart=%ld, *pacpResultEnd=%ld)", this, *pacpResultStart, *pacpResultEnd)); return S_OK; } STDMETHODIMP nsTextStore::GetSelection(ULONG ulIndex, ULONG ulCount, TS_SELECTION_ACP *pSelection, ULONG *pcFetched) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetSelection(ulIndex=%lu, ulCount=%lu, " "pSelection=0x%p, pcFetched=0x%p)", this, ulIndex, ulCount, pSelection, pcFetched)); if (!IsReadLocked()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetSelection() FAILED due to not locked", this)); return TS_E_NOLOCK; } if (!ulCount || !pSelection || !pcFetched) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetSelection() FAILED due to " "null argument", this)); return E_INVALIDARG; } *pcFetched = 0; if (ulIndex != static_cast<ULONG>(TS_DEFAULT_SELECTION) && ulIndex != 0) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetSelection() FAILED due to " "unsupported selection", this)); return TS_E_NOSELECTION; } if (!GetSelectionInternal(*pSelection)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetSelection() FAILED to get selection", this)); return E_FAIL; } *pcFetched = 1; PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetSelection() succeeded", this)); return S_OK; } bool nsTextStore::GetSelectionInternal(TS_SELECTION_ACP &aSelectionACP) { if (mCompositionView) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::GetSelectionInternal(), " "there is no composition view", this)); // Emulate selection during compositions aSelectionACP = mCompositionSelection; } else { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::GetSelectionInternal(), " "try to get normal selection...", this)); // Construct and initialize an event to get selection info nsQueryContentEvent event(true, NS_QUERY_SELECTED_TEXT, mWindow); mWindow->InitEvent(event); mWindow->DispatchWindowEvent(&event); if (!event.mSucceeded) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetSelectionInternal() FAILED to " "query selected text", this)); return false; } // Usually the selection anchor (beginning) position corresponds to the // TSF start and the selection focus (ending) position corresponds to // the TSF end, but if selection is reversed the focus now corresponds // to the TSF start and the anchor now corresponds to the TSF end aSelectionACP.acpStart = event.mReply.mOffset; aSelectionACP.acpEnd = aSelectionACP.acpStart + event.mReply.mString.Length(); aSelectionACP.style.ase = event.mReply.mString.Length() && event.mReply.mReversed ? TS_AE_START : TS_AE_END; // No support for interim character aSelectionACP.style.fInterimChar = FALSE; } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetSelectionInternal() succeeded: " "acpStart=%lu, acpEnd=%lu, style.ase=%s, style.fInterimChar=%s", this, aSelectionACP.acpStart, aSelectionACP.acpEnd, GetActiveSelEndName(aSelectionACP.style.ase), GetBoolName(aSelectionACP.style.fInterimChar))); return true; } static HRESULT GetRangeExtent(ITfRange* aRange, LONG* aStart, LONG* aLength) { nsRefPtr<ITfRangeACP> rangeACP; aRange->QueryInterface(IID_ITfRangeACP, getter_AddRefs(rangeACP)); NS_ENSURE_TRUE(rangeACP, E_FAIL); return rangeACP->GetExtent(aStart, aLength); } static uint32_t GetGeckoSelectionValue(TF_DISPLAYATTRIBUTE &aDisplayAttr) { uint32_t result; switch (aDisplayAttr.bAttr) { case TF_ATTR_TARGET_CONVERTED: result = NS_TEXTRANGE_SELECTEDCONVERTEDTEXT; break; case TF_ATTR_CONVERTED: result = NS_TEXTRANGE_CONVERTEDTEXT; break; case TF_ATTR_TARGET_NOTCONVERTED: result = NS_TEXTRANGE_SELECTEDRAWTEXT; break; default: result = NS_TEXTRANGE_RAWINPUT; break; } return result; } HRESULT nsTextStore::GetDisplayAttribute(ITfProperty* aAttrProperty, ITfRange* aRange, TF_DISPLAYATTRIBUTE* aResult) { NS_ENSURE_TRUE(aAttrProperty, E_FAIL); NS_ENSURE_TRUE(aRange, E_FAIL); NS_ENSURE_TRUE(aResult, E_FAIL); HRESULT hr; #ifdef PR_LOGGING if (PR_LOG_TEST(sTextStoreLog, PR_LOG_DEBUG)) { LONG start = 0, length = 0; hr = GetRangeExtent(aRange, &start, &length); PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::GetDisplayAttribute(): " "GetDisplayAttribute range=%ld-%ld (hr=%s)", this, start - mCompositionStart, start - mCompositionStart + length, GetCommonReturnValueName(hr))); } #endif VARIANT propValue; ::VariantInit(&propValue); hr = aAttrProperty->GetValue(TfEditCookie(mEditCookie), aRange, &propValue); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetDisplayAttribute() FAILED due to " "ITfProperty::GetValue() failed", this)); return hr; } if (VT_I4 != propValue.vt) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetDisplayAttribute() FAILED due to " "ITfProperty::GetValue() returns non-VT_I4 value", this)); ::VariantClear(&propValue); return E_FAIL; } NS_ENSURE_TRUE(sCategoryMgr, E_FAIL); GUID guid; hr = sCategoryMgr->GetGUID(DWORD(propValue.lVal), &guid); ::VariantClear(&propValue); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetDisplayAttribute() FAILED due to " "ITfCategoryMgr::GetGUID() failed", this)); return hr; } NS_ENSURE_TRUE(sDisplayAttrMgr, E_FAIL); nsRefPtr<ITfDisplayAttributeInfo> info; hr = sDisplayAttrMgr->GetDisplayAttributeInfo(guid, getter_AddRefs(info), NULL); if (FAILED(hr) || !info) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetDisplayAttribute() FAILED due to " "ITfDisplayAttributeMgr::GetDisplayAttributeInfo() failed", this)); return hr; } hr = info->GetAttributeInfo(aResult); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetDisplayAttribute() FAILED due to " "ITfDisplayAttributeInfo::GetAttributeInfo() failed", this)); return hr; } PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::GetDisplayAttribute() succeeded: " "Result={ %s }", this, GetDisplayAttrStr(*aResult).get())); return S_OK; } HRESULT nsTextStore::SaveTextEvent(const nsTextEvent* aEvent) { if (mLastDispatchedTextEvent) { if (mLastDispatchedTextEvent->rangeArray) delete [] mLastDispatchedTextEvent->rangeArray; delete mLastDispatchedTextEvent; mLastDispatchedTextEvent = nullptr; } if (!aEvent) return S_OK; mLastDispatchedTextEvent = new nsTextEvent(true, NS_TEXT_TEXT, nullptr); if (!mLastDispatchedTextEvent) return E_OUTOFMEMORY; mLastDispatchedTextEvent->rangeCount = aEvent->rangeCount; mLastDispatchedTextEvent->theText = aEvent->theText; mLastDispatchedTextEvent->rangeArray = nullptr; if (aEvent->rangeCount == 0) return S_OK; NS_ENSURE_TRUE(aEvent->rangeArray, E_FAIL); mLastDispatchedTextEvent->rangeArray = new nsTextRange[aEvent->rangeCount]; if (!mLastDispatchedTextEvent->rangeArray) { delete mLastDispatchedTextEvent; mLastDispatchedTextEvent = nullptr; return E_OUTOFMEMORY; } memcpy(mLastDispatchedTextEvent->rangeArray, aEvent->rangeArray, sizeof(nsTextRange) * aEvent->rangeCount); return S_OK; } static bool IsSameTextEvent(const nsTextEvent* aEvent1, const nsTextEvent* aEvent2) { NS_PRECONDITION(aEvent1 || aEvent2, "both events are null"); NS_PRECONDITION(aEvent2 && (aEvent1 != aEvent2), "both events are same instance"); return (aEvent1 && aEvent2 && aEvent1->rangeCount == aEvent2->rangeCount && aEvent1->theText == aEvent2->theText && (aEvent1->rangeCount == 0 || ((aEvent1->rangeArray && aEvent2->rangeArray) && !memcmp(aEvent1->rangeArray, aEvent2->rangeArray, sizeof(nsTextRange) * aEvent1->rangeCount)))); } HRESULT nsTextStore::UpdateCompositionExtent(ITfRange* aRangeNew) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::UpdateCompositionExtent(aRangeNew=0x%p), " "mCompositionView=0x%p", this, aRangeNew, mCompositionView.get())); if (!mCompositionView) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::UpdateCompositionExtent() FAILED due to " "no composition view", this)); return E_FAIL; } HRESULT hr; nsRefPtr<ITfCompositionView> pComposition(mCompositionView); nsRefPtr<ITfRange> composingRange(aRangeNew); if (!composingRange) { hr = pComposition->GetRange(getter_AddRefs(composingRange)); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::UpdateCompositionExtent() FAILED due to " "pComposition->GetRange() failure", this)); return hr; } } // Get starting offset of the composition LONG compStart = 0, compLength = 0; hr = GetRangeExtent(composingRange, &compStart, &compLength); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::UpdateCompositionExtent() FAILED due to " "GetRangeExtent() failure", this)); return hr; } PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::UpdateCompositionExtent(), range=%ld-%ld, " "mCompositionStart=%ld, mCompositionString.Length()=%lu", this, compStart, compStart + compLength, mCompositionStart, mCompositionString.Length())); if (mCompositionStart != compStart || mCompositionString.Length() != (ULONG)compLength) { // If the queried composition length is different from the length // of our composition string, OnUpdateComposition is being called // because a part of the original composition was committed. // Reflect that by committing existing composition and starting // a new one. OnEndComposition followed by OnStartComposition // will accomplish this automagically. OnEndComposition(pComposition); OnStartCompositionInternal(pComposition, composingRange, true); } else { mCompositionLength = compLength; } PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::UpdateCompositionExtent() succeeded", this)); return S_OK; } static bool GetColor(const TF_DA_COLOR &aTSFColor, nscolor &aResult) { switch (aTSFColor.type) { case TF_CT_SYSCOLOR: { DWORD sysColor = ::GetSysColor(aTSFColor.nIndex); aResult = NS_RGB(GetRValue(sysColor), GetGValue(sysColor), GetBValue(sysColor)); return true; } case TF_CT_COLORREF: aResult = NS_RGB(GetRValue(aTSFColor.cr), GetGValue(aTSFColor.cr), GetBValue(aTSFColor.cr)); return true; case TF_CT_NONE: default: return false; } } static bool GetLineStyle(TF_DA_LINESTYLE aTSFLineStyle, uint8_t &aTextRangeLineStyle) { switch (aTSFLineStyle) { case TF_LS_NONE: aTextRangeLineStyle = nsTextRangeStyle::LINESTYLE_NONE; return true; case TF_LS_SOLID: aTextRangeLineStyle = nsTextRangeStyle::LINESTYLE_SOLID; return true; case TF_LS_DOT: aTextRangeLineStyle = nsTextRangeStyle::LINESTYLE_DOTTED; return true; case TF_LS_DASH: aTextRangeLineStyle = nsTextRangeStyle::LINESTYLE_DASHED; return true; case TF_LS_SQUIGGLE: aTextRangeLineStyle = nsTextRangeStyle::LINESTYLE_WAVY; return true; default: return false; } } HRESULT nsTextStore::SendTextEventForCompositionString() { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::SendTextEventForCompositionString(), " "mCompositionView=0x%p, mCompositionString=\"%s\"", this, mCompositionView.get(), NS_ConvertUTF16toUTF8(mCompositionString).get())); if (!mCompositionView) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SendTextEventForCompositionString() FAILED " "due to no composition view", this)); return E_FAIL; } // Getting display attributes is *really* complicated! // We first get the context and the property objects to query for // attributes, but since a big range can have a variety of values for // the attribute, we have to find out all the ranges that have distinct // attribute values. Then we query for what the value represents through // the display attribute manager and translate that to nsTextRange to be // sent in NS_TEXT_TEXT nsRefPtr<ITfProperty> attrPropetry; HRESULT hr = mContext->GetProperty(GUID_PROP_ATTRIBUTE, getter_AddRefs(attrPropetry)); if (FAILED(hr) || !attrPropetry) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SendTextEventForCompositionString() FAILED " "due to mContext->GetProperty() failure", this)); return FAILED(hr) ? hr : E_FAIL; } // Use NS_TEXT_TEXT to set composition string nsTextEvent event(true, NS_TEXT_TEXT, mWindow); mWindow->InitEvent(event); nsRefPtr<ITfRange> composingRange; hr = mCompositionView->GetRange(getter_AddRefs(composingRange)); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SendTextEventForCompositionString() FAILED " "due to mCompositionView->GetRange() failure", this)); return hr; } nsRefPtr<IEnumTfRanges> enumRanges; hr = attrPropetry->EnumRanges(TfEditCookie(mEditCookie), getter_AddRefs(enumRanges), composingRange); if (FAILED(hr) || !enumRanges) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SendTextEventForCompositionString() FAILED " "due to attrPropetry->EnumRanges() failure", this)); return FAILED(hr) ? hr : E_FAIL; } nsAutoTArray<nsTextRange, 4> textRanges; nsTextRange newRange; // No matter if we have display attribute info or not, // we always pass in at least one range to NS_TEXT_TEXT newRange.mStartOffset = 0; newRange.mEndOffset = mCompositionString.Length(); newRange.mRangeType = NS_TEXTRANGE_RAWINPUT; textRanges.AppendElement(newRange); nsRefPtr<ITfRange> range; while (S_OK == enumRanges->Next(1, getter_AddRefs(range), NULL) && range) { LONG start = 0, length = 0; if (FAILED(GetRangeExtent(range, &start, &length))) continue; nsTextRange newRange; newRange.mStartOffset = uint32_t(start - mCompositionStart); // The end of the last range in the array is // always kept at the end of composition newRange.mEndOffset = mCompositionString.Length(); TF_DISPLAYATTRIBUTE attr; hr = GetDisplayAttribute(attrPropetry, range, &attr); if (FAILED(hr)) { newRange.mRangeType = NS_TEXTRANGE_RAWINPUT; } else { newRange.mRangeType = GetGeckoSelectionValue(attr); if (GetColor(attr.crText, newRange.mRangeStyle.mForegroundColor)) { newRange.mRangeStyle.mDefinedStyles |= nsTextRangeStyle::DEFINED_FOREGROUND_COLOR; } if (GetColor(attr.crBk, newRange.mRangeStyle.mBackgroundColor)) { newRange.mRangeStyle.mDefinedStyles |= nsTextRangeStyle::DEFINED_BACKGROUND_COLOR; } if (GetColor(attr.crLine, newRange.mRangeStyle.mUnderlineColor)) { newRange.mRangeStyle.mDefinedStyles |= nsTextRangeStyle::DEFINED_UNDERLINE_COLOR; } if (GetLineStyle(attr.lsStyle, newRange.mRangeStyle.mLineStyle)) { newRange.mRangeStyle.mDefinedStyles |= nsTextRangeStyle::DEFINED_LINESTYLE; newRange.mRangeStyle.mIsBoldLine = attr.fBoldLine != 0; } } nsTextRange& lastRange = textRanges[textRanges.Length() - 1]; if (lastRange.mStartOffset == newRange.mStartOffset) { // Replace range if last range is the same as this one // So that ranges don't overlap and confuse the editor lastRange = newRange; } else { lastRange.mEndOffset = newRange.mStartOffset; textRanges.AppendElement(newRange); } } // We need to hack for Korean Input System which is Korean standard TIP. // It sets no change style to IME selection (the selection is always only // one). So, the composition string looks like normal (or committed) string. // At this time, mCompositionSelection range is same as the composition // string range. Other applications set a wide caret which covers the // composition string, however, Gecko doesn't support the wide caret drawing // now (Gecko doesn't support XOR drawing), unfortunately. For now, we should // change the range style to undefined. if (mCompositionSelection.acpStart != mCompositionSelection.acpEnd && textRanges.Length() == 1) { nsTextRange& range = textRanges[0]; LONG start = NS_MIN(mCompositionSelection.acpStart, mCompositionSelection.acpEnd); LONG end = NS_MAX(mCompositionSelection.acpStart, mCompositionSelection.acpEnd); if ((LONG)range.mStartOffset == start - mCompositionStart && (LONG)range.mEndOffset == end - mCompositionStart && range.mRangeStyle.IsNoChangeStyle()) { range.mRangeStyle.Clear(); // The looks of selected type is better than others. range.mRangeType = NS_TEXTRANGE_SELECTEDRAWTEXT; } } // The caret position has to be collapsed. LONG caretPosition = NS_MAX(mCompositionSelection.acpStart, mCompositionSelection.acpEnd); caretPosition -= mCompositionStart; nsTextRange caretRange; caretRange.mStartOffset = caretRange.mEndOffset = uint32_t(caretPosition); caretRange.mRangeType = NS_TEXTRANGE_CARETPOSITION; textRanges.AppendElement(caretRange); event.theText = mCompositionString; event.rangeArray = textRanges.Elements(); event.rangeCount = textRanges.Length(); // If we are already send same text event, we should not resend it. Because // it can be a cause of flickering. if (IsSameTextEvent(mLastDispatchedTextEvent, &event)) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::SendTextEventForCompositionString() " "succeeded but any DOM events are not dispatched", this)); return S_OK; } if (mCompositionString != mLastDispatchedCompositionString) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::SendTextEventForCompositionString() " "dispatching compositionupdate event...", this)); nsCompositionEvent compositionUpdate(true, NS_COMPOSITION_UPDATE, mWindow); mWindow->InitEvent(compositionUpdate); compositionUpdate.data = mCompositionString; mLastDispatchedCompositionString = mCompositionString; mWindow->DispatchWindowEvent(&compositionUpdate); } if (mWindow && !mWindow->Destroyed()) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::SendTextEventForCompositionString() " "dispatching text event...", this)); mWindow->DispatchWindowEvent(&event); } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::SendTextEventForCompositionString() " "succeeded", this)); return SaveTextEvent(&event); } HRESULT nsTextStore::SetSelectionInternal(const TS_SELECTION_ACP* pSelection, bool aDispatchTextEvent) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::SetSelectionInternal(pSelection=%ld-%ld, " "aDispatchTextEvent=%s), %s", this, pSelection->acpStart, pSelection->acpEnd, GetBoolName(aDispatchTextEvent), mCompositionView ? "there is composition view" : "there is no composition view")); if (mCompositionView) { if (aDispatchTextEvent) { HRESULT hr = UpdateCompositionExtent(nullptr); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SetSelectionInternal() FAILED due to " "UpdateCompositionExtent() failure", this)); return hr; } } if (pSelection->acpStart < mCompositionStart || pSelection->acpEnd > mCompositionStart + static_cast<LONG>(mCompositionString.Length())) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SetSelectionInternal() FAILED due to " "the selection being out of the composition string", this)); return TS_E_INVALIDPOS; } // Emulate selection during compositions mCompositionSelection = *pSelection; if (aDispatchTextEvent) { HRESULT hr = SendTextEventForCompositionString(); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SetSelectionInternal() FAILED due to " "SendTextEventForCompositionString() failure", this)); return hr; } } return S_OK; } else { nsSelectionEvent event(true, NS_SELECTION_SET, mWindow); event.mOffset = pSelection->acpStart; event.mLength = uint32_t(pSelection->acpEnd - pSelection->acpStart); event.mReversed = pSelection->style.ase == TS_AE_START; mWindow->InitEvent(event); mWindow->DispatchWindowEvent(&event); if (!event.mSucceeded) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SetSelectionInternal() FAILED due to " "NS_SELECTION_SET failure", this)); return E_FAIL; } } return S_OK; } STDMETHODIMP nsTextStore::SetSelection(ULONG ulCount, const TS_SELECTION_ACP *pSelection) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::SetSelection(ulCount=%lu)", this, ulCount)); if (!IsReadWriteLocked()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SetSelection() FAILED due to " "not locked (read-write)", this)); return TS_E_NOLOCK; } if (ulCount != 1) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SetSelection() FAILED due to " "trying setting multiple selection", this)); return E_INVALIDARG; } if (!pSelection) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SetSelection() FAILED due to " "null argument", this)); return E_INVALIDARG; } HRESULT hr = SetSelectionInternal(pSelection, true); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SetSelection() FAILED due to " "SetSelectionInternal() failure", this)); } else { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::SetSelection() succeeded", this)); } return hr; } STDMETHODIMP nsTextStore::GetText(LONG acpStart, LONG acpEnd, WCHAR *pchPlain, ULONG cchPlainReq, ULONG *pcchPlainOut, TS_RUNINFO *prgRunInfo, ULONG ulRunInfoReq, ULONG *pulRunInfoOut, LONG *pacpNext) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetText(acpStart=%ld, acpEnd=%ld, pchPlain=0x%p, " "cchPlainReq=%lu, pcchPlainOut=0x%p, prgRunInfo=0x%p, ulRunInfoReq=%lu, " "pulRunInfoOut=0x%p, pacpNext=0x%p), %s, mCompositionStart=%ld, " "mCompositionLength=%ld, mCompositionString.Length()=%lu", this, acpStart, acpEnd, pchPlain, cchPlainReq, pcchPlainOut, prgRunInfo, ulRunInfoReq, pulRunInfoOut, pacpNext, mCompositionView ? "there is composition view" : "there is no composition view", mCompositionStart, mCompositionLength, mCompositionString.Length())); if (!IsReadLocked()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetText() FAILED due to " "not locked (read)", this)); return TS_E_NOLOCK; } if (!pcchPlainOut || (!pchPlain && !prgRunInfo) || !cchPlainReq != !pchPlain || !ulRunInfoReq != !prgRunInfo) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetText() FAILED due to " "invalid argument", this)); return E_INVALIDARG; } if (acpStart < 0 || acpEnd < -1 || (acpEnd != -1 && acpStart > acpEnd)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetText() FAILED due to " "invalid position", this)); return TS_E_INVALIDPOS; } // Making sure to NULL-terminate string just to be on the safe side *pcchPlainOut = 0; if (pchPlain && cchPlainReq) *pchPlain = 0; if (pulRunInfoOut) *pulRunInfoOut = 0; if (pacpNext) *pacpNext = acpStart; if (prgRunInfo && ulRunInfoReq) { prgRunInfo->uCount = 0; prgRunInfo->type = TS_RT_PLAIN; } uint32_t length = -1 == acpEnd ? UINT32_MAX : uint32_t(acpEnd - acpStart); if (cchPlainReq && cchPlainReq - 1 < length) { length = cchPlainReq - 1; } if (length) { LONG compNewStart = 0, compOldEnd = 0, compNewEnd = 0; if (mCompositionView) { // Sometimes GetText gets called between InsertTextAtSelection and // OnUpdateComposition. In this case the returned text would // be out of sync because we haven't sent NS_TEXT_TEXT in // OnUpdateComposition yet. Manually resync here. compOldEnd = NS_MIN(LONG(length) + acpStart, mCompositionLength + mCompositionStart); compNewEnd = NS_MIN(LONG(length) + acpStart, LONG(mCompositionString.Length()) + mCompositionStart); compNewStart = NS_MAX(acpStart, mCompositionStart); // Check if the range is affected if (compOldEnd > compNewStart || compNewEnd > compNewStart) { NS_ASSERTION(compOldEnd >= mCompositionStart && compNewEnd >= mCompositionStart, "Range end is less than start\n"); length = uint32_t(LONG(length) + compOldEnd - compNewEnd); } } // Send NS_QUERY_TEXT_CONTENT to get text content nsQueryContentEvent event(true, NS_QUERY_TEXT_CONTENT, mWindow); mWindow->InitEvent(event); event.InitForQueryTextContent(uint32_t(acpStart), length); mWindow->DispatchWindowEvent(&event); if (!event.mSucceeded) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetText() FAILED due to " "NS_QUERY_TEXT_CONTENT failure: length=%lu", this, length)); return E_FAIL; } if (compOldEnd > compNewStart || compNewEnd > compNewStart) { // Resync composition string const PRUnichar* compStrStart = mCompositionString.BeginReading() + NS_MAX<LONG>(compNewStart - mCompositionStart, 0); event.mReply.mString.Replace(compNewStart - acpStart, compOldEnd - mCompositionStart, compStrStart, compNewEnd - mCompositionStart); length = uint32_t(LONG(length) - compOldEnd + compNewEnd); } if (-1 != acpEnd && event.mReply.mString.Length() != length) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetText() FAILED due to " "unexpected length=%lu", this, length)); return TS_E_INVALIDPOS; } length = NS_MIN(length, event.mReply.mString.Length()); if (pchPlain && cchPlainReq) { memcpy(pchPlain, event.mReply.mString.BeginReading(), length * sizeof(*pchPlain)); pchPlain[length] = 0; *pcchPlainOut = length; } if (prgRunInfo && ulRunInfoReq) { prgRunInfo->uCount = length; prgRunInfo->type = TS_RT_PLAIN; if (pulRunInfoOut) *pulRunInfoOut = 1; } if (pacpNext) *pacpNext = acpStart + length; } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetText() succeeded: pcchPlainOut=0x%p, " "*prgRunInfo={ uCount=%lu, type=%s }, *pulRunInfoOut=%lu, " "*pacpNext=%ld)", this, pcchPlainOut, prgRunInfo ? prgRunInfo->uCount : 0, prgRunInfo ? GetTextRunTypeName(prgRunInfo->type) : "N/A", pulRunInfoOut ? pulRunInfoOut : 0, pacpNext ? pacpNext : 0)); return S_OK; } STDMETHODIMP nsTextStore::SetText(DWORD dwFlags, LONG acpStart, LONG acpEnd, const WCHAR *pchText, ULONG cch, TS_TEXTCHANGE *pChange) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::SetText(dwFlags=%s, acpStart=%ld, acpEnd=%ld, " "pchText=0x%p \"%s\", cch=%lu, pChange=0x%p), %s", this, dwFlags == TS_ST_CORRECTION ? "TS_ST_CORRECTION" : "not-specified", acpStart, acpEnd, pchText, pchText && cch ? NS_ConvertUTF16toUTF8(pchText, cch).get() : "", cch, pChange, mCompositionView ? "there is composition view" : "there is no composition view")); // Per SDK documentation, and since we don't have better // ways to do this, this method acts as a helper to // call SetSelection followed by InsertTextAtSelection if (!IsReadWriteLocked()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SetText() FAILED due to " "not locked (read)", this)); return TS_E_NOLOCK; } TS_SELECTION_ACP selection; selection.acpStart = acpStart; selection.acpEnd = acpEnd; selection.style.ase = TS_AE_END; selection.style.fInterimChar = 0; // Set selection to desired range HRESULT hr = SetSelectionInternal(&selection); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SetText() FAILED due to " "SetSelectionInternal() failure", this)); return hr; } // Replace just selected text if (!InsertTextAtSelectionInternal(nsDependentString(pchText, cch), pChange)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::SetText() FAILED due to " "InsertTextAtSelectionInternal() failure", this)); return E_FAIL; } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::SetText() succeeded: pChange={ " "acpStart=%ld, acpOldEnd=%ld, acpNewEnd=%ld }", this, pChange ? pChange->acpStart : 0, pChange ? pChange->acpOldEnd : 0, pChange ? pChange->acpNewEnd : 0)); return S_OK; } STDMETHODIMP nsTextStore::GetFormattedText(LONG acpStart, LONG acpEnd, IDataObject **ppDataObject) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetFormattedText() called " "but not supported (E_NOTIMPL)", this)); // no support for formatted text return E_NOTIMPL; } STDMETHODIMP nsTextStore::GetEmbedded(LONG acpPos, REFGUID rguidService, REFIID riid, IUnknown **ppunk) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetEmbedded() called " "but not supported (E_NOTIMPL)", this)); // embedded objects are not supported return E_NOTIMPL; } STDMETHODIMP nsTextStore::QueryInsertEmbedded(const GUID *pguidService, const FORMATETC *pFormatEtc, BOOL *pfInsertable) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::QueryInsertEmbedded() called " "but not supported, *pfInsertable=FALSE (S_OK)", this)); // embedded objects are not supported *pfInsertable = FALSE; return S_OK; } STDMETHODIMP nsTextStore::InsertEmbedded(DWORD dwFlags, LONG acpStart, LONG acpEnd, IDataObject *pDataObject, TS_TEXTCHANGE *pChange) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::InsertEmbedded() called " "but not supported (E_NOTIMPL)", this)); // embedded objects are not supported return E_NOTIMPL; } STDMETHODIMP nsTextStore::RequestSupportedAttrs(DWORD dwFlags, ULONG cFilterAttrs, const TS_ATTRID *paFilterAttrs) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::RequestSupportedAttrs() called " "but not supported (S_OK)", this)); // no attributes defined return S_OK; } STDMETHODIMP nsTextStore::RequestAttrsAtPosition(LONG acpPos, ULONG cFilterAttrs, const TS_ATTRID *paFilterAttrs, DWORD dwFlags) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::RequestAttrsAtPosition() called " "but not supported (S_OK)", this)); // no per character attributes defined return S_OK; } STDMETHODIMP nsTextStore::RequestAttrsTransitioningAtPosition(LONG acpPos, ULONG cFilterAttrs, const TS_ATTRID *paFilterAttr, DWORD dwFlags) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::RequestAttrsTransitioningAtPosition() called " "but not supported (S_OK)", this)); // no per character attributes defined return S_OK; } STDMETHODIMP nsTextStore::FindNextAttrTransition(LONG acpStart, LONG acpHalt, ULONG cFilterAttrs, const TS_ATTRID *paFilterAttrs, DWORD dwFlags, LONG *pacpNext, BOOL *pfFound, LONG *plFoundOffset) { if (!pacpNext || !pfFound || !plFoundOffset) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::FindNextAttrTransition() FAILED due to " "null argument", this)); return E_INVALIDARG; } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::FindNextAttrTransition() called " "but not supported (S_OK)", this)); // no per character attributes defined *pacpNext = *plFoundOffset = acpHalt; *pfFound = FALSE; return S_OK; } STDMETHODIMP nsTextStore::RetrieveRequestedAttrs(ULONG ulCount, TS_ATTRVAL *paAttrVals, ULONG *pcFetched) { if (!pcFetched || !ulCount || !paAttrVals) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::RetrieveRequestedAttrs() FAILED due to " "null argument", this)); return E_INVALIDARG; } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::RetrieveRequestedAttrs() called " "but not supported, *pcFetched=0 (S_OK)", this)); // no attributes defined *pcFetched = 0; return S_OK; } STDMETHODIMP nsTextStore::GetEndACP(LONG *pacp) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetEndACP(pacp=0x%p)", this, pacp)); if (!IsReadLocked()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetEndACP() FAILED due to " "not locked (read)", this)); return TS_E_NOLOCK; } if (!pacp) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetEndACP() FAILED due to " "null argument", this)); return E_INVALIDARG; } // Flattened text is retrieved and its length returned nsQueryContentEvent event(true, NS_QUERY_TEXT_CONTENT, mWindow); mWindow->InitEvent(event); // Return entire text event.InitForQueryTextContent(0, INT32_MAX); mWindow->DispatchWindowEvent(&event); if (!event.mSucceeded) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetEndACP() FAILED due to " "NS_QUERY_TEXT_CONTENT failure", this)); return E_FAIL; } *pacp = LONG(event.mReply.mString.Length()); return S_OK; } #define TEXTSTORE_DEFAULT_VIEW (1) STDMETHODIMP nsTextStore::GetActiveView(TsViewCookie *pvcView) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetActiveView(pvcView=0x%p)", this, pvcView)); if (!pvcView) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetActiveView() FAILED due to " "null argument", this)); return E_INVALIDARG; } *pvcView = TEXTSTORE_DEFAULT_VIEW; PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetActiveView() succeeded: *pvcView=%ld", this, *pvcView)); return S_OK; } STDMETHODIMP nsTextStore::GetACPFromPoint(TsViewCookie vcView, const POINT *pt, DWORD dwFlags, LONG *pacp) { if (!IsReadLocked()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetACPFromPoint() FAILED due to " "not locked (read)", this)); return TS_E_NOLOCK; } if (vcView != TEXTSTORE_DEFAULT_VIEW) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetACPFromPoint() FAILED due to " "called with invalid view", this)); return E_INVALIDARG; } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetACPFromPoint(vcView=%ld, " "pt(0x%p)={ x=%ld, y=%ld }, dwFlags=%s, pacp=0x%p) called " "but not supported (E_NOTIMPL)", this)); // not supported for now return E_NOTIMPL; } STDMETHODIMP nsTextStore::GetTextExt(TsViewCookie vcView, LONG acpStart, LONG acpEnd, RECT *prc, BOOL *pfClipped) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetTextExt(vcView=%ld, " "acpStart=%ld, acpEnd=%ld, prc=0x%p, pfClipped=0x%p)", this, vcView, acpStart, acpEnd, prc, pfClipped)); if (!IsReadLocked()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetTextExt() FAILED due to " "not locked (read)", this)); return TS_E_NOLOCK; } if (vcView != TEXTSTORE_DEFAULT_VIEW) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetTextExt() FAILED due to " "called with invalid view", this)); return E_INVALIDARG; } if (!prc || !pfClipped) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetTextExt() FAILED due to " "null argument", this)); return E_INVALIDARG; } if (acpStart < 0 || acpEnd < acpStart) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetTextExt() FAILED due to " "invalid position", this)); return TS_E_INVALIDPOS; } // use NS_QUERY_TEXT_RECT to get rect in system, screen coordinates nsQueryContentEvent event(true, NS_QUERY_TEXT_RECT, mWindow); mWindow->InitEvent(event); event.InitForQueryTextRect(acpStart, acpEnd - acpStart); mWindow->DispatchWindowEvent(&event); if (!event.mSucceeded) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetTextExt() FAILED due to " "NS_QUERY_TEXT_RECT failure", this)); return TS_E_INVALIDPOS; // but unexpected failure, maybe. } // IMEs don't like empty rects, fix here if (event.mReply.mRect.width <= 0) event.mReply.mRect.width = 1; if (event.mReply.mRect.height <= 0) event.mReply.mRect.height = 1; // convert to unclipped screen rect nsWindow* refWindow = static_cast<nsWindow*>( event.mReply.mFocusedWidget ? event.mReply.mFocusedWidget : mWindow); // Result rect is in top level widget coordinates refWindow = refWindow->GetTopLevelWindow(false); if (!refWindow) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetTextExt() FAILED due to " "no top level window", this)); return E_FAIL; } event.mReply.mRect.MoveBy(refWindow->WidgetToScreenOffset()); // get bounding screen rect to test for clipping if (!GetScreenExtInternal(*prc)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetTextExt() FAILED due to " "GetScreenExtInternal() failure", this)); return E_FAIL; } // clip text rect to bounding rect RECT textRect; ::SetRect(&textRect, event.mReply.mRect.x, event.mReply.mRect.y, event.mReply.mRect.XMost(), event.mReply.mRect.YMost()); if (!::IntersectRect(prc, prc, &textRect)) // Text is not visible ::SetRectEmpty(prc); // not equal if text rect was clipped *pfClipped = !::EqualRect(prc, &textRect); PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetTextExt() succeeded: " "*prc={ left=%ld, top=%ld, right=%ld, bottom=%ld }, *pfClipped=%s", this, prc->left, prc->top, prc->right, prc->bottom, GetBoolName(*pfClipped))); return S_OK; } STDMETHODIMP nsTextStore::GetScreenExt(TsViewCookie vcView, RECT *prc) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetScreenExt(vcView=%ld, prc=0x%p)", this, vcView, prc)); if (vcView != TEXTSTORE_DEFAULT_VIEW) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetScreenExt() FAILED due to " "called with invalid view", this)); return E_INVALIDARG; } if (!prc) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetScreenExt() FAILED due to " "null argument", this)); return E_INVALIDARG; } if (!GetScreenExtInternal(*prc)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetScreenExt() FAILED due to " "GetScreenExtInternal() failure", this)); return E_FAIL; } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetScreenExt() succeeded: " "*prc={ left=%ld, top=%ld, right=%ld, bottom=%ld }", this, prc->left, prc->top, prc->right, prc->bottom)); return S_OK; } bool nsTextStore::GetScreenExtInternal(RECT &aScreenExt) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::GetScreenExtInternal()", this)); // use NS_QUERY_EDITOR_RECT to get rect in system, screen coordinates nsQueryContentEvent event(true, NS_QUERY_EDITOR_RECT, mWindow); mWindow->InitEvent(event); mWindow->DispatchWindowEvent(&event); if (!event.mSucceeded) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetScreenExtInternal() FAILED due to " "NS_QUERY_EDITOR_RECT failure", this)); return false; } nsWindow* refWindow = static_cast<nsWindow*>( event.mReply.mFocusedWidget ? event.mReply.mFocusedWidget : mWindow); // Result rect is in top level widget coordinates refWindow = refWindow->GetTopLevelWindow(false); if (!refWindow) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetScreenExtInternal() FAILED due to " "no top level window", this)); return false; } nsIntRect boundRect; if (NS_FAILED(refWindow->GetClientBounds(boundRect))) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetScreenExtInternal() FAILED due to " "failed to get the client bounds", this)); return false; } boundRect.MoveTo(0, 0); // Clip frame rect to window rect boundRect.IntersectRect(event.mReply.mRect, boundRect); if (!boundRect.IsEmpty()) { boundRect.MoveBy(refWindow->WidgetToScreenOffset()); ::SetRect(&aScreenExt, boundRect.x, boundRect.y, boundRect.XMost(), boundRect.YMost()); } else { ::SetRectEmpty(&aScreenExt); } PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::GetScreenExtInternal() succeeded: " "aScreenExt={ left=%ld, top=%ld, right=%ld, bottom=%ld }", this, aScreenExt.left, aScreenExt.top, aScreenExt.right, aScreenExt.bottom)); return true; } STDMETHODIMP nsTextStore::GetWnd(TsViewCookie vcView, HWND *phwnd) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetWnd(vcView=%ld, phwnd=0x%p), mWindow=0x%p", this, vcView, phwnd, mWindow)); if (vcView != TEXTSTORE_DEFAULT_VIEW) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetWnd() FAILED due to " "called with invalid view", this)); return E_INVALIDARG; } if (!phwnd) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::GetScreenExt() FAILED due to " "null argument", this)); return E_INVALIDARG; } *phwnd = mWindow->GetWindowHandle(); PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::GetWnd() succeeded: *phwnd=0x%p", this, static_cast<void*>(*phwnd))); return S_OK; } STDMETHODIMP nsTextStore::InsertTextAtSelection(DWORD dwFlags, const WCHAR *pchText, ULONG cch, LONG *pacpStart, LONG *pacpEnd, TS_TEXTCHANGE *pChange) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::InsertTextAtSelection(dwFlags=%s, " "pchText=0x%p \"%s\", cch=%lu, pacpStart=0x%p, pacpEnd=0x%p, " "pChange=0x%p), %s", this, dwFlags == 0 ? "0" : dwFlags == TF_IAS_NOQUERY ? "TF_IAS_NOQUERY" : dwFlags == TF_IAS_QUERYONLY ? "TF_IAS_QUERYONLY" : "Unknown", pchText, pchText && cch ? NS_ConvertUTF16toUTF8(pchText, cch).get() : "", cch, pacpStart, pacpEnd, pChange, mCompositionView ? "there is composition view" : "there is no composition view")); if (cch && !pchText) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelection() FAILED due to " "null pchText", this)); return E_INVALIDARG; } if (TS_IAS_QUERYONLY == dwFlags) { if (!IsReadLocked()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelection() FAILED due to " "not locked (read)", this)); return TS_E_NOLOCK; } if (!pacpStart || !pacpEnd) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelection() FAILED due to " "null argument", this)); return E_INVALIDARG; } // Get selection first TS_SELECTION_ACP sel; if (!GetSelectionInternal(sel)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelection() FAILED due to " "GetSelectionInternal() failure", this)); return E_FAIL; } // Simulate text insertion *pacpStart = sel.acpStart; *pacpEnd = sel.acpEnd; if (pChange) { pChange->acpStart = sel.acpStart; pChange->acpOldEnd = sel.acpEnd; pChange->acpNewEnd = sel.acpStart + cch; } } else { if (!IsReadWriteLocked()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelection() FAILED due to " "not locked (read-write)", this)); return TS_E_NOLOCK; } if (!pChange) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelection() FAILED due to " "null pChange", this)); return E_INVALIDARG; } if (TS_IAS_NOQUERY != dwFlags && (!pacpStart || !pacpEnd)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelection() FAILED due to " "null argument", this)); return E_INVALIDARG; } if (!InsertTextAtSelectionInternal(nsDependentString(pchText, cch), pChange)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelection() FAILED due to " "InsertTextAtSelectionInternal() failure", this)); return E_FAIL; } if (TS_IAS_NOQUERY != dwFlags) { *pacpStart = pChange->acpStart; *pacpEnd = pChange->acpNewEnd; } } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::InsertTextAtSelection() succeeded: " "*pacpStart=%ld, *pacpEnd=%ld, " "*pChange={ acpStart=%ld, acpOldEnd=%ld, acpNewEnd=%ld })", this, pacpStart ? *pacpStart : 0, pacpEnd ? *pacpEnd : 0, pChange ? pChange->acpStart: 0, pChange ? pChange->acpOldEnd : 0, pChange ? pChange->acpNewEnd : 0)); return S_OK; } bool nsTextStore::InsertTextAtSelectionInternal(const nsAString &aInsertStr, TS_TEXTCHANGE* aTextChange) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal(" "aInsertStr=\"%s\", aTextChange=0x%p), %s", this, NS_ConvertUTF16toUTF8(aInsertStr).get(), aTextChange, mCompositionView ? "there is composition view" : "there is no composition view")); TS_SELECTION_ACP oldSelection; oldSelection.acpStart = 0; oldSelection.acpEnd = 0; if (mCompositionView) { oldSelection = mCompositionSelection; // Emulate text insertion during compositions, because during a // composition, editor expects the whole composition string to // be sent in NS_TEXT_TEXT, not just the inserted part. // The actual NS_TEXT_TEXT will be sent in SetSelection or // OnUpdateComposition. mCompositionString.Replace( static_cast<uint32_t>(oldSelection.acpStart) - mCompositionStart, static_cast<uint32_t>(oldSelection.acpEnd - oldSelection.acpStart), aInsertStr); mCompositionSelection.acpStart += aInsertStr.Length(); mCompositionSelection.acpEnd = mCompositionSelection.acpStart; mCompositionSelection.style.ase = TS_AE_END; PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() replaced " "a part of (%lu-%lu) the composition string, waiting " "SetSelection() or OnUpdateComposition()...", this, oldSelection.acpStart - mCompositionStart, oldSelection.acpEnd - mCompositionStart)); } else { // Use actual selection if it's not composing. if (aTextChange && !GetSelectionInternal(oldSelection)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() FAILED " "due to GetSelectionInternal() failure", this)); return false; } // Use a temporary composition to contain the text PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() " "dispatching a compositionstart event...", this)); nsCompositionEvent compStartEvent(true, NS_COMPOSITION_START, mWindow); mWindow->InitEvent(compStartEvent); mWindow->DispatchWindowEvent(&compStartEvent); if (!mWindow || mWindow->Destroyed()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() FAILED " "due to the widget destroyed by compositionstart event", this)); return false; } if (!aInsertStr.IsEmpty()) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() " "dispatching a compositionupdate event...", this)); nsCompositionEvent compUpdateEvent(true, NS_COMPOSITION_UPDATE, mWindow); compUpdateEvent.data = aInsertStr; mWindow->DispatchWindowEvent(&compUpdateEvent); if (!mWindow || mWindow->Destroyed()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() " "FAILED due to the widget destroyed by compositionupdate event", this)); return false; } } PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() " "dispatching a text event...", this)); nsTextEvent textEvent(true, NS_TEXT_TEXT, mWindow); mWindow->InitEvent(textEvent); textEvent.theText = aInsertStr; textEvent.theText.ReplaceSubstring(NS_LITERAL_STRING("\r\n"), NS_LITERAL_STRING("\n")); mWindow->DispatchWindowEvent(&textEvent); if (!mWindow || mWindow->Destroyed()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() FAILED " "due to the widget destroyed by text event", this)); return false; } PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() " "dispatching a compositionend event...", this)); nsCompositionEvent compEndEvent(true, NS_COMPOSITION_END, mWindow); compEndEvent.data = aInsertStr; mWindow->DispatchWindowEvent(&compEndEvent); if (!mWindow || mWindow->Destroyed()) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() FAILED " "due to the widget destroyed by compositionend event", this)); return false; } } if (aTextChange) { aTextChange->acpStart = oldSelection.acpStart; aTextChange->acpOldEnd = oldSelection.acpEnd; // Get new selection TS_SELECTION_ACP newSelection; if (!GetSelectionInternal(newSelection)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() FAILED " "due to GetSelectionInternal() failure after inserted the text", this)); return false; } aTextChange->acpNewEnd = newSelection.acpEnd; } PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::InsertTextAtSelectionInternal() succeeded: " "mWindow=0x%p, mWindow->Destroyed()=%s, aTextChange={ acpStart=%ld, " "acpOldEnd=%ld, acpNewEnd=%ld }", this, mWindow, GetBoolName(mWindow ? mWindow->Destroyed() : true), aTextChange ? aTextChange->acpStart : 0, aTextChange ? aTextChange->acpOldEnd : 0, aTextChange ? aTextChange->acpNewEnd : 0)); return true; } STDMETHODIMP nsTextStore::InsertEmbeddedAtSelection(DWORD dwFlags, IDataObject *pDataObject, LONG *pacpStart, LONG *pacpEnd, TS_TEXTCHANGE *pChange) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::InsertEmbeddedAtSelection() called " "but not supported (E_NOTIMPL)", this)); // embedded objects are not supported return E_NOTIMPL; } HRESULT nsTextStore::OnStartCompositionInternal(ITfCompositionView* pComposition, ITfRange* aRange, bool aPreserveSelection) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::OnStartCompositionInternal(" "pComposition=0x%p, aRange=0x%p, aPreserveSelection=%s), " "mCompositionView=0x%p", this, pComposition, aRange, GetBoolName(aPreserveSelection), mCompositionView.get())); mCompositionView = pComposition; HRESULT hr = GetRangeExtent(aRange, &mCompositionStart, &mCompositionLength); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnStartCompositionInternal() FAILED due " "to GetRangeExtent() failure", this)); return hr; } PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::OnStartCompositionInternal(), " "mCompositionStart=%ld, mCompositionLength=%ld", this, mCompositionStart, mCompositionLength)); PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::OnStartCompositionInternal(), " "dispatching selectionset event...")); // Select composition range so the new composition replaces the range nsSelectionEvent selEvent(true, NS_SELECTION_SET, mWindow); mWindow->InitEvent(selEvent); selEvent.mOffset = uint32_t(mCompositionStart); selEvent.mLength = uint32_t(mCompositionLength); selEvent.mReversed = false; mWindow->DispatchWindowEvent(&selEvent); if (!selEvent.mSucceeded) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnStartCompositionInternal() FAILED due " "to NS_SELECTION_SET failure", this)); return E_FAIL; } // Set up composition nsQueryContentEvent queryEvent(true, NS_QUERY_SELECTED_TEXT, mWindow); mWindow->InitEvent(queryEvent); mWindow->DispatchWindowEvent(&queryEvent); if (!queryEvent.mSucceeded) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnStartCompositionInternal() FAILED due " "to NS_QUERY_SELECTED_TEXT failure", this)); return E_FAIL; } PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::OnStartCompositionInternal(), " "dispatching compositionstart event...")); mCompositionString = queryEvent.mReply.mString; if (!aPreserveSelection) { mCompositionSelection.acpStart = mCompositionStart; mCompositionSelection.acpEnd = mCompositionStart + mCompositionLength; mCompositionSelection.style.ase = TS_AE_END; mCompositionSelection.style.fInterimChar = FALSE; } nsCompositionEvent event(true, NS_COMPOSITION_START, mWindow); mWindow->InitEvent(event); mWindow->DispatchWindowEvent(&event); PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::OnStartCompositionInternal() succeeded: " "mCompositionStart=%ld, mCompositionLength=%ld, " "mCompositionSelection={ acpStart=%ld, acpEnd=%ld, style.ase=%s, " "style.iInterimChar=%s }", this, mCompositionStart, mCompositionLength, mCompositionSelection.acpStart, mCompositionSelection.acpEnd, GetActiveSelEndName(mCompositionSelection.style.ase), GetBoolName(mCompositionSelection.style.fInterimChar))); return S_OK; } static uint32_t GetLayoutChangeIntervalTime() { static int32_t sTime = -1; if (sTime > 0) return uint32_t(sTime); sTime = NS_MAX(10, Preferences::GetInt("intl.tsf.on_layout_change_interval", 100)); return uint32_t(sTime); } STDMETHODIMP nsTextStore::OnStartComposition(ITfCompositionView* pComposition, BOOL* pfOk) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnStartComposition(pComposition=0x%p, " "pfOk=0x%p), mCompositionView=0x%p", this, pComposition, pfOk, mCompositionView.get())); *pfOk = FALSE; // Only one composition at a time if (mCompositionView) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnStartComposition() FAILED due to " "there is another composition already (but returns S_OK)", this)); return S_OK; } nsRefPtr<ITfRange> range; HRESULT hr = pComposition->GetRange(getter_AddRefs(range)); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnStartComposition() FAILED due to " "pComposition->GetRange() failure", this)); return hr; } hr = OnStartCompositionInternal(pComposition, range, false); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnStartComposition() FAILED due to " "OnStartCompositionInternal() failure", this)); return hr; } NS_ASSERTION(!mCompositionTimer, "The timer is alive!"); mCompositionTimer = do_CreateInstance(NS_TIMER_CONTRACTID); if (mCompositionTimer) { mCompositionTimer->InitWithFuncCallback(CompositionTimerCallbackFunc, this, GetLayoutChangeIntervalTime(), nsITimer::TYPE_REPEATING_SLACK); } *pfOk = TRUE; PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnStartComposition() succeeded", this)); return S_OK; } STDMETHODIMP nsTextStore::OnUpdateComposition(ITfCompositionView* pComposition, ITfRange* pRangeNew) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnUpdateComposition(pComposition=0x%p, " "pRangeNew=0x%p), mCompositionView=0x%p", this, pComposition, pRangeNew, mCompositionView.get())); if (!mDocumentMgr || !mContext) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnUpdateComposition() FAILED due to " "not ready for the composition", this)); return E_UNEXPECTED; } if (!mCompositionView) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnUpdateComposition() FAILED due to " "no active composition", this)); return E_UNEXPECTED; } if (mCompositionView != pComposition) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnUpdateComposition() FAILED due to " "different composition view specified", this)); return E_UNEXPECTED; } // pRangeNew is null when the update is not complete if (!pRangeNew) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnUpdateComposition() succeeded but " "not complete", this)); return S_OK; } HRESULT hr = UpdateCompositionExtent(pRangeNew); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnUpdateComposition() FAILED due to " "UpdateCompositionExtent() failure", this)); return hr; } hr = SendTextEventForCompositionString(); if (FAILED(hr)) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnUpdateComposition() FAILED due to " "SendTextEventForCompositionString() failure", this)); return hr; } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnUpdateComposition() succeeded: " "mCompositionStart=%ld, mCompositionLength=%ld, " "mCompositionSelection={ acpStart=%ld, acpEnd=%ld, style.ase=%s, " "style.iInterimChar=%s }, mCompositionString=\"%s\"", this, mCompositionStart, mCompositionLength, mCompositionSelection.acpStart, mCompositionSelection.acpEnd, GetActiveSelEndName(mCompositionSelection.style.ase), GetBoolName(mCompositionSelection.style.fInterimChar), NS_ConvertUTF16toUTF8(mCompositionString).get())); return S_OK; } STDMETHODIMP nsTextStore::OnEndComposition(ITfCompositionView* pComposition) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnEndComposition(pComposition=0x%p), " "mCompositionView=0x%p, mCompositionString=\"%s\"", this, pComposition, mCompositionView.get(), NS_ConvertUTF16toUTF8(mCompositionString).get())); if (!mCompositionView) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnEndComposition() FAILED due to " "no active composition", this)); return E_UNEXPECTED; } if (mCompositionView != pComposition) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: 0x%p nsTextStore::OnEndComposition() FAILED due to " "different composition view specified", this)); return E_UNEXPECTED; } // Clear the saved text event SaveTextEvent(nullptr); if (mCompositionTimer) { mCompositionTimer->Cancel(); mCompositionTimer = nullptr; } if (mCompositionString != mLastDispatchedCompositionString) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnEndComposition(), " "dispatching compositionupdate event...", this)); nsCompositionEvent compositionUpdate(true, NS_COMPOSITION_UPDATE, mWindow); mWindow->InitEvent(compositionUpdate); compositionUpdate.data = mCompositionString; mLastDispatchedCompositionString = mCompositionString; mWindow->DispatchWindowEvent(&compositionUpdate); if (!mWindow || mWindow->Destroyed()) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnEndComposition(), " "succeeded, but the widget has gone", this)); return S_OK; } } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnEndComposition(), " "dispatching text event...", this)); // Use NS_TEXT_TEXT to commit composition string nsTextEvent textEvent(true, NS_TEXT_TEXT, mWindow); mWindow->InitEvent(textEvent); textEvent.theText = mCompositionString; textEvent.theText.ReplaceSubstring(NS_LITERAL_STRING("\r\n"), NS_LITERAL_STRING("\n")); mWindow->DispatchWindowEvent(&textEvent); if (!mWindow || mWindow->Destroyed()) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnEndComposition(), " "succeeded, but the widget has gone", this)); return S_OK; } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnEndComposition(), " "dispatching compositionend event...", this)); nsCompositionEvent event(true, NS_COMPOSITION_END, mWindow); event.data = mLastDispatchedCompositionString; mWindow->InitEvent(event); mWindow->DispatchWindowEvent(&event); if (!mWindow || mWindow->Destroyed()) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnEndComposition(), " "succeeded, but the widget has gone", this)); return S_OK; } mCompositionView = NULL; mCompositionString.Truncate(0); mLastDispatchedCompositionString.Truncate(); // Maintain selection SetSelectionInternal(&mCompositionSelection); PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnEndComposition(), succeeded", this)); return S_OK; } // static nsresult nsTextStore::OnFocusChange(bool aFocus, nsWindow* aWindow, IMEState::Enabled aIMEEnabled) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: nsTextStore::OnFocusChange(aFocus=%s, aWindow=0x%p, " "aIMEEnabled=%s), sTsfThreadMgr=0x%p, sTsfTextStore=0x%p", GetBoolName(aFocus), aWindow, GetIMEEnabledName(aIMEEnabled), sTsfThreadMgr, sTsfTextStore)); // no change notifications if TSF is disabled if (!sTsfThreadMgr || !sTsfTextStore) return NS_ERROR_NOT_AVAILABLE; if (aFocus) { bool bRet = sTsfTextStore->Create(aWindow, aIMEEnabled); NS_ENSURE_TRUE(bRet, NS_ERROR_FAILURE); NS_ENSURE_TRUE(sTsfTextStore->mDocumentMgr, NS_ERROR_FAILURE); HRESULT hr = sTsfThreadMgr->SetFocus(sTsfTextStore->mDocumentMgr); NS_ENSURE_TRUE(SUCCEEDED(hr), NS_ERROR_FAILURE); } else { sTsfTextStore->Destroy(); } return NS_OK; } nsresult nsTextStore::OnTextChangeInternal(uint32_t aStart, uint32_t aOldEnd, uint32_t aNewEnd) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::OnTextChangeInternal(aStart=%lu, " "aOldEnd=%lu, aNewEnd=%lu), mLock=%s, mSink=0x%p, mSinkMask=%s, " "mTextChange={ acpStart=%ld, acpOldEnd=%ld, acpNewEnd=%ld }", this, aStart, aOldEnd, aNewEnd, GetLockFlagNameStr(mLock).get(), mSink.get(), GetSinkMaskNameStr(mSinkMask).get(), mTextChange.acpStart, mTextChange.acpOldEnd, mTextChange.acpNewEnd)); if (!mLock && mSink && 0 != (mSinkMask & TS_AS_TEXT_CHANGE)) { mTextChange.acpStart = NS_MIN(mTextChange.acpStart, LONG(aStart)); mTextChange.acpOldEnd = NS_MAX(mTextChange.acpOldEnd, LONG(aOldEnd)); mTextChange.acpNewEnd = NS_MAX(mTextChange.acpNewEnd, LONG(aNewEnd)); ::PostMessageW(mWindow->GetWindowHandle(), WM_USER_TSF_TEXTCHANGE, 0, 0); } return NS_OK; } void nsTextStore::OnTextChangeMsgInternal(void) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::OnTextChangeMsgInternal(), mLock=%s, " "mSink=0x%p, mSinkMask=%s, mTextChange={ acpStart=%ld, " "acpOldEnd=%ld, acpNewEnd=%ld }", this, GetLockFlagNameStr(mLock).get(), mSink.get(), GetSinkMaskNameStr(mSinkMask).get(), mTextChange.acpStart, mTextChange.acpOldEnd, mTextChange.acpNewEnd)); if (!mLock && mSink && 0 != (mSinkMask & TS_AS_TEXT_CHANGE) && INT32_MAX > mTextChange.acpStart) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnTextChangeMsgInternal(), calling" "mSink->OnTextChange(0, { acpStart=%ld, acpOldEnd=%ld, " "acpNewEnd=%ld })...", this, mTextChange.acpStart, mTextChange.acpOldEnd, mTextChange.acpNewEnd)); mSink->OnTextChange(0, &mTextChange); mTextChange.acpStart = INT32_MAX; mTextChange.acpOldEnd = mTextChange.acpNewEnd = 0; } } nsresult nsTextStore::OnSelectionChangeInternal(void) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::OnSelectionChangeInternal(), mLock=%s, " "mSink=0x%p, mSinkMask=%s", this, GetLockFlagNameStr(mLock).get(), mSink.get(), GetSinkMaskNameStr(mSinkMask).get())); if (!mLock && mSink && 0 != (mSinkMask & TS_AS_SEL_CHANGE)) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnSelectionChangeInternal(), calling " "mSink->OnSelectionChange()...", this)); mSink->OnSelectionChange(); } return NS_OK; } nsresult nsTextStore::OnCompositionTimer() { NS_ENSURE_TRUE(mContext, NS_ERROR_FAILURE); NS_ENSURE_TRUE(mSink, NS_ERROR_FAILURE); // XXXmnakano We always call OnLayoutChange for now, but this might use CPU // power when the focused editor has very long text. Ideally, we should call // this only when the composition string screen position is changed by window // moving, resizing. And also reflowing and scrolling the contents. PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::OnCompositionTimer(), calling " "mSink->OnLayoutChange()...", this)); HRESULT hr = mSink->OnLayoutChange(TS_LC_CHANGE, TEXTSTORE_DEFAULT_VIEW); NS_ENSURE_TRUE(SUCCEEDED(hr), NS_ERROR_FAILURE); return NS_OK; } void nsTextStore::CommitCompositionInternal(bool aDiscard) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::CommitCompositionInternal(aDiscard=%s), " "mLock=%s, mSink=0x%p, mContext=0x%p, mCompositionView=0x%p, " "mCompositionString=\"%s\"", this, GetBoolName(aDiscard), GetLockFlagNameStr(mLock).get(), mSink.get(), mContext.get(), mCompositionView.get(), NS_ConvertUTF16toUTF8(mCompositionString).get())); if (mCompositionView && aDiscard) { mCompositionString.Truncate(0); if (mSink && !mLock) { TS_TEXTCHANGE textChange; textChange.acpStart = mCompositionStart; textChange.acpOldEnd = mCompositionStart + mCompositionLength; textChange.acpNewEnd = mCompositionStart; PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: 0x%p nsTextStore::CommitCompositionInternal(), calling" "mSink->OnTextChange(0, { acpStart=%ld, acpOldEnd=%ld, " "acpNewEnd=%ld })...", this, textChange.acpStart, textChange.acpOldEnd, textChange.acpNewEnd)); mSink->OnTextChange(0, &textChange); } } // Terminate two contexts, the base context (mContext) and the top // if the top context is not the same as the base context nsRefPtr<ITfContext> context = mContext; do { if (context) { nsRefPtr<ITfContextOwnerCompositionServices> services; context->QueryInterface(IID_ITfContextOwnerCompositionServices, getter_AddRefs(services)); if (services) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::CommitCompositionInternal(), " "requesting TerminateComposition() for the context 0x%p...", this, context.get())); services->TerminateComposition(NULL); } } if (context != mContext) break; if (mDocumentMgr) mDocumentMgr->GetTop(getter_AddRefs(context)); } while (context != mContext); } static bool GetCompartment(IUnknown* pUnk, const GUID& aID, ITfCompartment** aCompartment) { if (!pUnk) return false; nsRefPtr<ITfCompartmentMgr> compMgr; pUnk->QueryInterface(IID_ITfCompartmentMgr, getter_AddRefs(compMgr)); if (!compMgr) return false; return SUCCEEDED(compMgr->GetCompartment(aID, aCompartment)) && (*aCompartment) != NULL; } // static void nsTextStore::SetIMEOpenState(bool aState) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: nsTextStore::SetIMEOpenState(aState=%s)", GetBoolName(aState))); nsRefPtr<ITfCompartment> comp; if (!GetCompartment(sTsfThreadMgr, GUID_COMPARTMENT_KEYBOARD_OPENCLOSE, getter_AddRefs(comp))) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: nsTextStore::SetIMEOpenState() FAILED due to" "no compartment available")); return; } VARIANT variant; variant.vt = VT_I4; variant.lVal = aState; PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: nsTextStore::SetIMEOpenState(), setting " "0x%04X to GUID_COMPARTMENT_KEYBOARD_OPENCLOSE...", variant.lVal)); comp->SetValue(sTsfClientId, &variant); } // static bool nsTextStore::GetIMEOpenState(void) { nsRefPtr<ITfCompartment> comp; if (!GetCompartment(sTsfThreadMgr, GUID_COMPARTMENT_KEYBOARD_OPENCLOSE, getter_AddRefs(comp))) return false; VARIANT variant; ::VariantInit(&variant); if (SUCCEEDED(comp->GetValue(&variant)) && variant.vt == VT_I4) return variant.lVal != 0; ::VariantClear(&variant); // clear up in case variant.vt != VT_I4 return false; } void nsTextStore::SetInputContextInternal(IMEState::Enabled aState) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::SetInputContextInternal(aState=%s), " "mContext=0x%p", this, GetIMEEnabledName(aState), mContext.get())); VARIANT variant; variant.vt = VT_I4; variant.lVal = (aState != IMEState::ENABLED); // Set two contexts, the base context (mContext) and the top // if the top context is not the same as the base context nsRefPtr<ITfContext> context = mContext; nsRefPtr<ITfCompartment> comp; do { if (GetCompartment(context, GUID_COMPARTMENT_KEYBOARD_DISABLED, getter_AddRefs(comp))) { PR_LOG(sTextStoreLog, PR_LOG_DEBUG, ("TSF: 0x%p nsTextStore::SetInputContextInternal(), setting " "0x%04X to GUID_COMPARTMENT_KEYBOARD_DISABLED of context 0x%p...", this, variant.lVal, context.get())); comp->SetValue(sTsfClientId, &variant); } if (context != mContext) break; if (mDocumentMgr) mDocumentMgr->GetTop(getter_AddRefs(context)); } while (context != mContext); } // static void nsTextStore::Initialize(void) { #ifdef PR_LOGGING if (!sTextStoreLog) { sTextStoreLog = PR_NewLogModule("nsTextStoreWidgets"); } #endif bool enableTsf = Preferences::GetBool("intl.enable_tsf_support", false); PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: nsTextStore::Initialize(), TSF is %s", enableTsf ? "enabled" : "disabled")); if (!enableTsf) { return; } if (!sTsfThreadMgr) { if (SUCCEEDED(CoCreateInstance(CLSID_TF_ThreadMgr, NULL, CLSCTX_INPROC_SERVER, IID_ITfThreadMgr, reinterpret_cast<void**>(&sTsfThreadMgr)))) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: nsTextStore::Initialize() succeeded to " "create the thread manager, activating...")); if (FAILED(sTsfThreadMgr->Activate(&sTsfClientId))) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: nsTextStore::Initialize() FAILED to activate, " "releasing the thread manager...")); NS_RELEASE(sTsfThreadMgr); } } #ifdef PR_LOGGING else { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: nsTextStore::Initialize() FAILED to " "create the thread manager")); } #endif // #ifdef PR_LOGGING } if (sTsfThreadMgr && !sTsfTextStore) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: nsTextStore::Initialize() is creating " "an nsTextStore instance...")); sTsfTextStore = new nsTextStore(); } if (sTsfThreadMgr && !sDisplayAttrMgr) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: nsTextStore::Initialize() is creating " "a display attribute manager instance...")); HRESULT hr = ::CoCreateInstance(CLSID_TF_DisplayAttributeMgr, NULL, CLSCTX_INPROC_SERVER, IID_ITfDisplayAttributeMgr, reinterpret_cast<void**>(&sDisplayAttrMgr)); if (FAILED(hr) || !sDisplayAttrMgr) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: nsTextStore::Initialize() FAILED to create " "a display attribute manager instance")); } } if (sTsfThreadMgr && sDisplayAttrMgr && !sCategoryMgr) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: nsTextStore::Initialize() is creating " "a category manager instance...")); HRESULT hr = ::CoCreateInstance(CLSID_TF_CategoryMgr, NULL, CLSCTX_INPROC_SERVER, IID_ITfCategoryMgr, reinterpret_cast<void**>(&sCategoryMgr)); if (FAILED(hr) || !sCategoryMgr) { PR_LOG(sTextStoreLog, PR_LOG_ERROR, ("TSF: nsTextStore::Initialize() FAILED to create " "a category manager instance")); // release the display manager because it cannot work without the // category manager NS_RELEASE(sDisplayAttrMgr); } } if (sTsfThreadMgr && !sFlushTIPInputMessage) { sFlushTIPInputMessage = ::RegisterWindowMessageW( NS_LITERAL_STRING("Flush TIP Input Message").get()); } PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: nsTextStore::Initialize(), sTsfThreadMgr=0x%p, " "sTsfClientId=0x%08X, sTsfTextStore=0x%p, sDisplayAttrMgr=0x%p, " "sCategoryMgr=0x%p", sTsfThreadMgr, sTsfClientId, sTsfTextStore, sDisplayAttrMgr, sCategoryMgr)); } // static void nsTextStore::Terminate(void) { PR_LOG(sTextStoreLog, PR_LOG_ALWAYS, ("TSF: nsTextStore::Terminate()")); NS_IF_RELEASE(sDisplayAttrMgr); NS_IF_RELEASE(sCategoryMgr); NS_IF_RELEASE(sTsfTextStore); sTsfClientId = 0; if (sTsfThreadMgr) { sTsfThreadMgr->Deactivate(); NS_RELEASE(sTsfThreadMgr); } }
34.542069
84
0.648135
wilebeast
82d6a6123fcf3664d4a8f2e930bda06514fdff6f
320
cpp
C++
vs_plrlsght_cpp_fndmntls/vs_plrlsght_cpp_fndmntls/Resource.cpp
mugofjoe/cpp-journal
8b9f4d14343a2241ebe7def8b1f03062dae9caf6
[ "MIT" ]
null
null
null
vs_plrlsght_cpp_fndmntls/vs_plrlsght_cpp_fndmntls/Resource.cpp
mugofjoe/cpp-journal
8b9f4d14343a2241ebe7def8b1f03062dae9caf6
[ "MIT" ]
null
null
null
vs_plrlsght_cpp_fndmntls/vs_plrlsght_cpp_fndmntls/Resource.cpp
mugofjoe/cpp-journal
8b9f4d14343a2241ebe7def8b1f03062dae9caf6
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Resource.h" #include <iostream> using std::cout; using std::endl; using std::string; Resource::Resource(string n) :name(n) { cout << "constructing Resource object: " << name << endl; } Resource::~Resource(void) { cout << "destructing Resource object: " << name << endl; }
20
59
0.64375
mugofjoe
82d78efdc9af1a0230545fa4003afdc2c0bb975c
912
cpp
C++
ProjectEuler/ProjectEuler#1.cpp
ChameleonTartu/competitive_programming
f8658ba99e7d188c99692d03d52fe9652092ffc6
[ "Apache-2.0" ]
1
2016-08-19T12:14:07.000Z
2016-08-19T12:14:07.000Z
ProjectEuler/ProjectEuler#1.cpp
ChameleonTartu/competitive_programming
f8658ba99e7d188c99692d03d52fe9652092ffc6
[ "Apache-2.0" ]
null
null
null
ProjectEuler/ProjectEuler#1.cpp
ChameleonTartu/competitive_programming
f8658ba99e7d188c99692d03d52fe9652092ffc6
[ "Apache-2.0" ]
null
null
null
/* * ===================================================================================== * * Filename: ProjectEuler#1.cpp * * Description: * * Version: 1.0 * Created: 07/11/2016 12:27:05 PM * Revision: none * Compiler: gcc * * Author: DMYTRO CHASOVSKYI (), dmitriy.chasovskoy@gmail.com * Organization: * * ===================================================================================== */ #include <iostream> using namespace std; int main() { cout.sync_with_stdio(0); cin.tie(0); int tests; cin >> tests; for(int i = 0; i < tests; ++i) { unsigned long long n; cin >> n; --n; unsigned long long three = n/3, five = n/5, fifteen = n/15, sum = 0; sum += 3 * three * (three + 1)/2; sum += 5 * five * (five + 1)/2; sum -= 15 * fifteen * (fifteen + 1)/2; cout << sum << endl; } return 0; }
21.714286
88
0.416667
ChameleonTartu
82d8ba2a0cc8c64558242fe0159ce3cf81b413fc
28,976
cc
C++
storage/perfschema/table_events_waits.cc
hervewenjie/mysql
49a37eda4e2cc87e20ba99e2c29ffac2fc322359
[ "BSD-3-Clause" ]
null
null
null
storage/perfschema/table_events_waits.cc
hervewenjie/mysql
49a37eda4e2cc87e20ba99e2c29ffac2fc322359
[ "BSD-3-Clause" ]
null
null
null
storage/perfschema/table_events_waits.cc
hervewenjie/mysql
49a37eda4e2cc87e20ba99e2c29ffac2fc322359
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ /** @file storage/perfschema/table_events_waits.cc Table EVENTS_WAITS_xxx (implementation). */ #include "my_global.h" #include "my_pthread.h" #include "table_events_waits.h" #include "pfs_global.h" #include "pfs_instr_class.h" #include "pfs_instr.h" #include "pfs_events_waits.h" #include "pfs_timer.h" #include "m_string.h" THR_LOCK table_events_waits_current::m_table_lock; static const TABLE_FIELD_TYPE field_types[]= { { { C_STRING_WITH_LEN("THREAD_ID") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("EVENT_ID") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("END_EVENT_ID") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("EVENT_NAME") }, { C_STRING_WITH_LEN("varchar(128)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("SOURCE") }, { C_STRING_WITH_LEN("varchar(64)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("TIMER_START") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("TIMER_END") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("TIMER_WAIT") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("SPINS") }, { C_STRING_WITH_LEN("int(10)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("OBJECT_SCHEMA") }, { C_STRING_WITH_LEN("varchar(64)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("OBJECT_NAME") }, { C_STRING_WITH_LEN("varchar(512)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("INDEX_NAME") }, { C_STRING_WITH_LEN("varchar(64)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("OBJECT_TYPE") }, { C_STRING_WITH_LEN("varchar(64)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("OBJECT_INSTANCE_BEGIN") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("NESTING_EVENT_ID") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("NESTING_EVENT_TYPE") }, { C_STRING_WITH_LEN("enum(\'STATEMENT\',\'STAGE\',\'WAIT\'") }, { NULL, 0} }, { { C_STRING_WITH_LEN("OPERATION") }, { C_STRING_WITH_LEN("varchar(32)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("NUMBER_OF_BYTES") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("FLAGS") }, { C_STRING_WITH_LEN("int(10)") }, { NULL, 0} } }; TABLE_FIELD_DEF table_events_waits_current::m_field_def= { 19, field_types }; PFS_engine_table_share table_events_waits_current::m_share= { { C_STRING_WITH_LEN("events_waits_current") }, &pfs_truncatable_acl, &table_events_waits_current::create, NULL, /* write_row */ &table_events_waits_current::delete_all_rows, NULL, /* get_row_count */ 1000, /* records */ sizeof(pos_events_waits_current), /* ref length */ &m_table_lock, &m_field_def, false /* checked */ }; THR_LOCK table_events_waits_history::m_table_lock; PFS_engine_table_share table_events_waits_history::m_share= { { C_STRING_WITH_LEN("events_waits_history") }, &pfs_truncatable_acl, &table_events_waits_history::create, NULL, /* write_row */ &table_events_waits_history::delete_all_rows, NULL, /* get_row_count */ 1000, /* records */ sizeof(pos_events_waits_history), /* ref length */ &m_table_lock, &table_events_waits_current::m_field_def, false /* checked */ }; THR_LOCK table_events_waits_history_long::m_table_lock; PFS_engine_table_share table_events_waits_history_long::m_share= { { C_STRING_WITH_LEN("events_waits_history_long") }, &pfs_truncatable_acl, &table_events_waits_history_long::create, NULL, /* write_row */ &table_events_waits_history_long::delete_all_rows, NULL, /* get_row_count */ 10000, /* records */ sizeof(PFS_simple_index), /* ref length */ &m_table_lock, &table_events_waits_current::m_field_def, false /* checked */ }; table_events_waits_common::table_events_waits_common (const PFS_engine_table_share *share, void *pos) : PFS_engine_table(share, pos), m_row_exists(false) {} void table_events_waits_common::clear_object_columns() { m_row.m_object_type= NULL; m_row.m_object_type_length= 0; m_row.m_object_schema_length= 0; m_row.m_object_name_length= 0; m_row.m_index_name_length= 0; m_row.m_object_instance_addr= 0; } int table_events_waits_common::make_table_object_columns(volatile PFS_events_waits *wait) { uint safe_index; PFS_table_share *safe_table_share; safe_table_share= sanitize_table_share(wait->m_weak_table_share); if (unlikely(safe_table_share == NULL)) return 1; if (wait->m_object_type == OBJECT_TYPE_TABLE) { m_row.m_object_type= "TABLE"; m_row.m_object_type_length= 5; } else { m_row.m_object_type= "TEMPORARY TABLE"; m_row.m_object_type_length= 15; } if (safe_table_share->get_version() == wait->m_weak_version) { /* OBJECT SCHEMA */ m_row.m_object_schema_length= safe_table_share->m_schema_name_length; if (unlikely((m_row.m_object_schema_length == 0) || (m_row.m_object_schema_length > sizeof(m_row.m_object_schema)))) return 1; memcpy(m_row.m_object_schema, safe_table_share->m_schema_name, m_row.m_object_schema_length); /* OBJECT NAME */ m_row.m_object_name_length= safe_table_share->m_table_name_length; if (unlikely((m_row.m_object_name_length == 0) || (m_row.m_object_name_length > sizeof(m_row.m_object_name)))) return 1; memcpy(m_row.m_object_name, safe_table_share->m_table_name, m_row.m_object_name_length); /* INDEX NAME */ safe_index= wait->m_index; uint safe_key_count= sanitize_index_count(safe_table_share->m_key_count); if (safe_index < safe_key_count) { PFS_table_key *key= & safe_table_share->m_keys[safe_index]; m_row.m_index_name_length= key->m_name_length; if (unlikely((m_row.m_index_name_length == 0) || (m_row.m_index_name_length > sizeof(m_row.m_index_name)))) return 1; memcpy(m_row.m_index_name, key->m_name, m_row.m_index_name_length); } else m_row.m_index_name_length= 0; } else { m_row.m_object_schema_length= 0; m_row.m_object_name_length= 0; m_row.m_index_name_length= 0; } m_row.m_object_instance_addr= (intptr) wait->m_object_instance_addr; return 0; } int table_events_waits_common::make_file_object_columns(volatile PFS_events_waits *wait) { PFS_file *safe_file; safe_file= sanitize_file(wait->m_weak_file); if (unlikely(safe_file == NULL)) return 1; m_row.m_object_type= "FILE"; m_row.m_object_type_length= 4; m_row.m_object_schema_length= 0; m_row.m_object_instance_addr= (intptr) wait->m_object_instance_addr; if (safe_file->get_version() == wait->m_weak_version) { /* OBJECT NAME */ m_row.m_object_name_length= safe_file->m_filename_length; if (unlikely((m_row.m_object_name_length == 0) || (m_row.m_object_name_length > sizeof(m_row.m_object_name)))) return 1; memcpy(m_row.m_object_name, safe_file->m_filename, m_row.m_object_name_length); } else { m_row.m_object_name_length= 0; } m_row.m_index_name_length= 0; return 0; } int table_events_waits_common::make_socket_object_columns(volatile PFS_events_waits *wait) { PFS_socket *safe_socket; safe_socket= sanitize_socket(wait->m_weak_socket); if (unlikely(safe_socket == NULL)) return 1; m_row.m_object_type= "SOCKET"; m_row.m_object_type_length= 6; m_row.m_object_schema_length= 0; m_row.m_object_instance_addr= (intptr) wait->m_object_instance_addr; if (safe_socket->get_version() == wait->m_weak_version) { /* Convert port number to string, include delimiter in port name length */ uint port; char port_str[128]; char ip_str[INET6_ADDRSTRLEN+1]; uint ip_len= 0; port_str[0]= ':'; /* Get the IP address and port number */ ip_len= pfs_get_socket_address(ip_str, sizeof(ip_str), &port, &safe_socket->m_sock_addr, safe_socket->m_addr_len); /* Convert port number to a string (length includes ':') */ int port_len= int10_to_str(port, (port_str+1), 10) - port_str + 1; /* OBJECT NAME */ m_row.m_object_name_length= ip_len + port_len; if (unlikely((m_row.m_object_name_length == 0) || (m_row.m_object_name_length > sizeof(m_row.m_object_name)))) return 1; char *name= m_row.m_object_name; memcpy(name, ip_str, ip_len); memcpy(name + ip_len, port_str, port_len); } else { m_row.m_object_name_length= 0; } m_row.m_index_name_length= 0; return 0; } /** Build a row. @param thread_own_wait True if the memory for the wait is owned by pfs_thread @param pfs_thread the thread the cursor is reading @param wait the wait the cursor is reading */ void table_events_waits_common::make_row(bool thread_own_wait, PFS_thread *pfs_thread, volatile PFS_events_waits *wait) { pfs_lock lock; PFS_thread *safe_thread; PFS_instr_class *safe_class; const char *base; const char *safe_source_file; m_row_exists= false; safe_thread= sanitize_thread(pfs_thread); if (unlikely(safe_thread == NULL)) return; /* Protect this reader against a thread termination */ if (thread_own_wait) safe_thread->m_lock.begin_optimistic_lock(&lock); /* Design choice: We could have used a pfs_lock in PFS_events_waits here, to protect the reader from concurrent event generation, but this leads to too many pfs_lock atomic operations each time an event is recorded: - 1 dirty() + 1 allocated() per event start, for EVENTS_WAITS_CURRENT - 1 dirty() + 1 allocated() per event end, for EVENTS_WAITS_CURRENT - 1 dirty() + 1 allocated() per copy to EVENTS_WAITS_HISTORY - 1 dirty() + 1 allocated() per copy to EVENTS_WAITS_HISTORY_LONG or 8 atomics per recorded event. The problem is that we record a *lot* of events ... This code is prepared to accept *dirty* records, and sanitizes all the data before returning a row. */ /* PFS_events_waits::m_class needs to be sanitized, for race conditions when this code: - reads a new value in m_wait_class, - reads an old value in m_class. */ switch (wait->m_wait_class) { case WAIT_CLASS_IDLE: clear_object_columns(); safe_class= sanitize_idle_class(wait->m_class); break; case WAIT_CLASS_MUTEX: clear_object_columns(); safe_class= sanitize_mutex_class((PFS_mutex_class*) wait->m_class); break; case WAIT_CLASS_RWLOCK: clear_object_columns(); safe_class= sanitize_rwlock_class((PFS_rwlock_class*) wait->m_class); break; case WAIT_CLASS_COND: clear_object_columns(); safe_class= sanitize_cond_class((PFS_cond_class*) wait->m_class); break; case WAIT_CLASS_TABLE: if (make_table_object_columns(wait)) return; safe_class= sanitize_table_class(wait->m_class); break; case WAIT_CLASS_FILE: if (make_file_object_columns(wait)) return; safe_class= sanitize_file_class((PFS_file_class*) wait->m_class); break; case WAIT_CLASS_SOCKET: if (make_socket_object_columns(wait)) return; safe_class= sanitize_socket_class((PFS_socket_class*) wait->m_class); break; case NO_WAIT_CLASS: default: return; } if (unlikely(safe_class == NULL)) return; m_row.m_thread_internal_id= safe_thread->m_thread_internal_id; m_row.m_event_id= wait->m_event_id; m_row.m_end_event_id= wait->m_end_event_id; m_row.m_nesting_event_id= wait->m_nesting_event_id; m_row.m_nesting_event_type= wait->m_nesting_event_type; get_normalizer(safe_class); m_normalizer->to_pico(wait->m_timer_start, wait->m_timer_end, & m_row.m_timer_start, & m_row.m_timer_end, & m_row.m_timer_wait); m_row.m_name= safe_class->m_name; m_row.m_name_length= safe_class->m_name_length; /* We are assuming this pointer is sane, since it comes from __FILE__. */ safe_source_file= wait->m_source_file; if (unlikely(safe_source_file == NULL)) return; base= base_name(wait->m_source_file); m_row.m_source_length= my_snprintf(m_row.m_source, sizeof(m_row.m_source), "%s:%d", base, wait->m_source_line); if (m_row.m_source_length > sizeof(m_row.m_source)) m_row.m_source_length= sizeof(m_row.m_source); m_row.m_operation= wait->m_operation; m_row.m_number_of_bytes= wait->m_number_of_bytes; m_row.m_flags= wait->m_flags; if (thread_own_wait) { if (safe_thread->m_lock.end_optimistic_lock(&lock)) m_row_exists= true; } else { /* For EVENTS_WAITS_HISTORY_LONG (thread_own_wait is false), the wait record is always valid, because it is not stored in memory owned by pfs_thread. Even when the thread terminated, the record is mostly readable, so this record is displayed. */ m_row_exists= true; } } /** Operations names map, as displayed in the 'OPERATION' column. Indexed by enum_operation_type - 1. Note: enum_operation_type contains a more precise definition, since more details are needed internally by the instrumentation. Different similar operations (CLOSE vs STREAMCLOSE) are displayed with the same name 'close'. */ static const LEX_STRING operation_names_map[]= { /* Mutex operations */ { C_STRING_WITH_LEN("lock") }, { C_STRING_WITH_LEN("try_lock") }, /* RWLock operations */ { C_STRING_WITH_LEN("read_lock") }, { C_STRING_WITH_LEN("write_lock") }, { C_STRING_WITH_LEN("try_read_lock") }, { C_STRING_WITH_LEN("try_write_lock") }, /* Condition operations */ { C_STRING_WITH_LEN("wait") }, { C_STRING_WITH_LEN("timed_wait") }, /* File operations */ { C_STRING_WITH_LEN("create") }, { C_STRING_WITH_LEN("create") }, /* create tmp */ { C_STRING_WITH_LEN("open") }, { C_STRING_WITH_LEN("open") }, /* stream open */ { C_STRING_WITH_LEN("close") }, { C_STRING_WITH_LEN("close") }, /* stream close */ { C_STRING_WITH_LEN("read") }, { C_STRING_WITH_LEN("write") }, { C_STRING_WITH_LEN("seek") }, { C_STRING_WITH_LEN("tell") }, { C_STRING_WITH_LEN("flush") }, { C_STRING_WITH_LEN("stat") }, { C_STRING_WITH_LEN("stat") }, /* fstat */ { C_STRING_WITH_LEN("chsize") }, { C_STRING_WITH_LEN("delete") }, { C_STRING_WITH_LEN("rename") }, { C_STRING_WITH_LEN("sync") }, /* Table io operations */ { C_STRING_WITH_LEN("fetch") }, { C_STRING_WITH_LEN("insert") }, /* write row */ { C_STRING_WITH_LEN("update") }, /* update row */ { C_STRING_WITH_LEN("delete") }, /* delete row */ /* Table lock operations */ { C_STRING_WITH_LEN("read normal") }, { C_STRING_WITH_LEN("read with shared locks") }, { C_STRING_WITH_LEN("read high priority") }, { C_STRING_WITH_LEN("read no inserts") }, { C_STRING_WITH_LEN("write allow write") }, { C_STRING_WITH_LEN("write concurrent insert") }, { C_STRING_WITH_LEN("write delayed") }, { C_STRING_WITH_LEN("write low priority") }, { C_STRING_WITH_LEN("write normal") }, { C_STRING_WITH_LEN("read external") }, { C_STRING_WITH_LEN("write external") }, /* Socket operations */ { C_STRING_WITH_LEN("create") }, { C_STRING_WITH_LEN("connect") }, { C_STRING_WITH_LEN("bind") }, { C_STRING_WITH_LEN("close") }, { C_STRING_WITH_LEN("send") }, { C_STRING_WITH_LEN("recv") }, { C_STRING_WITH_LEN("sendto") }, { C_STRING_WITH_LEN("recvfrom") }, { C_STRING_WITH_LEN("sendmsg") }, { C_STRING_WITH_LEN("recvmsg") }, { C_STRING_WITH_LEN("seek") }, { C_STRING_WITH_LEN("opt") }, { C_STRING_WITH_LEN("stat") }, { C_STRING_WITH_LEN("shutdown") }, { C_STRING_WITH_LEN("select") }, /* Idle operations */ { C_STRING_WITH_LEN("idle") } }; int table_events_waits_common::read_row_values(TABLE *table, unsigned char *buf, Field **fields, bool read_all) { Field *f; const LEX_STRING *operation; compile_time_assert(COUNT_OPERATION_TYPE == array_elements(operation_names_map)); if (unlikely(! m_row_exists)) return HA_ERR_RECORD_DELETED; /* Set the null bits */ DBUG_ASSERT(table->s->null_bytes == 2); buf[0]= 0; buf[1]= 0; /* Some columns are unreliable, because they are joined with other buffers, which could have changed and been reused for something else. These columns are: - THREAD_ID (m_thread joins with PFS_thread), - SCHEMA_NAME (m_schema_name joins with PFS_table_share) - OBJECT_NAME (m_object_name joins with PFS_table_share) */ for (; (f= *fields) ; fields++) { if (read_all || bitmap_is_set(table->read_set, f->field_index)) { switch(f->field_index) { case 0: /* THREAD_ID */ set_field_ulonglong(f, m_row.m_thread_internal_id); break; case 1: /* EVENT_ID */ set_field_ulonglong(f, m_row.m_event_id); break; case 2: /* END_EVENT_ID */ if (m_row.m_end_event_id > 0) set_field_ulonglong(f, m_row.m_end_event_id - 1); else f->set_null(); break; case 3: /* EVENT_NAME */ set_field_varchar_utf8(f, m_row.m_name, m_row.m_name_length); break; case 4: /* SOURCE */ set_field_varchar_utf8(f, m_row.m_source, m_row.m_source_length); break; case 5: /* TIMER_START */ if (m_row.m_timer_start != 0) set_field_ulonglong(f, m_row.m_timer_start); else f->set_null(); break; case 6: /* TIMER_END */ if (m_row.m_timer_end != 0) set_field_ulonglong(f, m_row.m_timer_end); else f->set_null(); break; case 7: /* TIMER_WAIT */ if (m_row.m_timer_wait != 0) set_field_ulonglong(f, m_row.m_timer_wait); else f->set_null(); break; case 8: /* SPINS */ f->set_null(); break; case 9: /* OBJECT_SCHEMA */ if (m_row.m_object_schema_length > 0) { set_field_varchar_utf8(f, m_row.m_object_schema, m_row.m_object_schema_length); } else f->set_null(); break; case 10: /* OBJECT_NAME */ if (m_row.m_object_name_length > 0) { set_field_varchar_utf8(f, m_row.m_object_name, m_row.m_object_name_length); } else f->set_null(); break; case 11: /* INDEX_NAME */ if (m_row.m_index_name_length > 0) { set_field_varchar_utf8(f, m_row.m_index_name, m_row.m_index_name_length); } else f->set_null(); break; case 12: /* OBJECT_TYPE */ if (m_row.m_object_type) { set_field_varchar_utf8(f, m_row.m_object_type, m_row.m_object_type_length); } else f->set_null(); break; case 13: /* OBJECT_INSTANCE */ set_field_ulonglong(f, m_row.m_object_instance_addr); break; case 14: /* NESTING_EVENT_ID */ if (m_row.m_nesting_event_id != 0) set_field_ulonglong(f, m_row.m_nesting_event_id); else f->set_null(); break; case 15: /* NESTING_EVENT_TYPE */ if (m_row.m_nesting_event_id != 0) set_field_enum(f, m_row.m_nesting_event_type); else f->set_null(); break; case 16: /* OPERATION */ operation= &operation_names_map[(int) m_row.m_operation - 1]; set_field_varchar_utf8(f, operation->str, operation->length); break; case 17: /* NUMBER_OF_BYTES */ if ((m_row.m_operation == OPERATION_TYPE_FILEREAD) || (m_row.m_operation == OPERATION_TYPE_FILEWRITE) || (m_row.m_operation == OPERATION_TYPE_FILECHSIZE) || (m_row.m_operation == OPERATION_TYPE_SOCKETSEND) || (m_row.m_operation == OPERATION_TYPE_SOCKETRECV) || (m_row.m_operation == OPERATION_TYPE_SOCKETSENDTO) || (m_row.m_operation == OPERATION_TYPE_SOCKETRECVFROM)) set_field_ulonglong(f, m_row.m_number_of_bytes); else f->set_null(); break; case 18: /* FLAGS */ f->set_null(); break; default: DBUG_ASSERT(false); } } } return 0; } PFS_engine_table* table_events_waits_current::create(void) { return new table_events_waits_current(); } table_events_waits_current::table_events_waits_current() : table_events_waits_common(&m_share, &m_pos), m_pos(), m_next_pos() {} void table_events_waits_current::reset_position(void) { m_pos.reset(); m_next_pos.reset(); } int table_events_waits_current::rnd_next(void) { PFS_thread *pfs_thread; PFS_events_waits *wait; for (m_pos.set_at(&m_next_pos); m_pos.m_index_1 < thread_max; m_pos.next_thread()) { pfs_thread= &thread_array[m_pos.m_index_1]; if (! pfs_thread->m_lock.is_populated()) { /* This thread does not exist */ continue; } /* We do not show nested events for now, this will be revised with TABLE io */ // #define ONLY_SHOW_ONE_WAIT #ifdef ONLY_SHOW_ONE_WAIT if (m_pos.m_index_2 >= 1) continue; #else /* m_events_waits_stack[0] is a dummy record */ PFS_events_waits *top_wait = &pfs_thread->m_events_waits_stack[WAIT_STACK_BOTTOM]; wait= &pfs_thread->m_events_waits_stack[m_pos.m_index_2 + WAIT_STACK_BOTTOM]; PFS_events_waits *safe_current = pfs_thread->m_events_waits_current; if (safe_current == top_wait) { /* Display the last top level wait, when completed */ if (m_pos.m_index_2 >= 1) continue; } else { /* Display all pending waits, when in progress */ if (wait >= safe_current) continue; } #endif if (wait->m_wait_class == NO_WAIT_CLASS) { /* This locker does not exist. There can not be more lockers in the stack, skip to the next thread */ continue; } make_row(true, pfs_thread, wait); /* Next iteration, look for the next locker in this thread */ m_next_pos.set_after(&m_pos); return 0; } return HA_ERR_END_OF_FILE; } int table_events_waits_current::rnd_pos(const void *pos) { PFS_thread *pfs_thread; PFS_events_waits *wait; set_position(pos); DBUG_ASSERT(m_pos.m_index_1 < thread_max); pfs_thread= &thread_array[m_pos.m_index_1]; if (! pfs_thread->m_lock.is_populated()) return HA_ERR_RECORD_DELETED; #ifdef ONLY_SHOW_ONE_WAIT if (m_pos.m_index_2 >= 1) return HA_ERR_RECORD_DELETED; #else /* m_events_waits_stack[0] is a dummy record */ PFS_events_waits *top_wait = &pfs_thread->m_events_waits_stack[WAIT_STACK_BOTTOM]; wait= &pfs_thread->m_events_waits_stack[m_pos.m_index_2 + WAIT_STACK_BOTTOM]; PFS_events_waits *safe_current = pfs_thread->m_events_waits_current; if (safe_current == top_wait) { /* Display the last top level wait, when completed */ if (m_pos.m_index_2 >= 1) return HA_ERR_RECORD_DELETED; } else { /* Display all pending waits, when in progress */ if (wait >= safe_current) return HA_ERR_RECORD_DELETED; } #endif DBUG_ASSERT(m_pos.m_index_2 < WAIT_STACK_LOGICAL_SIZE); if (wait->m_wait_class == NO_WAIT_CLASS) return HA_ERR_RECORD_DELETED; make_row(true, pfs_thread, wait); return 0; } int table_events_waits_current::delete_all_rows(void) { reset_events_waits_current(); return 0; } PFS_engine_table* table_events_waits_history::create(void) { return new table_events_waits_history(); } table_events_waits_history::table_events_waits_history() : table_events_waits_common(&m_share, &m_pos), m_pos(), m_next_pos() {} void table_events_waits_history::reset_position(void) { m_pos.reset(); m_next_pos.reset(); } int table_events_waits_history::rnd_next(void) { PFS_thread *pfs_thread; PFS_events_waits *wait; if (events_waits_history_per_thread == 0) return HA_ERR_END_OF_FILE; for (m_pos.set_at(&m_next_pos); m_pos.m_index_1 < thread_max; m_pos.next_thread()) { pfs_thread= &thread_array[m_pos.m_index_1]; if (! pfs_thread->m_lock.is_populated()) { /* This thread does not exist */ continue; } if (m_pos.m_index_2 >= events_waits_history_per_thread) { /* This thread does not have more (full) history */ continue; } if ( ! pfs_thread->m_waits_history_full && (m_pos.m_index_2 >= pfs_thread->m_waits_history_index)) { /* This thread does not have more (not full) history */ continue; } if (pfs_thread->m_waits_history[m_pos.m_index_2].m_wait_class == NO_WAIT_CLASS) { /* This locker does not exist. There can not be more lockers in the stack, skip to the next thread */ continue; } wait= &pfs_thread->m_waits_history[m_pos.m_index_2]; make_row(true, pfs_thread, wait); /* Next iteration, look for the next history in this thread */ m_next_pos.set_after(&m_pos); return 0; } return HA_ERR_END_OF_FILE; } int table_events_waits_history::rnd_pos(const void *pos) { PFS_thread *pfs_thread; PFS_events_waits *wait; DBUG_ASSERT(events_waits_history_per_thread != 0); set_position(pos); DBUG_ASSERT(m_pos.m_index_1 < thread_max); pfs_thread= &thread_array[m_pos.m_index_1]; if (! pfs_thread->m_lock.is_populated()) return HA_ERR_RECORD_DELETED; DBUG_ASSERT(m_pos.m_index_2 < events_waits_history_per_thread); if ( ! pfs_thread->m_waits_history_full && (m_pos.m_index_2 >= pfs_thread->m_waits_history_index)) return HA_ERR_RECORD_DELETED; wait= &pfs_thread->m_waits_history[m_pos.m_index_2]; if (wait->m_wait_class == NO_WAIT_CLASS) return HA_ERR_RECORD_DELETED; make_row(true, pfs_thread, wait); return 0; } int table_events_waits_history::delete_all_rows(void) { reset_events_waits_history(); return 0; } PFS_engine_table* table_events_waits_history_long::create(void) { return new table_events_waits_history_long(); } table_events_waits_history_long::table_events_waits_history_long() : table_events_waits_common(&m_share, &m_pos), m_pos(0), m_next_pos(0) {} void table_events_waits_history_long::reset_position(void) { m_pos.m_index= 0; m_next_pos.m_index= 0; } int table_events_waits_history_long::rnd_next(void) { PFS_events_waits *wait; uint limit; if (events_waits_history_long_size == 0) return HA_ERR_END_OF_FILE; if (events_waits_history_long_full) limit= events_waits_history_long_size; else limit= events_waits_history_long_index % events_waits_history_long_size; for (m_pos.set_at(&m_next_pos); m_pos.m_index < limit; m_pos.next()) { wait= &events_waits_history_long_array[m_pos.m_index]; if (wait->m_wait_class != NO_WAIT_CLASS) { make_row(false, wait->m_thread, wait); /* Next iteration, look for the next entry */ m_next_pos.set_after(&m_pos); return 0; } } return HA_ERR_END_OF_FILE; } int table_events_waits_history_long::rnd_pos(const void *pos) { PFS_events_waits *wait; uint limit; if (events_waits_history_long_size == 0) return HA_ERR_RECORD_DELETED; set_position(pos); if (events_waits_history_long_full) limit= events_waits_history_long_size; else limit= events_waits_history_long_index % events_waits_history_long_size; if (m_pos.m_index >= limit) return HA_ERR_RECORD_DELETED; wait= &events_waits_history_long_array[m_pos.m_index]; if (wait->m_wait_class == NO_WAIT_CLASS) return HA_ERR_RECORD_DELETED; make_row(false, wait->m_thread, wait); return 0; } int table_events_waits_history_long::delete_all_rows(void) { reset_events_waits_history_long(); return 0; }
27.969112
97
0.671211
hervewenjie
82d9ec8e2f7e34826104e47fa7794f403330e2cd
6,048
cpp
C++
Tests/UnitTests/Sources/FunctionTest/BroadcastTest.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
6
2021-07-06T10:52:33.000Z
2021-12-30T11:30:04.000Z
Tests/UnitTests/Sources/FunctionTest/BroadcastTest.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
1
2022-01-07T12:18:03.000Z
2022-01-08T12:23:13.000Z
Tests/UnitTests/Sources/FunctionTest/BroadcastTest.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
3
2021-12-05T06:21:50.000Z
2022-01-09T12:44:23.000Z
// Copyright (c) 2021, Justin Kim // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <FunctionTest/BroadcastTest.hpp> #include <Sapphire/compute/BasicOps.hpp> #include <Sapphire/compute/Initialize.hpp> #include <Sapphire/util/Shape.hpp> #include <Sapphire/tensor/TensorData.hpp> #include <Sapphire/util/CudaDevice.hpp> #include <Sapphire/util/ResourceManager.hpp> #include <TestUtil.hpp> #include <iostream> #include <random> namespace Sapphire::Test { void BroadcastWithOneDimension(bool print) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distrib(1, 10); const int M = distrib(gen); const int N = distrib(gen); const int K = distrib(gen); const int batchSize = distrib(gen) % 3 + 1; //! Set shape so they can be broadcasted const Shape shapeA({ batchSize, 1, M, K }); const Shape shapeB({ batchSize, M, K, N }); const Shape shapeOut({ batchSize, M, M, N }); std::cout << "M : " << M << " N: " << N << " K: " << K << " batchSize : " << batchSize << std::endl; const CudaDevice cuda(0, "device0"); //! Initialize tensors with cuda mode TensorUtil::TensorData A(shapeA, Type::Dense, cuda); TensorUtil::TensorData B(shapeB, Type::Dense, cuda); TensorUtil::TensorData Out(shapeOut, Type::Dense, cuda); A.SetMode(ComputeMode::Host); B.SetMode(ComputeMode::Host); Out.SetMode(ComputeMode::Host); //! Initialize input tensors with normal distribution and output tensors as zeros Compute::Initialize::Normal(A, 10, 5); Compute::Initialize::Normal(B, 10, 5); Compute::Initialize::Zeros(Out); Compute::Gemm(Out, A, B); //! Set temporary buffer and copy the result auto* cpuGemmResult = new float[Out.HostTotalSize]; std::memcpy(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize * sizeof(float)); //! Initialize output with zeros Compute::Initialize::Zeros(Out); //! Send data to cuda A.ToCuda(); B.ToCuda(); Out.ToCuda(); //! Perform Gemm on cuda Compute::Gemm(Out, A, B); //! Send output data to host Out.ToHost(); //! Check for non zero equality CheckNoneZeroEquality(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize, print, 1.5f); delete[] cpuGemmResult; } void BroadcastWithMissingDimension(bool print) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distrib(1, 10); const int M = distrib(gen); const int N = distrib(gen); const int K = distrib(gen); //! Set shape so they can be broadcasted const Shape shapeA({ M, K }); const Shape shapeB({ M, K, N }); const Shape shapeOut({ M, M, N }); std::cout << "M : " << M << " N: " << N << " K: " << K << std::endl; const CudaDevice cuda(0, "device0"); //! Initialize tensors with cuda mode TensorUtil::TensorData A(shapeA, Type::Dense, cuda); TensorUtil::TensorData B(shapeB, Type::Dense, cuda); TensorUtil::TensorData Out(shapeOut, Type::Dense, cuda); A.SetMode(ComputeMode::Host); B.SetMode(ComputeMode::Host); Out.SetMode(ComputeMode::Host); //! Initialize input tensors with normal distribution and output tensors as //! zeros Compute::Initialize::Normal(A, 10, 5); Compute::Initialize::Normal(B, 10, 5); Compute::Initialize::Zeros(Out); //! Perform Gemm on host Compute::Gemm(Out, A, B); //! Set temporary buffer and copy the result auto* cpuGemmResult = new float[Out.HostTotalSize]; std::memcpy(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize * sizeof(float)); //! Initialize output with zeros Compute::Initialize::Zeros(Out); //! Send data to cuda A.ToCuda(); B.ToCuda(); Out.ToCuda(); //! Perform Gemm on cuda Compute::Gemm(Out, A, B); //! Send output data to host Out.ToHost(); //! Check for non zero equality CheckNoneZeroEquality(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize, print, 1.5f); delete[] cpuGemmResult; } void BroadcastMixed(bool print) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distrib(1, 10); const int M = distrib(gen); const int N = distrib(gen); const int K = distrib(gen); //! Set shape so they can be broadcasted const Shape shapeA({ M, K }); const Shape shapeB({ N, M, K, N }); const Shape shapeOut({ N, M, M, N }); std::cout << "M : " << M << " N: " << N << " K: " << K << std::endl; const CudaDevice cuda(0, "device0"); //! Initialize tensors with cuda mode TensorUtil::TensorData A(shapeA, Type::Dense, cuda); TensorUtil::TensorData B(shapeB, Type::Dense, cuda); TensorUtil::TensorData Out(shapeOut, Type::Dense, cuda); A.SetMode(ComputeMode::Host); B.SetMode(ComputeMode::Host); Out.SetMode(ComputeMode::Host); //! Initialize input tensors with normal distribution and output tensors //! as zeros Compute::Initialize::Normal(A, 10, 5); Compute::Initialize::Normal(B, 10, 5); Compute::Initialize::Zeros(Out); //! Perform Gemm on host Compute::Gemm(Out, A, B); //! Set temporary buffer and copy the result auto* cpuGemmResult = new float[Out.HostTotalSize]; std::memcpy(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize * sizeof(float)); //! Initialize output with zeros Compute::Initialize::Zeros(Out); //! Send data to cuda A.ToCuda(); B.ToCuda(); Out.ToCuda(); //! Perform Gemm on cuda Compute::Gemm(Out, A, B); //! Send output data to host Out.ToHost(); //! Check for non zero equality CheckNoneZeroEquality(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize, print, 1.5f); delete[] cpuGemmResult; } } // namespace Sapphire::Test
29.647059
85
0.636409
sukim96
82dae90f2be355927b6f9fec6a8e6c65ada1a099
526
cpp
C++
src/core/menu/default_behaviour.cpp
miguelalexbt/FEUP-CAL
ee417df5bb0150c2a289b100324b1f8d0086f634
[ "MIT" ]
null
null
null
src/core/menu/default_behaviour.cpp
miguelalexbt/FEUP-CAL
ee417df5bb0150c2a289b100324b1f8d0086f634
[ "MIT" ]
null
null
null
src/core/menu/default_behaviour.cpp
miguelalexbt/FEUP-CAL
ee417df5bb0150c2a289b100324b1f8d0086f634
[ "MIT" ]
null
null
null
#include "trip_planner/core/menu/default_behaviour.h" using namespace std; namespace trip_planner { int default_behaviour::display() { cout << " -- Trip Planner --" << endl << endl; cout << " [1] Start " << endl; cout << " [0] Exit. " << endl; cout << endl << " Input: "; string input; getline(cin, input); if (input.length() > 1) return 1; switch (input[0]) { case '0': return 0; case '1': break; default: return 1; } menu::instance().set_behaviour(CRITERIA); return 1; } }
15.470588
53
0.585551
miguelalexbt
82e1671d75e2ef454b2c17af1df7a2ffcab632f9
4,118
cpp
C++
discoFever/main.cpp
oskrs111/pimcw
6b40830b97ca7b6d2e5e7c50227ac7b2f5981749
[ "MIT" ]
2
2017-11-01T01:18:12.000Z
2017-12-13T06:04:00.000Z
discoFever/main.cpp
oskrs111/pimcw
6b40830b97ca7b6d2e5e7c50227ac7b2f5981749
[ "MIT" ]
null
null
null
discoFever/main.cpp
oskrs111/pimcw
6b40830b97ca7b6d2e5e7c50227ac7b2f5981749
[ "MIT" ]
1
2019-12-01T23:40:25.000Z
2019-12-01T23:40:25.000Z
#include "main.h" #include "networkthread.h" #include "../qtkVirtualMIDI/qtkvirtualmidi.h" void debugLogger(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); switch (type) { default: case QtInfoMsg: case QtDebugMsg: localMsg.prepend("DEBUG: "); fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); break; case QtWarningMsg: localMsg.prepend("WARNING: "); fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); break; case QtCriticalMsg: localMsg.prepend("CRITICAL: "); fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); break; case QtFatalMsg: localMsg.prepend("FATAL: "); fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); abort(); } localMsg.append("\r\n"); QFile f("debug.log"); f.open(QIODevice::Append); f.write(localMsg); f.close(); } static QtKApplicationParameters* g_appParameters = 0; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug() << "discoFever starting..."; g_appParameters = new QtKApplicationParameters(0,QString("discoFever")); if(g_appParameters->fileLoad(false)) { setDefaultParameters(); QString msg = "discoFever.cfg not found!\r\nSetting default configuration."; qDebug() << msg; a.exit(); } if(!g_appParameters->loadParam(QString("aplicacion"),QString("fileLog"),0).compare("1")) { qInstallMessageHandler(debugLogger); } qtkVirtualMIDI midi; networkThread network(QHostAddress(g_appParameters->loadParam(QString("network"),QString("udpHost"),0)), (quint16)g_appParameters->loadParam(QString("network"),QString("udpPort"),0).toInt(), (quint8)g_appParameters->loadParam(QString("network"),QString("statusRepeat"),0).toInt(), (quint8)g_appParameters->loadParam(QString("network"),QString("midiOffIgnore"),0).toInt(), (quint8)g_appParameters->loadParam(QString("network"),QString("midiChannelFilter"),0).toInt(), (quint8)g_appParameters->loadParam(QString("network"),QString("midiChannelFilterEnable"),0).toInt(), (quint8)g_appParameters->loadParam(QString("network"),QString("midiNoteOffset"),0).toInt()); switch(midi.getStatus()) { case stReady: QObject::connect(&midi,SIGNAL(midiReceived(midiMessage)),&network, SLOT(OnMidiReceived(midiMessage))); network.start(); qDebug() << "discoFever is ready to dance!"; return a.exec(); break; case stUnknown: case stClosed: case stError: default: qDebug() << "qtkVirtualMIDI error, status: " << midi.getStatus(); qDebug() << "discoFever will exit now..."; break; } return 0; } void setDefaultParameters() { //fileLog->Enables "1" or disables "0" debug log to file. g_appParameters->saveParam(QString("aplicacion"),QString("fileLog"),QString("0")); g_appParameters->saveParam(QString("network"),QString("udpHost"),QString("192.168.0.100")); g_appParameters->saveParam(QString("network"),QString("udpPort"),QString("12340")); g_appParameters->saveParam(QString("network"),QString("statusRepeat"),QString("3")); g_appParameters->saveParam(QString("network"),QString("midiOffIgnore"),QString("0")); g_appParameters->saveParam(QString("network"),QString("midiChannelFilter"),QString("0")); g_appParameters->saveParam(QString("network"),QString("midiChannelFilterEnable"),QString("0")); g_appParameters->saveParam(QString("network"),QString("midiNoteOffset"),QString("0")); g_appParameters->fileSave(); }
38.849057
126
0.63356
oskrs111
82e247eeecf88645ed78f119061fa3b1cf88ce6e
1,970
cpp
C++
src/test.cpp
tonyganchev/stoyozipxx
a19493d53a8c118e06003480b1614e5fa1cacb72
[ "Apache-2.0" ]
1
2019-11-25T17:02:51.000Z
2019-11-25T17:02:51.000Z
src/test.cpp
tonyganchev/stoyozipxx
a19493d53a8c118e06003480b1614e5fa1cacb72
[ "Apache-2.0" ]
null
null
null
src/test.cpp
tonyganchev/stoyozipxx
a19493d53a8c118e06003480b1614e5fa1cacb72
[ "Apache-2.0" ]
1
2019-11-11T11:11:02.000Z
2019-11-11T11:11:02.000Z
#include <iostream> #include <sstream> #include "buffer.hpp" #include "oligorithm.hpp" using namespace std; void test_find_longest_match(string needle, string haystack, size_t expected_length, size_t expected_start_idx) { auto m = szxx::find_longest_prefix(needle.begin(), needle.end(), haystack.begin(), haystack.end()); if (expected_length != m.second - m.first || (expected_length > 0 && expected_start_idx != m.first - haystack.begin())) { cout << "FAIL finding the expected prefix of '" << needle << "' in '" << haystack << "'.\n"; cout << "Instead matched '"; copy(m.first, m.second, ostream_iterator<char>(cout)); cout << "' of length " << m.second - m.first << "." << endl; } } int main() { stringstream is("sum dolor sit amet gatsi gatsi."); szxx::buffer buf{ 4u, 4u }; buf.push_back('L'); buf.push_back('o'); buf.push_back('r'); buf.push_back('e'); buf.push_back('m'); buf.push_back(' '); buf.push_back('i'); buf.push_back('p'); cout << buf << endl; while (!buf.lookahead_empty()) { cout << "--------------------------" << endl; cout << buf << endl; buf.forward(1u, is); cout << buf << endl; } test_find_longest_match("abc", "efghijk", 0, 0); test_find_longest_match("cde", "efghijk", 0, 0); test_find_longest_match("exyz", "efghijk", 1, 0); test_find_longest_match("efghijk", "efghijk", 7, 0); test_find_longest_match("abc", "efghijk", 0, 0); test_find_longest_match("", "efghijk", 0, 0); test_find_longest_match("efghijklmnop", "efghijk", 7, 0); test_find_longest_match("efghij", "efghijk", 6, 0); test_find_longest_match("ghij", "efghijk", 4, 2); test_find_longest_match("ghijk", "efghijk", 5, 2); test_find_longest_match("ghijkl", "efghijk", 5, 2); test_find_longest_match("kl", "efghijk", 1, 6); test_find_longest_match("f", "efghijk efghijk efghijk", 1, 1); return 0; }
32.833333
82
0.614721
tonyganchev
82e2cb8aaacffae8dbcfa3f9c0fb6cd461f1f59e
1,031
cpp
C++
Development_Platformer/Development_Platformer/GUIThumb.cpp
vsRushy/Development_Platformer
b9b6d3ce1611bd3e83d0dab2485c55d5acb32afe
[ "MIT" ]
1
2018-10-10T12:09:31.000Z
2018-10-10T12:09:31.000Z
Development_Platformer/Development_Platformer/GUIThumb.cpp
vsRushy/Development_Platformer
b9b6d3ce1611bd3e83d0dab2485c55d5acb32afe
[ "MIT" ]
null
null
null
Development_Platformer/Development_Platformer/GUIThumb.cpp
vsRushy/Development_Platformer
b9b6d3ce1611bd3e83d0dab2485c55d5acb32afe
[ "MIT" ]
null
null
null
#include "j1App.h" #include "j1Input.h" #include "j1GUIManager.h" #include "GUIElement.h" #include "GUIThumb.h" #include "p2Log.h" GUIThumb::GUIThumb(int x, int y, SDL_Rect image_area, SDL_Rect image_area_hover, SDL_Rect image_area_pressed, GUIElement* son) : GUIElement(type, x, y, area, son) { type = GUI_ELEMENT_TYPE::GUI_THUMB; initial_area = image_area; area = initial_area; img_area_hover = image_area_hover; img_area_pressed = image_area_pressed; } void GUIThumb::Update(float dt) { Click(); Move(); } void GUIThumb::Click() { int x, y; App->input->GetMousePosition(x, y); bool is_inside = x > position.x && x < position.x + initial_area.w && y > position.y && y < position.y + initial_area.h; if (is_inside) { if (App->input->GetMouseButtonDown(1) == SDL_PRESSED) { is_clicked = true; area = img_area_pressed; } else if (App->input->GetMouseButtonDown(1) == SDL_RELEASED) { is_clicked = false; area = img_area_hover; } } else { is_clicked = false; area = initial_area; } }
20.62
162
0.691562
vsRushy
82e5b49b726d3270932472e1c9c1a2ce689f8f6f
3,097
cpp
C++
alignmentstats.cpp
egafni/glia
700da972bf119284da8df868546e0034ebd79910
[ "MIT" ]
33
2015-03-03T22:33:07.000Z
2022-02-02T10:40:43.000Z
alignmentstats.cpp
egafni/glia
700da972bf119284da8df868546e0034ebd79910
[ "MIT" ]
2
2017-07-09T16:36:44.000Z
2021-08-16T19:43:37.000Z
alignmentstats.cpp
egafni/glia
700da972bf119284da8df868546e0034ebd79910
[ "MIT" ]
7
2016-04-21T12:23:28.000Z
2022-02-27T21:54:49.000Z
#include "alignmentstats.h" void countMismatchesAndGaps( BamAlignment& alignment, Cigar& cigar, string& referenceSequence, long int& referenceStart, AlignmentStats& stats, bool debug ) { int sp = alignment.Position - referenceStart; int rp = 0; int softclip_start = (cigar.begin()->type == 'S' ? cigar.begin()->length : 0); if (debug) { cerr << "pos : " << alignment.Position << endl; cerr << "ref : " << referenceSequence << endl; cerr << "ref : " << string(softclip_start, ' ') << referenceSequence.substr(sp, cigar.refLen()) << endl; cerr << "read : " << alignment.QueryBases << endl; cerr << "quals: " << alignment.Qualities << endl; cerr << "cigar: "; for (Cigar::const_iterator c = cigar.begin(); c != cigar.end(); ++c) { int l = c->length; char t = c->type; cerr << l << t; } cerr << endl; cerr << "starts at " << sp << " of cached ref (" << referenceSequence.size() << "bp long)" << endl; } if (alignment.Qualities.size() != alignment.QueryBases.size()) { cerr << "glia error: alignment has mismatch between length of aligned bases (" << alignment.QueryBases.size() << ") and length of qualities (" << alignment.Qualities.size() << ")" << endl; exit(1); } for (Cigar::const_iterator c = cigar.begin(); c != cigar.end(); ++c) { int l = c->length; char t = c->type; //cerr << l << t << " " << sp << " " << rp << endl; if (t == 'M') { // match or mismatch for (int i = 0; i < l; ++i) { if (alignment.QueryBases.at(rp) != referenceSequence.at(sp)) { ++stats.mismatches; //cerr << "trying to access qualities at " << rp << " they are " << alignment.Qualities.size() << " long" << endl; stats.mismatch_qsum += qualityChar2ShortInt(alignment.Qualities.at(rp)); } ++sp; ++rp; } } else if (t == 'D') { // deletion stats.gaps++; stats.gapslen += l; sp += l; // update reference sequence position } else if (t == 'I') { // insertion stats.gaps++; stats.gapslen += l; rp += l; // update read position } else if (t == 'S') { // soft clip, clipped sequence present in the read not matching the reference stats.softclips += l; for (int i = 0; i < l; ++i) { //cerr << "trying to access qualities at " << rp << " they are " << alignment.Qualities.size() << " long" << endl; stats.softclip_qsum += qualityChar2ShortInt(alignment.Qualities.at(rp)); ++rp; } } else if (t == 'H') { // hard clip on the read, clipped sequence is not present in the read } else if (t == 'N') { // skipped region in the reference not present in read, aka splice sp += l; } } }
39.202532
134
0.497578
egafni
82e5e7c61a71dae841dd78c1880c78673b750b27
7,789
cpp
C++
CCDFDataModel/CCDFDataModel.cpp
ernstdevreede/adaguc-server
3516bf1a2ea6abb4f2e85e72944589dfcc990f7c
[ "Apache-2.0" ]
1
2019-08-21T11:03:09.000Z
2019-08-21T11:03:09.000Z
CCDFDataModel/CCDFDataModel.cpp
ernstdevreede/adaguc-server
3516bf1a2ea6abb4f2e85e72944589dfcc990f7c
[ "Apache-2.0" ]
null
null
null
CCDFDataModel/CCDFDataModel.cpp
ernstdevreede/adaguc-server
3516bf1a2ea6abb4f2e85e72944589dfcc990f7c
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * * Project: Generic common data format * Purpose: Generic Data model to read netcdf and hdf5 * Author: Maarten Plieger, plieger "at" knmi.nl * Date: 2013-06-01 * ****************************************************************************** * * Copyright 2013, Royal Netherlands Meteorological Institute (KNMI) * * 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 "json_adaguc.h" #include "CCDFDataModel.h" #include "CCDFNetCDFIO.h" void CDF::_dumpPrintAttributes(const char *variableName, std::vector<CDF::Attribute *>attributes,CT::string *dumpString, int returnType){ //print attributes: for(size_t a=0;a<attributes.size();a++){ CDF::Attribute *attr=attributes[a]; if(attr->type!=CDF_STRING){ dumpString->printconcat("\t\t%s:%s =",variableName,attr->name.c_str()); }else{ dumpString->printconcat("\t\tstring %s:%s =",variableName,attr->name.c_str()); } //print data if(attr->type==CDF_CHAR){ char *data = new char[attr->length+1]; memcpy(data,attr->data,attr->length); data[attr->length]='\0'; dumpString->printconcat(" \"%s\"",data); //if(attr->type==CDF_UBYTE)dumpString->printconcat(" \"%s\"",data); //if(attr->type==CDF_BYTE)dumpString->printconcat(" \"%s\"",data); delete[] data; } if(attr->type==CDF_BYTE)for(size_t n=0;n<attr->length;n++)dumpString->printconcat(" %db",((char*)attr->data)[n]); if(attr->type==CDF_UBYTE)for(size_t n=0;n<attr->length;n++)dumpString->printconcat(" %uub",((unsigned char*)attr->data)[n]); if(attr->type==CDF_INT)for(size_t n=0;n<attr->length;n++)dumpString->printconcat(" %d",((int*)attr->data)[n]); if(attr->type==CDF_UINT)for(size_t n=0;n<attr->length;n++)dumpString->printconcat(" %u",((unsigned int*)attr->data)[n]); if(attr->type==CDF_INT64)for(size_t n=0;n<attr->length;n++)dumpString->printconcat(" %ldll",((long*)attr->data)[n]); if(attr->type==CDF_UINT64)for(size_t n=0;n<attr->length;n++)dumpString->printconcat(" %luul",((unsigned long*)attr->data)[n]); if(attr->type==CDF_SHORT)for(size_t n=0;n<attr->length;n++)dumpString->printconcat(" %d",((short*)attr->data)[n]); if(attr->type==CDF_USHORT)for(size_t n=0;n<attr->length;n++)dumpString->printconcat(" %u",((unsigned short*)attr->data)[n]); if(attr->type==CDF_FLOAT)for(size_t n=0;n<attr->length;n++)dumpString->printconcat(" %ff",((float*)attr->data)[n]); if(attr->type==CDF_DOUBLE)for(size_t n=0;n<attr->length;n++)dumpString->printconcat(" %fdf",((double*)attr->data)[n]); if(attr->type==CDF_STRING)for(size_t n=0;n<attr->length;n++)dumpString->printconcat(" \"%s\"",((char**)attr->data)[n]); dumpString->printconcat(" ;\n"); } } void CDF::_dump(CDF::Variable* cdfVariable,CT::string* dumpString, int returnType){ char temp[1024]; char dataTypeName[20]; CDF::getCDataTypeName(dataTypeName,19,cdfVariable->getNativeType()); snprintf(temp,1023,"\t%s %s",dataTypeName,cdfVariable->name.c_str()); dumpString->printconcat("%s",temp); if(cdfVariable->dimensionlinks.size()>0){ dumpString->printconcat("("); for(size_t i=0;i<cdfVariable->dimensionlinks.size();i++){ if(i>0&&i<cdfVariable->dimensionlinks.size())dumpString->printconcat(", "); dumpString->printconcat("%s",cdfVariable->dimensionlinks[i]->name.c_str()); } dumpString->printconcat(")"); } dumpString->printconcat(" ;\n"); _dumpPrintAttributes(cdfVariable->name.c_str(),cdfVariable->attributes, dumpString, returnType); } CT::string CDF::dump(CDFObject* cdfObject){ CT::string d; _dump(cdfObject, &d, CCDFDATAMODEL_DUMP_STANDARD); return d; } json convertCDFVariableToJSON(CDF::Variable *variable) { json variableJSON; json variableDimensionsJSON = json::array(); for(size_t i=0;i<variable->dimensionlinks.size();i++){ variableDimensionsJSON.push_back(variable->dimensionlinks[i]->name.c_str()); } json variableAttributesJSON = json::object(); for(size_t i=0;i<variable->attributes.size();i++){ CDF::Attribute *attr=variable->attributes[i]; if (!attr->name.equals("_NCProperties")) { /* The NetCDF library sometimes add their own attributes, skip those */ variableAttributesJSON[attr->name.c_str()] = attr->toString().c_str(); } } variableJSON["dimensions"] = variableDimensionsJSON; variableJSON["attributes"] = variableAttributesJSON; variableJSON["type"] = CDFNetCDFWriter::NCtypeConversionToString(variable->getNativeType()).c_str(); return variableJSON; } CT::string CDF::dumpAsJSON(CDFObject* cdfObject){ CT::string d; /* List dimensions */ json dimensionsJSON; for(size_t j=0;j<cdfObject->dimensions.size();j++){ json dimensionJSON; dimensionJSON = { {"length", cdfObject->dimensions[j]->getSize()} }; dimensionsJSON[cdfObject->dimensions[j]->name.c_str()] = dimensionJSON; } json resultJSON; resultJSON["dimensions"] = dimensionsJSON; /* List variables */ json variablesJSON; for(size_t j=0;j<cdfObject->variables.size();j++){ CDF::Variable *variable = cdfObject->variables[j]; variablesJSON[variable->name.c_str()] = convertCDFVariableToJSON(variable); variablesJSON["nc_global"] = convertCDFVariableToJSON(cdfObject); } resultJSON["variables"] = variablesJSON; d = resultJSON.dump(2).c_str(); return d; } CT::string CDF::dump(CDF::Variable* cdfVariable) { CT::string d; _dump(cdfVariable, &d, CCDFDATAMODEL_DUMP_STANDARD); return d; } void CDF::_dump(CDFObject* cdfObject,CT::string* dumpString, int returnType){ //print dimensions: char temp[1024]; char dataTypeName[20]; dumpString->copy("CCDFDataModel {\ndimensions:\n"); for(size_t j=0;j<cdfObject->dimensions.size();j++){ snprintf(temp,1023,"%s",cdfObject->dimensions[j]->name.c_str()); dumpString->printconcat("\t%s = %d ;\n",temp,int(cdfObject->dimensions[j]->length)); } dumpString->printconcat("variables:\n"); for(size_t j=0;j<cdfObject->variables.size();j++){ { CDF::getCDataTypeName(dataTypeName,19,cdfObject->variables[j]->getNativeType()); snprintf(temp,1023,"\t%s %s",dataTypeName,cdfObject->variables[j]->name.c_str()); dumpString->printconcat("%s",temp); if(cdfObject->variables[j]->dimensionlinks.size()>0){ dumpString->printconcat("("); for(size_t i=0;i<cdfObject->variables[j]->dimensionlinks.size();i++){ if(i>0&&i<cdfObject->variables[j]->dimensionlinks.size())dumpString->printconcat(", "); dumpString->printconcat("%s",cdfObject->variables[j]->dimensionlinks[i]->name.c_str()); } dumpString->printconcat(")"); } dumpString->printconcat(" ;\n"); //print attributes: _dumpPrintAttributes(cdfObject->variables[j]->name.c_str(), cdfObject->variables[j]->attributes, dumpString, returnType); } } //print GLOBAL attributes: dumpString->concat("\n// global attributes:\n"); _dumpPrintAttributes("",cdfObject->attributes,dumpString, returnType); dumpString->concat("}\n"); }
43.513966
137
0.650019
ernstdevreede
82e7dfaa6b8e56ed5cda49b057e9012cb81bbe82
14,113
cpp
C++
src/temporal_diff.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
null
null
null
src/temporal_diff.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
2
2020-11-06T19:45:34.000Z
2020-11-07T03:22:25.000Z
src/temporal_diff.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
null
null
null
/************************************************ 3D Wavlet Libraries for pcvipr.e Initial Author: Kevin M. Johnson Description: This code controls transfroms in the non-spatial dimensions *************************************************/ #include "temporal_diff.h" using namespace NDarray; using arma::cx_mat; using arma::cx_vec; TRANSFORMS::TRANSFORMS() { reinit_pca = true; pca_count = 0; } void TRANSFORMS::get_difference_transform(cx_mat &A, cx_mat &Ai, int N) { A.zeros(N, N); Ai.zeros(N, N); for (int i = 0; i < N; i++) { A(0, i) = 1.0; } for (int i = 1; i < N; i++) { A(i, i - 1) = 1.0; A(i, i) = -1.0; } Ai = A.i(); return; } void TRANSFORMS::get_wavelet_transform(cx_mat &A, cx_mat &Ai, int N) { A.zeros(N, N); Ai.zeros(N, N); int levels = (int)log2((double)N); // cout << "Levels = " << levels << endl; for (int level = 0; level < levels; level++) { // R is the center of the matrix int R = (int)(0.5 * (float)N / pow((float)2.0, (float)level)); int span = (int)pow(2.0f, (float)level); for (int i = 0; i < R; i++) { int offset = 2 * span * i; // Zero the rows for (int j = 0; j < N; j++) { A(i, j) = complex<float>(0.0, 0.0); A(i + R, j) = complex<float>(0.0, 0.0); } // Set the average for (int j = offset; j < offset + 2 * span; j++) { A(i, j) = 1.0; } // Set the difference for (int j = offset; j < offset + span; j++) { A(i + R, j) = 1.0; A(i + R, j + span) = -1.0; } } // A.print("A-wavelet"); } // Normalize for (int i = 0; i < N; i++) { float temp = 0.0; for (int j = 0; j < N; j++) { temp += norm(A(i, j)); } temp = sqrt(temp); for (int j = 0; j < N; j++) { A(i, j) /= temp; } } // A.print("A-noramlize wavelet"); Ai = A.i(); return; } void TRANSFORMS::tdiff(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(firstDim) == 1) { return; } cx_mat A; cx_mat Ai; get_difference_transform(A, Ai, temp.length(firstDim)); multiply_in_time(temp, A); return; } void TRANSFORMS::inv_tdiff(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(firstDim) == 1) { return; } cx_mat A; cx_mat Ai; get_difference_transform(A, Ai, temp.length(firstDim)); multiply_in_time(temp, Ai); return; } void TRANSFORMS::twave(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(firstDim) == 1) { return; } cx_mat A; cx_mat Ai; get_wavelet_transform(A, Ai, temp.length(firstDim)); multiply_in_time(temp, A); return; } void TRANSFORMS::inv_twave(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(firstDim) == 1) { return; } cx_mat A; cx_mat Ai; get_wavelet_transform(A, Ai, temp.length(firstDim)); multiply_in_time(temp, Ai); return; } void TRANSFORMS::ediff(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(secondDim) == 1) { return; } cx_mat A; cx_mat Ai; get_difference_transform(A, Ai, temp.length(secondDim)); multiply_in_encode(temp, A); return; } void TRANSFORMS::inv_ediff(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(secondDim) == 1) { return; } cx_mat A; cx_mat Ai; get_difference_transform(A, Ai, temp.length(secondDim)); multiply_in_encode(temp, Ai); return; } void TRANSFORMS::ewave(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(secondDim) == 1) { return; } cx_mat A; cx_mat Ai; get_wavelet_transform(A, Ai, temp.length(secondDim)); multiply_in_encode(temp, A); return; } void TRANSFORMS::inv_ewave(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(secondDim) == 1) { return; } cx_mat A; cx_mat Ai; get_wavelet_transform(A, Ai, temp.length(secondDim)); multiply_in_encode(temp, Ai); return; } //----------------------------------------------------- // Clear Threshold Call //----------------------------------------------------- void TRANSFORMS::eigen(Array<Array<complex<float>, 3>, 2> &image, int dim, int direction) { pca_count++; if (reinit_pca && (direction == FORWARD)) { if (pca_count > 5) { reinit_pca = false; } // Shorthand int Nt = image.extent(firstDim); int Ne = image.extent(secondDim); int Nx = image(0, 0).extent(firstDim); int Ny = image(0, 0).extent(secondDim); int Nz = image(0, 0).extent(thirdDim); int block_size_x = 8; int block_size_y = 8; int block_size_z = 8; block_size_x = (block_size_x > Nx) ? (Nx) : (block_size_x); block_size_y = (block_size_y > Ny) ? (Ny) : (block_size_y); block_size_z = (block_size_z > Nz) ? (Nz) : (block_size_z); int block_Nx = (int)(Nx / block_size_x); int block_Ny = (int)(Ny / block_size_y); int block_Nz = (int)(Nz / block_size_z); int total_blocks = block_Nx * block_Ny * block_Nz; /* Get Image Size*/ int N = image.extent(dim); int Np = total_blocks; cout << " Learning Eigen Mat (N=" << N << ")(Np = " << Np << ")" << endl; // For nested parallelism fix int count = 0; arma::Col<int> act_i(total_blocks); arma::Col<int> act_j(total_blocks); arma::Col<int> act_k(total_blocks); for (int i = 0; i < block_Nx; i++) { for (int j = 0; j < block_Ny; j++) { for (int k = 0; k < block_Nz; k++) { act_i(count) = i; act_j(count) = j; act_k(count) = k; count++; } } } // Storage Block arma::cx_mat A; A.zeros(Np, N); cout << "Collecting Blocks" << endl; #pragma omp parallel for for (int block = 0; block < total_blocks; block++) { // Nested parallelism workaround int i = act_i(block) * block_size_x; int j = act_j(block) * block_size_y; int k = act_k(block) * block_size_z; //----------------------------------------------------- // Block Gather //----------------------------------------------------- switch (dim) { case (0): { for (int t = 0; t < Nt; t++) { for (int e = 0; e < Ne; e++) { for (int kk = (k); kk < (k + block_size_z); kk++) { for (int jj = (j); jj < (j + block_size_y); jj++) { for (int ii = (i); ii < (i + block_size_x); ii++) { int px = (ii + Nx) % Nx; int py = (jj + Ny) % Ny; int pz = (kk + Nz) % Nz; A(block, t) += image(t, e)(px, py, pz); } } } } } } break; case (1): { for (int e = 0; e < Ne; e++) { for (int t = 0; t < Nt; t++) { for (int kk = (k); kk < (k + block_size_z); kk++) { for (int jj = (j); jj < (j + block_size_y); jj++) { for (int ii = (i); ii < (i + block_size_x); ii++) { int px = (ii + Nx) % Nx; int py = (jj + Ny) % Ny; int pz = (kk + Nz) % Nz; A(block, e) += image(t, e)(px, py, pz); } } } } } } break; } // Switch Dim } // Block Loop cout << "Learning PCA " << endl; arma::cx_mat U; arma::cx_mat V; arma::vec s; arma::svd_econ(U, s, V, A); cx_mat wV = diagmat(s) * V.t(); E = wV; Ei = wV.i(); } /* Reinit PCA*/ if (dim == 0) { if (direction == FORWARD) { multiply_in_time(image, E); } else { multiply_in_time(image, Ei); } } else { if (direction == FORWARD) { multiply_in_encode(image, E); } else { multiply_in_encode(image, Ei); } } if (direction == FORWARD) { if (image.numElements() > 1) { int count = 0; for (Array<Array<complex<float>, 3>, 2>::iterator miter = image.begin(); miter != image.end(); miter++) { Array<complex<float>, 2> Xf = (*miter)(Range::all(), Range::all(), image(0, 0).length(2) / 2); if (count == 0) { ArrayWriteMag(Xf, "Xtrans_frames.dat"); } else { ArrayWriteMagAppend(Xf, "Xtrans_frames.dat"); } count++; } } } } void TRANSFORMS::multiply_in_time(Array<Array<complex<float>, 3>, 2> &temp, cx_mat A) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); for (int e = 0; e < Ne; e++) { #pragma omp parallel for for (int k = 0; k < Nz; k++) { cx_vec s(Nt); cx_vec ss(Nt); for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int t = 0; t < Nt; t++) { s(t) = temp(t, e)(i, j, k); } // Transform ss = A * s; // Copy Back for (int t = 0; t < Nt; t++) { temp(t, e)(i, j, k) = ss(t); } } } } } return; } void TRANSFORMS::multiply_in_encode(Array<Array<complex<float>, 3>, 2> &temp, cx_mat A) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); for (int t = 0; t < Nt; t++) { #pragma omp parallel for for (int k = 0; k < Nz; k++) { cx_vec s(Ne); cx_vec ss(Ne); for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int e = 0; e < Ne; e++) { s(e) = temp(t, e)(i, j, k); } // Transform ss = A * s; // Copy Back for (int e = 0; e < Ne; e++) { temp(t, e)(i, j, k) = ss(e); } } } } } return; } void TRANSFORMS::fft_t(Array<Array<complex<float>, 3>, 2> &temp) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); fftwf_plan p; complex<float> *in = new complex<float>[Nt]; // fftwf_init_threads(); // fftwf_plan_with_nthreads(1); p = fftwf_plan_dft_1d(Nt, (fftwf_complex *)in, (fftwf_complex *)in, FFTW_FORWARD, FFTW_MEASURE); float fft_scale = 1 / sqrt(Nt); for (int e = 0; e < Ne; e++) { for (int k = 0; k < Nz; k++) { for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int t = 0; t < Nt; t++) { in[t] = temp(t, e)(i, j, k); } fftwf_execute(p); // Copy Back for (int t = 0; t < Nt; t++) { temp(t, e)(i, j, k) = (fft_scale * in[t]); } } } } } fftwf_destroy_plan(p); delete[] in; return; } void TRANSFORMS::ifft_t(Array<Array<complex<float>, 3>, 2> &temp) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); fftwf_plan p; complex<float> *in = new complex<float>[Nt]; // fftwf_init_threads(); // fftwf_plan_with_nthreads(1); p = fftwf_plan_dft_1d(Nt, (fftwf_complex *)in, (fftwf_complex *)in, FFTW_BACKWARD, FFTW_MEASURE); float fft_scale = 1 / sqrt(Nt); for (int e = 0; e < Ne; e++) { for (int k = 0; k < Nz; k++) { for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int t = 0; t < Nt; t++) { in[t] = temp(t, e)(i, j, k); } fftwf_execute(p); // Copy Back for (int t = 0; t < Nt; t++) { temp(t, e)(i, j, k) = (fft_scale * in[t]); } } } } } fftwf_destroy_plan(p); delete[] in; return; } void TRANSFORMS::fft_e(Array<Array<complex<float>, 3>, 2> &temp) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); fftwf_plan p; complex<float> *in = new complex<float>[Ne]; // fftwf_init_threads(); // fftwf_plan_with_nthreads(1); p = fftwf_plan_dft_1d(Ne, (fftwf_complex *)in, (fftwf_complex *)in, FFTW_FORWARD, FFTW_MEASURE); float fft_scale = 1 / sqrt(Ne); for (int t = 0; t < Nt; t++) { for (int k = 0; k < Nz; k++) { for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int e = 0; e < Ne; e++) { in[e] = temp(t, e)(i, j, k); } fftwf_execute(p); // Copy Back for (int e = 0; e < Ne; e++) { temp(t, e)(i, j, k) = (fft_scale * in[e]); } } } } } fftwf_destroy_plan(p); delete[] in; return; } void TRANSFORMS::ifft_e(Array<Array<complex<float>, 3>, 2> &temp) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); fftwf_plan p; complex<float> *in = new complex<float>[Ne]; // fftwf_init_threads(); // fftwf_plan_with_nthreads(1); p = fftwf_plan_dft_1d(Ne, (fftwf_complex *)in, (fftwf_complex *)in, FFTW_BACKWARD, FFTW_MEASURE); float fft_scale = 1 / sqrt(Ne); for (int t = 0; t < Nt; t++) { for (int k = 0; k < Nz; k++) { for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int e = 0; e < Ne; e++) { in[e] = temp(t, e)(i, j, k); } fftwf_execute(p); // Copy Back for (int e = 0; e < Ne; e++) { temp(t, e)(i, j, k) = (fft_scale * in[e]); } } } } } fftwf_destroy_plan(p); delete[] in; return; }
24.416955
78
0.489124
uwmri
82e9519183a5fb683af7b80b261fdcc518f15543
12,327
cpp
C++
src/wrapper/store/provider_cryptopro.cpp
microshine/trusted-crypto
22a6496bd390ebe2ed516a15636d911fae4c6407
[ "Apache-2.0" ]
null
null
null
src/wrapper/store/provider_cryptopro.cpp
microshine/trusted-crypto
22a6496bd390ebe2ed516a15636d911fae4c6407
[ "Apache-2.0" ]
null
null
null
src/wrapper/store/provider_cryptopro.cpp
microshine/trusted-crypto
22a6496bd390ebe2ed516a15636d911fae4c6407
[ "Apache-2.0" ]
1
2020-07-01T16:32:57.000Z
2020-07-01T16:32:57.000Z
#include "../stdafx.h" #include "provider_cryptopro.h" ProviderCryptopro::ProviderCryptopro(){ LOGGER_FN(); try{ type = new std::string("CRYPTOPRO"); providerItemCollection = new PkiItemCollection(); init(); } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Cannot be constructed ProviderCryptopro"); } } void ProviderCryptopro::init(){ LOGGER_FN(); try{ std::string listStore[] = { "MY", "AddressBook", "ROOT", "TRUST", "CA", "Request" }; HCERTSTORE hCertStore; for (int i = 0, c = sizeof(listStore) / sizeof(*listStore); i < c; i++){ std::wstring widestr = std::wstring(listStore[i].begin(), listStore[i].end()); hCertStore = CertOpenStore( CERT_STORE_PROV_SYSTEM, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, NULL, CERT_SYSTEM_STORE_CURRENT_USER, widestr.c_str() ); if (!hCertStore) { THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Error open store"); } enumCertificates(hCertStore, &listStore[i]); enumCrls(hCertStore, &listStore[i]); if (hCertStore) { CertCloseStore(hCertStore, 0); } } } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error init CryptoPRO provider"); } } void ProviderCryptopro::enumCertificates(HCERTSTORE hCertStore, std::string *category){ LOGGER_FN(); try{ X509 *cert = NULL; const unsigned char *p; if (!hCertStore){ THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Certificate store not opened"); } PCCERT_CONTEXT pCertContext = NULL; do { pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext); if (pCertContext){ p = pCertContext->pbCertEncoded; LOGGER_OPENSSL(d2i_X509); if (!(cert = d2i_X509(NULL, &p, pCertContext->cbCertEncoded))) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "'d2i_X509' Error decode len bytes"); } Handle<PkiItem> item = objectToPKIItem(new Certificate(cert)); item->category = new std::string(*category); DWORD * pdwKeySpec; BOOL * pfCallerFreeProv; HCRYPTPROV m_hProv; if (CryptAcquireCertificatePrivateKey(pCertContext, NULL, NULL, &m_hProv, pdwKeySpec, pfCallerFreeProv)){ item->certKey = new std::string("1"); } providerItemCollection->push(item); } } while (pCertContext != NULL); if (pCertContext){ CertFreeCertificateContext(pCertContext); } } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error enum certificates in store"); } } void ProviderCryptopro::enumCrls(HCERTSTORE hCertStore, std::string *category){ LOGGER_FN(); try{ X509_CRL *crl = NULL; const unsigned char *p; if (!hCertStore){ THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Certificate store not opened"); } PCCRL_CONTEXT pCrlContext = NULL; do { pCrlContext = CertEnumCRLsInStore(hCertStore, pCrlContext); if (pCrlContext){ p = pCrlContext->pbCrlEncoded; LOGGER_OPENSSL(d2i_X509_CRL); if (!(crl = d2i_X509_CRL(NULL, &p, pCrlContext->cbCrlEncoded))) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "'d2i_X509_CRL' Error decode len bytes"); } Handle<PkiItem> item = objectToPKIItem(new CRL(crl)); item->category = new std::string(*category); providerItemCollection->push(item); } } while (pCrlContext != NULL); if (pCrlContext){ CertFreeCRLContext(pCrlContext); } } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error enum CRLs in store"); } } Handle<PkiItem> ProviderCryptopro::objectToPKIItem(Handle<Certificate> cert){ LOGGER_FN(); try{ if (cert.isEmpty()){ THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Certificate empty"); } Handle<PkiItem> item = new PkiItem(); item->format = new std::string("DER"); item->type = new std::string("CERTIFICATE"); item->provider = new std::string("CRYPTOPRO"); char * hexHash; Handle<std::string> hhash = cert->getThumbprint(); PkiStore::bin_to_strhex((unsigned char *)hhash->c_str(), hhash->length(), &hexHash); item->hash = new std::string(hexHash); item->certSubjectName = cert->getSubjectName(); item->certSubjectFriendlyName = cert->getSubjectFriendlyName(); item->certIssuerName = cert->getIssuerName(); item->certIssuerFriendlyName = cert->getIssuerFriendlyName(); item->certSerial = cert->getSerialNumber(); item->certOrganizationName = cert->getOrganizationName(); item->certSignatureAlgorithm = cert->getSignatureAlgorithm(); item->certNotBefore = cert->getNotBefore(); item->certNotAfter = cert->getNotAfter(); return item; } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error create PkiItem from certificate"); } } Handle<PkiItem> ProviderCryptopro::objectToPKIItem(Handle<CRL> crl){ LOGGER_FN(); try{ if (crl.isEmpty()){ THROW_EXCEPTION(0, ProviderCryptopro, NULL, "CRL empty"); } Handle<PkiItem> item = new PkiItem(); item->format = new std::string("DER"); item->type = new std::string("CRL"); item->provider = new std::string("CRYPTOPRO"); char * hexHash; Handle<std::string> hhash = crl->getThumbprint(); PkiStore::bin_to_strhex((unsigned char *)hhash->c_str(), hhash->length(), &hexHash); item->hash = new std::string(hexHash); item->crlIssuerName = crl->issuerName(); item->crlIssuerFriendlyName = crl->issuerFriendlyName(); item->crlLastUpdate = crl->getThisUpdate(); item->crlNextUpdate = crl->getNextUpdate(); return item; } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error create PkiItem from crl"); } } Handle<Certificate> ProviderCryptopro::getCert(Handle<std::string> hash, Handle<std::string> category){ LOGGER_FN(); X509 *hcert = NULL; try{ HCERTSTORE hCertStore; PCCERT_CONTEXT pCertContext = NULL; const unsigned char *p; std::wstring wCategory = std::wstring(category->begin(), category->end()); char cHash[20] = { 0 }; hex2bin(hash->c_str(), cHash); CRYPT_HASH_BLOB cblobHash; cblobHash.pbData = (BYTE *)cHash; cblobHash.cbData = (DWORD)20; hCertStore = CertOpenStore( CERT_STORE_PROV_SYSTEM, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, NULL, CERT_SYSTEM_STORE_CURRENT_USER, wCategory.c_str() ); if (!hCertStore) { THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Error open store"); } pCertContext = CertFindCertificateInStore( hCertStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_HASH, &cblobHash, NULL); if (pCertContext) { p = pCertContext->pbCertEncoded; LOGGER_OPENSSL(d2i_X509); if (!(hcert = d2i_X509(NULL, &p, pCertContext->cbCertEncoded))) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "'d2i_X509' Error decode len bytes"); } if (pCertContext){ CertFreeCertificateContext(pCertContext); } if (hCertStore) { CertCloseStore(hCertStore, 0); } return new Certificate(hcert); } else{ THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Cannot find certificate in store"); } } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error get certificate"); } } Handle<CRL> ProviderCryptopro::getCRL(Handle<std::string> hash, Handle<std::string> category){ LOGGER_FN(); try{ HCERTSTORE hCertStore; PCCRL_CONTEXT pCrlContext = NULL; const unsigned char *p; std::wstring wCategory = std::wstring(category->begin(), category->end()); hCertStore = CertOpenStore( CERT_STORE_PROV_SYSTEM, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, NULL, CERT_SYSTEM_STORE_CURRENT_USER, wCategory.c_str() ); if (!hCertStore) { THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Error open store"); } do { pCrlContext = CertEnumCRLsInStore(hCertStore, pCrlContext); if (pCrlContext){ X509_CRL *tempCrl = NULL; p = pCrlContext->pbCrlEncoded; LOGGER_OPENSSL(d2i_X509_CRL); if (!(tempCrl = d2i_X509_CRL(NULL, &p, pCrlContext->cbCrlEncoded))) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "'d2i_X509_CRL' Error decode len bytes"); } Handle<CRL> hTempCrl = new CRL(tempCrl); char * hexHash; Handle<std::string> hhash = hTempCrl->getThumbprint(); PkiStore::bin_to_strhex((unsigned char *)hhash->c_str(), hhash->length(), &hexHash); std::string sh(hexHash); if (strcmp(sh.c_str(), hash->c_str()) == 0){ return hTempCrl; } } } while (pCrlContext != NULL); if (pCrlContext){ CertFreeCRLContext(pCrlContext); } if (hCertStore) { CertCloseStore(hCertStore, 0); } THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Cannot find CRL in store"); } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error get CRL"); } } Handle<Key> ProviderCryptopro::getKey(Handle<Certificate> cert) { LOGGER_FN(); EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *pkey = NULL; EVP_MD_CTX *mctx = NULL; try{ #ifndef OPENSSL_NO_CTGOSTCP #define MAX_SIGNATURE_LEN 128 size_t len; unsigned char buf[MAX_SIGNATURE_LEN]; ENGINE *e = ENGINE_by_id("ctgostcp"); if (e == NULL) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "CTGSOTCP is not loaded"); } LOGGER_OPENSSL(EVP_PKEY_CTX_new_id); pctx = EVP_PKEY_CTX_new_id(NID_id_GostR3410_2001, e); LOGGER_OPENSSL(EVP_PKEY_keygen_init); if (EVP_PKEY_keygen_init(pctx) <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "EVP_PKEY_keygen_init"); } LOGGER_OPENSSL(EVP_PKEY_CTX_ctrl_str); if (EVP_PKEY_CTX_ctrl_str(pctx, CTGOSTCP_PKEY_CTRL_STR_PARAM_KEYSET, "all") <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "EVP_PKEY_CTX_ctrl_str CTGOSTCP_PKEY_CTRL_STR_PARAM_KEYSET 'all'"); } LOGGER_OPENSSL(EVP_PKEY_CTX_ctrl_str); if (EVP_PKEY_CTX_ctrl_str(pctx, CTGOSTCP_PKEY_CTRL_STR_PARAM_EXISTING, "true") <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "EVP_PKEY_CTX_ctrl_str CTGOSTCP_PKEY_CTRL_STR_PARAM_EXISTING 'true'"); } LOGGER_OPENSSL(CTGOSTCP_EVP_PKEY_CTX_init_key_by_cert); if (CTGOSTCP_EVP_PKEY_CTX_init_key_by_cert(pctx, cert->internal()) <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "Can not init key context by certificate"); } LOGGER_OPENSSL(EVP_PKEY_CTX_ctrl_str); if (EVP_PKEY_CTX_ctrl_str(pctx, CTGOSTCP_PKEY_CTRL_STR_PARAM_EXISTING, "true") <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "Parameter 'existing' setting error"); } LOGGER_OPENSSL(EVP_PKEY_keygen); if (EVP_PKEY_keygen(pctx, &pkey) <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "Can not init key by certificate"); } int md_type = 0; const EVP_MD *md = NULL; LOGGER_OPENSSL(EVP_PKEY_get_default_digest_nid); if (EVP_PKEY_get_default_digest_nid(pkey, &md_type) <= 0) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "default digest for key type not found"); } LOGGER_OPENSSL(EVP_get_digestbynid); md = EVP_get_digestbynid(md_type); LOGGER_OPENSSL(EVP_MD_CTX_create); if (!(mctx = EVP_MD_CTX_create())) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "Error creating digest context"); } len = sizeof(buf); LOGGER_OPENSSL(EVP_DigestSignInit); if (!EVP_DigestSignInit(mctx, NULL, md, e, pkey) || (EVP_DigestSignUpdate(mctx, "123", 3) <= 0) || !EVP_DigestSignFinal(mctx, buf, &len)) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "Error testing private key (via signing data)"); } return new Key(pkey); #else THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Only with CTGSOTCP"); #endif } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error get key"); } if (mctx) EVP_MD_CTX_destroy(mctx); if (pkey) EVP_PKEY_free(pkey); if (pctx) EVP_PKEY_CTX_free(pctx); } int ProviderCryptopro::char2int(char input) { LOGGER_FN(); try{ if (input >= '0' && input <= '9'){ return input - '0'; } if (input >= 'A' && input <= 'F'){ return input - 'A' + 10; } if (input >= 'a' && input <= 'f'){ return input - 'a' + 10; } THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Invalid input string"); } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error char to int"); } } void ProviderCryptopro::hex2bin(const char* src, char* target) { LOGGER_FN(); while (*src && src[1]){ *(target++) = char2int(*src) * 16 + char2int(src[1]); src += 2; } }
26.739696
125
0.699602
microshine
82e96104ae37f5d80d98a84276832cef5cb47420
6,893
cc
C++
mindspore/lite/src/runtime/kernel/arm/int8/fullconnection_int8.cc
HappyKL/mindspore
479cb89e8b5c9d859130891567038bb849a30bce
[ "Apache-2.0" ]
1
2020-10-18T12:27:45.000Z
2020-10-18T12:27:45.000Z
mindspore/lite/src/runtime/kernel/arm/int8/fullconnection_int8.cc
ReIadnSan/mindspore
c3d1f54c7f6d6f514e5748430d24b16a4f9ee9e5
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/runtime/kernel/arm/int8/fullconnection_int8.cc
ReIadnSan/mindspore
c3d1f54c7f6d6f514e5748430d24b16a4f9ee9e5
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/runtime/kernel/arm/int8/fullconnection_int8.h" #include "nnacl/int8/matmul_int8.h" #include "nnacl/common_func.h" #include "src/runtime/runtime_api.h" #include "include/errorcode.h" using mindspore::lite::RET_MEMORY_FAILED; using mindspore::lite::RET_OK; namespace mindspore::kernel { int FullconnectionInt8CPUKernel::Init() { if (!InferShapeDone()) { return RET_OK; } return ReSize(); } int FullconnectionInt8CPUKernel::ReSize() { FreeTmpBuffer(); int row = 1; for (size_t i = 0; i < out_tensors_[0]->shape().size() - 1; ++i) row *= (out_tensors_[0]->shape())[i]; fc_param_->row_ = row; fc_param_->col_ = out_tensors_[0]->shape().back(); fc_param_->deep_ = (in_tensors_[1]->shape())[1]; fc_param_->row_8_ = UP_ROUND(fc_param_->row_, 8); fc_param_->col_8_ = UP_ROUND(fc_param_->col_, 8); r4_ = UP_ROUND(fc_param_->row_, 4); c4_ = UP_ROUND(fc_param_->col_, 4); d16_ = UP_ROUND(fc_param_->deep_, 16); thread_count_ = MSMIN(thread_count_, UP_DIV(c4_, 4)); thread_stride_ = UP_DIV(UP_DIV(c4_, 4), thread_count_); a_r4x16_ptr_ = reinterpret_cast<int8_t *>(ctx_->allocator->Malloc(r4_ * d16_ * sizeof(int8_t))); if (!a_r4x16_ptr_) return RET_MEMORY_FAILED; memset(a_r4x16_ptr_, 0, r4_ * d16_ * sizeof(int8_t)); b_c16x4_ptr_ = reinterpret_cast<int8_t *>(ctx_->allocator->Malloc(c4_ * d16_ * sizeof(int8_t))); if (!b_c16x4_ptr_) return RET_MEMORY_FAILED; memset(b_c16x4_ptr_, 0, c4_ * d16_ * sizeof(int8_t)); input_sums_ = reinterpret_cast<int *>(ctx_->allocator->Malloc(r4_ * sizeof(int))); if (!input_sums_) return RET_MEMORY_FAILED; memset(input_sums_, 0, r4_ * sizeof(int)); weight_bias_sums_ = reinterpret_cast<int *>(ctx_->allocator->Malloc(c4_ * sizeof(int))); if (!weight_bias_sums_) return RET_MEMORY_FAILED; memset(weight_bias_sums_, 0, c4_ * sizeof(int)); if (in_tensors_.size() == 3) { auto bias_len = fc_param_->col_8_ * sizeof(int); bias_ptr_ = reinterpret_cast<int *>(ctx_->allocator->Malloc(bias_len)); if (!bias_ptr_) return RET_MEMORY_FAILED; memcpy(bias_ptr_, in_tensors_[2]->data_c(), bias_len); } else { bias_ptr_ = NULL; } auto input_tensor = in_tensors_[0]; auto params = input_tensor->GetQuantParams(); MS_ASSERT(params.size() == 1); quant_params_.input.zp_ = params.front().zeroPoint; quant_params_.input.scale_ = params.front().scale; auto weight_tensor = in_tensors_[1]; params = weight_tensor->GetQuantParams(); MS_ASSERT(params.size() == 1); quant_params_.weight.zp_ = params.front().zeroPoint; quant_params_.weight.scale_ = params.front().scale; auto output_tensor = out_tensors_[0]; params = output_tensor->GetQuantParams(); MS_ASSERT(params.size() == 1); quant_params_.output.zp_ = params.front().zeroPoint; quant_params_.output.scale_ = params.front().scale; double real_multiplier = quant_params_.input.scale_ * quant_params_.weight.scale_ / quant_params_.output.scale_; QuantizeRoundParameter(real_multiplier, &quant_params_.quant_multiplier, &quant_params_.left_shift, &quant_params_.right_shift); CalculateActivationRangeQuantized(fc_param_->act_type_ == ActType_Relu, fc_param_->act_type_ == ActType_Relu6, quant_params_.output.zp_, quant_params_.output.scale_, &quant_params_.out_act_min, &quant_params_.out_act_max); fc_param_->b_const_ = (in_tensors_[1]->data_c() != nullptr); if (fc_param_->b_const_) { auto weight_data = reinterpret_cast<int8_t *>(in_tensors_[1]->data_c()); RowMajor2Row16x4MajorInt8(weight_data, b_c16x4_ptr_, fc_param_->col_, fc_param_->deep_); CalcWeightBiasSums(weight_data, fc_param_->deep_, fc_param_->col_, quant_params_.input.zp_, quant_params_.weight.zp_, bias_ptr_, weight_bias_sums_, ColMajor); } return RET_OK; } int FullconnectionInt8CPUKernel::RunImpl(int task_id) { int cur_oc = MSMIN(thread_stride_, UP_DIV(c4_, 4) - task_id * thread_stride_); if (cur_oc <= 0) { return RET_OK; } int cur_oc_res = MSMIN(thread_stride_ * C4NUM, fc_param_->col_ - task_id * thread_stride_ * C4NUM); auto &q = quant_params_; auto &p = fc_param_; auto cur_b = b_c16x4_ptr_ + task_id * thread_stride_ * C4NUM * d16_; auto cur_bias = weight_bias_sums_ + task_id * thread_stride_ * C4NUM; auto output_ptr = reinterpret_cast<int8_t *>(out_tensors_[0]->data_c()); auto cur_c = output_ptr + task_id * thread_stride_ * C4NUM; #ifdef ENABLE_ARM64 MatmulInt8Neon64(a_r4x16_ptr_, cur_b, cur_c, r4_, cur_oc * C4NUM, d16_, input_sums_, cur_bias, q.out_act_min, q.out_act_max, q.output.zp_, &q.quant_multiplier, &q.left_shift, &q.right_shift, p->row_, cur_oc_res, p->col_ * sizeof(int8_t), 0); #else MatMulInt8_16x4_r(a_r4x16_ptr_, cur_b, cur_c, p->row_, cur_oc_res, d16_, p->col_, input_sums_, cur_bias, &q.left_shift, &q.right_shift, &q.quant_multiplier, q.output.zp_, INT8_MIN, INT8_MAX, false); #endif return RET_OK; } int FcInt8Run(void *cdata, int task_id) { auto fc = reinterpret_cast<FullconnectionInt8CPUKernel *>(cdata); auto ret = fc->RunImpl(task_id); if (ret != RET_OK) { MS_LOG(ERROR) << "FcInt8Run error task_id[" << task_id << "] error_code[" << ret << "]"; return ret; } return RET_OK; } int FullconnectionInt8CPUKernel::Run() { auto ret = Prepare(); if (ret != RET_OK) { MS_LOG(ERROR) << "Prepare failed."; return RET_ERROR; } auto input_ptr = reinterpret_cast<int8_t *>(in_tensors_[0]->data_c()); RowMajor2Row16x4MajorInt8(input_ptr, a_r4x16_ptr_, fc_param_->row_, fc_param_->deep_); CalcInputSums(input_ptr, fc_param_->row_, fc_param_->deep_, quant_params_.weight.zp_, input_sums_, RowMajor); if (!fc_param_->b_const_) { auto weight_data = reinterpret_cast<int8_t *>(in_tensors_[1]->data_c()); RowMajor2Row16x4MajorInt8(weight_data, b_c16x4_ptr_, fc_param_->col_, fc_param_->deep_); CalcWeightBiasSums(weight_data, fc_param_->deep_, fc_param_->col_, quant_params_.input.zp_, quant_params_.weight.zp_, bias_ptr_, weight_bias_sums_, ColMajor); } ParallelLaunch(this->context_->thread_pool_, FcInt8Run, this, thread_count_); return RET_OK; } } // namespace mindspore::kernel
44.185897
120
0.709996
HappyKL
82ea8dd36206e5b09d557281591a37ecd9cfdd00
560
hpp
C++
src/utils/hittable.hpp
Kingfish404/ray-tracing-cpp
d4c2e3d32df0febd028e7e0ba36d21c3abc25664
[ "MIT" ]
1
2022-03-25T10:46:34.000Z
2022-03-25T10:46:34.000Z
src/utils/hittable.hpp
Kingfish404/ray-tracing-cpp
d4c2e3d32df0febd028e7e0ba36d21c3abc25664
[ "MIT" ]
null
null
null
src/utils/hittable.hpp
Kingfish404/ray-tracing-cpp
d4c2e3d32df0febd028e7e0ba36d21c3abc25664
[ "MIT" ]
null
null
null
#pragma once #ifndef HITTABLE_HPP #define HITTABLE_HPP #include "../common.hpp" class material; struct hit_record { point3 p; vec3 normal; shared_ptr<material> mat_ptr; double t; bool front_face; inline void set_face_normal(const ray &r, const vec3 &outward_normal) { front_face = r.direction().dot(outward_normal) < 0; normal = front_face ? outward_normal : -outward_normal; } }; class hittable { public: virtual bool hit(const ray &r, double t_min, double t_max, hit_record &rec) const = 0; }; #endif
18.666667
90
0.680357
Kingfish404
82efaacf949fc75362d7bcbca2c0dc2e6c935856
24,115
cxx
C++
src/openlcb/EventHandlerTemplates.cxx
TrainzLuvr/openmrn
b3bb9d4995e49aa39856740d292d38cf4a99845b
[ "BSD-2-Clause" ]
null
null
null
src/openlcb/EventHandlerTemplates.cxx
TrainzLuvr/openmrn
b3bb9d4995e49aa39856740d292d38cf4a99845b
[ "BSD-2-Clause" ]
null
null
null
src/openlcb/EventHandlerTemplates.cxx
TrainzLuvr/openmrn
b3bb9d4995e49aa39856740d292d38cf4a99845b
[ "BSD-2-Clause" ]
null
null
null
/** \copyright * Copyright (c) 2013, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file EventHandlerTemplates.cxx * * Implementations of common event handlers. * * @author Balazs Racz * @date 6 November 2013 */ #include <unistd.h> #include "utils/logging.h" #include "openlcb/EventHandlerTemplates.hxx" #include "openlcb/EventService.hxx" #ifdef __linux__ //#define DESCRIBE_VAR #endif #ifdef DESCRIBE_VAR extern int debug_variables; int debug_variables = 0; #include <string> namespace openlcb { extern const string &GetNameForEvent(uint64_t); __attribute__((weak)) const string &GetNameForEvent(uint64_t) { static string empty; return empty; } } #endif namespace openlcb { BitRangeEventPC::BitRangeEventPC(Node *node, uint64_t event_base, uint32_t *backing_store, unsigned size) : event_base_(event_base) , node_(node) , data_(backing_store) , size_(size) { unsigned mask = EventRegistry::align_mask(&event_base, size * 2); EventRegistry::instance()->register_handler( EventRegistryEntry(this, event_base), mask); } BitRangeEventPC::~BitRangeEventPC() { EventRegistry::instance()->unregister_handler(this); } void BitRangeEventPC::GetBitAndMask(unsigned bit, uint32_t **data, uint32_t *mask) const { *data = nullptr; if (bit >= size_) return; *data = data_ + (bit >> 5); *mask = 1 << (bit & 31); } bool BitRangeEventPC::Get(unsigned bit) const { HASSERT(bit < size_); uint32_t *ofs; uint32_t mask; GetBitAndMask(bit, &ofs, &mask); if (!ofs) return false; return (*ofs) & mask; } void BitRangeEventPC::Set(unsigned bit, bool new_value, WriteHelper *writer, BarrierNotifiable *done) { HASSERT(bit < size_); uint32_t *ofs; uint32_t mask; GetBitAndMask(bit, &ofs, &mask); bool old_value = new_value; HASSERT(ofs); if (ofs) old_value = (*ofs) & mask; if (old_value != new_value) { #ifdef DESCRIBE_VAR if (debug_variables) { fprintf(stderr, "BitRange: OUT bit %x (%s) to %d\n", bit, GetNameForEvent(event_base_ + (bit * 2)).c_str(), new_value); } #else LOG(VERBOSE, "BitRange: set bit %x to %d", bit, new_value); #endif if (new_value) { *ofs |= mask; } else { *ofs &= ~mask; } uint64_t event = event_base_ + bit * 2; if (!new_value) event++; writer->WriteAsync(node_, Defs::MTI_EVENT_REPORT, WriteHelper::global(), eventid_to_buffer(event), done); #ifndef TARGET_LPC11Cxx if (!done) { // We wait for the sent-out event to come back. Otherwise there is a // race // condition where the automata processing could have gone further, // but // the "set" message will arrive. while (EventService::instance->event_processing_pending()) { usleep(100); } } #endif } else { #ifdef DESCRIBE_VAR if (debug_variables > 2) { fprintf(stderr, "BitRange: out bit %x (%s) to %d\n", bit, GetNameForEvent(event_base_ + (bit * 2)).c_str(), new_value); } #endif if (done) done->notify(); } } void BitRangeEventPC::handle_event_report(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { done->notify(); if (event->event < event_base_) return; uint64_t d = (event->event - event_base_); bool new_value = !(d & 1); d >>= 1; if (d >= size_) return; int bit = d; #ifdef DESCRIBE_VAR if (debug_variables) { fprintf(stderr, "BitRange: IN bit %x (%s) to %d\n", bit, GetNameForEvent(event_base_ + (2 * bit)).c_str(), new_value); } #else LOG(VERBOSE, "BitRange: evt bit %x to %d", bit, new_value); #endif uint32_t *ofs = nullptr; uint32_t mask = 0; GetBitAndMask(bit, &ofs, &mask); if (new_value) { *ofs |= mask; } else { *ofs &= ~mask; } } void BitRangeEventPC::handle_identify_producer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { HandleIdentifyBase(Defs::MTI_PRODUCER_IDENTIFIED_VALID, event, done); } void BitRangeEventPC::handle_identify_consumer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { HandleIdentifyBase(Defs::MTI_CONSUMER_IDENTIFIED_VALID, event, done); } void BitRangeEventPC::HandleIdentifyBase(Defs::MTI mti_valid, EventReport *event, BarrierNotifiable *done) { if (event->event < event_base_) return done->notify(); uint64_t d = (event->event - event_base_); bool new_value = !(d & 1); d >>= 1; if (d >= size_) return done->notify(); uint32_t *ofs = nullptr; uint32_t mask = 0; GetBitAndMask(d, &ofs, &mask); Defs::MTI mti = mti_valid; bool old_value = *ofs & mask; if (old_value != new_value) { mti++; // mti INVALID } event->event_write_helper<1>()->WriteAsync(node_, mti, WriteHelper::global(), eventid_to_buffer(event->event), done); } uint64_t EncodeRange(uint64_t begin, unsigned size) { // We assemble a valid event range identifier that covers our block. uint64_t end = begin + size - 1; uint64_t shift = 1; while ((begin + shift) < end) { begin &= ~shift; shift <<= 1; } if (begin & shift) { // last real bit is 1 => range ends with zero. return begin; } else { // last real bit is zero. Set all lower bits to 1. begin |= shift - 1; return begin; } } void BitRangeEventPC::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != node_) { return done->notify(); } uint64_t range = EncodeRange(event_base_, size_ * 2); event->event_write_helper<1>()->WriteAsync(node_, Defs::MTI_PRODUCER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done->new_child()); event->event_write_helper<2>()->WriteAsync(node_, Defs::MTI_CONSUMER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done->new_child()); done->maybe_done(); } void BitRangeEventPC::SendIdentified(WriteHelper *writer, BarrierNotifiable *done) { uint64_t range = EncodeRange(event_base_, size_ * 2); writer->WriteAsync(node_, Defs::MTI_PRODUCER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done); } ByteRangeEventC::ByteRangeEventC(Node *node, uint64_t event_base, uint8_t *backing_store, unsigned size) : event_base_(event_base) , node_(node) , data_(backing_store) , size_(size) { unsigned mask = EventRegistry::align_mask(&event_base, size * 256); EventRegistry::instance()->register_handler( EventRegistryEntry(this, event_base), mask); } ByteRangeEventC::~ByteRangeEventC() { EventRegistry::instance()->unregister_handler(this); } void ByteRangeEventC::handle_event_report(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { done->notify(); uint8_t *storage; uint8_t value; if (!DecodeEventId(event->event, &storage, &value)) return; #ifdef DESCRIBE_VAR if (debug_variables) { fprintf(stderr, "ByteRange: IN byte %" PRIxPTR " to %d\n", storage - data_, value); } #else LOG(VERBOSE, "ByteRange: evt %x to %d", (unsigned)(storage - data_), value); #endif *storage = value; notify_changed(storage - data_); } bool ByteRangeEventC::DecodeEventId(uint64_t event, uint8_t **storage, uint8_t *value) { *storage = nullptr; *value = 0; if (event < event_base_) return false; event -= event_base_; *value = event & 0xff; event >>= 8; if (event >= size_) return false; *storage = data_ + event; return true; } void ByteRangeEventC::handle_identify_consumer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { uint8_t *storage; uint8_t value; if (!DecodeEventId(event->event, &storage, &value)) { return done->notify(); } Defs::MTI mti = Defs::MTI_CONSUMER_IDENTIFIED_VALID; if (*storage != value) { mti++; // mti INVALID } event->event_write_helper<1>()->WriteAsync(node_, mti, WriteHelper::global(), eventid_to_buffer(event->event), done); } void ByteRangeEventC::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != node_) { return done->notify(); } uint64_t range = EncodeRange(event_base_, size_ * 256); event->event_write_helper<1>()->WriteAsync(node_, Defs::MTI_CONSUMER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done->new_child()); done->maybe_done(); } void ByteRangeEventC::SendIdentified(WriteHelper *writer, BarrierNotifiable *done) { uint64_t range = EncodeRange(event_base_, size_ * 256); writer->WriteAsync(node_, Defs::MTI_CONSUMER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done); } ByteRangeEventP::ByteRangeEventP(Node *node, uint64_t event_base, uint8_t *backing_store, unsigned size) : ByteRangeEventC(node, event_base, backing_store, size) { } void ByteRangeEventP::handle_event_report(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { // Nothing to do for producers. done->notify(); } void ByteRangeEventP::handle_identify_consumer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { // Nothing to do for producers. done->notify(); } uint64_t ByteRangeEventP::CurrentEventId(unsigned byte) { return event_base_ + (byte << 8) + data_[byte]; } void ByteRangeEventP::handle_identify_producer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { uint8_t *storage; uint8_t value; if (!DecodeEventId(event->event, &storage, &value)) { return done->notify(); } Defs::MTI mti = Defs::MTI_PRODUCER_IDENTIFIED_VALID; if (*storage != value) { mti++; // mti INVALID // We also send off the currently valid value. Update( storage - data_, event->event_write_helper<2>(), done->new_child()); } event->event_write_helper<1>()->WriteAsync(node_, mti, WriteHelper::global(), eventid_to_buffer(event->event), done->new_child()); done->maybe_done(); } void ByteRangeEventP::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != node_) { return done->notify(); } uint64_t range = EncodeRange(event_base_, size_ * 256); event->event_write_helper<1>()->WriteAsync(node_, Defs::MTI_PRODUCER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done); } void ByteRangeEventP::SendIdentified(WriteHelper *writer, BarrierNotifiable *done) { uint64_t range = EncodeRange(event_base_, size_ * 256); writer->WriteAsync(node_, Defs::MTI_PRODUCER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done); } void ByteRangeEventP::Update(unsigned byte, WriteHelper *writer, BarrierNotifiable *done) { // @TODO(balazs.racz): Should we use producer identified valid or event // report here? writer->WriteAsync(node_, Defs::MTI_EVENT_REPORT, WriteHelper::global(), eventid_to_buffer(CurrentEventId(byte)), done); } // Responses to possible queries. void ByteRangeEventP::handle_consumer_identified(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { uint8_t *storage; uint8_t value; if (!DecodeEventId(event->event, &storage, &value)) { return done->notify(); } Update(storage - data_, event->event_write_helper<1>(), done); } void ByteRangeEventP::handle_consumer_range_identified(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { /** @TODO(balazs.racz): We should respond with the correct signal aspect * for each offset that we offer. */ if (event->event + event->mask < event_base_) { return done->notify(); } if (event->event >= event_base_ + size_ * 256) { return done->notify(); } unsigned start_offset = 0; unsigned end_offset = 0; uint8_t *storage; uint8_t value; if (!DecodeEventId(event->event, &storage, &value)) { start_offset = 0; } else { start_offset = storage - data_; } if (!DecodeEventId(event->event + event->mask, &storage, &value)) { end_offset = size_; } else { end_offset = storage - data_ + 1; } unsigned cur = start_offset; if (cur < end_offset) { Update(cur++, event->event_write_helper<1>(), done->new_child()); } if (cur < end_offset) { Update(cur++, event->event_write_helper<2>(), done->new_child()); } if (cur < end_offset) { Update(cur++, event->event_write_helper<3>(), done->new_child()); } if (cur < end_offset) { Update(cur++, event->event_write_helper<4>(), done->new_child()); } // This will crash if more than four packets are to be produced. The above // code should be replaced by a background iteration in that case. HASSERT(cur >= end_offset); done->maybe_done(); } BitEventHandler::BitEventHandler(BitEventInterface *bit) : bit_(bit) { } void BitEventHandler::register_handler(uint64_t event_on, uint64_t event_off) { if ((event_on ^ event_off) == 1ULL) { // Register once for two eventids. uint64_t id = event_on & (~1ULL); unsigned user_data = 0; if (event_on & 1) { user_data |= BOTH_OFF_IS_ZERO; } else { user_data |= BOTH_ON_IS_ZERO; } EventRegistry::instance()->register_handler( EventRegistryEntry(this, id, user_data), 1); } else { EventRegistry::instance()->register_handler( EventRegistryEntry(this, event_on, EVENT_ON), 0); EventRegistry::instance()->register_handler( EventRegistryEntry(this, event_off, EVENT_OFF), 0); } } void BitEventHandler::unregister_handler() { EventRegistry::instance()->unregister_handler(this); } void BitEventHandler::SendProducerIdentified( EventReport *event, BarrierNotifiable *done) { EventState state = bit_->get_current_state(); Defs::MTI mti = Defs::MTI_PRODUCER_IDENTIFIED_VALID + state; event->event_write_helper<1>()->WriteAsync(bit_->node(), mti, WriteHelper::global(), eventid_to_buffer(bit_->event_on()), done->new_child()); mti = Defs::MTI_PRODUCER_IDENTIFIED_VALID + invert_event_state(state); event->event_write_helper<2>()->WriteAsync(bit_->node(), mti, WriteHelper::global(), eventid_to_buffer(bit_->event_off()), done->new_child()); } void BitEventHandler::SendConsumerIdentified( EventReport *event, BarrierNotifiable *done) { EventState state = bit_->get_current_state(); Defs::MTI mti = Defs::MTI_CONSUMER_IDENTIFIED_VALID + state; event->event_write_helper<3>()->WriteAsync(bit_->node(), mti, WriteHelper::global(), eventid_to_buffer(bit_->event_on()), done->new_child()); mti = Defs::MTI_CONSUMER_IDENTIFIED_VALID + invert_event_state(state); event->event_write_helper<4>()->WriteAsync(bit_->node(), mti, WriteHelper::global(), eventid_to_buffer(bit_->event_off()), done->new_child()); } void BitEventHandler::SendEventReport(WriteHelper *writer, Notifiable *done) { EventState value = bit_->get_requested_state(); uint64_t event; if (value == EventState::VALID) { event = bit_->event_on(); } else if (value == EventState::INVALID) { event = bit_->event_off(); } else { DIE("Requested sending event report for a bit event that is in unknown " "state."); } writer->WriteAsync(bit_->node(), Defs::MTI_EVENT_REPORT, WriteHelper::global(), eventid_to_buffer(event), done); } void BitEventHandler::HandlePCIdentify(Defs::MTI mti, EventReport *event, BarrierNotifiable *done) { if (event->src_node.id == bit_->node()->node_id()) { // We don't respond to queries from our own node. This is not nice, but // we // want to avoid to answering our own Query command. done->notify(); return; } EventState active; if (event->event == bit_->event_on()) { active = bit_->get_current_state(); } else if (event->event == bit_->event_off()) { active = invert_event_state(bit_->get_current_state()); } else { done->notify(); return; } mti = mti + active; event->event_write_helper<1>()->WriteAsync(bit_->node(), mti, WriteHelper::global(), eventid_to_buffer(event->event), done); } void BitEventConsumer::handle_producer_identified(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { done->notify(); bool value; if (event->state == EventState::VALID) { value = true; } else if (event->state == EventState::INVALID) { value = false; } else { return; // nothing to learn from this message. } if (event->event == bit_->event_on()) { bit_->set_state(value); } else if (event->event == bit_->event_off()) { bit_->set_state(!value); } else { return; // uninteresting event id. } } void BitEventConsumer::SendQuery(WriteHelper *writer, BarrierNotifiable *done) { writer->WriteAsync(bit_->node(), Defs::MTI_PRODUCER_IDENTIFY, WriteHelper::global(), eventid_to_buffer(bit_->event_on()), done); } void BitEventConsumer::handle_event_report(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->event == bit_->event_on()) { bit_->set_state(true); } else if (event->event == bit_->event_off()) { bit_->set_state(false); } done->notify(); } void BitEventProducer::SendQuery(WriteHelper *writer, BarrierNotifiable *done) { writer->WriteAsync(bit_->node(), Defs::MTI_CONSUMER_IDENTIFY, WriteHelper::global(), eventid_to_buffer(bit_->event_on()), done); } void BitEventProducer::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != bit_->node()) { return done->notify(); } SendProducerIdentified(event, done); done->maybe_done(); } void BitEventProducer::handle_identify_producer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { HandlePCIdentify(Defs::MTI_PRODUCER_IDENTIFIED_VALID, event, done); } void BitEventPC::handle_identify_producer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { HandlePCIdentify(Defs::MTI_PRODUCER_IDENTIFIED_VALID, event, done); } void BitEventConsumer::handle_identify_consumer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { HandlePCIdentify(Defs::MTI_CONSUMER_IDENTIFIED_VALID, event, done); } void BitEventConsumer::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != bit_->node()) { return done->notify(); } SendConsumerIdentified(event, done); done->maybe_done(); } void BitEventPC::SendQueryConsumer(WriteHelper *writer, BarrierNotifiable *done) { writer->WriteAsync(bit_->node(), Defs::MTI_CONSUMER_IDENTIFY, WriteHelper::global(), eventid_to_buffer(bit_->event_on()), done); } void BitEventPC::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != bit_->node()) { return done->notify(); } SendProducerIdentified(event, done); SendConsumerIdentified(event, done); done->maybe_done(); } void BitEventPC::handle_consumer_identified(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { done->notify(); bool value; if (event->state == EventState::VALID) { value = true; } else if (event->state == EventState::INVALID) { value = false; } else { return; // nothing to learn from this message. } if (event->event == bit_->event_on()) { bit_->set_state(value); } else if (event->event == bit_->event_off()) { bit_->set_state(!value); } else { return; // uninteresting event id. } } }; /* namespace openlcb */
30.758929
107
0.612109
TrainzLuvr
82f1902a27eef2878a10b22fbe3abbddd49a5e4e
4,366
cpp
C++
src/shadereditor/src/shadereditor/nodes/vnode_matrices.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/shadereditor/src/shadereditor/nodes/vnode_matrices.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/shadereditor/src/shadereditor/nodes/vnode_matrices.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
 #include "cbase.h" #include "editorCommon.h" CNodeMatrix_MVP::CNodeMatrix_MVP(CNodeView *p) : BaseClass("Matrix MVP", p) { GenerateJacks_Output(1); LockJackOutput_Flags(0, HLSLVAR_MATRIX4X4, "Model View Projection"); } bool CNodeMatrix_MVP::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_MVP *solver = new CHLSL_Solver_MVP(GetUniqueIndex()); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; } CNodeMatrix_VP::CNodeMatrix_VP(CNodeView *p) : BaseClass("Matrix VP", p) { GenerateJacks_Output(1); LockJackOutput_Flags(0, HLSLVAR_MATRIX4X4, "View Projection"); } bool CNodeMatrix_VP::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_VP *solver = new CHLSL_Solver_VP(GetUniqueIndex()); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; } CNodeMatrix_M::CNodeMatrix_M(CNodeView *p) : BaseClass("Matrix Model", p) { GenerateJacks_Output(1); LockJackOutput_Flags(0, HLSLVAR_MATRIX4X3, "Model transform"); } bool CNodeMatrix_M::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_M *solver = new CHLSL_Solver_M(GetUniqueIndex()); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; } CNodeMatrix_VM::CNodeMatrix_VM(CNodeView *p) : BaseClass("Matrix VP", p) { GenerateJacks_Output(1); LockJackOutput_Flags(0, HLSLVAR_MATRIX4X4, "View Model"); } bool CNodeMatrix_VM::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_VM *solver = new CHLSL_Solver_VM(GetUniqueIndex()); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; } CNodeMatrix_FVP::CNodeMatrix_FVP(CNodeView *p) : BaseClass("Flashlight VP", p) { GenerateJacks_Output(1); LockJackOutput_Flags(0, HLSLVAR_MATRIX4X4, "Flashlight View Proj"); } bool CNodeMatrix_FVP::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_FVP *solver = new CHLSL_Solver_FVP(GetUniqueIndex()); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; } CNodeMatrix_Custom::CNodeMatrix_Custom(CNodeView *p) : BaseClass("Custom matrix", p) { m_iCustomID = CMATRIX_VIEW; GenerateJacks_Output(1); UpdateNode(); } void CNodeMatrix_Custom::UpdateNode() { const customMatrix_t *data = GetCMatrixInfo(m_iCustomID); LockJackOutput_Flags(0, data->iHLSLVarFlag, data->szCanvasName); } KeyValues *CNodeMatrix_Custom::AllocateKeyValues(int NodeIndex) { KeyValues *pKV = BaseClass::AllocateKeyValues(NodeIndex); pKV->SetInt("i_c_matrix", m_iCustomID); return pKV; } void CNodeMatrix_Custom::RestoreFromKeyValues_Specific(KeyValues *pKV) { m_iCustomID = pKV->GetInt("i_c_matrix"); UpdateNode(); } bool CNodeMatrix_Custom::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_CMatrix *solver = new CHLSL_Solver_CMatrix(GetUniqueIndex()); solver->SetMatrixID(m_iCustomID); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; }
29.70068
86
0.72721
cstom4994
82f4383c4b8b94f7530e5383d774075ffc28df0d
634
cpp
C++
Nowcoder/64J/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
Nowcoder/64J/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
Nowcoder/64J/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <string> #include <iomanip> #include <climits> using namespace std; int mapping[26]; int main() { ios::sync_with_stdio(false); for (int i = 0; i < 26; i++) { mapping[i] = i; } string s; cin >> s; int queryNum; cin >> queryNum; while (queryNum--) { char a, b; cin >> a >> b; swap(mapping[b - 'a'], mapping[a - 'a']); } for (int i = 0; i < s.length(); i++) { s[i] = mapping[s[i] - 'a'] + 'a'; } cout << s << endl; return 0; }
17.135135
49
0.498423
codgician
82fc7cf3155ac30eb2a42e2d690d5be36b76e689
1,816
cpp
C++
trainings/2015-11-03-Changsha-2013/I.cpp
HcPlu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
9
2017-10-07T13:35:45.000Z
2021-06-07T17:36:55.000Z
trainings/2015-11-03-Changsha-2013/I.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
null
null
null
trainings/2015-11-03-Changsha-2013/I.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
3
2018-04-24T05:27:21.000Z
2019-04-25T06:06:00.000Z
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <iostream> using namespace std; const int N = 100005; int n, X, Y, tot = 0; int value[N], S[N], P[N], F[N]; int start[N]; pair<int, int> f[N][2]; struct Node { int x, y, next; } road[N << 1]; void build(int x, int y) { tot++; road[tot].x = x, road[tot].y = y, road[tot].next = start[x], start[x] = tot; } pair<int, int> add(pair<int, int> x, pair<int, int> y) { return make_pair(x.first + y.first, x.second + y.second); } pair<int, int> uni(pair<int, int> x, pair<int, int> y) { return make_pair(max(x.first, y.first), min(x.second, y.second)); } void dfs(int x, int fa, int flag) { flag ^= S[x]; int now_value = value[x]; if ((flag ^ P[x]) == 1) { now_value *= -1; } pair<int, int> current = make_pair(now_value, now_value); f[x][0] = current; for (int i = start[x]; i; i = road[i].next) { int to = road[i].y; if (to == fa) { continue; } dfs(to, x, flag); f[x][0] = add(f[x][0], uni(f[to][0], f[to][1])); } f[x][1] = make_pair(-f[x][0].second, -f[x][0].first); int delta = 0; if (S[x]) { delta = Y; } else { delta = X; } f[x][1].first -= delta; f[x][1].second += delta; return; } void work() { tot = 0; for (int i = 1; i <= n + 1; i++) { start[i] = 0; } for (int i = 2; i <= n + 1; i++) { scanf("%d%d%d%d", &value[i], &F[i], &S[i], &P[i]); F[i]++; build(F[i], i); } dfs(1, 0, 0); if (f[1][0].first < 0) { puts("HAHAHAOMG"); } else { printf("%d\n", f[1][0].first); } return; } int main() { while (scanf("%d%d%d", &n, &X, &Y) == 3) { work(); } return 0; }
20.873563
80
0.467511
HcPlu
82fccde8b90c432f1a32fadf9a0ec364c7aeb791
8,385
cpp
C++
src/gl9_scene/player.cpp
andsulavik/ppgso
44385aa9d8ee5f9a2951dfeb5e7c3e605377c68b
[ "MIT" ]
null
null
null
src/gl9_scene/player.cpp
andsulavik/ppgso
44385aa9d8ee5f9a2951dfeb5e7c3e605377c68b
[ "MIT" ]
null
null
null
src/gl9_scene/player.cpp
andsulavik/ppgso
44385aa9d8ee5f9a2951dfeb5e7c3e605377c68b
[ "MIT" ]
null
null
null
#include "player.h" #include "scene.h" #include "road.h" #include "Pipe.h" #include "Monster.h" #include "shadow.h" #include <shaders/diffuse_vert_glsl.h> #include <shaders/diffuse_frag_glsl.h> // shared resources std::unique_ptr<ppgso::Mesh> Player::mesh; std::unique_ptr<ppgso::Texture> Player::texture; std::unique_ptr<ppgso::Shader> Player::shader; Player::Player() { // Scale the default model scale *= 3.0f; position.y = 4.0f; // Initialize static resources if needed if (!shader) shader = std::make_unique<ppgso::Shader>(diffuse_vert_glsl, diffuse_frag_glsl); if (!texture) { texture = std::make_unique<ppgso::Texture>(ppgso::image::loadBMP("Toot_Braustein.bmp")); } if (!mesh) mesh = std::make_unique<ppgso::Mesh>("Toot_Braustein.obj"); } bool decrease, increase = true, death = false, intangibleL = true, intangibleR = true, monsterKill = false, pipe = false; float dist1 = 0, dist2 = 0; bool Player::update(Scene &scene, float dt) { // Fire delay increment fireDelay += dt; float closestDist = 0; for (auto &obj : scene.objects) { // Ignore self in scene if (obj.get() == this) continue; // We only need to collide with asteroids and projectiles, ignore other objects auto road = dynamic_cast<Road*>(obj.get()); // dynamic_pointer_cast<Road>(obj); auto pipe = dynamic_cast<Pipe*>(obj.get()); auto monster = dynamic_cast<Monster*>(obj.get()); if (!road and !pipe and !monster) continue; // When colliding with other asteroids make sure the object is older than .5s // This prevents excessive collisions when asteroids explode. // if (asteroid && age < 0.5f) continue; // Compare distance to approximate size of the asteroid estimated from scale.y if(closestDist != 0 and closestDist > distance(position, obj->position)){ closestRd = road; closestDist = distance(position, obj->position); } else if(closestDist == 0){ closestRd = road; closestDist = distance(position, obj->position); } } if((closestRd->monster != nullptr) and !monsterKill and ((closestRd->monster->position.x + 5.5f >= position.x and closestRd->monster->position.x <= position.x) or (closestRd->monster->position.x - 5.5f <= position.x and closestRd->monster->position.x >= position.x)) and abs(abs(closestRd->monster->position.y)-abs(position.y)) < 9.5f){ position.y += 10.6f; monsterKill = true; } if((position.y <= closestRd->position.y + 4.f and position.y >= closestRd->position.y-17.f) and (position.x < closestRd->position.x-2.f or position.x > closestRd->position.x+2.f)){ intangibleL = true; intangibleR = true; if(position.x > closestRd->position.x - 30.f and (position.x < closestRd->position.x)){ intangibleR = false; intangibleL = true; } else if(position.x < closestRd->position.x + 30.f and (position.x > closestRd->position.x)){ intangibleL = false; intangibleR = true; } } else{ intangibleL = true; intangibleR = true; } if (glm::length(closestRd->position.x - position.x) < (closestRd->scale.x + scale.x)*0.6 and distance(position, closestRd->position) < (closestRd->scale.y + scale.y) *2.f ) { death = false; } else{ death = true; } if(monsterKill == true){ position.y -= 1.6f; rotation.x -= 0.05f; rotation.z -= 0.005f; rotation.y -= 0.005f; scene.camera->position.y -= 1.6f; if(position.y <= -50){ monsterKill = false; return false; } } else { if(closestRd->pipe != nullptr){ if(closestRd->right){ position.x -= 0.6f; scene.camera->position.x -= 0.6f; } else{ position.x += 0.6f; scene.camera->position.x += 0.6f; } } if (position.y >= dist1 + 45.f) { increase = false; decrease = true; } if (increase) { position.y += 1.6f; scene.camera->position.y += 1.6f; } else if (decrease or (decrease and increase)) { if (closestRd->pipe != nullptr and position.x <= closestRd->pipe->position.x + 11.f and position.x >= closestRd->pipe->position.x - 11.f and position.y <= closestRd->pipe->position.y + 1.f and position.y >= closestRd->pipe->position.y - 0.5f) { pipe = true; if(closestRd->pipe->cactus->position.y > closestRd->pipe->position.y +1.f){ monsterKill = true; pipe = death = increase = decrease = false; } } else{ pipe = false; position.y -= 1.6f; scene.camera->position.y -= 1.6f; } } else if (death) { increase = false; decrease = true; position.y -= 1.6f; scene.camera->position.y -= 1.6f; } if ((position.y >= closestRd->position.y + 4.f and position.y <= closestRd->position.y + 4.8f) and !death) { decrease = increase = false; } if (position.y <= -50 and death) { death = false; increase = true; return false; } if (rotation.z == NULL) { //rotation.z = 4.4f; rotation.z = 9; } // Keyboard controls if (scene.keyboard[GLFW_KEY_LEFT]) { if (increase or decrease) { if (intangibleR) { position.x += 10 * 8 * dt; scene.camera->position.x += 10 * 8 * dt; } } else { if (intangibleR) { position.x += 10 * 6 * dt; scene.camera->position.x += 10 * 6 * dt; } } rotation.z = -4.8f; if (scene.keyboard[GLFW_KEY_SPACE] and !death and !increase and !decrease or (scene.keyboard[GLFW_KEY_SPACE] and !increase and pipe)) { if(pipe){ dist1 = closestRd->pipe->position.y; } else{ dist1 = closestRd->position.y; } increase = true; } } else if (scene.keyboard[GLFW_KEY_RIGHT]) { if (increase or decrease) { if (intangibleL) { position.x -= 10 * 8 * dt; scene.camera->position.x -= 10 * 8 * dt; } } else { if (intangibleL) { position.x -= 10 * 6 * dt; scene.camera->position.x -= 10 * 6 * dt; } } rotation.z = 4.8f; if (scene.keyboard[GLFW_KEY_SPACE] and !death and !increase and !decrease or (scene.keyboard[GLFW_KEY_SPACE] and !increase and pipe)) { increase = true; if(pipe){ dist1 = closestRd->pipe->position.y; } else{ dist1 = closestRd->position.y; } } } else if (scene.keyboard[GLFW_KEY_SPACE] and !death and !increase and !decrease or (scene.keyboard[GLFW_KEY_SPACE] and pipe)) { increase = true; if(pipe){ dist1 = closestRd->pipe->position.y; } else{ dist1 = closestRd->position.y; } } } if(shadow != nullptr){ shadow->posPlayerX = position.x; shadow->posPlayerY = closestRd->position.y+5.f; shadow->update(scene, dt); } generateModelMatrix(); return true; } void Player::render(Scene &scene) { shader->use(); if(shadow != nullptr and !death ){ if(position.x <= closestRd->position.x + 10.5f){ shadow->render(scene); } } // Set up light shader->setUniform("LightDirection", scene.lightDirection); // use camera shader->setUniform("ProjectionMatrix", scene.camera->projectionMatrix); shader->setUniform("ViewMatrix", scene.camera->viewMatrix); // render mesh shader->setUniform("ModelMatrix", modelMatrix); shader->setUniform("Texture", *texture); mesh->render(); } void Player::onClick(Scene &scene) { std::cout << "Player has been clicked!" << std::endl; }
35.231092
339
0.545021
andsulavik
82fd78c9bf8f1f535b4665f06a6c897b2ea7553f
2,646
cpp
C++
ogsr_engine/xrCore/cpuid.cpp
WarezzK/OGSE-WarezzKCZ-Engine
9d5a594edd7d8f2edf5e1d831f380bc817400e17
[ "Apache-2.0" ]
3
2019-09-10T13:37:08.000Z
2021-05-18T14:53:29.000Z
ogsr_engine/xrCore/cpuid.cpp
Rikoshet-234/rebirth_engine
7ad4e8a711434e8346b7c97b3a82447695418344
[ "Apache-2.0" ]
null
null
null
ogsr_engine/xrCore/cpuid.cpp
Rikoshet-234/rebirth_engine
7ad4e8a711434e8346b7c97b3a82447695418344
[ "Apache-2.0" ]
2
2020-06-26T11:50:59.000Z
2020-12-30T11:07:31.000Z
#include "stdafx.h" #include "cpuid.h" #include <intrin.h> decltype(auto) countSetBits(ULONG_PTR bitMask) { DWORD LSHIFT = sizeof(ULONG_PTR) * 8 - 1; DWORD bitSetCount = 0; auto bitTest = static_cast<ULONG_PTR>(1) << LSHIFT; DWORD i; for (i = 0; i <= LSHIFT; ++i) { bitSetCount += ((bitMask & bitTest) ? 1 : 0); bitTest /= 2; } return bitSetCount; } _processor_info::_processor_info() { int cpinfo[4]; // detect cpu vendor __cpuid(cpinfo, 0); memcpy(vendor, &(cpinfo[1]), sizeof(int)); memcpy(vendor + sizeof(int), &(cpinfo[3]), sizeof(int)); memcpy(vendor + 2 * sizeof(int), &(cpinfo[2]), sizeof(int)); // detect cpu model __cpuid(cpinfo, 0x80000002); memcpy(brand, cpinfo, sizeof(cpinfo)); __cpuid(cpinfo, 0x80000003); memcpy(brand + sizeof(cpinfo), cpinfo, sizeof(cpinfo)); __cpuid(cpinfo, 0x80000004); memcpy(brand + 2 * sizeof(cpinfo), cpinfo, sizeof(cpinfo)); // detect cpu main features __cpuid(cpinfo, 1); stepping = cpinfo[0] & 0xf; model = (u8)((cpinfo[0] >> 4) & 0xf) | ((u8)((cpinfo[0] >> 16) & 0xf) << 4); family = (u8)((cpinfo[0] >> 8) & 0xf) | ((u8)((cpinfo[0] >> 20) & 0xff) << 4); m_f1_ECX = cpinfo[2]; m_f1_EDX = cpinfo[3]; __cpuid(cpinfo, 7); m_f7_EBX = cpinfo[1]; m_f7_ECX = cpinfo[2]; // and check 3DNow! support __cpuid(cpinfo, 0x80000001); m_f81_ECX = cpinfo[2]; m_f81_EDX = cpinfo[3]; // get version of OS DWORD dwMajorVersion = 0; DWORD dwVersion = 0; dwVersion = GetVersion(); dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); if (dwMajorVersion <= 5) // XP don't support SSE3+ instruction sets { m_f1_ECX[0] = 0; m_f1_ECX[9] = 0; m_f1_ECX[19] = 0; m_f1_ECX[20] = 0; m_f81_ECX[6] = 0; m_f1_ECX[28] = 0; m_f7_EBX[5] = 0; } // Calculate available processors DWORD returnedLength = 0; DWORD byteOffset = 0; GetLogicalProcessorInformation(nullptr, &returnedLength); auto buffer = std::make_unique<u8[]>(returnedLength); auto ptr = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION>(buffer.get()); GetLogicalProcessorInformation(ptr, &returnedLength); auto processorCoreCount = 0u; auto logicalProcessorCount = 0u; while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnedLength) { switch (ptr->Relationship) { case RelationProcessorCore: processorCoreCount++; // A hyperthreaded core supplies more than one logical processor. logicalProcessorCount += countSetBits(ptr->ProcessorMask); break; default: break; } byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ptr++; } // All logical processors coresCount = processorCoreCount; threadCount = logicalProcessorCount; }
25.442308
86
0.685563
WarezzK
82ffd34e6213c3599aab61f248440f88097cc972
252
cpp
C++
src/examples/04_module/01_while/main.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Grecia1813
f356c1ed8f6e75b9e9d6164747a5c199bead8c95
[ "MIT" ]
null
null
null
src/examples/04_module/01_while/main.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Grecia1813
f356c1ed8f6e75b9e9d6164747a5c199bead8c95
[ "MIT" ]
null
null
null
src/examples/04_module/01_while/main.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Grecia1813
f356c1ed8f6e75b9e9d6164747a5c199bead8c95
[ "MIT" ]
null
null
null
#include "while.h" #include<iostream> using std::cout; using std::cin; int main() { char choice = 'y'; while (choice == 'y' || choice == 'Y') { cout << "Enter y to continue, any other char to exit: "; cin >> choice; } return 0; }
14
60
0.563492
acc-cosc-1337-fall-2020
d2016de542aef1d6c665c2f8b9aa17391c792f1a
12,458
hpp
C++
ares/component/processor/sh2/sh7604/sh7604.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
ares/component/processor/sh2/sh7604/sh7604.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
176
2020-07-25T19:11:23.000Z
2021-10-04T17:11:32.000Z
ares/component/processor/sh2/sh7604/sh7604.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
#pragma once //Hitachi SH7604 //struct SH2 { enum : u32 { Byte, Word, Long }; struct Area { enum : u32 { Cached = 0, Uncached = 1, Purge = 2, Address = 3, Data = 6, IO = 7, };}; //bus.cpp auto readByte(u32 address) -> u32; auto readWord(u32 address) -> u32; auto readLong(u32 address) -> u32; auto writeByte(u32 address, u32 data) -> void; auto writeWord(u32 address, u32 data) -> void; auto writeLong(u32 address, u32 data) -> void; //io.cpp auto internalReadByte(u32 address, n8 data = 0) -> n8; auto internalWriteByte(u32 address, n8 data) -> void; struct Cache { maybe<SH2&> self; //cache.cpp template<u32 Size> auto read(u32 address) -> u32; template<u32 Size> auto write(u32 address, u32 data) -> void; template<u32 Size> auto readData(u32 address) -> u32; template<u32 Size> auto writeData(u32 address, u32 data) -> void; auto readAddress(u32 address) -> u32; auto writeAddress(u32 address, u32 data) -> void; auto purge(u32 address) -> void; template<u32 Ways> auto purge() -> void; auto power() -> void; //serialization.cpp auto serialize(serializer&) -> void; enum : u32 { Way0 = 0 * 64, Way1 = 1 * 64, Way2 = 2 * 64, Way3 = 3 * 64, Invalid = 1 << 19, }; union Line { u8 bytes[16]; u16 words[8]; u32 longs[4]; }; u8 lrus[64]; u32 tags[4 * 64]; Line lines[4 * 64]; n1 enable; n1 disableCode; n1 disableData; n2 twoWay; //0 = 4-way, 2 = 2-way (forces ways 2 and 3) n2 waySelect; //internal: n2 lruSelect[64]; n6 lruUpdate[4][64]; } cache; //interrupt controller struct INTC { maybe<SH2&> self; //interrupts.cpp auto run() -> void; //serialization.cpp auto serialize(serializer&) -> void; struct ICR { //interrupt control register n1 vecmd; //IRL interrupt vector mode select n1 nmie; //NMI edge select n1 nmil; //NMI input level } icr; struct IPRA { //interrupt priority level setting register A n4 wdtip; //WDT interrupt priority n4 dmacip; //DMAC interrupt priority n4 divuip; //DIVU interrupt priority } ipra; struct IPRB { //interrupt priority level setting register B n4 frtip; //FRT interrupt priority n4 sciip; //SCI interrupt priority } iprb; struct VCRA { //vector number setting register A n7 srxv; //SCI receive data full interrupt vector number n7 serv; //SCI receive error interrupt vector number } vcra; struct VCRB { //vector number setting register B n7 stev; //SCI transmit end interrupt vector number n7 stxv; //SCI transmit data empty interrupt vector number } vcrb; struct VCRC { //vector number setting register C n7 focv; //FRT output compare interrupt vector number n7 ficv; //FRT input capture interrupt vector number } vcrc; struct VCRD { //vector number setting register D n7 fovv; //FRT overflow interrupt vector number } vcrd; struct VCRWDT { //vector number setting register WDT n4 bcmv; //BSC compare match interrupt vector number n4 witv; //WDT interval interrupt vector number } vcrwdt; } intc; //DMA controller struct DMAC { maybe<SH2&> self; //dma.cpp auto run() -> void; auto transfer(bool c) -> void; //serialization.cpp auto serialize(serializer&) -> void; n32 sar[2]; //DMA source address registers n32 dar[2]; //DMA destination address registers n24 tcr[2]; //DMA transfer count registers struct CHCR { //DMA channel control registers n1 de; //DMA enable n1 te; //transfer end flag n1 ie; //interrupt enable n1 ta; //transfer address mode n1 tb; //transfer bus mode n1 dl; //DREQn level bit n1 ds; //DREQn select bit n1 al; //acknowledge level bit n1 am; //acknowledge/transfer mode bit n1 ar; //auto request mode bit n2 ts; //transfer size n2 sm; //source address mode n2 dm; //destination address mode } chcr[2]; n8 vcrdma[2]; //DMA vector number registers n2 drcr[2]; //DMA request/response selection control registers struct DMAOR { //DMA operation register n1 dme; //DMA master enable bit n1 nmif; //NMI flag bit n1 ae; //address error flag bit n1 pr; //priority mode bit } dmaor; //internal: n1 dreq; n2 pendingIRQ; } dmac; //serial communication interface struct SCI { maybe<SH2&> self; maybe<SH2&> link; //serial.cpp auto run() -> void; //serialization.cpp auto serialize(serializer&) -> void; struct SMR { //serial mode register n2 cks; //clock select n1 mp; //multi-processor mode n1 stop; //stop bit length n1 oe; //parity mode n1 pe; //parity enable n1 chr; //character length n1 ca; //communication mode } smr; struct SCR { //serial control register n2 cke; //clock enable n1 teie; //transmit end interrupt enable n1 mpie; //multi-processor interrupt enable n1 re; //receive enable n1 te; //transmit enable n1 rie; //receive interrupt enable n1 tie; //transmit interrupt enable } scr; struct SSR { //serial status register n1 mpbt; //multi-processor bit transfer n1 mpb; //multi-processor bit n1 tend = 1; //transmit end n1 per; //parity error n1 fer; //framing error n1 orer; //overrun error n1 rdrf; //receive data register full n1 tdre; //transmit data register empty } ssr; n8 brr = 0xff; //bit rate register n8 tdr = 0xff; //transmit data register n8 rdr = 0x00; //receive data register //internal: n1 pendingTransmitEmptyIRQ; n1 pendingReceiveFullIRQ; } sci; //watchdog timer struct WDT { //serialization.cpp auto serialize(serializer&) -> void; struct WTCSR { //watchdog timer control/status register n3 cks; //clock select n1 tme; //timer enable n1 wtit; //timer mode select n1 ovf; //overflow flag } wtcsr; struct RSTCSR { //reset control/status register n1 rsts; //reset select n1 rste; //reset enable n1 wovf; //watchdog timer overflow flag } rstcsr; n8 wtcnt; //watchdog timer counter } wdt; //user break controller struct UBC { //serialization.cpp auto serialize(serializer&) -> void; n32 bara; //break address register A n32 bamra; //break address mask register A struct BBRA { //break bus register A n2 sza; //operand size select A n2 rwa; //read/write select A n2 ida; //instruction fetch/data access select A n2 cpa; //CPU cycle/peripheral cycle select A } bbra; n32 barb; //break address register B n32 bamrb; //break address mask register B struct BBRB { //break bus register B n2 szb; //operand size select B n2 rwb; //read/write select B n2 idb; //instruction fetch/data access select B n2 cpb; //CPU cycle/peripheral cycle select B } bbrb; n32 bdrb; //break data register B n32 bdmrb; //break data mask register B struct BRCR { //break control register n1 pcbb; //instruction break select B n1 dbeb; //data break enable B n1 seq; //sequence condition select n1 cmfpb; //peripheral condition match flag B n1 cmfcb; //CPU condition match flag B n1 pcba; //PC break select A n1 umd; //UBC mode n1 ebbe; //external bus break enable n1 cmfpa; //peripheral condition match flag A n1 cmfca; //CPU condition match flag A } brcr; } ubc; //16-bit free-running timer struct FRT { maybe<SH2&> self; //timer.cpp auto run() -> void; //serialization.cpp auto serialize(serializer&) -> void; struct TIER { //timer interrupt enable register n1 ovie; //timer overflow interrupt enable n1 ociae; //output compare interrupt enable A n1 ocibe; //output compare interrupt enable B n1 icie; //input capture interrupt enable } tier; struct FTCSR { //free-running timer control/status register n1 cclra; //counter clear A n1 ovf; //timer overflow flag n1 ocfa; //output compare flag A n1 ocfb; //output compare flag B n1 icf; //input capture flag } ftcsr; n16 frc; //free-running counter n16 ocra; //output compare register A n16 ocrb; //output compare register B struct TCR { //timer control register n2 cks; //clock select n1 iedg; //input edge select } tcr; struct TOCR { //timer output compare control register n1 olvla; //output level A n1 olvlb; //output level B n1 ocrs; //output compare register select } tocr; n16 ficr; //input capture register //internal: n32 counter; n1 pendingOutputIRQ; } frt; //bus state controller struct BSC { //serialization.cpp auto serialize(serializer&) -> void; struct BCR1 { //bus control register 1 n3 dram; //enable for DRAM and other memory n2 a0lw; //long wait specification for area 0 n2 a1lw; //long wait specification for area 1 n2 ahlw; //long wait specification for ares 2 and 3 n1 pshr; //partial space share specification n1 bstrom; //area 0 burst ROM enable n1 a2endian; //endian specification for area 2 n1 master; //bus arbitration (0 = master; 1 = slave) } bcr1; struct BCR2 { //bus control register 2 n2 a1sz; //bus size specification for area 1 n2 a2sz; //bus size specification for area 2 n2 a3sz; //bus size specification for area 3 } bcr2; struct WCR { //wait control register n2 w0; //wait control for area 0 n2 w1; //wait control for area 1 n2 w2; //wait control for area 2 n2 w3; //wait control for area 3 n2 iw0; //idles between cycles for area 0 n2 iw1; //idles between cycles for area 1 n2 iw2; //idles between cycles for area 2 n2 iw3; //idles between cycles for area 3 } wcr; struct MCR { //individual memory control register n1 rcd; //RAS-CAS delay n1 trp; //RSA precharge time n1 rmode; //refresh mode n1 rfsh; //refresh control n3 amx; //address multiplex n1 sz; //memory data size n1 trwl; //write-precharge delay n1 rasd; //bank active mode n1 be; //burst enable n2 tras; //CAS before RAS refresh RAS assert time } mcr; struct RTCSR { //refresh timer control/status register n3 cks; //clock select n1 cmie; //compare match interrupt enable n1 cmf; //compare match flag } rtcsr; n8 rtcnt; //refresh timer counter n8 rtcor; //refresh time constant register } bsc; //standby control register struct SBYCR { //serialization.cpp auto serialize(serializer&) -> void; n1 sci; //SCI halted n1 frt; //FRT halted n1 divu; //DIVU halted n1 mult; //MULT halted n1 dmac; //DMAC halted n1 hiz; //port high impedance n1 sby; //standby } sbycr; //division unit struct DIVU { //serialization.cpp auto serialize(serializer&) -> void; n32 dvsr; //divisor register struct DVCR { //division control register n1 ovf; //overflow flag n1 ovfie; //overflow interrupt enable } dvcr; n7 vcrdiv; //vector number setting register n32 dvdnth; //dividend register H n32 dvdntl; //dividend register L } divu; //};
32.025707
70
0.581153
CasualPokePlayer
d203bf517b9b61576aa40c7c8c7f8827b60d7bb8
12,034
cpp
C++
MEX/src/cpp/vision/features/low_level/self_similarity.cpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
47
2016-07-25T00:48:59.000Z
2021-02-17T09:19:03.000Z
MEX/src/cpp/vision/features/low_level/self_similarity.cpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
5
2016-09-17T19:40:46.000Z
2018-11-07T06:49:02.000Z
MEX/src/cpp/vision/features/low_level/self_similarity.cpp
iqbalu/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
35
2016-07-21T09:13:15.000Z
2019-05-13T14:11:37.000Z
/* * self_similarity.cpp * * Created on: Jan 25, 2012 * Author: lbossard */ #include "self_similarity.hpp" #include <boost/math/constants/constants.hpp> #include <boost/foreach.hpp> namespace vision { namespace features { SelfSimilarityExtractor::SelfSimilarityExtractor( bool color_ssd, unsigned int patch_size, unsigned int window_radius, unsigned int radius_bin_count, unsigned int angle_bin_count, float var_noise, unsigned int auto_var_radius) { color_ssd_ = color_ssd; this->setSelfSimilarityParameters( patch_size, window_radius, radius_bin_count, angle_bin_count, var_noise, auto_var_radius); } void SelfSimilarityExtractor::setSelfSimilarityParameters( unsigned int patch_size, unsigned int window_radius, unsigned int radius_bin_count, unsigned int angle_bin_count, float var_noise, unsigned int auto_var_radius) { self_similarity_.setParameters(patch_size, window_radius, radius_bin_count, angle_bin_count, var_noise, auto_var_radius); } /*virtual*/ SelfSimilarityExtractor::~SelfSimilarityExtractor() { } /*virtual*/ cv::Mat_<float> SelfSimilarityExtractor::denseExtract( const cv::Mat& input_image, std::vector<cv::Point>& locations, const cv::Mat_<uchar>& mask ) const { const unsigned int radius = 5; // generate locations locations.clear(); LowLevelFeatureExtractor::generateGridLocations( input_image.size(), cv::Size(radius, radius), radius, radius, locations, mask); if (locations.size() == 0) { return cv::Mat_<float>(); } // convert to gray if necessary cv::Mat image = input_image; if (!color_ssd_ && image.type() != CV_8U) { cv::cvtColor(image, image, CV_BGR2GRAY); } // allocate memroy cv::Mat_<float> features(locations.size(), descriptorLength()); // loop over locations and compute descriptors std::size_t point_idx = 0; BOOST_FOREACH(const cv::Point& p, locations) { cv::Mat_<float> descriptor = features.row(point_idx); if (self_similarity_.extract(image, p, descriptor)) { ++point_idx; } } if (point_idx == 0) { return cv::Mat_<float>(); } features.resize(point_idx); return features; } /*virtual*/ unsigned int SelfSimilarityExtractor::descriptorLength() const { return self_similarity_.descriptorLength(); } //////////////////////////////////////////////////////////////////////////////// /** * * @param patch_size odd * @param window_radius even * @param radius_bin_count * @param angle_bin_count * @param var_noise * @param auto_var_radius */ SelfSimilarity::SelfSimilarity( unsigned int patch_size, unsigned int window_radius, unsigned int radius_bin_count, unsigned int angle_bin_count, float var_noise, unsigned int auto_var_radius) { setParameters(patch_size, window_radius, radius_bin_count, angle_bin_count, var_noise, auto_var_radius); } /*virtual*/ SelfSimilarity::~SelfSimilarity() { } void SelfSimilarity::setParameters(unsigned int patch_size, unsigned int window_radius, unsigned int radius_bin_count, unsigned int angle_bin_count, float var_noise, unsigned int auto_var_radius) { // set parameters patch_size_ = patch_size; window_radius_ = window_radius; radius_bin_count_ = radius_bin_count; angle_bin_count_ = angle_bin_count; var_noise_ = var_noise; // precompute binning and autovar indices const int window_size = 2 * window_radius_ + 1; bin_map_= -cv::Mat_<int>::ones(window_size, window_size); // init to -1 autovar_indices_.clear(); autovar_indices_.reserve((2*auto_var_radius + 1)*(2*auto_var_radius + 1)); // upper bound double angle = 0.f; double radius = 0.f; int angle_bin = 0; int radius_bin = 0; int bin_id = 0; for (int y = -window_radius_; y < window_size; ++y) { for (int x = -window_radius_; x < window_size; ++x) { /* * scale log(y) to (bin_count - 1)...0 */ radius = std::sqrt(static_cast<float>(x * x + y * y)); if (radius > window_radius_ || radius == 0.) { continue; } radius_bin = static_cast<int>( ( std::log(radius)) / std::log(window_radius_+.5) * radius_bin_count_); /* * \alpha \in [ -\pi ... +\pi ] * bin_id \in [0 ... (bin_count - 1) ] * bin_id = floor( (\alpha + \pi) / ( 2 \pi) * bin_count ) * = floor( \alpha bin_count / ( 2 \pi) + bin_count/2 ) */ angle = std::atan2(y, x); // [-pi ... pi] angle_bin = static_cast<int>( ((angle * angle_bin_count_) / ( boost::math::constants::two_pi<double>())) + angle_bin_count_/2.) % angle_bin_count; // atan2 gives [-pi ... pi] and not (-pi ... pi] that's why we mod bin_id = angle_bin * radius_bin_count + radius_bin; bin_map_(y + window_radius_, x + window_radius_) = bin_id; if (radius <= auto_var_radius && radius > 0) { autovar_indices_.push_back(cv::Point(y + window_radius_, x + window_radius_)); } } } } bool SelfSimilarity::extract(const cv::Mat& image, const cv::Point& location, cv::Mat_<float>& descriptor) const { // compute the distance surface cv::Mat_<float> distance_surface; compute_distance_surface(image, location, distance_surface); if (distance_surface.rows == 0 || distance_surface.cols == 0) { return false; } // put it into the logpolar descriptor compute_descriptor(distance_surface, descriptor); return true; } //void showmat(const std::string titile, const cv::Mat& mat, int size) //{ // cv::Mat scaled; // cv::resize(mat, scaled, cv::Size(mat.rows * size, mat.cols * size), 0, 0, cv::INTER_AREA); // cv::imshow(titile, scaled); //} void SelfSimilarity::compute_distance_surface(const cv::Mat& image, const cv::Point& loaction, cv::Mat_<float>& distance_surface) const { const int patch_radius = patch_size_ / 2; const int window_size = window_radius_ * 2 + 1; // check boundaries if ( (loaction.x - (int)window_radius_ - patch_radius) < 0 || (loaction.y - (int)window_radius_ - patch_radius) < 0 || (loaction.x + (int)window_radius_ + patch_size_) >= image.cols || (loaction.y + (int)window_radius_ + patch_size_) >= image.rows) { distance_surface = cv::Mat_<float>(); return; } // allocate memory and precompute some structures distance_surface.create(window_size, window_size); const cv::Mat inner_patch = image( cv::Range(loaction.y - patch_radius, loaction.y + patch_radius + 1), cv::Range(loaction.x - patch_radius, loaction.x + patch_radius + 1)); // assert(distance_surface.rows == window_size); // assert(distance_surface.cols == window_size); for (unsigned int r = 0; r < window_size; ++r) { const int y_window_patch_start = loaction.y - window_radius_ + r - patch_radius ; const cv::Range y_window_range( y_window_patch_start, y_window_patch_start + patch_size_); for (unsigned int c = 0; c < window_size; ++c) { // const int bin_idx = bin_map_(r,c); // if (bin_idx < 0) // { // continue; // } const int x_window_patch_start = loaction.x - window_radius_ + c - patch_radius; const cv::Range x_window_range( x_window_patch_start, x_window_patch_start + patch_size_); const cv::Mat window_patch = image(y_window_range, x_window_range); if (image.channels() == 3) { distance_surface(r, c) = ssd3(inner_patch, window_patch); } else { distance_surface(r, c) = ssd1(inner_patch, window_patch); } // showmat("inner", inner_patch, 100); // showmat("window_patch", window_patch, 100); // cv::Mat d = image.clone(); // // window_patch // cv::rectangle(d, // cv::Point(x_window_range.start, y_window_range.start), // cv::Point(x_window_range.end-1, y_window_range.end-1), // CV_RGB(0,255,255) // ); // // center_patch // cv::rectangle(d, // cv::Point(loaction.x - patch_radius, loaction.y - patch_radius), // cv::Point(loaction.x + patch_radius, loaction.y + patch_radius), // CV_RGB(255,0,255) // ); // // whole window // cv::rectangle(d, // cv::Point( // loaction.x - window_radius_, // loaction.y - window_radius_), // cv::Point( // loaction.x + window_radius_, // loaction.y + window_radius_), // CV_RGB(255,0,255) // ); // showmat("all", d, 5); // cv::waitKey(); } } } void SelfSimilarity::compute_descriptor(const cv::Mat_<float>& distance_surface, cv::Mat_<float>& descriptor) const { // allocate log-polar descriptor. we init it with -1 as the e^-x is // always > 0 for x < \inf const int descriptor_length = radius_bin_count_*angle_bin_count_; descriptor.create(1, descriptor_length); descriptor = -1; // compute auto noise (like original paper matlab implementation): // find max ssd at the autovar_indices (<- places with within radius 1) float variance = var_noise_; for (unsigned int i = 0; i < autovar_indices_.size(); ++i) { const cv::Point& p = autovar_indices_[i]; variance = std::max(variance, distance_surface(p.y, p.x)); } // compute finally the descriptor float min_correlation = std::numeric_limits<float>::max(); float max_correlation = std::numeric_limits<float>::min(); for (int r = 0; r < distance_surface.rows; ++r) { for (int c = 0; c < distance_surface.cols; ++c) { const int bin_idx = bin_map_(r,c); if (bin_idx < 0) { continue; } // compute S_q(x,y) float correlation = std::exp(-distance_surface(r, c) / variance); // we store only the max ssd const float current_value = descriptor(bin_idx); if (current_value < correlation) { descriptor(bin_idx) = correlation; min_correlation = std::min(correlation, min_correlation); max_correlation = std::max(correlation, max_correlation); } } } // finally: normalize to [0 ... 1] //XXX: Note: in the original implementation, there would be only stretching to max without substracting min // however, the paper states "normalized by linearly streticht its values to the range [0...1]" // descriptor = (descriptor - min_correlation) / (max_correlation - min_correlation); //XXX: strange enough: "correct" normalization gives a segfault while clustering descriptor = descriptor / max_correlation; // normalisation from the paper implementation } } /* namespace features */ } /* namespace vision */
32.524324
135
0.575453
umariqb
d2083f4db1d876becc56a5bad6bee2ad78e4305a
1,491
hpp
C++
include/tinycoro/Algorithms.hpp
asmei1/tinycoro
5b6d3dc9412c8c9e369f652707894a586a8bd9a8
[ "MIT" ]
7
2020-12-21T02:16:33.000Z
2022-03-18T23:57:05.000Z
include/tinycoro/Algorithms.hpp
asmei1/tinycoro
5b6d3dc9412c8c9e369f652707894a586a8bd9a8
[ "MIT" ]
null
null
null
include/tinycoro/Algorithms.hpp
asmei1/tinycoro
5b6d3dc9412c8c9e369f652707894a586a8bd9a8
[ "MIT" ]
null
null
null
// // Created by Asmei on 11/25/2020. // #ifndef TINYCORO_ALGORITHMS_HPP #define TINYCORO_ALGORITHMS_HPP #include "FireAndForget.hpp" #include "Generator.hpp" namespace tinycoro { /* * Create endless stream, yielding objects from begin (inclusive). */ template <std::incrementable T> tinycoro::Generator<T> range(T begin) { while(true) { co_yield begin++; } } /* * Yield objects from begin (inclusive) to end (enxclusive) with incremental. */ template <std::incrementable T> tinycoro::Generator<T> range(T begin, T end) { while(begin != end) { co_yield begin++; } } /* * Yield objects from begin (inclusive) to end (enxclusive) with given step. */ template <typename T, typename Step> requires requires (T x, Step s) { x + s; } tinycoro::Generator<T> range(T begin, T end, Step step) { while(begin < end) { co_yield begin; begin += step; } } /* * Helper function to execute any coroutine as fire and forget function. * It could receive any awaitable object or coroutine function. */ template <typename T> FireAndForget fireAndForget(T t) { if constexpr(std::is_invocable_v<T>) { co_await t(); } else { co_await std::move(t); } } } #endif // TINYCORO_ALGORITHMS_HPP
21.926471
81
0.564051
asmei1
d20b2cb8304b6b684bfa429f9574104307dd5698
202
cpp
C++
FrameLib_Max_Objects/Complex_Unary/fl.complex.tanh~.cpp
AlexHarker/FrameLib
04b9882561c83d3240c6cb07f14861244d1d6272
[ "BSD-3-Clause" ]
33
2017-08-13T00:02:41.000Z
2022-03-10T23:02:17.000Z
FrameLib_Max_Objects/Complex_Unary/fl.complex.tanh~.cpp
AlexHarker/FrameLib
04b9882561c83d3240c6cb07f14861244d1d6272
[ "BSD-3-Clause" ]
60
2018-02-01T23:33:36.000Z
2022-03-23T23:25:13.000Z
FrameLib_Max_Objects/Complex_Unary/fl.complex.tanh~.cpp
AlexHarker/FrameLib
04b9882561c83d3240c6cb07f14861244d1d6272
[ "BSD-3-Clause" ]
8
2018-02-01T20:18:46.000Z
2020-07-03T12:53:04.000Z
#include "FrameLib_Complex_Unary_Objects.h" #include "FrameLib_MaxClass.h" extern "C" int C74_EXPORT main(void) { FrameLib_MaxClass_Expand<FrameLib_Complex_Tanh>::makeClass("fl.complex.tanh~"); }
22.444444
83
0.782178
AlexHarker
d20de518295a56f0fefa5c15bd74d41f867164d3
1,282
cpp
C++
test/echd/jsonrpc/eth_client.cpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
2
2020-06-01T00:30:12.000Z
2020-06-05T18:41:48.000Z
test/echd/jsonrpc/eth_client.cpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
null
null
null
test/echd/jsonrpc/eth_client.cpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
1
2020-06-05T18:33:28.000Z
2020-06-05T18:33:28.000Z
#include "catch2/catch.hpp" // Project includes #include "echd/jsonrpc/eth_client.hpp" using namespace ech; using Catch::Matchers::Equals; TEST_CASE("eth jsonrpc client leading zeroes empty", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::removeLeadingZeroes(std::string("")); REQUIRE(std::string_view("0") == s); } TEST_CASE("eth jsonrpc client leading zeroes zero", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::removeLeadingZeroes(std::string("0")); REQUIRE(std::string_view("0") == s); } TEST_CASE("eth jsonrpc client leading zeroes padded zero", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::removeLeadingZeroes(std::string("0000")); REQUIRE(std::string_view("0") == s); } TEST_CASE("eth jsonrpc client leading zeroes non-zero", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::removeLeadingZeroes(std::string("10")); REQUIRE(std::string_view("10") == s); } TEST_CASE("eth jsonrpc client leading zeroes padded non-zero", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::removeLeadingZeroes(std::string("0010")); REQUIRE(std::string_view("10") == s); } TEST_CASE("eth jsonrpc client 0x", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::formatHex(std::string("42")); REQUIRE(std::string_view("0x42") == s); }
26.163265
83
0.697348
adlerjohn
d20f99fe44a1a5a905bd94ecf7da6d4ec4d8bbbf
403
cpp
C++
BASIC c++/templetes/overloading_template_function.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/templetes/overloading_template_function.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/templetes/overloading_template_function.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
// // Created by rahul on 17/8/19. // #include <iostream> #include <string> using namespace std; template <class T> void display(T x) { cout<<"template display" << x<< '\n'; } void display(int x) { cout<<"explicit display"<<x<<'\n'; } void ccode(char ch) { int code; code=ch; cout<<code<<endl; } int main() { display(100); display(12.34); display('c'); ccode('A'); }
13.896552
41
0.575682
jattramesh
d210bf388a3ab5fc8635810fef0e3cb8fd428009
2,195
cpp
C++
code/test/inverted_index.cpp
mbeckem/msc
93e71ba163a7ffef4eec3e83934fa793f3f50ff6
[ "MIT" ]
null
null
null
code/test/inverted_index.cpp
mbeckem/msc
93e71ba163a7ffef4eec3e83934fa793f3f50ff6
[ "MIT" ]
null
null
null
code/test/inverted_index.cpp
mbeckem/msc
93e71ba163a7ffef4eec3e83934fa793f3f50ff6
[ "MIT" ]
null
null
null
#include <catch.hpp> #include "geodb/irwi/inverted_index.hpp" #include "geodb/irwi/inverted_index_internal.hpp" #include "geodb/irwi/inverted_index_external.hpp" #include "geodb/utility/temp_dir.hpp" using namespace geodb; using internal = inverted_index_internal_storage; using external = inverted_index_external<4096>; static constexpr u32 Lambda = 16; template<typename Func> void test_internal_external(Func&& f) { { INFO("internal"); inverted_index<internal, Lambda> i; f(i); } { tpie::temp_file tmp; block_collection<4096> blocks(tmp.path(), 32); INFO("external"); temp_dir dir; inverted_index<external, Lambda> i(external(dir.path(), blocks)); f(i); } } TEST_CASE("inverted file creation", "[inverted-file]") { test_internal_external([](auto&& index) { auto i1 = index.create(1); REQUIRE((i1 != index.end())); REQUIRE((i1->label() == 1)); auto i2 = index.create(2); REQUIRE((i2 != index.end())); REQUIRE((i2->label() == 2)); REQUIRE((i1 != i2)); REQUIRE((std::distance(index.begin(), index.end()) == 2)); }); } TEST_CASE("find or create", "[inverted-file]") { test_internal_external([](auto&& index) { REQUIRE(index.find(123) == index.end()); auto i1 = index.find_or_create(123); REQUIRE(i1->label() == 123); REQUIRE(index.find_or_create(123) == i1); auto i2 = index.create(124); REQUIRE(i2->label() == 124); REQUIRE(index.find_or_create(124) == i2); }); } TEST_CASE("inverted file iteration", "[inverted-file]") { test_internal_external([](auto&& index) { index.create(1); index.create(2); index.create(7); index.create(42); std::set<label_type> seen; for (auto i : index) { INFO("label: " << i.label()); REQUIRE((!seen.count(i.label()))); seen.insert(i.label()); } REQUIRE((seen.size() == 4)); REQUIRE((seen.count(1))); REQUIRE((seen.count(2))); REQUIRE((seen.count(7))); REQUIRE((seen.count(42))); }); }
25.823529
73
0.573576
mbeckem
d210dfdab9fff4b7cffd630368c58ae205af467c
39,299
cpp
C++
samsung/hardware/exynos4/hal/libhwcomposer/SecHWCUtils.cpp
DrDoubt/android_device_samsung_universal9810-common-1
5a937d2994044c041c3c19192d7744200a036cc8
[ "Apache-2.0" ]
null
null
null
samsung/hardware/exynos4/hal/libhwcomposer/SecHWCUtils.cpp
DrDoubt/android_device_samsung_universal9810-common-1
5a937d2994044c041c3c19192d7744200a036cc8
[ "Apache-2.0" ]
null
null
null
samsung/hardware/exynos4/hal/libhwcomposer/SecHWCUtils.cpp
DrDoubt/android_device_samsung_universal9810-common-1
5a937d2994044c041c3c19192d7744200a036cc8
[ "Apache-2.0" ]
2
2021-07-04T19:41:36.000Z
2021-07-29T12:59:47.000Z
/* * Copyright (C) 2010 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. */ /* * Revision History: * - 2011/03/11 : Rama, Meka(v.meka@samsung.com) * Initial version * * - 2011/12/07 : Jeonghee, Kim(jhhhh.kim@samsung.com) * Add V4L2_PIX_FMT_YUV420M V4L2_PIX_FMT_NV12M * */ #include "SecHWCUtils.h" #define V4L2_BUF_TYPE_OUTPUT V4L2_BUF_TYPE_VIDEO_OUTPUT #define V4L2_BUF_TYPE_CAPTURE V4L2_BUF_TYPE_VIDEO_CAPTURE #define EXYNOS4_ALIGN( value, base ) (((value) + ((base) - 1)) & ~((base) - 1)) //#define CHECK_FPS #ifdef CHECK_FPS #include <sys/time.h> #include <unistd.h> #define CHK_FRAME_CNT 57 void check_fps() { static struct timeval tick, tick_old; static int total = 0; static int cnt = 0; int FPS; cnt++; gettimeofday(&tick, NULL); if (cnt > 10) { if (tick.tv_sec > tick_old.tv_sec) total += ((tick.tv_usec/1000) + (tick.tv_sec - tick_old.tv_sec)*1000 - (tick_old.tv_usec/1000)); else total += ((tick.tv_usec - tick_old.tv_usec)/1000); memcpy(&tick_old, &tick, sizeof(timeval)); if (cnt == (10 + CHK_FRAME_CNT)) { FPS = 1000*CHK_FRAME_CNT/total; ALOGE("[FPS]:%d\n", FPS); total = 0; cnt = 10; } } else { memcpy(&tick_old, &tick, sizeof(timeval)); total = 0; } } #endif struct yuv_fmt_list yuv_list[] = { { "V4L2_PIX_FMT_NV12", "YUV420/2P/LSB_CBCR", V4L2_PIX_FMT_NV12, 12, 2 }, { "V4L2_PIX_FMT_NV12T", "YUV420/2P/LSB_CBCR", V4L2_PIX_FMT_NV12T, 12, 2 }, { "V4L2_PIX_FMT_NV21", "YUV420/2P/LSB_CRCB", V4L2_PIX_FMT_NV21, 12, 2 }, { "V4L2_PIX_FMT_NV21X", "YUV420/2P/MSB_CBCR", V4L2_PIX_FMT_NV21X, 12, 2 }, { "V4L2_PIX_FMT_NV12X", "YUV420/2P/MSB_CRCB", V4L2_PIX_FMT_NV12X, 12, 2 }, { "V4L2_PIX_FMT_YUV420", "YUV420/3P", V4L2_PIX_FMT_YUV420, 12, 3 }, { "V4L2_PIX_FMT_YUYV", "YUV422/1P/YCBYCR", V4L2_PIX_FMT_YUYV, 16, 1 }, { "V4L2_PIX_FMT_YVYU", "YUV422/1P/YCRYCB", V4L2_PIX_FMT_YVYU, 16, 1 }, { "V4L2_PIX_FMT_UYVY", "YUV422/1P/CBYCRY", V4L2_PIX_FMT_UYVY, 16, 1 }, { "V4L2_PIX_FMT_VYUY", "YUV422/1P/CRYCBY", V4L2_PIX_FMT_VYUY, 16, 1 }, { "V4L2_PIX_FMT_UV12", "YUV422/2P/LSB_CBCR", V4L2_PIX_FMT_NV16, 16, 2 }, { "V4L2_PIX_FMT_UV21", "YUV422/2P/LSB_CRCB", V4L2_PIX_FMT_NV61, 16, 2 }, { "V4L2_PIX_FMT_UV12X", "YUV422/2P/MSB_CBCR", V4L2_PIX_FMT_NV16X, 16, 2 }, { "V4L2_PIX_FMT_UV21X", "YUV422/2P/MSB_CRCB", V4L2_PIX_FMT_NV61X, 16, 2 }, { "V4L2_PIX_FMT_YUV422P", "YUV422/3P", V4L2_PIX_FMT_YUV422P, 16, 3 }, }; int window_open(struct hwc_win_info_t *win, int id) { int fd = 0; char name[64]; int vsync = 1; int real_id = id; char const * const device_template = "/dev/graphics/fb%u"; // window & FB maping // fb0 -> win-id : 2 // fb1 -> win-id : 3 // fb2 -> win-id : 4 // fb3 -> win-id : 0 // fb4 -> win_id : 1 // it is pre assumed that ...win0 or win1 is used here.. switch (id) { case 0: real_id = 3; break; case 1: real_id = 4; break; case 2: real_id = 0; break; case 3: real_id = 1; break; case 4: real_id = 2; break; default: SEC_HWC_Log(HWC_LOG_ERROR, "%s::id(%d) is weird", __func__, id); goto error; } // 0/10 // snprintf(name, 64, device_template, id + 3); // 5/10 // snprintf(name, 64, device_template, id + 0); // 0/10 // snprintf(name, 64, device_template, id + 1); snprintf(name, 64, device_template, real_id); win->fd = open(name, O_RDWR); if (win->fd <= 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Failed to open window device (%s) : %s", __func__, strerror(errno), name); goto error; } #ifdef ENABLE_FIMD_VSYNC if (ioctl(win->fd, S3CFB_SET_VSYNC_INT, &vsync) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::S3CFB_SET_VSYNC_INT fail", __func__); goto error; } #endif return 0; error: if (0 < win->fd) close(win->fd); win->fd = 0; return -1; } int window_close(struct hwc_win_info_t *win) { int ret = 0; if (0 < win->fd) { #ifdef ENABLE_FIMD_VSYNC int vsync = 0; if (ioctl(win->fd, S3CFB_SET_VSYNC_INT, &vsync) < 0) SEC_HWC_Log(HWC_LOG_ERROR, "%s::S3CFB_SET_VSYNC_INT fail", __func__); #endif ret = close(win->fd); } win->fd = 0; return ret; } int window_set_pos(struct hwc_win_info_t *win) { struct s3cfb_user_window window; //before changing the screen configuration...powerdown the window if (window_hide(win) != 0) return -1; SEC_HWC_Log(HWC_LOG_DEBUG, "%s:: x(%d), y(%d)", __func__, win->rect_info.x, win->rect_info.y); win->var_info.xres_virtual = (win->lcd_info.xres + 15) & ~ 15; win->var_info.yres_virtual = win->lcd_info.yres * NUM_OF_WIN_BUF; win->var_info.xres = win->rect_info.w; win->var_info.yres = win->rect_info.h; win->var_info.activate &= ~FB_ACTIVATE_MASK; win->var_info.activate |= FB_ACTIVATE_FORCE; if (ioctl(win->fd, FBIOPUT_VSCREENINFO, &(win->var_info)) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::FBIOPUT_VSCREENINFO(%d, %d) fail", __func__, win->rect_info.w, win->rect_info.h); return -1; } window.x = win->rect_info.x; window.y = win->rect_info.y; if (ioctl(win->fd, S3CFB_WIN_POSITION, &window) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::S3CFB_WIN_POSITION(%d, %d) fail", __func__, window.x, window.y); return -1; } return 0; } int window_get_info(struct hwc_win_info_t *win, int win_num) { int temp_size = 0; if (ioctl(win->fd, FBIOGET_FSCREENINFO, &win->fix_info) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "FBIOGET_FSCREENINFO failed : %s", strerror(errno)); goto error; } win->size = win->fix_info.line_length * win->var_info.yres; for (int j = 0; j < NUM_OF_WIN_BUF; j++) { temp_size = win->size * j; win->addr[j] = win->fix_info.smem_start + temp_size; SEC_HWC_Log(HWC_LOG_DEBUG, "%s::win-%d add[%d] %x ", __func__, win_num, j, win->addr[j]); } return 0; error: win->fix_info.smem_start = 0; return -1; } int window_pan_display(struct hwc_win_info_t *win) { struct fb_var_screeninfo *lcd_info = &(win->lcd_info); #ifdef ENABLE_FIMD_VSYNC if (ioctl(win->fd, FBIO_WAITFORVSYNC, 0) < 0) SEC_HWC_Log(HWC_LOG_ERROR, "%s::FBIO_WAITFORVSYNC fail(%s)", __func__, strerror(errno)); #endif lcd_info->yoffset = lcd_info->yres * win->buf_index; if (ioctl(win->fd, FBIOPAN_DISPLAY, lcd_info) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::FBIOPAN_DISPLAY(%d / %d / %d) fail(%s)", __func__, lcd_info->yres, win->buf_index, lcd_info->yres_virtual, strerror(errno)); return -1; } return 0; } int window_show(struct hwc_win_info_t *win) { if (win->power_state == 0) { if (ioctl(win->fd, FBIOBLANK, FB_BLANK_UNBLANK) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::FBIOBLANK failed : (%d:%s)", __func__, win->fd, strerror(errno)); return -1; } win->power_state = 1; } return 0; } int window_hide(struct hwc_win_info_t *win) { if (win->power_state == 1) { if (ioctl(win->fd, FBIOBLANK, FB_BLANK_POWERDOWN) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::FBIOBLANK failed : (%d:%s)", __func__, win->fd, strerror(errno)); return -1; } win->power_state = 0; } return 0; } int window_get_global_lcd_info(struct hwc_context_t *ctx) { if (ioctl(ctx->global_lcd_win.fd, FBIOGET_VSCREENINFO, &ctx->lcd_info) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "FBIOGET_VSCREENINFO failed : %s", strerror(errno)); return -1; } if (ctx->lcd_info.xres == 0) { SEC_HWC_Log(HWC_LOG_ERROR, "ATTENTION: XRES IS 0"); } if (ctx->lcd_info.yres == 0) { SEC_HWC_Log(HWC_LOG_ERROR, "ATTENTION: YRES IS 0"); } if (ctx->lcd_info.bits_per_pixel == 0) { SEC_HWC_Log(HWC_LOG_ERROR, "ATTENTION: BPP IS 0"); } return 0; } int fimc_v4l2_set_src(int fd, unsigned int hw_ver, s5p_fimc_img_info *src) { struct v4l2_format fmt; struct v4l2_cropcap cropcap; struct v4l2_crop crop; struct v4l2_requestbuffers req; fmt.fmt.pix.width = src->full_width; fmt.fmt.pix.height = src->full_height; fmt.fmt.pix.pixelformat = src->color_space; fmt.fmt.pix.field = V4L2_FIELD_NONE; fmt.type = V4L2_BUF_TYPE_OUTPUT; if (ioctl(fd, VIDIOC_S_FMT, &fmt) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::VIDIOC_S_FMT failed : errno=%d (%s)" " : fd=%d\n", __func__, errno, strerror(errno), fd); return -1; } /* crop input size */ crop.type = V4L2_BUF_TYPE_OUTPUT; crop.c.width = src->width; crop.c.height = src->height; if (0x50 <= hw_ver) { crop.c.left = src->start_x; crop.c.top = src->start_y; } else { crop.c.left = 0; crop.c.top = 0; } if (ioctl(fd, VIDIOC_S_CROP, &crop) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_CROP :" "crop.c.left : (%d), crop.c.top : (%d), crop.c.width : (%d), crop.c.height : (%d)", __func__, crop.c.left, crop.c.top, crop.c.width, crop.c.height); return -1; } /* input buffer type */ req.count = 1; req.memory = V4L2_MEMORY_USERPTR; req.type = V4L2_BUF_TYPE_OUTPUT; if (ioctl(fd, VIDIOC_REQBUFS, &req) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in VIDIOC_REQBUFS", __func__); return -1; } return 0; } int fimc_v4l2_set_dst(int fd, s5p_fimc_img_info *dst, int rotation, int hflip, int vflip, unsigned int addr) { struct v4l2_format sFormat; struct v4l2_control vc; struct v4l2_framebuffer fbuf; int ret; /* set rotation configuration */ vc.id = V4L2_CID_ROTATION; vc.value = rotation; ret = ioctl(fd, VIDIOC_S_CTRL, &vc); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_CTRL - rotation (%d)" "vc.id : (%d), vc.value : (%d)", __func__, ret, vc.id, vc.value); return -1; } vc.id = V4L2_CID_HFLIP; vc.value = hflip; ret = ioctl(fd, VIDIOC_S_CTRL, &vc); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_CTRL - hflip (%d)" "vc.id : (%d), vc.value : (%d)", __func__, ret, vc.id, vc.value); return -1; } vc.id = V4L2_CID_VFLIP; vc.value = vflip; ret = ioctl(fd, VIDIOC_S_CTRL, &vc); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_CTRL - vflip (%d)" "vc.id : (%d), vc.value : (%d)", __func__, ret, vc.id, vc.value); return -1; } /* set size, format & address for destination image (DMA-OUTPUT) */ ret = ioctl(fd, VIDIOC_G_FBUF, &fbuf); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_G_FBUF (%d)", __func__, ret); return -1; } fbuf.base = (void *)addr; fbuf.fmt.width = dst->full_width; fbuf.fmt.height = dst->full_height; fbuf.fmt.pixelformat = dst->color_space; ret = ioctl(fd, VIDIOC_S_FBUF, &fbuf); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_FBUF (%d)", __func__, ret); return -1; } /* set destination window */ sFormat.type = V4L2_BUF_TYPE_VIDEO_OVERLAY; sFormat.fmt.win.w.left = dst->start_x; sFormat.fmt.win.w.top = dst->start_y; sFormat.fmt.win.w.width = dst->width; sFormat.fmt.win.w.height = dst->height; ret = ioctl(fd, VIDIOC_S_FMT, &sFormat); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_FMT (%d)", __func__, ret); return -1; } return 0; } int fimc_v4l2_stream_on(int fd, enum v4l2_buf_type type) { if (-1 == ioctl(fd, VIDIOC_STREAMON, &type)) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_STREAMON\n"); return -1; } return 0; } int fimc_v4l2_queue(int fd, struct fimc_buf *fimc_buf, enum v4l2_buf_type type, int index) { struct v4l2_buffer buf; int ret; buf.length = 0; buf.m.userptr = (unsigned long)fimc_buf; buf.memory = V4L2_MEMORY_USERPTR; buf.index = index; buf.type = type; ret = ioctl(fd, VIDIOC_QBUF, &buf); if (0 > ret) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_QBUF : (%d)", ret); return -1; } return 0; } int fimc_v4l2_dequeue(int fd, struct fimc_buf *fimc_buf, enum v4l2_buf_type type) { struct v4l2_buffer buf; buf.memory = V4L2_MEMORY_USERPTR; buf.type = type; if (-1 == ioctl(fd, VIDIOC_DQBUF, &buf)) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_DQBUF\n"); return -1; } return buf.index; } int fimc_v4l2_stream_off(int fd, enum v4l2_buf_type type) { if (-1 == ioctl(fd, VIDIOC_STREAMOFF, &type)) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_STREAMOFF\n"); return -1; } return 0; } int fimc_v4l2_clr_buf(int fd, enum v4l2_buf_type type) { struct v4l2_requestbuffers req; req.count = 0; req.memory = V4L2_MEMORY_USERPTR; req.type = type; if (ioctl(fd, VIDIOC_REQBUFS, &req) == -1) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_REQBUFS"); } return 0; } int fimc_v4l2_S_ctrl(int fd) { struct v4l2_control vc; vc.id = V4L2_CID_CACHEABLE; vc.value = 1; if (ioctl(fd, VIDIOC_S_CTRL, &vc) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_S_CTRL"); return -1; } return 0; } int fimc_handle_oneshot(int fd, struct fimc_buf *fimc_src_buf, struct fimc_buf *fimc_dst_buf) { #ifdef CHECK_FPS check_fps(); #endif if (fimc_v4l2_stream_on(fd, V4L2_BUF_TYPE_OUTPUT) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Fail : SRC v4l2_stream_on()"); return -5; } if (fimc_v4l2_queue(fd, fimc_src_buf, V4L2_BUF_TYPE_OUTPUT, 0) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Fail : SRC v4l2_queue()"); goto STREAM_OFF; } if (fimc_v4l2_dequeue(fd, fimc_src_buf, V4L2_BUF_TYPE_OUTPUT) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Fail : SRC v4l2_dequeue()"); return -6; } STREAM_OFF: if (fimc_v4l2_stream_off(fd, V4L2_BUF_TYPE_OUTPUT) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Fail : SRC v4l2_stream_off()"); return -8; } if (fimc_v4l2_clr_buf(fd, V4L2_BUF_TYPE_OUTPUT) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Fail : SRC v4l2_clr_buf()"); return -10; } return 0; } static int memcpy_rect(void *dst, void *src, int fullW, int fullH, int realW, int realH, int format) { unsigned char *srcCb, *srcCr; unsigned char *dstCb, *dstCr; unsigned char *srcY, *dstY; int srcCbOffset, srcCrOffset; int dstCbOffset, dstFrameOffset, dstCrOffset; int cbFullW, cbRealW, cbFullH, cbRealH; int ySrcFW, ySrcFH, ySrcRW, ySrcRH; int planes; int i; SEC_HWC_Log(HWC_LOG_DEBUG, "++memcpy_rect()::" "dst(0x%x),src(0x%x),f.w(%d),f.h(%d),r.w(%d),r.h(%d),format(0x%x)", (unsigned int)dst, (unsigned int)src, fullW, fullH, realW, realH, format); // Set dst Y, Cb, Cr address for FIMC { cbFullW = fullW >> 1; cbRealW = realW >> 1; cbFullH = fullH >> 1; cbRealH = realH >> 1; dstFrameOffset = fullW * fullH; dstCrOffset = cbFullW * cbFullH; dstY = (unsigned char *)dst; dstCb = (unsigned char *)dst + dstFrameOffset; dstCr = (unsigned char *)dstCb + dstCrOffset; } // Get src Y, Cb, Cr address for source buffer. // Each address is aligned by 16's multiple for GPU both width and height. { ySrcFW = fullW; ySrcFH = fullH; ySrcRW = realW; ySrcRH = realH; srcCbOffset = EXYNOS4_ALIGN(ySrcRW,16)* EXYNOS4_ALIGN(ySrcRH,16); srcCrOffset = EXYNOS4_ALIGN(cbRealW,16)* EXYNOS4_ALIGN(cbRealH,16); srcY = (unsigned char *)src; srcCb = (unsigned char *)src + srcCbOffset; srcCr = (unsigned char *)srcCb + srcCrOffset; } SEC_HWC_Log(HWC_LOG_DEBUG, "--memcpy_rect()::\n" "dstY(0x%x),dstCb(0x%x),dstCr(0x%x) \n" "srcY(0x%x),srcCb(0x%x),srcCr(0x%x) \n" "cbRealW(%d),cbRealH(%d)", (unsigned int)dstY,(unsigned int)dstCb,(unsigned int)dstCr, (unsigned int)srcY,(unsigned int)srcCb,(unsigned int)srcCr, cbRealW, cbRealH); if (format == HAL_PIXEL_FORMAT_YV12) { //YV12(Y,Cr,Cv) planes = 3; //This is code for VE, deleted temporory by SSONG 2011.09.22 // This will be enabled later. /* //as defined in hardware.h, cb & cr full_width should be aligned to 16. ALIGN(y_stride/2, 16). ////Alignment is hard coded to 16. ////for example...check frameworks/media/libvideoeditor/lvpp/VideoEditorTools.cpp file for UV stride cal cbSrcFW = (cbSrcFW + 15) & (~15); srcCbOffset = ySrcFW * fullH; srcCrOffset = srcCbOffset + ((cbSrcFW * fullH) >> 1); srcY = (unsigned char *)src; srcCb = (unsigned char *)src + srcCbOffset; srcCr = (unsigned char *)src + srcCrOffset; */ } else if ((format == HAL_PIXEL_FORMAT_YCbCr_420_P)) { planes = 3; } else if (format == HAL_PIXEL_FORMAT_YCbCr_420_SP || format == HAL_PIXEL_FORMAT_YCrCb_420_SP) { planes = 2; } else { SEC_HWC_Log(HWC_LOG_ERROR, "use default memcpy instead of memcpy_rect"); return -1; } //#define CHECK_PERF #ifdef CHECK_PERF struct timeval start, end; gettimeofday(&start, NULL); #endif for (i = 0; i < realH; i++) memcpy(dstY + fullW * i, srcY + ySrcFW * i, ySrcRW); if (planes == 2) { for (i = 0; i < cbRealH; i++) memcpy(dstCb + ySrcFW * i, srcCb + ySrcFW * i, ySrcRW); } else if (planes == 3) { for (i = 0; i < cbRealH; i++) memcpy(dstCb + cbFullW * i, srcCb + cbFullW * i, cbRealW); for (i = 0; i < cbRealH; i++) memcpy(dstCr + cbFullW * i, srcCr + cbFullW * i, cbRealW); } #ifdef CHECK_PERF gettimeofday(&end, NULL); SEC_HWC_Log(HWC_LOG_ERROR, "[COPY]=%d,",(end.tv_sec - start.tv_sec)*1000+(end.tv_usec - start.tv_usec)/1000); #endif return 0; } /*****************************************************************************/ static int get_src_phys_addr(struct hwc_context_t *ctx, sec_img *src_img, sec_rect *src_rect) { s5p_fimc_t *fimc = &ctx->fimc; unsigned int src_virt_addr = 0; unsigned int src_phys_addr = 0; unsigned int src_frame_size = 0; ADDRS * addr; // error check routine if (0 == src_img->base && !(src_img->usage & GRALLOC_USAGE_HW_FIMC1)) { SEC_HWC_Log(HWC_LOG_ERROR, "%s invalid src image base\n", __func__); return 0; } switch (src_img->mem_type) { case HWC_PHYS_MEM_TYPE: src_phys_addr = src_img->base + src_img->offset; break; case HWC_VIRT_MEM_TYPE: case HWC_UNKNOWN_MEM_TYPE: switch (src_img->format) { case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP_TILED: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_SP: addr = (ADDRS *)(src_img->base); fimc->params.src.buf_addr_phy_rgb_y = addr->addr_y; fimc->params.src.buf_addr_phy_cb = addr->addr_cbcr; src_phys_addr = fimc->params.src.buf_addr_phy_rgb_y; if (0 == src_phys_addr) { SEC_HWC_Log(HWC_LOG_ERROR, "%s address error " "(format=CUSTOM_YCbCr/YCrCb_420_SP Y-addr=0x%x " "CbCr-Addr=0x%x)", __func__, fimc->params.src.buf_addr_phy_rgb_y, fimc->params.src.buf_addr_phy_cb); return 0; } break; case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_I: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CbYCrY_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CrYCbY_422_I: addr = (ADDRS *)(src_img->base + src_img->offset); fimc->params.src.buf_addr_phy_rgb_y = addr->addr_y; src_phys_addr = fimc->params.src.buf_addr_phy_rgb_y; if (0 == src_phys_addr) { SEC_HWC_Log(HWC_LOG_ERROR, "%s address error " "(format=CUSTOM_YCbCr/CbYCrY_422_I Y-addr=0x%x)", __func__, fimc->params.src.buf_addr_phy_rgb_y); return 0; } break; default: if (src_img->usage & GRALLOC_USAGE_HW_FIMC1) { fimc->params.src.buf_addr_phy_rgb_y = src_img->paddr; fimc->params.src.buf_addr_phy_cb = src_img->paddr + src_img->uoffset; fimc->params.src.buf_addr_phy_cr = src_img->paddr + src_img->uoffset + src_img->voffset; src_phys_addr = fimc->params.src.buf_addr_phy_rgb_y; } else { SEC_HWC_Log(HWC_LOG_ERROR, "%s::\nformat = 0x%x : Not " "GRALLOC_USAGE_HW_FIMC1 can not supported\n", __func__, src_img->format); } break; } } return src_phys_addr; } static inline int rotateValueHAL2PP(unsigned char transform) { int rotate_flag = transform & 0x7; switch (rotate_flag) { case HAL_TRANSFORM_ROT_90: return 90; case HAL_TRANSFORM_ROT_180: return 180; case HAL_TRANSFORM_ROT_270: return 270; case HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90: return 90; case HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90: return 90; case HAL_TRANSFORM_FLIP_H: return 0; case HAL_TRANSFORM_FLIP_V: return 0; } return 0; } static inline int hflipValueHAL2PP(unsigned char transform) { int flip_flag = transform & 0x7; switch (flip_flag) { case HAL_TRANSFORM_FLIP_H: case HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90: return 1; case HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90: case HAL_TRANSFORM_ROT_90: case HAL_TRANSFORM_ROT_180: case HAL_TRANSFORM_ROT_270: case HAL_TRANSFORM_FLIP_V: break; } return 0; } static inline int vflipValueHAL2PP(unsigned char transform) { int flip_flag = transform & 0x7; switch (flip_flag) { case HAL_TRANSFORM_FLIP_V: case HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90: return 1; case HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90: case HAL_TRANSFORM_ROT_90: case HAL_TRANSFORM_ROT_180: case HAL_TRANSFORM_ROT_270: case HAL_TRANSFORM_FLIP_H: break; } return 0; } static inline int multipleOf2(int number) { if (number % 2 == 1) return (number - 1); else return number; } static inline int multipleOf4(int number) { int remain_number = number % 4; if (remain_number != 0) return (number - remain_number); else return number; } static inline int multipleOf8(int number) { int remain_number = number % 8; if (remain_number != 0) return (number - remain_number); else return number; } static inline int multipleOf16(int number) { int remain_number = number % 16; if (remain_number != 0) return (number - remain_number); else return number; } static inline int widthOfPP(unsigned int ver, int pp_color_format, int number) { if (0x50 <= ver) { switch (pp_color_format) { /* 422 1/2/3 plane */ case V4L2_PIX_FMT_YUYV: case V4L2_PIX_FMT_UYVY: case V4L2_PIX_FMT_NV61: case V4L2_PIX_FMT_NV16: case V4L2_PIX_FMT_YUV422P: /* 420 2/3 plane */ case V4L2_PIX_FMT_NV21: case V4L2_PIX_FMT_NV12: case V4L2_PIX_FMT_NV12T: case V4L2_PIX_FMT_YUV420: return multipleOf2(number); default : return number; } } else { switch (pp_color_format) { case V4L2_PIX_FMT_RGB565: return multipleOf8(number); case V4L2_PIX_FMT_RGB32: return multipleOf4(number); case V4L2_PIX_FMT_YUYV: case V4L2_PIX_FMT_UYVY: return multipleOf4(number); case V4L2_PIX_FMT_NV61: case V4L2_PIX_FMT_NV16: return multipleOf8(number); case V4L2_PIX_FMT_YUV422P: return multipleOf16(number); case V4L2_PIX_FMT_NV21: case V4L2_PIX_FMT_NV12: case V4L2_PIX_FMT_NV12T: return multipleOf8(number); case V4L2_PIX_FMT_YUV420: return multipleOf16(number); default : return number; } } return number; } static inline int heightOfPP(int pp_color_format, int number) { switch (pp_color_format) { case V4L2_PIX_FMT_NV21: case V4L2_PIX_FMT_NV12: case V4L2_PIX_FMT_NV12T: case V4L2_PIX_FMT_YUV420: return multipleOf2(number); default : return number; break; } return number; } static unsigned int get_yuv_bpp(unsigned int fmt) { int i, sel = -1; for (i = 0; i < (int)(sizeof(yuv_list) / sizeof(struct yuv_fmt_list)); i++) { if (yuv_list[i].fmt == fmt) { sel = i; break; } } if (sel == -1) return sel; else return yuv_list[sel].bpp; } static unsigned int get_yuv_planes(unsigned int fmt) { int i, sel = -1; for (i = 0; i < (int)(sizeof(yuv_list) / sizeof(struct yuv_fmt_list)); i++) { if (yuv_list[i].fmt == fmt) { sel = i; break; } } if (sel == -1) return sel; else return yuv_list[sel].planes; } static int runFimcCore(struct hwc_context_t *ctx, unsigned int src_phys_addr, sec_img *src_img, sec_rect *src_rect, uint32_t src_color_space, unsigned int dst_phys_addr, sec_img *dst_img, sec_rect *dst_rect, uint32_t dst_color_space, int transform) { s5p_fimc_t * fimc = &ctx->fimc; s5p_fimc_params_t * params = &(fimc->params); struct fimc_buf fimc_src_buf; int src_bpp, src_planes; unsigned int frame_size = 0; bool src_cbcr_order = true; int rotate_value = rotateValueHAL2PP(transform); int hflip = 0; int vflip = 0; /* 1. param(fimc config)->src information * - src_img,src_rect => s_fw,s_fh,s_w,s_h,s_x,s_y */ params->src.full_width = src_img->f_w; params->src.full_height = src_img->f_h; params->src.width = src_rect->w; params->src.height = src_rect->h; params->src.start_x = src_rect->x; params->src.start_y = src_rect->y; params->src.color_space = src_color_space; params->src.buf_addr_phy_rgb_y = src_phys_addr; /* check src minimum */ if (src_rect->w < 16 || src_rect->h < 8) { SEC_HWC_Log(HWC_LOG_ERROR, "%s src size is not supported by fimc : f_w=%d f_h=%d " "x=%d y=%d w=%d h=%d (ow=%d oh=%d) format=0x%x", __func__, params->src.full_width, params->src.full_height, params->src.start_x, params->src.start_y, params->src.width, params->src.height, src_rect->w, src_rect->h, params->src.color_space); return -1; } /* 2. param(fimc config)->dst information * - dst_img,dst_rect,rot => d_fw,d_fh,d_w,d_h,d_x,d_y */ switch (rotate_value) { case 0: hflip = hflipValueHAL2PP(transform); vflip = vflipValueHAL2PP(transform); params->dst.full_width = dst_img->f_w; params->dst.full_height = dst_img->f_h; params->dst.start_x = dst_rect->x; params->dst.start_y = dst_rect->y; params->dst.width = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->w); params->dst.height = heightOfPP(dst_color_space, dst_rect->h); break; case 90: hflip = vflipValueHAL2PP(transform); vflip = hflipValueHAL2PP(transform); params->dst.full_width = dst_img->f_h; params->dst.full_height = dst_img->f_w; params->dst.start_x = dst_rect->y; params->dst.start_y = dst_img->f_w - (dst_rect->x + dst_rect->w); params->dst.width = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->h); params->dst.height = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->w); if (0x50 > fimc->hw_ver) params->dst.start_y += (dst_rect->w - params->dst.height); break; case 180: params->dst.full_width = dst_img->f_w; params->dst.full_height = dst_img->f_h; params->dst.start_x = dst_img->f_w - (dst_rect->x + dst_rect->w); params->dst.start_y = dst_img->f_h - (dst_rect->y + dst_rect->h); params->dst.width = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->w); params->dst.height = heightOfPP(dst_color_space, dst_rect->h); break; case 270: params->dst.full_width = dst_img->f_h; params->dst.full_height = dst_img->f_w; params->dst.start_x = dst_img->f_h - (dst_rect->y + dst_rect->h); params->dst.start_y = dst_rect->x; params->dst.width = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->h); params->dst.height = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->w); if (0x50 > fimc->hw_ver) params->dst.start_y += (dst_rect->w - params->dst.height); break; } params->dst.color_space = dst_color_space; SEC_HWC_Log(HWC_LOG_DEBUG, "runFimcCore()::" "SRC f.w(%d),f.h(%d),x(%d),y(%d),w(%d),h(%d)=>" "DST f.w(%d),f.h(%d),x(%d),y(%d),w(%d),h(%d)", params->src.full_width, params->src.full_height, params->src.start_x, params->src.start_y, params->src.width, params->src.height, params->dst.full_width, params->dst.full_height, params->dst.start_x, params->dst.start_y, params->dst.width, params->dst.height); /* check dst minimum */ if (dst_rect->w < 8 || dst_rect->h < 4) { SEC_HWC_Log(HWC_LOG_ERROR, "%s dst size is not supported by fimc : f_w=%d f_h=%d " "x=%d y=%d w=%d h=%d (ow=%d oh=%d) format=0x%x", __func__, params->dst.full_width, params->dst.full_height, params->dst.start_x, params->dst.start_y, params->dst.width, params->dst.height, dst_rect->w, dst_rect->h, params->dst.color_space); return -1; } /* check scaling limit * the scaling limie must not be more than MAX_RESIZING_RATIO_LIMIT */ if (((src_rect->w > dst_rect->w) && ((src_rect->w / dst_rect->w) > MAX_RESIZING_RATIO_LIMIT)) || ((dst_rect->w > src_rect->w) && ((dst_rect->w / src_rect->w) > MAX_RESIZING_RATIO_LIMIT))) { SEC_HWC_Log(HWC_LOG_ERROR, "%s over scaling limit : src.w=%d dst.w=%d (limit=%d)", __func__, src_rect->w, dst_rect->w, MAX_RESIZING_RATIO_LIMIT); return -1; } /* 3. Set configuration related to destination (DMA-OUT) * - set input format & size * - crop input size * - set input buffer * - set buffer type (V4L2_MEMORY_USERPTR) */ if (fimc_v4l2_set_dst(fimc->dev_fd, &params->dst, rotate_value, hflip, vflip, dst_phys_addr) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "fimc_v4l2_set_dst is failed\n"); return -1; } /* 4. Set configuration related to source (DMA-INPUT) * - set input format & size * - crop input size * - set input buffer * - set buffer type (V4L2_MEMORY_USERPTR) */ if (fimc_v4l2_set_src(fimc->dev_fd, fimc->hw_ver, &params->src) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "fimc_v4l2_set_src is failed\n"); return -1; } /* 5. Set input dma address (Y/RGB, Cb, Cr) * - zero copy : mfc, camera */ switch (src_img->format) { case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP_TILED: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_SP: /* for video contents zero copy case */ fimc_src_buf.base[0] = params->src.buf_addr_phy_rgb_y; fimc_src_buf.base[1] = params->src.buf_addr_phy_cb; break; case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_I: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CbYCrY_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CrYCbY_422_I: case HAL_PIXEL_FORMAT_RGB_565: case HAL_PIXEL_FORMAT_YV12: default: if (src_img->format == HAL_PIXEL_FORMAT_YV12){ src_cbcr_order = false; } if (src_img->usage & GRALLOC_USAGE_HW_FIMC1) { fimc_src_buf.base[0] = params->src.buf_addr_phy_rgb_y; if (src_cbcr_order == true) { fimc_src_buf.base[1] = params->src.buf_addr_phy_cb; fimc_src_buf.base[2] = params->src.buf_addr_phy_cr; } else { fimc_src_buf.base[2] = params->src.buf_addr_phy_cb; fimc_src_buf.base[1] = params->src.buf_addr_phy_cr; } SEC_HWC_Log(HWC_LOG_DEBUG, "runFimcCore - Y=0x%X, U=0x%X, V=0x%X\n", fimc_src_buf.base[0], fimc_src_buf.base[1],fimc_src_buf.base[2]); break; } } /* 6. Run FIMC * - stream on => queue => dequeue => stream off => clear buf */ if (fimc_handle_oneshot(fimc->dev_fd, &fimc_src_buf, NULL) < 0) { ALOGE("fimcrun fail"); fimc_v4l2_clr_buf(fimc->dev_fd, V4L2_BUF_TYPE_OUTPUT); return -1; } return 0; } int createFimc(s5p_fimc_t *fimc) { struct v4l2_capability cap; struct v4l2_format fmt; struct v4l2_control vc; // open device file if (fimc->dev_fd <= 0) fimc->dev_fd = open(PP_DEVICE_DEV_NAME, O_RDWR); if (fimc->dev_fd <= 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Post processor open error (%d)", __func__, errno); goto err; } // check capability if (ioctl(fimc->dev_fd, VIDIOC_QUERYCAP, &cap) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "VIDIOC_QUERYCAP failed"); goto err; } if (!(cap.capabilities & V4L2_CAP_STREAMING)) { SEC_HWC_Log(HWC_LOG_ERROR, "%d has no streaming support", fimc->dev_fd); goto err; } if (!(cap.capabilities & V4L2_CAP_VIDEO_OUTPUT)) { SEC_HWC_Log(HWC_LOG_ERROR, "%d is no video output", fimc->dev_fd); goto err; } /* * malloc fimc_outinfo structure */ fmt.type = V4L2_BUF_TYPE_OUTPUT; if (ioctl(fimc->dev_fd, VIDIOC_G_FMT, &fmt) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_G_FMT", __func__); goto err; } vc.id = V4L2_CID_FIMC_VERSION; vc.value = 0; if (ioctl(fimc->dev_fd, VIDIOC_G_CTRL, &vc) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_G_CTRL", __func__); goto err; } fimc->hw_ver = vc.value; return 0; err: if (0 < fimc->dev_fd) close(fimc->dev_fd); fimc->dev_fd =0; return -1; } int destroyFimc(s5p_fimc_t *fimc) { if (fimc->out_buf.virt_addr != NULL) { fimc->out_buf.virt_addr = NULL; fimc->out_buf.length = 0; } // close if (0 < fimc->dev_fd) close(fimc->dev_fd); fimc->dev_fd = 0; return 0; } int runFimc(struct hwc_context_t *ctx, struct sec_img *src_img, struct sec_rect *src_rect, struct sec_img *dst_img, struct sec_rect *dst_rect, uint32_t transform) { s5p_fimc_t * fimc = &ctx->fimc; unsigned int src_phys_addr = 0; unsigned int dst_phys_addr = 0; int rotate_value = 0; int32_t src_color_space; int32_t dst_color_space; /* 1. source address and size */ src_phys_addr = get_src_phys_addr(ctx, src_img, src_rect); if (0 == src_phys_addr) return -1; /* 2. destination address and size */ dst_phys_addr = dst_img->base; if (0 == dst_phys_addr) return -2; /* 3. check whether fimc supports the src format */ src_color_space = HAL_PIXEL_FORMAT_2_V4L2_PIX(src_img->format); if (0 > src_color_space) return -3; dst_color_space = HAL_PIXEL_FORMAT_2_V4L2_PIX(dst_img->format); if (0 > dst_color_space) return -4; /* 4. FIMC: src_rect of src_img => dst_rect of dst_img */ if (runFimcCore(ctx, src_phys_addr, src_img, src_rect, (uint32_t)src_color_space, dst_phys_addr, dst_img, dst_rect, (uint32_t)dst_color_space, transform) < 0) return -5; return 0; } int check_yuv_format(unsigned int color_format) { switch (color_format) { case HAL_PIXEL_FORMAT_YV12: case HAL_PIXEL_FORMAT_YCbCr_422_SP: case HAL_PIXEL_FORMAT_YCrCb_420_SP: case HAL_PIXEL_FORMAT_YCbCr_422_I: case HAL_PIXEL_FORMAT_YCbCr_422_P: case HAL_PIXEL_FORMAT_YCbCr_420_P: case HAL_PIXEL_FORMAT_YCbCr_420_I: case HAL_PIXEL_FORMAT_CbYCrY_422_I: case HAL_PIXEL_FORMAT_CbYCrY_420_I: case HAL_PIXEL_FORMAT_YCbCr_420_SP: case HAL_PIXEL_FORMAT_YCrCb_422_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP_TILED: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_I: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CbYCrY_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CrYCbY_422_I: return 1; default: return 0; } }
30.702344
113
0.600906
DrDoubt
d2153e7df539f5c2633bd75befe4fdc6f23dd8ab
2,123
cpp
C++
Jx3Full/Source/Source/Common/SO3Represent/Src/case/actionobject/krlridesmgr.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
2
2021-07-31T15:35:01.000Z
2022-02-28T05:54:54.000Z
Jx3Full/Source/Source/Common/SO3Represent/Src/case/actionobject/krlridesmgr.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
null
null
null
Jx3Full/Source/Source/Common/SO3Represent/Src/case/actionobject/krlridesmgr.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
5
2021-02-03T10:25:39.000Z
2022-02-23T07:08:37.000Z
#include "stdafx.h" #include "./krlrides.h" #include "./krlridesmgr.h" KRLRidesMgr::KRLRidesMgr() { } KRLRidesMgr::~KRLRidesMgr() { } HRESULT KRLRidesMgr::Append(DWORD dwRides, KRLRides* pRLRides) { ASSERT(pRLRides); KPtrMap::iterator it = m_aRides.find(dwRides); KGLOG_PROCESS_ERROR(it == m_aRides.end()); m_aRides.insert(std::make_pair(dwRides, pRLRides)); return S_OK; Exit0: return E_FAIL; } HRESULT KRLRidesMgr::Remove(DWORD dwRides) { KPtrMap::iterator it = m_aRides.find(dwRides); KGLOG_PROCESS_ERROR(it != m_aRides.end()); m_aRides.erase(it); return S_OK; Exit0: return E_FAIL; } KRLRides* KRLRidesMgr::Lookup(DWORD dwRides) { KPtrMap::iterator it = m_aRides.find(dwRides); KG_PROCESS_ERROR(it != m_aRides.end()); return (*it).second; Exit0: return NULL; } BOOL KRLRidesMgr::Init() { return TRUE; } void KRLRidesMgr::Exit() { for (KPtrMap::iterator it = m_aRides.begin(); it != m_aRides.end();) { KRLRides* pRides = (*it).second; ASSERT(pRides); KPtrMap::iterator itRemove = it++; SAFE_DELETE(pRides); m_aRides.erase(itRemove); } } BOOL KRLRidesMgr::Reset() { int nRetCode = false; Exit(); nRetCode = Init(); KGLOG_PROCESS_ERROR(nRetCode); return TRUE; Exit0: Exit(); return FALSE; } BOOL KRLRidesMgr::Activate(double fTime, double fTimeLast, DWORD dwGameLoop, BOOL bFrame) { BOOL bRetResult = TRUE; BOOL bHasFinished = FALSE; for (KPtrMap::iterator it = m_aRides.begin(); it != m_aRides.end(); ++it) { KRLRides* pRides = (*it).second; pRides->UpdateRemote(fTime, fTimeLast, dwGameLoop, bFrame); if (!bHasFinished && pRides->IsFinished()) { bHasFinished = TRUE; } } if (bHasFinished) { for (KPtrMap::iterator it = m_aRides.begin(); it != m_aRides.end();) { KRLRides* pRides = (*it).second; if (pRides->IsFinished()) { KPtrMap::iterator itRemove = it++; SAFE_DELETE(pRides); m_aRides.erase(itRemove); } else { ++it; } } } return bRetResult; }
17.401639
90
0.628356
RivenZoo
d217ed7d6d8c307a61fe6d63d5cb54093fe7051e
136
cpp
C++
pizza/tomatosauce.cpp
StevenHPham/CS-2150-Program-and-Data-Representation
044acae0f3a28d83f9bd0a01fbbb3c0252f7ae90
[ "CC-BY-4.0" ]
null
null
null
pizza/tomatosauce.cpp
StevenHPham/CS-2150-Program-and-Data-Representation
044acae0f3a28d83f9bd0a01fbbb3c0252f7ae90
[ "CC-BY-4.0" ]
null
null
null
pizza/tomatosauce.cpp
StevenHPham/CS-2150-Program-and-Data-Representation
044acae0f3a28d83f9bd0a01fbbb3c0252f7ae90
[ "CC-BY-4.0" ]
null
null
null
#include <iostream> using namespace std; #include "tomatosauce.h" TomatoSauce::TomatoSauce(int amount) { quantity=amount; }
17
39
0.705882
StevenHPham
d21ab982d94cac4650779f3d51a8af4dfa20f686
19,814
cpp
C++
dev/AppNotifications/AppNotificationManager.cpp
G-arj/WindowsAppSDK
4b9003aef5c22f4edbbb702bac6a5aa1a7d59ebc
[ "CC-BY-4.0", "MIT" ]
null
null
null
dev/AppNotifications/AppNotificationManager.cpp
G-arj/WindowsAppSDK
4b9003aef5c22f4edbbb702bac6a5aa1a7d59ebc
[ "CC-BY-4.0", "MIT" ]
null
null
null
dev/AppNotifications/AppNotificationManager.cpp
G-arj/WindowsAppSDK
4b9003aef5c22f4edbbb702bac6a5aa1a7d59ebc
[ "CC-BY-4.0", "MIT" ]
null
null
null
#include "pch.h" #include "AppNotificationManager.h" #include "Microsoft.Windows.AppNotifications.AppNotificationManager.g.cpp" #include <winrt/Windows.ApplicationModel.Core.h> #include <winrt/Windows.Storage.h> #include <winrt/base.h> #include "externs.h" #include "PushNotificationUtility.h" #include "AppNotificationUtility.h" #include <frameworkudk/pushnotifications.h> #include <frameworkudk/toastnotifications.h> #include <FrameworkUdk/toastnotificationsrt.h> #include "NotificationProperties.h" #include "NotificationTransientProperties.h" #include "AppNotification.h" #include <NotificationProgressData.h> #include "AppNotificationTelemetry.h" #include <algorithm> #include <winerror.h> #include <string_view> #include <winrt/Windows.Foundation.Collections.h> #include <TerminalVelocityFeatures-AppNotifications.h> using namespace std::literals; constexpr std::wstring_view expectedAppServerArgs = L"----AppNotificationActivated:"sv; namespace winrt { using namespace winrt::Windows::UI; using namespace winrt::Windows::Foundation; using namespace winrt::Windows::Foundation::Collections; using namespace winrt::Microsoft::Windows::AppNotifications; using namespace Windows::ApplicationModel::Core; } namespace ToastABI { using namespace ::ABI::Microsoft::Internal::ToastNotifications; using namespace ::ABI::Windows::Foundation::Collections; } namespace PushNotificationHelpers { using namespace winrt::Microsoft::Windows::PushNotifications::Helpers; } using namespace Microsoft::Windows::AppNotifications::Helpers; namespace winrt::Microsoft::Windows::AppNotifications::implementation { AppNotificationManager::AppNotificationManager() : m_processName(GetCurrentProcessPath()), m_appId(RetrieveNotificationAppId()) {} winrt::Microsoft::Windows::AppNotifications::AppNotificationManager AppNotificationManager::Default() { THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::AppNotifications::Feature_AppNotifications::IsEnabled()); static auto appNotificationManager{winrt::make<AppNotificationManager>()}; return appNotificationManager; } void AppNotificationManager::Register() { HRESULT hr{ S_OK }; auto logTelemetry{ wil::scope_exit([&]() { AppNotificationTelemetry::LogRegister(hr, m_appId); }) }; try { winrt::guid storedComActivatorGuid{ GUID_NULL }; if (!PushNotificationHelpers::IsPackagedAppScenario()) { if (!AppModel::Identity::IsPackagedProcess()) { THROW_IF_FAILED(PushNotifications_RegisterFullTrustApplication(m_appId.c_str(), GUID_NULL)); storedComActivatorGuid = RegisterComActivatorGuidAndAssets(); } auto notificationPlatform{ PushNotificationHelpers::GetNotificationPlatform() }; THROW_IF_FAILED(notificationPlatform->AddToastRegistrationMapping(m_processName.c_str(), m_appId.c_str())); } winrt::guid registeredClsid{ GUID_NULL }; if (AppModel::Identity::IsPackagedProcess()) { registeredClsid = PushNotificationHelpers::GetComRegistrationFromRegistry(expectedAppServerArgs.data()); } // Create event handle before COM Registration otherwise if a notification arrives will lead to race condition GetWaitHandleForArgs().create(); { auto lock{ m_lock.lock_exclusive() }; THROW_HR_IF_MSG(E_INVALIDARG, m_notificationComActivatorRegistration, "Already Registered for App Notifications!"); // Check if the caller has registered event handlers, if so the REGCLS_MULTIPLEUSE flag will cause COM to ensure that all activators // are routed inproc, otherwise with REGCLS_MULTIPLEUSE COM will launch a new process of the Win32 app for each invocation. THROW_IF_FAILED(::CoRegisterClassObject( AppModel::Identity::IsPackagedProcess() ? registeredClsid : storedComActivatorGuid, winrt::make<AppNotificationManagerFactory>().get(), CLSCTX_LOCAL_SERVER, m_notificationHandlers ? REGCLS_MULTIPLEUSE : REGCLS_SINGLEUSE, &m_notificationComActivatorRegistration)); } } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } void AppNotificationManager::Unregister() { HRESULT hr{ S_OK }; auto logTelemetry{ wil::scope_exit([&]() { AppNotificationTelemetry::LogUnregister(hr, m_appId); }) }; try { auto lock{ m_lock.lock_exclusive() }; THROW_HR_IF_MSG(HRESULT_FROM_WIN32(ERROR_NOT_FOUND), !m_notificationComActivatorRegistration, "Not Registered for App Notifications!"); m_notificationComActivatorRegistration.reset(); } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } void AppNotificationManager::UnregisterAll() { HRESULT hr{ S_OK }; auto logTelemetry{ wil::scope_exit([&]() { AppNotificationTelemetry::LogUnregisterAll(hr, m_appId); }) }; try { Unregister(); // Remove any Registrations from the Long Running Process that are necessary for Cloud toasts if (!PushNotificationHelpers::IsPackagedAppScenario()) { auto notificationPlatform{ PushNotificationHelpers::GetNotificationPlatform() }; THROW_IF_FAILED(notificationPlatform->RemoveToastRegistrationMapping(m_processName.c_str())); } if (!AppModel::Identity::IsPackagedProcess()) { std::wstring storedComActivatorString; THROW_IF_FAILED(GetActivatorGuid(storedComActivatorString)); UnRegisterComServer(storedComActivatorString); UnRegisterNotificationAppIdentifierFromRegistry(); THROW_IF_FAILED(PushNotifications_UnregisterFullTrustApplication(m_appId.c_str())); } } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } winrt::event_token AppNotificationManager::NotificationInvoked(winrt::Windows::Foundation::TypedEventHandler<winrt::Microsoft::Windows::AppNotifications::AppNotificationManager, winrt::Microsoft::Windows::AppNotifications::AppNotificationActivatedEventArgs> const& handler) { auto lock{ m_lock.lock_exclusive() }; THROW_HR_IF_MSG(HRESULT_FROM_WIN32(ERROR_NOT_FOUND), m_notificationComActivatorRegistration, "Must register event handlers before calling Register()"); return m_notificationHandlers.add(handler); } void AppNotificationManager::NotificationInvoked(winrt::event_token const& token) noexcept { auto lock{ m_lock.lock_exclusive() }; m_notificationHandlers.remove(token); } IFACEMETHODIMP AppNotificationManager::Activate( LPCWSTR appUserModelId, LPCWSTR invokedArgs, [[maybe_unused]] NOTIFICATION_USER_INPUT_DATA const* data, [[maybe_unused]] ULONG dataCount) noexcept try { winrt::IMap<winrt::hstring, winrt::hstring> userInput{ winrt::single_threaded_map<winrt::hstring, winrt::hstring>() }; for (unsigned long i = 0; i < dataCount; i++) { userInput.Insert(data[i].Key, data[i].Value); } winrt::AppNotificationActivatedEventArgs activatedEventArgs = winrt::make<implementation::AppNotificationActivatedEventArgs>(invokedArgs, userInput); // Need to store the first notification in the case of ToastActivation auto lock{ m_lock.lock_exclusive() }; if (!m_firstNotificationReceived) { m_firstNotificationReceived = true; std::wstring commandLine{ GetCommandLine() }; // If the app was not launched due to ToastActivation, we will launch a new instance or invoke the foreground handlers. // Otherwise we store the EventArgs and signal to the Main thread auto pos{ commandLine.find(c_notificationActivatedArgument) }; if (pos == std::wstring::npos) // Any launch kind that is not AppNotification { // If the Process was launched due to other Activation Kinds, we will need to // re-route the payload to a new process if there are no registered event handlers. if (!m_notificationHandlers) { winrt::guid registeredClsid{ GUID_NULL }; if (AppModel::Identity::IsPackagedProcess()) { registeredClsid = PushNotificationHelpers::GetComRegistrationFromRegistry(expectedAppServerArgs.data()); } else { registeredClsid = RegisterComActivatorGuidAndAssets(); } auto notificationCallback{ winrt::create_instance<INotificationActivationCallback>(registeredClsid, CLSCTX_ALL) }; THROW_IF_FAILED(notificationCallback->Activate(appUserModelId, invokedArgs, data, dataCount)); } else { m_notificationHandlers(Default(), activatedEventArgs); } } else { auto appProperties = winrt::CoreApplication::Properties(); appProperties.Insert(ACTIVATED_EVENT_ARGS_KEY, activatedEventArgs); SetEvent(GetWaitHandleForArgs().get()); } } else { m_notificationHandlers(Default(), activatedEventArgs); } return S_OK; } CATCH_RETURN() void AppNotificationManager::Show(winrt::Microsoft::Windows::AppNotifications::AppNotification const& notification) { THROW_HR_IF(WPN_E_NOTIFICATION_POSTED, notification.Id() != 0); HRESULT hr{ S_OK }; auto logTelemetry{ wil::scope_exit([&]() { AppNotificationTelemetry::LogShow(hr, m_appId, notification.Payload(), notification.Tag(), notification.Group()); }) }; try { winrt::com_ptr<::ABI::Microsoft::Internal::ToastNotifications::INotificationProperties> notificationProperties = winrt::make_self<NotificationProperties>(notification); winrt::com_ptr<::ABI::Microsoft::Internal::ToastNotifications::INotificationTransientProperties> notificationTransientProperties = winrt::make_self<NotificationTransientProperties>(notification); DWORD notificationId = 0; THROW_IF_FAILED(ToastNotifications_PostToast(m_appId.c_str(), notificationProperties.get(), notificationTransientProperties.get(), &notificationId)); THROW_HR_IF(E_UNEXPECTED, notificationId == 0); implementation::AppNotification* notificationImpl = get_self<implementation::AppNotification>(notification); notificationImpl->SetNotificationId(notificationId); } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } winrt::Windows::Foundation::IAsyncOperation<winrt::Microsoft::Windows::AppNotifications::AppNotificationProgressResult> AppNotificationManager::UpdateAsync(winrt::Microsoft::Windows::AppNotifications::AppNotificationProgressData const data, hstring const tag, hstring const group) { THROW_HR_IF_MSG(E_INVALIDARG, tag == winrt::hstring(L""), "Update operation isn't guaranteed to find a specific notification to replace correctly."); THROW_HR_IF_MSG(E_INVALIDARG, data.SequenceNumber() == 0, "Sequence Number for Updates should be greater than 0!"); HRESULT hr{ S_OK }; auto strong = get_strong(); co_await resume_background(); auto logTelemetry{ wil::scope_exit([&]() { AppNotificationTelemetry::LogUpdateAsync(hr, m_appId, tag, group); }) }; try { winrt::com_ptr<ToastABI::IToastProgressData> toastProgressData{ winrt::make_self<NotificationProgressData>(data) }; hr = ToastNotifications_UpdateNotificationData(m_appId.c_str(), tag.c_str(), group.c_str(), toastProgressData.get()); if (SUCCEEDED(hr)) { co_return winrt::AppNotificationProgressResult::Succeeded; } else if (hr == E_NOT_SET) { co_return winrt::AppNotificationProgressResult::AppNotificationNotFound; } else { THROW_HR(hr); } } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } winrt::Windows::Foundation::IAsyncOperation<winrt::Microsoft::Windows::AppNotifications::AppNotificationProgressResult> AppNotificationManager::UpdateAsync(winrt::Microsoft::Windows::AppNotifications::AppNotificationProgressData const data, hstring const tag) { co_return co_await UpdateAsync(data, tag, L""); } winrt::Microsoft::Windows::AppNotifications::AppNotificationSetting AppNotificationManager::Setting() { HRESULT hr{ S_OK }; auto logTelemetry{ wil::scope_exit([&]() { AppNotificationTelemetry::LogSetting(hr, m_appId); }) }; try { DWORD appNotificationSetting{ 0 }; ToastNotifications_QuerySettings(m_appId.c_str(), &appNotificationSetting); return static_cast<winrt::Microsoft::Windows::AppNotifications::AppNotificationSetting>(appNotificationSetting); } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } winrt::Windows::Foundation::IAsyncAction AppNotificationManager::RemoveByIdAsync(uint32_t notificationId) { THROW_HR_IF(E_INVALIDARG, notificationId == 0); HRESULT hr{ S_OK }; auto strong = get_strong(); co_await winrt::resume_background(); auto logTelemetry{ wil::scope_exit([&]() { AppNotificationTelemetry::LogRemoveByIdAsync(hr, m_appId, notificationId); }) }; try { THROW_IF_FAILED(ToastNotifications_RemoveToast(m_appId.c_str(), notificationId)); } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } winrt::Windows::Foundation::IAsyncAction AppNotificationManager::RemoveByTagAsync(hstring const tag) { THROW_HR_IF(E_INVALIDARG, tag == winrt::hstring(L"")); HRESULT hr{ S_OK }; auto strong = get_strong(); co_await winrt::resume_background(); auto logTelemetry{ wil::scope_exit([&]() { AppNotificationTelemetry::LogRemoveByTagAsync(hr, m_appId, tag); }) }; try { THROW_IF_FAILED(ToastNotifications_RemoveToastsWithTagAndGroup(m_appId.c_str(), tag.c_str(), nullptr)); } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } winrt::Windows::Foundation::IAsyncAction AppNotificationManager::RemoveByTagAndGroupAsync(hstring const tag, hstring const group) { THROW_HR_IF(E_INVALIDARG, tag == winrt::hstring(L"")); THROW_HR_IF(E_INVALIDARG, group == winrt::hstring(L"")); HRESULT hr{ S_OK }; auto strong = get_strong(); co_await winrt::resume_background(); auto logTelemetry{ wil::scope_exit([&]() { AppNotificationTelemetry::LogRemoveByTagAndGroupAsync(hr, m_appId, tag, group); }) }; try { THROW_IF_FAILED(ToastNotifications_RemoveToastsWithTagAndGroup(m_appId.c_str(), tag.c_str(), group.c_str())); } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } winrt::Windows::Foundation::IAsyncAction AppNotificationManager::RemoveByGroupAsync(hstring const group) { THROW_HR_IF(E_INVALIDARG, group == winrt::hstring(L"")); HRESULT hr{ S_OK }; auto strong = get_strong(); co_await winrt::resume_background(); auto logTelemetry{ wil::scope_exit([&]() { AppNotificationTelemetry::LogRemoveByGroupAsync(hr, m_appId); }) }; try { THROW_IF_FAILED(ToastNotifications_RemoveToastsWithTagAndGroup(m_appId.c_str(), nullptr, group.c_str())); } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } winrt::Windows::Foundation::IAsyncAction AppNotificationManager::RemoveAllAsync() { HRESULT hr{ S_OK }; auto strong = get_strong(); co_await winrt::resume_background(); auto logTelemetry{ wil::scope_exit([&]() { AppNotificationTelemetry::LogRemoveAllAsync(hr, m_appId); }) }; try { THROW_IF_FAILED(ToastNotifications_RemoveAllToastsForApp(m_appId.c_str())); } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Foundation::Collections::IVector<winrt::Microsoft::Windows::AppNotifications::AppNotification>> AppNotificationManager::GetAllAsync() { HRESULT hr{ S_OK }; auto strong = get_strong(); co_await winrt::resume_background(); auto logTelemetry{ wil::scope_exit([&](){ AppNotificationTelemetry::LogGetAllAsync(hr, m_appId); }) }; try { winrt::com_ptr<ToastABI::IVector<ToastABI::INotificationProperties*>> toastPropertiesCollection{}; auto result{ ToastNotifications_GetHistory(m_appId.c_str(), toastPropertiesCollection.put()) }; THROW_HR_IF(result, result != S_OK && result != E_NOT_SET); // Swallow E_NOT_SET and return an empty properties vector to signal that there are no active toasts unsigned int count{}; if (toastPropertiesCollection) { THROW_IF_FAILED(toastPropertiesCollection->get_Size(&count)); } winrt::IVector<winrt::Microsoft::Windows::AppNotifications::AppNotification> toastNotifications{ winrt::single_threaded_vector<winrt::Microsoft::Windows::AppNotifications::AppNotification>() }; for (unsigned i = 0; i < count; ++i) { ToastABI::INotificationProperties* toastProperties; THROW_IF_FAILED(toastPropertiesCollection->GetAt(i, &toastProperties)); auto toastNotification{ ToastNotificationFromToastProperties(toastProperties) }; toastNotifications.Append(toastNotification); } co_return toastNotifications; } catch (...) { hr = wil::ResultFromCaughtException(); throw; } } }
38.548638
285
0.621581
G-arj
d21b6e9713f457b6ccad2501eca75d468f16fc84
4,072
cc
C++
HLTrigger/Muon/plugins/HLTMuonTrackSelector.cc
sebwieland/cmssw
431e2fdfedec052e73c16e9f06de98ade41ebc56
[ "Apache-2.0" ]
1
2021-04-13T13:26:16.000Z
2021-04-13T13:26:16.000Z
HLTrigger/Muon/plugins/HLTMuonTrackSelector.cc
sebwieland/cmssw
431e2fdfedec052e73c16e9f06de98ade41ebc56
[ "Apache-2.0" ]
null
null
null
HLTrigger/Muon/plugins/HLTMuonTrackSelector.cc
sebwieland/cmssw
431e2fdfedec052e73c16e9f06de98ade41ebc56
[ "Apache-2.0" ]
null
null
null
/* * class HLTMuonTrackSelector * * See header file for documentation * * Author: Kyeongpil Lee (kplee@cern.ch) * */ #include "HLTMuonTrackSelector.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/MuonReco/interface/MuonFwd.h" #include "DataFormats/MuonReco/interface/Muon.h" #include "DataFormats/Math/interface/deltaR.h" HLTMuonTrackSelector::HLTMuonTrackSelector(const edm::ParameterSet& iConfig) : collectionCloner(producesCollector(), iConfig, true), collectionClonerTokens(iConfig.getParameter<edm::InputTag>("track"), consumesCollector()), token_muon(consumes<vector<reco::Muon> >(iConfig.getParameter<edm::InputTag>("muon"))), token_originalMVAVals(consumes<MVACollection>(iConfig.getParameter<edm::InputTag>("originalMVAVals"))), flag_copyMVA(iConfig.getParameter<bool>("copyMVA")) { produces<MVACollection>("MVAValues"); } HLTMuonTrackSelector::~HLTMuonTrackSelector() {} void HLTMuonTrackSelector::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<edm::InputTag>("track", edm::InputTag()); desc.add<edm::InputTag>("muon", edm::InputTag()); desc.add<edm::InputTag>("originalMVAVals", edm::InputTag()); desc.add<bool>("copyMVA", false); TrackCollectionCloner::fill(desc); // -- add copyExtras and copyTrajectories descriptions.add("HLTMuonTrackSelector", desc); } void HLTMuonTrackSelector::produce(edm::StreamID, edm::Event& iEvent, const edm::EventSetup& iSetup) const { TrackCollectionCloner::Producer producer(iEvent, collectionCloner); // -- load tracks auto const& originalTracks = collectionClonerTokens.tracks(iEvent); auto nTrack = originalTracks.size(); // -- load muons edm::Handle<vector<reco::Muon> > handle_muon; iEvent.getByToken(token_muon, handle_muon); auto nMuon = handle_muon->size(); // -- load MVA values if necessary edm::Handle<MVACollection> handle_originalMVAVals; if (flag_copyMVA) { iEvent.getByToken(token_originalMVAVals, handle_originalMVAVals); assert((*handle_originalMVAVals).size() == nTrack); } // -- containers for selected track informations std::vector<unsigned int> selectedIter; auto selectedMVAVals = std::make_unique<MVACollection>(); auto nSelected = 0U; //////////////////// // -- matching -- // //////////////////// // -- iteration over muons for (auto i_mu = 0U; i_mu < nMuon; ++i_mu) { // -- avoids crashing in case the muon is SA only. const reco::Muon& muon(handle_muon->at(i_mu)); TrackRef muonTrackRef = (muon.innerTrack().isNonnull()) ? muon.innerTrack() : muon.muonBestTrack(); double muonPt = muonTrackRef->pt(); double muonEta = muonTrackRef->eta(); double muonPhi = muonTrackRef->phi(); double smallestDPt = 1e30; unsigned int smallestDPtIter = 9999U; // -- iteration over tracks for (auto i_trk = 0U; i_trk < nTrack; ++i_trk) { auto const& track = originalTracks[i_trk]; double trackPt = track.pt(); double trackEta = track.eta(); double trackPhi = track.phi(); if (deltaR(trackEta, trackPhi, muonEta, muonPhi) < 0.1) { double dPt = fabs(trackPt - muonPt); if (dPt < smallestDPt) { smallestDPt = dPt; smallestDPtIter = i_trk; } } } // -- end of track iteration // -- if at least one track is matched if (smallestDPtIter != 9999U) { selectedIter.push_back(smallestDPtIter); if (flag_copyMVA) selectedMVAVals->push_back((*handle_originalMVAVals)[smallestDPtIter]); ++nSelected; } } // -- end of muon iteration assert(producer.selTracks_->empty()); // -- produces tracks and associated informations producer(collectionClonerTokens, selectedIter); assert(producer.selTracks_->size() == nSelected); if (flag_copyMVA) iEvent.put(std::move(selectedMVAVals), "MVAValues"); } #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(HLTMuonTrackSelector);
33.377049
109
0.698183
sebwieland
d21cbd4864f9361dc157fa57ac57f019c1a708fa
20,839
cxx
C++
dev/ese/src/os/event.cxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
1
2021-02-02T07:04:07.000Z
2021-02-02T07:04:07.000Z
dev/ese/src/os/event.cxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
null
null
null
dev/ese/src/os/event.cxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "osstd.hxx" ULONG g_cbEventHeapMax; #include <malloc.h> LOCAL CRITICAL_SECTION g_csEventCache; LOCAL BOOL g_fcsEventCacheInit; #ifdef DISABLE_EVENT_LOG void COSLayerPreInit::SetEventLogCache( ULONG cbEventCache ) {} #else NTOSFuncPD( g_pfnRegisterEventSourceW, RegisterEventSourceW ); NTOSFuncPD( g_pfnReportEvent, ReportEventW ); NTOSFuncPD( g_pfnDeregisterEventSource, DeregisterEventSource ); LOCAL volatile HANDLE g_hEventSource; #pragma warning ( disable : 4200 ) struct EVENT { SIZE_T cb; EVENT* peventNext; const WCHAR* szSourceEventKey; EEventType type; CategoryId catid; MessageId msgid; DWORD cbRawData; void* pvRawData; DWORD cString; const WCHAR* rgpsz[0]; }; LOCAL EVENT* g_peventCacheHead; LOCAL EVENT* g_peventCacheTail; LOCAL DWORD g_ceventLost; LOCAL SIZE_T cbEventCache; void COSLayerPreInit::SetEventLogCache( ULONG cbEventCacheSet ) { g_cbEventHeapMax = cbEventCacheSet; } void OSEventIFlushEventCache() { EVENT* peventPrev = NULL; EVENT* pevent; EVENT* peventNext; for ( pevent = g_peventCacheHead; NULL != pevent; pevent = peventNext ) { peventNext = pevent->peventNext; g_hEventSource = g_pfnRegisterEventSourceW( NULL, pevent->szSourceEventKey ); if ( g_hEventSource ) { SIZE_T cbAlloc = pevent->cb; if ( NULL == peventPrev ) { Assert( pevent == g_peventCacheHead ); g_peventCacheHead = pevent->peventNext; } else { peventPrev->peventNext = pevent->peventNext; } if ( pevent == g_peventCacheTail ) g_peventCacheTail = peventPrev; (void)g_pfnReportEvent( g_hEventSource, WORD( pevent->type ), WORD( pevent->catid ), pevent->msgid, 0, WORD( pevent->cString ), WORD( pevent->cbRawData ), (const WCHAR**)pevent->rgpsz, pevent->pvRawData ); const BOOL fFreedEventMemory = !LocalFree( pevent ); Assert( fFreedEventMemory ); g_pfnDeregisterEventSource( g_hEventSource ); g_hEventSource = NULL; Assert( cbEventCache >= cbAlloc ); cbEventCache -= cbAlloc; } else { peventPrev = pevent; } } Assert( NULL == g_peventCacheHead ? NULL == g_peventCacheTail : NULL != g_peventCacheTail ); if ( g_ceventLost ) { g_ceventLost = 0; } } #endif #ifdef DEBUG LOCAL BOOL g_fOSSuppressEvents = fFalse; #endif const size_t g_cLastEvent = 10; WCHAR* g_rgwszLastEvent[ g_cLastEvent ] = { NULL }; size_t g_iLastEvent = 0; void OSEventReportEvent( const WCHAR* szSourceEventKey, const EEventFacility eventfacility, const EEventType type, const CategoryId catid, const MessageId msgid, const DWORD cString, const WCHAR* rgpszString[], const DWORD cbRawData, void* pvRawData ) { Expected( eventfacility & eventfacilityOsDiagTracking ); Expected( eventfacility & eventfacilityRingBufferCache ); Expected( eventfacility & eventfacilityOsEventTrace ); Expected( eventfacility & eventfacilityOsTrace ); OnThreadWaitBegin(); EnterCriticalSection( &g_csEventCache ); OnThreadWaitEnd(); #ifdef DEBUG if ( g_fOSSuppressEvents ) { LeaveCriticalSection( &g_csEventCache ); return; } g_fOSSuppressEvents = fTrue; #endif LPWSTR wszEvent = NULL; if ( FormatMessageW( ( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_MAX_WIDTH_MASK ), PvUtilImageBaseAddress(), msgid, MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL ), LPWSTR( &wszEvent ), 0, (va_list *)rgpszString ) ) { const WCHAR * wszLogStrFormatter = L"EventLog[ID=%d(0x%x)@%I64d]: %ws"; const INT cchLogStr = wcslen( wszLogStrFormatter ) + 10 + 8 + 20 + wcslen( wszEvent ) + 1 ; WCHAR * wszLogStr = (WCHAR*)LocalAlloc( LMEM_FIXED, cchLogStr * sizeof(WCHAR) ); if ( wszLogStr ) { OSStrCbFormatW( wszLogStr, cchLogStr*sizeof(WCHAR), wszLogStrFormatter, msgid, msgid, HrtHRTCount(), wszEvent ); LocalFree( wszEvent ); wszEvent = NULL; } else { wszLogStr = wszEvent; wszEvent = NULL; } if ( eventfacility & eventfacilityOsTrace ) { OSTrace( JET_tracetagEventlog, OSFormat( "%hs", SzOSFormatStringW( wszLogStr ) ) ); } if ( eventfacility & eventfacilityOsEventTrace ) { switch ( type ) { case eventError: ETEventLogError( wszLogStr ); break; case eventWarning: ETEventLogWarn( wszLogStr ); break; default: AssertSz( fFalse, "If we have anything else, someone should figure this out (as maybe someone added Critical event support, which shouldn't masquerade as Info): %d", type ); case eventInformation: ETEventLogInfo( wszLogStr ); break; } } if ( eventfacility & eventfacilityRingBufferCache ) { if ( g_rgwszLastEvent[ g_iLastEvent ] ) { LocalFree( g_rgwszLastEvent[ g_iLastEvent ] ); g_rgwszLastEvent[ g_iLastEvent ] = NULL; } g_rgwszLastEvent[ g_iLastEvent ] = wszLogStr; wszLogStr = NULL; g_iLastEvent = ( g_iLastEvent + 1 ) % g_cLastEvent; } else { LocalFree( wszLogStr ); wszLogStr = NULL; } Assert( wszEvent == NULL ); Assert( wszLogStr == NULL ); } if ( ( type == eventWarning ) || ( type == eventError ) ) { if ( eventfacility & eventfacilityOsDiagTracking ) { OSDiagTrackEventLog( msgid ); } } else { AssertSz( ( type == eventSuccess ) || ( type == eventInformation ), "New event type %d, please determine whether or not it should be tracked in OS Diagnostics.", (INT)type ); } #ifndef DISABLE_EVENT_LOG NTOSFuncPtrPreinit( g_pfnRegisterEventSourceW, g_mwszzEventLogLegacyLibs, RegisterEventSourceW, oslfExpectedOnWin5x | oslfStrictFree | oslfNotExpectedOnCoreSystem ); NTOSFuncStdPreinit( g_pfnReportEvent, g_mwszzEventLogLegacyLibs, ReportEventW, oslfExpectedOnWin5x | oslfStrictFree | oslfNotExpectedOnCoreSystem ); NTOSFuncStdPreinit( g_pfnDeregisterEventSource, g_mwszzEventLogLegacyLibs, DeregisterEventSource, oslfExpectedOnWin5x | oslfStrictFree | oslfNotExpectedOnCoreSystem ); Assert( !g_hEventSource ); Assert( cbRawData == 0 || pvRawData != NULL ); if ( eventfacility & eventfacilityReportOsEvent ) { if ( NULL != g_peventCacheHead ) OSEventIFlushEventCache(); g_hEventSource = g_pfnRegisterEventSourceW( NULL, szSourceEventKey ); if ( !g_hEventSource ) { EVENT* pevent = NULL; SIZE_T cbAlloc = sizeof(EVENT); const DWORD cbRawDataAlligned = sizeof(WCHAR) * ( ( cbRawData + sizeof(WCHAR) - 1 ) / sizeof(WCHAR) ); Assert( cbRawDataAlligned >= cbRawData ); Assert( cbRawDataAlligned % sizeof(WCHAR) == 0 ); cbAlloc += sizeof(WCHAR) * LOSStrLengthW( szSourceEventKey ) + sizeof(WCHAR ); cbAlloc += sizeof(const WCHAR*) * cString; for ( DWORD ipsz = 0; ipsz < cString; ipsz++ ) { cbAlloc += sizeof(WCHAR) * LOSStrLengthW( rgpszString[ipsz] ) + sizeof(WCHAR); } cbAlloc += cbRawDataAlligned; if ( cbEventCache + cbAlloc < (SIZE_T)g_cbEventHeapMax ) { pevent = (EVENT*)LocalAlloc( LMEM_FIXED | LMEM_ZEROINIT, cbAlloc ); if ( pevent ) { cbEventCache += cbAlloc; } } if ( !pevent ) { g_ceventLost++; } else { WCHAR* psz; pevent->cb = cbAlloc; pevent->peventNext = NULL; pevent->type = type; pevent->catid = catid; pevent->msgid = msgid; pevent->cbRawData = cbRawData; pevent->cString = cString; psz = (WCHAR*)( (BYTE*)pevent->rgpsz + ( sizeof(const WCHAR*) * cString ) ); pevent->szSourceEventKey = psz; OSStrCbCopyW( psz, cbAlloc - (((BYTE*)psz)-(BYTE*)pevent), szSourceEventKey ); psz += 1 + LOSStrLengthW( szSourceEventKey ); if ( cbRawData > 0 ) { pevent->pvRawData = (void*)psz; memcpy( psz, pvRawData, cbRawData ); Assert( cbRawDataAlligned % sizeof(WCHAR) == 0 ); psz += cbRawDataAlligned/sizeof(WCHAR); } else { Assert( cbRawDataAlligned == 0 ); pevent->pvRawData = NULL; } for ( DWORD ipsz = 0; ipsz < cString; ipsz++ ) { pevent->rgpsz[ipsz] = psz; OSStrCbCopyW( psz, cbAlloc - (((BYTE*)psz)-(BYTE*)pevent), rgpszString[ipsz] ); psz += 1 + LOSStrLengthW( rgpszString[ipsz] ); } if ( ( (BYTE*)psz - (BYTE*)pevent ) == (LONG_PTR)cbAlloc ) { if ( NULL != g_peventCacheTail ) { Assert( NULL != g_peventCacheHead ); g_peventCacheTail->peventNext = pevent; } else { Assert( NULL == g_peventCacheHead ); g_peventCacheHead = pevent; } g_peventCacheTail = pevent; } else { Assert( fFalse ); const BOOL fFreedEventMemory = !LocalFree( pevent ); Assert( fFreedEventMemory ); } } } else { (void)g_pfnReportEvent( g_hEventSource, WORD( type ), WORD( catid ), msgid, 0, WORD( cString ), WORD( cbRawData ), rgpszString, pvRawData ); g_pfnDeregisterEventSource( g_hEventSource ); g_hEventSource = NULL; } } #endif #ifdef DEBUG g_fOSSuppressEvents = fFalse; #endif LeaveCriticalSection( &g_csEventCache ); } void OSEventPostterm() { #ifndef DISABLE_EVENT_LOG Assert( !g_hEventSource || FUtilProcessAbort() ); if ( NULL != g_peventCacheHead ) { Assert( NULL != g_peventCacheTail ); if ( g_hEventSource ) { Assert( FUtilProcessAbort() ); g_pfnDeregisterEventSource( g_hEventSource ); g_hEventSource = NULL; } OSEventIFlushEventCache(); EVENT* pevent; EVENT* peventNext; for ( pevent = g_peventCacheHead; pevent; pevent = pevent = peventNext ) { peventNext = pevent->peventNext; const BOOL fFreedEventMemory = !LocalFree( pevent ); Assert( fFreedEventMemory ); } } else { Assert( NULL == g_peventCacheTail ); } if ( g_hEventSource ) { Assert( FUtilProcessAbort() ); Assert( NULL == g_peventCacheHead ); Assert( NULL == g_peventCacheTail ); g_pfnDeregisterEventSource( g_hEventSource ); g_hEventSource = NULL; } g_peventCacheHead = NULL; g_peventCacheTail = NULL; g_ceventLost = 0; cbEventCache = 0; #endif for ( size_t iLastEvent = 0; iLastEvent < g_cLastEvent; iLastEvent++ ) { if ( g_rgwszLastEvent[ iLastEvent ] ) { LocalFree( g_rgwszLastEvent[ iLastEvent ] ); g_rgwszLastEvent[ iLastEvent ] = NULL; } } g_iLastEvent = 0; if( g_fcsEventCacheInit ) { DeleteCriticalSection( &g_csEventCache ); g_fcsEventCacheInit = fFalse; } } BOOL FOSEventPreinit() { #ifndef DISABLE_EVENT_LOG g_cbEventHeapMax = 0; #endif if ( !InitializeCriticalSectionAndSpinCount( &g_csEventCache, 0 ) ) { goto HandleError; } g_fcsEventCacheInit = fTrue; for ( size_t iLastEvent = 0; iLastEvent < g_cLastEvent; iLastEvent++ ) { g_rgwszLastEvent[ iLastEvent ] = NULL; } g_iLastEvent = 0; #ifndef DISABLE_EVENT_LOG g_peventCacheHead = NULL; g_peventCacheTail = NULL; g_ceventLost = 0; cbEventCache = 0; #endif return fTrue; HandleError: OSEventPostterm(); return fFalse; } VOID OSEventRegister() { #ifndef OFFICIAL_BUILD #ifdef OS_LAYER_VIOLATIONS NTOSFuncError( pfnRegCreateKeyExW, g_mwszzRegistryLibs, RegCreateKeyExW, oslfExpectedOnWin5x | oslfRequired ); NTOSFuncError( pfnRegQueryValueExW, g_mwszzRegistryLibs, RegQueryValueExW, oslfExpectedOnWin5x | oslfRequired ); NTOSFuncError( pfnRegSetValueExW, g_mwszzRegistryLibs, RegSetValueExW, oslfExpectedOnWin5x | oslfRequired ); NTOSFuncError( pfnRegCloseKey, g_mwszzRegistryLibs, RegCloseKey, oslfExpectedOnWin5x | oslfRequired ); if ( 0 != _wcsicmp( WszUtilImageName(), L"ESElibwithtests" ) ) { Expected( 0 == _wcsicmp( WszUtilImageName(), L"ESE" ) || 0 == _wcsicmp( WszUtilImageName(), L"ESENT" ) ); static const WCHAR wszApplicationKeyPath[] = L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\"; WCHAR wszImageKeyPath[ sizeof( wszApplicationKeyPath ) / sizeof( wszApplicationKeyPath[0] ) + _MAX_FNAME ]; OSStrCbFormatW( wszImageKeyPath, sizeof(wszImageKeyPath), L"%ws%.*ws", wszApplicationKeyPath, _MAX_FNAME, WszUtilImageVersionName() ); DWORD error; HKEY hkeyImage; DWORD Disposition; error = pfnRegCreateKeyExW( HKEY_LOCAL_MACHINE, wszImageKeyPath, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, &hkeyImage, &Disposition ); if ( error == ERROR_SUCCESS ) { DWORD dwType = 0; WCHAR rgbData[ _MAX_PATH ]; const size_t cbDataMax = sizeof( rgbData ); DWORD cbData; DWORD Data; cbData = cbDataMax; if ( pfnRegQueryValueExW( hkeyImage, L"EventMessageFile", 0, &dwType, LPBYTE(rgbData), &cbData ) != ERROR_SUCCESS || dwType != REG_EXPAND_SZ || wcscmp( rgbData, WszUtilImagePath() ) || cbData != ( wcslen( WszUtilImagePath() ) + 1 ) * sizeof( WCHAR ) ) { error = pfnRegSetValueExW( hkeyImage, L"EventMessageFile", 0, REG_EXPAND_SZ, LPBYTE( WszUtilImagePath() ), (ULONG)( ( wcslen( WszUtilImagePath() ) + 1 ) * sizeof( WCHAR ) ) ); Assert( error == ERROR_SUCCESS ); } cbData = cbDataMax; if ( pfnRegQueryValueExW( hkeyImage, L"CategoryMessageFile", 0, &dwType, LPBYTE(rgbData), &cbData ) != ERROR_SUCCESS || dwType != REG_EXPAND_SZ || wcscmp( rgbData, WszUtilImagePath() ) || cbData != ( wcslen( WszUtilImagePath() ) + 1 ) * sizeof( WCHAR ) ) { error = pfnRegSetValueExW( hkeyImage, L"CategoryMessageFile", 0, REG_EXPAND_SZ, LPBYTE( WszUtilImagePath() ), (ULONG)( ( wcslen( WszUtilImagePath() ) + 1 ) * sizeof( WCHAR ) ) ); Assert( error == ERROR_SUCCESS ); } Data = MAC_CATEGORY - 1; cbData = cbDataMax; if ( pfnRegQueryValueExW( hkeyImage, L"CategoryCount", 0, &dwType, LPBYTE(rgbData), &cbData ) != ERROR_SUCCESS || dwType != REG_DWORD || memcmp( (BYTE*)rgbData, &Data, sizeof( Data ) ) || cbData != sizeof( Data ) ) { error = pfnRegSetValueExW( hkeyImage, L"CategoryCount", 0, REG_DWORD, LPBYTE( &Data ), sizeof( Data ) ); Assert( error == ERROR_SUCCESS ); } Data = EVENTLOG_INFORMATION_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_ERROR_TYPE; cbData = cbDataMax; if ( pfnRegQueryValueExW( hkeyImage, L"TypesSupported", 0, &dwType, LPBYTE(rgbData), &cbData ) != ERROR_SUCCESS || dwType != REG_DWORD || memcmp( (BYTE*)rgbData, &Data, sizeof( Data ) ) || cbData != sizeof( Data ) ) { error = pfnRegSetValueExW( hkeyImage, L"TypesSupported", 0, REG_DWORD, LPBYTE( &Data ), sizeof( Data ) ); Assert( error == ERROR_SUCCESS ); } error = pfnRegCloseKey( hkeyImage ); Assert( error == ERROR_SUCCESS ); } } #endif #endif } void OSEventTerm() { } ERR ErrOSEventInit() { return JET_errSuccess; }
32.40902
193
0.478574
augustoproiete-forks
d21f36e288f9158449eec0a8719f3bb6bfe590ec
337
cpp
C++
Core/radio/RadioHardware.cpp
ji3gab/ExtIO_sddc
ff82dddc75ee9a1af3d5ca0d882a81b5ee78410d
[ "MIT" ]
24
2018-01-24T22:05:14.000Z
2022-03-28T00:46:09.000Z
Core/radio/RadioHardware.cpp
ji3gab/ExtIO_sddc
ff82dddc75ee9a1af3d5ca0d882a81b5ee78410d
[ "MIT" ]
106
2020-11-09T01:25:33.000Z
2022-03-15T08:32:26.000Z
Core/radio/RadioHardware.cpp
ji3gab/ExtIO_sddc
ff82dddc75ee9a1af3d5ca0d882a81b5ee78410d
[ "MIT" ]
18
2020-10-09T20:15:53.000Z
2022-03-27T07:29:20.000Z
#include "RadioHandler.h" bool RadioHardware::FX3SetGPIO(uint32_t mask) { gpios |= mask; return Fx3->Control(GPIOFX3, gpios); } bool RadioHardware::FX3UnsetGPIO(uint32_t mask) { gpios &= ~mask; return Fx3->Control(GPIOFX3, gpios); } RadioHardware::~RadioHardware() { if (Fx3) { FX3SetGPIO(SHDWN); } }
15.318182
47
0.652819
ji3gab
d22068426ebeea0934b49c935dde4027ca611721
1,144
cpp
C++
Emissions/Set_Link_List.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
Emissions/Set_Link_List.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
Emissions/Set_Link_List.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Set_Link_List.cpp - process the link equivalence data //********************************************************* #include "Emissions.hpp" //--------------------------------------------------------- // Set_Link_List //--------------------------------------------------------- void Emissions::Set_Link_List (void) { int i, num, link, lnk, dir; Link_Data *link_ptr; Integer_List *group; num = link_equiv.Max_Group (); for (i=1; i <= num; i++) { group = link_equiv.Group_List (i); if (group == NULL) continue; //---- process each link in the link group ---- for (link = group->First (); link != 0; link = group->Next ()) { if (vol_spd_flag) { dir = abs (link); } else { lnk = abs (link); link_ptr = link_data.Get (lnk); if (link_ptr == NULL) continue; if (link < 0) { dir = link_ptr->BA_Dir (); } else { dir = link_ptr->AB_Dir (); } } //---- add to the link list ---- if (link_list.Get_Index (dir) == 0) { if (!link_list.Add (dir)) { Error ("Adding Link to the Link List"); } } } } }
20.8
66
0.447552
kravitz
d221f39e2027e747d0dd2236eeee8d3c71a3e497
483
hpp
C++
src/crypto/Bip32.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/crypto/Bip32.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/crypto/Bip32.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
// Copyright (c) 2018 The Open-Transactions developers // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once #include "Internal.hpp" #include "opentxs/crypto/Bip32.hpp" namespace opentxs::crypto::implementation { class Bip32 : virtual public opentxs::crypto::Bip32 { }; } // namespace opentxs::crypto::implementation
26.833333
70
0.73913
nopdotcom
d2220f308dcec53eeb3d7d6538278fbad7c7e71f
209
cpp
C++
FlappyBird/src/FlappyBirdApp.cpp
HSadeghein/FlappyBird
749f60fd27dd881736ac55b73826d43f74f71332
[ "MIT" ]
1
2019-11-06T10:03:11.000Z
2019-11-06T10:03:11.000Z
FlappyBird/src/FlappyBirdApp.cpp
HSadeghein/FlappyBird
749f60fd27dd881736ac55b73826d43f74f71332
[ "MIT" ]
null
null
null
FlappyBird/src/FlappyBirdApp.cpp
HSadeghein/FlappyBird
749f60fd27dd881736ac55b73826d43f74f71332
[ "MIT" ]
null
null
null
#include<Immortal.h> class FlappyBird : public Immortal::Application { public: FlappyBird() { } ~FlappyBird() { } }; Immortal::Application* Immortal::CreateApplication() { return new FlappyBird(); }
11
52
0.69378
HSadeghein
d2267f043aec24676ea34be8e9b74b96faefc809
1,849
cc
C++
SampleMgr/test/samplegrp_test.cc
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
SampleMgr/test/samplegrp_test.cc
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
SampleMgr/test/samplegrp_test.cc
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
/******************************************************************************* * * Filename : samplegrp_test.cc * Description : Unit testing for Sample group class * Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ] * *******************************************************************************/ #include "ManagerUtils/Common/interface/ConfigReader.hpp" #include "ManagerUtils/SampleMgr/interface/SampleGroup.hpp" #include <iostream> using namespace std; using namespace mgr; void DumpInfo( const SampleGroup& ); int main(int argc, char* argv[]) { cout << "=====[UNIT TESTING FOR SAMPLEGROUP CLASS]=====" << endl; ConfigReader cfg( "./group.json" ); cout << "=====[SUBSET GROUP TESTING]=====" << endl; SampleMgr::InitStaticFromFile("./sample_static.json"); SampleMgr::SetFilePrefix("./"); SampleGroup subset( "SubSetInFile" ); subset.InitFromReader( cfg ); DumpInfo( subset ); SampleGroup subset_default( "SubSetInFile_WithDefault" ); subset_default.InitFromReader( cfg ); DumpInfo( subset_default ); cout << "=====[FILE BASED GROUP TESTING]=====" << endl; SampleGroup whole_file( "AllGroupsInFiles", cfg ); DumpInfo( whole_file ); cout << "=====[SINGLE SAMPLE TESTING]=====" << endl; SampleGroup single_in_file( "TTJets2" ); single_in_file.InitFromReader( cfg ); DumpInfo( single_in_file ); cout << "=====[SINGLE SAMPLE TESTING]=====" << endl; SampleGroup single_default( "TTJets" ); single_default.InitFromReader( cfg ); DumpInfo( single_default ); return 0; } void DumpInfo( const SampleGroup& x ) { cout << x.Name() << " " << x.LatexName() << endl; for( const auto& sample : x.SampleList() ){ cout << " > " << sample.Name() << " " << sample.LatexName() << sample.ExpectedYield() << endl; } }
29.349206
80
0.581395
NTUHEP-Tstar
d22896ef2b14f1c790d7a201fd476e336b53d5a5
14,888
cpp
C++
src/Source.cpp
fencl/Crs
902f6f293bcf33ff71ca6cfc306d8b833d1e0e63
[ "MIT" ]
null
null
null
src/Source.cpp
fencl/Crs
902f6f293bcf33ff71ca6cfc306d8b833d1e0e63
[ "MIT" ]
null
null
null
src/Source.cpp
fencl/Crs
902f6f293bcf33ff71ca6cfc306d8b833d1e0e63
[ "MIT" ]
null
null
null
#include "Source.hpp" #include <iostream> #include <fstream> #include <ctype.h> #include <algorithm> #include <string> #include <string_view> #include "CompileContext.hpp" #include "Error.hpp" #include "ConstantManager.hpp" #include "Compiler.hpp" #include "Ast.hpp" #include "Statement.hpp" #ifdef WINDOWS #include <windows.h> #endif #ifdef LINUX #include <cstdlib> #include <cstdio> #include <cstring> #endif namespace Crs { bool operator < (const SourceRange& l, const SourceRange& r) { return l.offset+l.length <= r.offset; } bool operator == (const SourceRange& l, const SourceRange& r) { return l.offset <= r.offset + r.length && r.offset <= l.offset+l.length; } std::size_t Cursor::line() const { if (src == nullptr) return 0; return src->get_line(*this); } std::size_t Source::get_line(Cursor c) const { if (c.src != this) { return 0; } SourceRange range; range.length = c.length; range.offset = c.offset; return lines.at(range); } void Source::register_debug() { if (debug_id == UINT16_MAX) { debug_id = Compiler::current()->global_module()->register_debug_source(name); } std::size_t l = 0; std::size_t off = 0; std::string_view src = data(); bool next = true; while (next) { std::size_t pos = src.find("\n", off); if (pos == src.npos) { pos = src.length()-1; next = false; } else { ++pos; } SourceRange range; range.length = pos - off; range.offset = off; if (range.length > 0) { lines[range] = l; } ++l; off = pos; } } const std::string_view Source::data() const { return std::string_view(buffer); } void Source::load(const char* file) { std::ifstream in(file, std::ios::in | std::ios::binary); if (in) { in.seekg(0, std::ios::end); const unsigned int buf_size = (const unsigned int)in.tellg(); buffer.resize(buf_size); in.seekg(0, std::ios::beg); in.read(&buffer[0], buffer.size()); in.close(); } else { throw string_exception("File not found"); } name = file; const std::size_t last_slash_idx = name.find_last_of("\\/"); if (std::string::npos != last_slash_idx) { name.erase(0, last_slash_idx + 1); } } void Source::load_data(const char* new_data, const char* nm) { buffer = new_data; name = nm; } void Source::read_after(Cursor& out, const Cursor& c) const { read(out, c.offset + c.length,c.x,c.y); } Cursor Source::read_first() { Cursor c; read(c, 0, 0, 0); return c; } bool operator < (const Cursor& c1, const Cursor& c2) { if (c1.src < c2.src) return true; if (c1.src > c2.src) return false; if (c1.offset < c2.offset) return true; return false; } std::string_view Cursor::buffer() const { return src->data().substr(offset, length); } Cursor Cursor::next() const { Cursor c; ((Crs::Source*)src)->read_after(c, *this); return c; } void Cursor::move() { ((Crs::Source*)src)->read_after(*this, *this); } void Source::read(Cursor& out, std::size_t offset, std::size_t x, std::size_t y) const { while (true) { while (offset < buffer.size() && isspace(buffer[offset])) { if (buffer[offset] == '\n') { x = 0; y++; } offset++; } if (offset < buffer.size() - 1 && buffer[offset] == '/' && buffer[offset + 1] == '*') { offset += 3; while (offset < buffer.size() && (buffer[offset] != '/' || buffer[offset - 1] != '*')) { if (buffer[offset] == '\n') { x = 0; y++; } offset++; } offset++; } else if (offset < buffer.size() - 1 && buffer[offset] == '/' && buffer[offset + 1] == '/') { offset += 2; while (offset < buffer.size()) { if (buffer[offset] == '\n') { x = 0; y++; break; } offset++; } offset++; } else break; } if (offset < buffer.size()) { if (isalpha(buffer[offset]) || buffer[offset] == '_') { std::size_t start = offset; std::size_t start_x = x; while (isalnum(buffer[offset]) || buffer[offset] == '_') { offset++; x++; } out.x = start_x; out.y = y; out.src = this; out.offset = start; out.length = offset - start; out.tok = RecognizedToken::Symbol; return; } else if (isdigit(buffer[offset])) { bool floatt = false; bool doublet = false; bool islong = false; bool isusg = false; std::size_t start = offset; std::size_t start_x = x; while (isdigit(buffer[offset]) || buffer[offset] == '.') { if (buffer[offset] == '.') floatt = true; offset++; x++; } if (buffer[offset] == 'd' && floatt) { doublet = true; offset++; x++; } if (buffer[offset] == 'u' && !floatt) { isusg = true; offset++; x++; } if (buffer[offset] == 'l' && !floatt) { islong = true; offset++; x++; } out.src = this; out.offset = start; out.length = offset - start; out.y = y; out.x = start_x; if (floatt) { if (doublet) out.tok = (RecognizedToken::DoubleNumber); else out.tok = (RecognizedToken::FloatNumber); } else if (islong) { if (isusg) out.tok = (RecognizedToken::UnsignedLongNumber); else out.tok = (RecognizedToken::LongNumber); } else { if (isusg) out.tok = (RecognizedToken::UnsignedNumber); else out.tok = (RecognizedToken::Number); } return; } else if (buffer[offset] == '"') { std::size_t start = offset; std::size_t start_x = x; bool escaped = false; while (true) { offset++; char boff = buffer[offset]; if (offset >= buffer.size() || boff == '\n') { out.src = this; out.offset = start; out.length = offset - start; out.x = start_x; out.y = y; throw_specific_error(out, "String literal not closed"); } else if (boff == '"' && !escaped) { break; } if (boff == '\\' && !escaped) { escaped = true; } else { escaped = false; } } offset++; x += offset-start; out.tok = RecognizedToken::String; out.src = this; out.offset = start; out.length = offset - start; out.x = start_x; out.y = y; } else { std::size_t start = offset; std::size_t start_x = x; char c = buffer[offset++]; char nc = '\0'; if (offset < buffer.size()) { nc = buffer[offset]; } switch (c) { case '@': out.tok = (RecognizedToken::At); break; case '[': out.tok = (RecognizedToken::OpenBracket); break; case ']': out.tok = (RecognizedToken::CloseBracket); break; case '{': out.tok = (RecognizedToken::OpenBrace); break; case '}': out.tok = (RecognizedToken::CloseBrace); break; case '(': out.tok = (RecognizedToken::OpenParenthesis); break; case ')': out.tok = (RecognizedToken::CloseParenthesis); break; case '+': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::PlusEquals); break; default: out.tok = (RecognizedToken::Plus); break; } break; case '-': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::MinusEquals); break; case '>': offset++; out.tok = (RecognizedToken::Arrow); break; default: out.tok = (RecognizedToken::Minus); break; }break; case '*': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::StarEquals); break; default: out.tok = (RecognizedToken::Star); break; } break; case '/': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::SlashEquals); break; default: out.tok = (RecognizedToken::Slash); break; } break; case ';': out.tok = (RecognizedToken::Semicolon); break; case ',': out.tok = (RecognizedToken::Comma); break; case '.': switch (nc) { case '.': offset++; out.tok = (RecognizedToken::DoubleDot); break; default: out.tok = (RecognizedToken::Dot); break; } break; case '%': out.tok = (RecognizedToken::Percent); break; case '^': out.tok = (RecognizedToken::Xor); break; case '\\': out.tok = (RecognizedToken::Backslash); break; case '?': out.tok = (RecognizedToken::QestionMark); break; case '!': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::NotEquals); break; default: out.tok = (RecognizedToken::ExclamationMark); break; } break; case '>': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::GreaterOrEqual); break; default: out.tok = (RecognizedToken::GreaterThan); break; }break; case '<': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::LessOrEqual); break; case '-': offset++; out.tok = (RecognizedToken::BackArrow); break; default: out.tok = (RecognizedToken::LessThan); break; }break; case ':': switch (nc) { case ':': offset++; out.tok = (RecognizedToken::DoubleColon); break; case '=': offset++; out.tok = (RecognizedToken::ColonEquals); break; default: out.tok = (RecognizedToken::Colon); break; }break; case '|': switch (nc) { case '|': offset++; out.tok = (RecognizedToken::DoubleOr); break; default: out.tok = (RecognizedToken::Or); break; }break; case '&': switch (nc) { case '&': offset++; out.tok = (RecognizedToken::DoubleAnd); break; default: out.tok = (RecognizedToken::And); break; }break; case '=': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::DoubleEquals); break; default: out.tok = (RecognizedToken::Equals); break; }break; default: out.tok = (RecognizedToken::Unknown); break; } x+= offset - start; out.src = this; out.offset = start; out.length = offset - start; out.x = start_x; out.y = y; return; } } else { out.tok = RecognizedToken::Eof; out.src = this; out.offset = offset+1; out.x = x+1; out.y = y; out.length = 0; } } void Cursor::move_matching() { if (src != nullptr && (tok == RecognizedToken::OpenBrace || tok == RecognizedToken::OpenParenthesis)) { src->move_matching(*this); if (tok == RecognizedToken::OpenBrace) tok = RecognizedToken::CloseBrace; if (tok == RecognizedToken::OpenParenthesis) tok = RecognizedToken::CloseParenthesis; } } void Source::move_matching(Cursor& c) const { c = token_pair.find(c.offset)->second; } errvoid Source::pair_tokens() { Cursor c = read_first(); int level_braces = 0; int level_parenthesies = 0; std::vector<Cursor> open_braces; std::vector<Cursor> open_parenthesies; while (c.tok != RecognizedToken::Eof) { switch (c.tok) { case RecognizedToken::OpenBrace: open_braces.push_back(c); level_braces++; break; case RecognizedToken::OpenParenthesis: open_parenthesies.push_back(c); level_parenthesies++; break; case RecognizedToken::CloseBrace: if (level_braces > 0) { token_pair[open_braces.back().offset] = c; open_braces.pop_back(); level_braces--; } else { return throw_specific_error(c, "There was no '}' to match this brace"); } break; case RecognizedToken::CloseParenthesis: if (level_parenthesies > 0) { token_pair[open_parenthesies.back().offset] = c; open_parenthesies.pop_back(); level_parenthesies--; } else { return throw_specific_error(c, "There was no ')' to match this parenthesis"); } break; } c.move(); } if (level_braces != 0) { return throw_specific_error(open_braces.back(), "There was no '}' to close this block"); } if (level_parenthesies != 0) { return throw_specific_error(open_parenthesies.back(), "There was no ')' to close this block"); } return err::ok; } ILBytecodeFunction* compile_build_block(Cursor& c) { Compiler* compiler = Compiler::current(); compiler->types()->t_build_script->compile(); auto func = compiler->global_module()->create_function(ILContext::compile); func->decl_id = compiler->types()->t_build_script->il_function_decl; ILBlock* b = func->create_and_append_block(); auto scope = ScopeState().function(func, compiler->types()->t_void).context(ILContext::compile).stack().compiler_stack(); Statement::parse_inner_block_start(b); Cursor name = c; BlockTermination term; c.move(); Statement::parse_inner_block(c, term, true, &name); return func; } std::string_view parent_path(std::string_view path) { std::size_t off=0; off = path.find_last_of("\\/"); if (off != std::string_view::npos) { return path.substr(0, off); }else { return "."; } } #ifdef WINDOWS std::string abs_path(std::string path) { char full[MAX_PATH]; GetFullPathNameA(path.c_str(), MAX_PATH, full, nullptr); return std::string(full); } #endif #ifdef LINUX std::string abs_path(std::string path) { char* abs = realpath(path.c_str(), nullptr); std::string res(abs); std::free(abs); return std::move(res); } #endif errvoid Source::require(std::string_view file, Source* src) { Compiler* compiler = Compiler::current(); std::string abs; if (src) { abs = parent_path(src->path); #ifdef WINDOWS abs += "\\"; #else abs += "/"; #endif abs += file; } else { abs = file; } { std::ifstream f(abs.c_str()); if (!f.good()) { std::string msg = "Required file \"" + std::string(abs) + "\" does not exist"; return throw_runtime_exception(compiler->evaluator(), msg); } } abs = abs_path(abs); auto f = compiler->included_sources.find(abs); if (f == compiler->included_sources.end()) { auto new_src = std::make_unique<Source>(); new_src->path = abs; new_src->load(abs.c_str()); new_src->register_debug(); if (!new_src->pair_tokens()) return err::fail; auto ptr = new_src.get(); compiler->included_sources[std::move(abs)] = std::move(new_src); std::unique_ptr<AstRootNode> node; if (!AstRootNode::parse(node,ptr)) return err::fail; ptr->root_node = std::move(node); if (!ptr->root_node->populate()) return err::fail; compiler->source_stack.push_back(ptr); for (auto&& r : ptr->root_node->compile) { auto scope = ScopeState().context(ILContext::compile).compiler_stack().function(nullptr,nullptr); Cursor c = load_cursor(r, ptr); BlockTermination termination; if (!Statement::parse(c, termination, ForceCompile::single)) return err::fail; } compiler->source_stack.pop_back(); } return err::ok; } void Source::require_wrapper(dword_t slice) { std::basic_string_view<char> data_string((char*)slice.p1, (std::size_t)slice.p2); if (!Source::require(data_string, Compiler::current()->source())) { ILEvaluator::ex_throw(); return; } } }
24.12966
123
0.592558
fencl
d22b970154e210c38ed25204a58b0638e7f62605
458
cpp
C++
libraries/networking/src/NodeData.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
272
2021-01-07T03:06:08.000Z
2022-03-25T03:54:07.000Z
libraries/networking/src/NodeData.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
1,021
2020-12-12T02:33:32.000Z
2022-03-31T23:36:37.000Z
libraries/networking/src/NodeData.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
77
2020-12-15T06:59:34.000Z
2022-03-23T22:18:04.000Z
// // NodeData.cpp // libraries/networking/src // // Created by Stephen Birarda on 2/19/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "NodeData.h" NodeData::NodeData(const QUuid& nodeID, NetworkPeer::LocalID nodeLocalID) : _mutex(), _nodeID(nodeID), _nodeLocalID(nodeLocalID) { }
21.809524
88
0.696507
Darlingnotin
d22e959e01a66ccdc2bd90337a1e1e811f83ffaf
2,119
hpp
C++
src/3rd party/boost/boost/numeric/interval/compare/set.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/boost/boost/numeric/interval/compare/set.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/3rd party/boost/boost/numeric/interval/compare/set.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
/* Boost interval/compare/set.hpp template implementation file * * Copyright Guillaume Melquiond 2002-2003 * Permission to use, copy, modify, sell, and distribute this software * is hereby granted without fee provided that the above copyright notice * appears in all copies and that both that copyright notice and this * permission notice appear in supporting documentation, * * None of the above authors make any representation about the * suitability of this software for any purpose. It is provided "as * is" without express or implied warranty. * * $Id: set.hpp,v 1.2 2003/02/05 17:34:31 gmelquio Exp $ */ #ifndef BOOST_NUMERIC_INTERVAL_COMPARE_SET_HPP #define BOOST_NUMERIC_INTERVAL_COMPARE_SET_HPP #include <boost/numeric/interval/detail/interval_prototype.hpp> #include <boost/numeric/interval/utility.hpp> namespace boost { namespace numeric { namespace interval_lib { namespace compare { namespace set { template<class T, class Policies1, class Policies2> inline bool operator<(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return proper_subset(x, y); } template<class T, class Policies1, class Policies2> inline bool operator<=(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return subset(x, y); } template<class T, class Policies1, class Policies2> inline bool operator>(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return proper_subset(y, x); } template<class T, class Policies1, class Policies2> inline bool operator>=(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return subset(y, x); } template<class T, class Policies1, class Policies2> inline bool operator==(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return equal(y, x); } template<class T, class Policies1, class Policies2> inline bool operator!=(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return !equal(y, x); } } // namespace set } // namespace compare } // namespace interval_lib } // namespace numeric } // namespace boost #endif // BOOST_NUMERIC_INTERVAL_COMPARE_SET_HPP
29.84507
81
0.754129
OLR-xray
d23000c42aac906690a6ab1287bf9f5559acfe05
843
cpp
C++
CodeForces/Solutions/1015D.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
5
2020-10-03T17:15:26.000Z
2022-03-29T21:39:22.000Z
CodeForces/Solutions/1015D.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
null
null
null
CodeForces/Solutions/1015D.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
1
2021-03-01T12:56:50.000Z
2021-03-01T12:56:50.000Z
#include <bits/stdc++.h> using namespace std; #define ll long long vector <ll> ans; int main() { ll n, k, s; cin >> n >> k >> s; ll mx = n - 1; if(s > (n - 1) * k || (s < k) ) { printf("NO\n"); return 0; } ll prv = 1, pls = 0; ll per = s / k; if(s % k != 0) { pls = 1; } ll sum = 0; for(ll i = 1; i <= k; i++) { if(i % 2 == 1) ans.push_back(prv + per + pls); else ans.push_back(prv - per - pls); sum = sum + per + pls; ll baki = k - i; ll dif = s - sum; if(dif == 0) break; if(dif % baki == 0) pls = 0; prv = ans[i - 1]; } printf("YES\n"); for(ll i = 0; i < ans.size(); i++) printf("%lld ", ans[i]); cout << endl; return 0; }
17.204082
43
0.376038
Shefin-CSE16
d231b6981bb75c523f0276942d2e2144eaa5505a
9,857
cpp
C++
inetsrv/msmq/src/mqsec/certifct/cmqcert.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/msmq/src/mqsec/certifct/cmqcert.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/msmq/src/mqsec/certifct/cmqcert.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1997 Microsoft Corporation Module Name: cmqcert.cpp Abstract: Implement the methods of class CMQSigCertificate Author: Doron Juster (DoronJ) 04-Dec-1997 Revision History: --*/ #include <stdh_sec.h> #include "certifct.h" #include "cmqcert.tmh" static WCHAR *s_FN=L"certifct/cmqcert"; extern DWORD g_cOpenCert; //+--------------------------------------------------------- // // constructor and destructor // //+--------------------------------------------------------- CMQSigCertificate::CMQSigCertificate() : m_fCreatedInternally(FALSE), m_fDeleted(FALSE), m_fKeepContext(FALSE), m_pEncodedCertBuf(NULL), m_pCertContext(NULL), m_hProvCreate(NULL), m_hProvRead(NULL), m_pPublicKeyInfo(NULL), m_pCertInfoRO(NULL), m_dwCertBufSize(0) { m_pCertInfo = NULL; } CMQSigCertificate::~CMQSigCertificate() { if (m_fCreatedInternally) { ASSERT(!m_pCertContext); if (m_pEncodedCertBuf) { ASSERT(m_dwCertBufSize > 0); delete m_pEncodedCertBuf; m_pEncodedCertBuf = NULL; } } else if (m_pCertContext) { ASSERT(m_pEncodedCertBuf); CertFreeCertificateContext(m_pCertContext); } else { ASSERT(m_fDeleted || m_fKeepContext); } } //+----------------------------------------------------------------------- // // HRESULT CMQSigCertificate::EncodeCert() // // This method sign and encode the certificate. The result is a buffer, // allocated here and returned in "ppCertBuf", which holds the encoded // certificate. // Both input pointers are optional. The encoded buffer is always kept // in the object and can be retieved later by calling "GetCertBlob". // //+----------------------------------------------------------------------- HRESULT CMQSigCertificate::EncodeCert( IN BOOL fMachine, OUT BYTE **ppCertBuf, OUT DWORD *pdwSize ) { ASSERT_CERT_INFO; HRESULT hr = _InitCryptProviderCreate(FALSE, fMachine); if (FAILED(hr)) { return LogHR(hr, s_FN, 10); } CRYPT_OBJID_BLOB Parameters; memset(&Parameters, 0, sizeof(Parameters)); CRYPT_ALGORITHM_IDENTIFIER SigAlg; SigAlg.pszObjId = szOID_RSA_MD5RSA; SigAlg.Parameters = Parameters; // // Call CryptSignAndEncodeCertificate to get the size of the // returned blob. // ASSERT(m_hProvCreate); BOOL fReturn = CryptSignAndEncodeCertificate( m_hProvCreate, // Crypto provider AT_SIGNATURE, // Key spec. MY_ENCODING_TYPE, // Encoding type X509_CERT_TO_BE_SIGNED, // Struct type m_pCertInfo, // Struct info &SigAlg, // Signature algorithm NULL, // Not used NULL, // pbSignedEncodedCertReq &m_dwCertBufSize // Size of cert blob ); if (!fReturn) { TrERROR(SECURITY, "Failed to get the size for signed and encoded certificate. %!winerr!", GetLastError()); return MQSec_E_ENCODE_CERT_FIRST; } m_pEncodedCertBuf = (BYTE*) new BYTE[m_dwCertBufSize]; // // Call CryptSignAndEncodeCertificate to get the // returned blob. // fReturn = CryptSignAndEncodeCertificate( m_hProvCreate, // Crypto provider AT_SIGNATURE, // Key spec. MY_ENCODING_TYPE, // Encoding type X509_CERT_TO_BE_SIGNED, // Struct type m_pCertInfo, // Struct info &SigAlg, // Signature algorithm NULL, // Not used m_pEncodedCertBuf, // buffer &m_dwCertBufSize // Size of cert blob ); if (!fReturn) { TrERROR(SECURITY, "Failed to signed and encoded certificate. %!winerr!", GetLastError()); return MQSec_E_ENCODE_CERT_SECOND; } if (ppCertBuf) { *ppCertBuf = m_pEncodedCertBuf; } if (pdwSize) { *pdwSize = m_dwCertBufSize; } m_pCertInfoRO = m_pCertInfo; return MQ_OK; } //+----------------------------------------------------------------------- // // HRESULT CMQSigCertificate::AddToStore( HCERTSTORE hStore ) // // Description: Add the certificate to a store // //+----------------------------------------------------------------------- HRESULT CMQSigCertificate::AddToStore(IN HCERTSTORE hStore) const { if (!m_pEncodedCertBuf) { return LogHR(MQSec_E_INVALID_CALL, s_FN, 40); } BOOL fAdd = CertAddEncodedCertificateToStore( hStore, MY_ENCODING_TYPE, m_pEncodedCertBuf, m_dwCertBufSize, CERT_STORE_ADD_NEW, NULL ); if (!fAdd) { TrERROR(SECURITY, "Failed add encoded crtificate to the store. %!winerr!", GetLastError()); return MQSec_E_CAN_NOT_ADD; } return MQSec_OK; } //+----------------------------------------------------------------------- // // HRESULT CMQSigCertificate::DeleteFromStore() // // Description: Delete the certificate from its store. This method // makes the certificate context (m_pCertContext) invalid. // //+----------------------------------------------------------------------- HRESULT CMQSigCertificate::DeleteFromStore() { if (!m_pCertContext) { return LogHR(MQSec_E_INVALID_CALL, s_FN, 60); } BOOL fDel = CertDeleteCertificateFromStore(m_pCertContext); m_pCertContext = NULL; m_fDeleted = TRUE; if (!fDel) { DWORD dwErr = GetLastError(); LogNTStatus(dwErr, s_FN, 65); if (dwErr == E_ACCESSDENIED) { return LogHR(MQ_ERROR_ACCESS_DENIED, s_FN, 70); } else { return LogHR(MQSec_E_CAN_NOT_DELETE, s_FN, 80); } } return MQ_OK; } //+----------------------------------------------------------------------- // // HRESULT CMQSigCertificate::GetCertDigest(OUT GUID *pguidDigest) // // Description: Compute the digest of the certificate. // Use only the "to be signed" portion of the certificate. This is // necessary for keeping compatibility with MSMQ 1.0, which used // digsig.dll. digsig hashes only the "to be signed" part. // // The encoded certificate, held by "m_pEncodedCertBuf" is already // signed so it can not be used for computing the digest. this is // why CERT_INFO (m_pCertInfoRO) is encoded again, with flag // X509_CERT_TO_BE_SIGNED. The result of this encoding is used to // compute the digest. // //+----------------------------------------------------------------------- HRESULT CMQSigCertificate::GetCertDigest(OUT GUID *pguidDigest) { HRESULT hr = MQSec_OK; if (!m_pCertInfoRO) { return LogHR(MQSec_E_INVALID_CALL, s_FN, 90); } DWORD dwSize = 0; BOOL fEncode = CryptEncodeObject( MY_ENCODING_TYPE, // Encoding type X509_CERT_TO_BE_SIGNED, // Struct type m_pCertInfoRO, // Address of struct. NULL, // pbEncoded &dwSize // pbEncoded size ); if ((dwSize == 0) || !fEncode) { TrERROR(SECURITY, "Failed to get the size for encoding certificate. %!winerr!", GetLastError()); return MQSec_E_ENCODE_HASH_FIRST; } P<BYTE> pBuf = new BYTE[dwSize]; fEncode = CryptEncodeObject( MY_ENCODING_TYPE, // Encoding type X509_CERT_TO_BE_SIGNED, // Struct type m_pCertInfoRO, // Address of struct. pBuf, // pbEncoded &dwSize // pbEncoded size ); if (!fEncode) { TrERROR(SECURITY, "Failed to encode certificate. %!winerr!", GetLastError()); return MQSec_E_ENCODE_HASH_SECOND; } hr = _InitCryptProviderRead(); if (FAILED(hr)) { return LogHR(hr, s_FN, 120); } ASSERT(m_hProvRead); CHCryptHash hHash; BOOL fCreate = CryptCreateHash( m_hProvRead, CALG_MD5, 0, 0, &hHash ); if (!fCreate) { TrERROR(SECURITY, "Failed to create MD5 hash. %!winerr!", GetLastError()); return MQSec_E_CANT_CREATE_HASH; } BOOL fHash = CryptHashData( hHash, pBuf, dwSize, 0 ); if (!fHash) { TrERROR(SECURITY, "Failed to hash data. %!winerr!", GetLastError()); return MQSec_E_CAN_NOT_HASH; } dwSize = sizeof(GUID); BOOL fGet = CryptGetHashParam( hHash, HP_HASHVAL, (BYTE*) pguidDigest, &dwSize, 0 ); if (!fGet) { TrERROR(SECURITY, "Failed to get hash value from hash object. %!winerr!", GetLastError()); return MQSec_E_CAN_NOT_GET_HASH; } return MQ_OK; } //+----------------------------------------------------------------------- // // HRESULT CMQSigCertificate::Release() // // Description: delete this object. cleanup is done in the destructor. // //+----------------------------------------------------------------------- HRESULT CMQSigCertificate::Release(BOOL fKeepContext) { if (fKeepContext) { m_fKeepContext = TRUE; m_pCertContext = NULL; } g_cOpenCert--; TrTRACE(SECURITY, "Releasing Cert, g_cOpenCert = %d", g_cOpenCert); delete this; return MQ_OK; }
27.456825
115
0.530587
npocmaka
d2339c2a2e67c474fcc62c9003793232129366b0
355
cpp
C++
ejercicio2/main.cpp
matbentancur/pav
df556249e342863286ad1c991a5613bd63e09902
[ "MIT" ]
null
null
null
ejercicio2/main.cpp
matbentancur/pav
df556249e342863286ad1c991a5613bd63e09902
[ "MIT" ]
1
2018-04-05T15:06:04.000Z
2018-04-15T21:46:44.000Z
ejercicio2/main.cpp
matbentancur/pav
df556249e342863286ad1c991a5613bd63e09902
[ "MIT" ]
null
null
null
#include <iostream> #include "A.h" #include "B.h" #include "C.h" using namespace std; int main(){ ClassA msg_a; msg_a = ClassA(); ClassB msg_b; msg_b = ClassB(); ClassC msg_c; msg_c = ClassC(); cout<<msg_a.getA()<<endl; cout<<msg_b.getB()<<endl; cout<<msg_c.getC()<<endl; return 0; }
14.2
30
0.535211
matbentancur
d2398630f54d13522c03b861d8d20976fa9aebdb
5,937
hpp
C++
RegNRecon/jly_sorting.hpp
MrJia1997/RenderKinect
6cc6d6a56ce6a925920e155db5aa6f5239c563e8
[ "MIT" ]
null
null
null
RegNRecon/jly_sorting.hpp
MrJia1997/RenderKinect
6cc6d6a56ce6a925920e155db5aa6f5239c563e8
[ "MIT" ]
null
null
null
RegNRecon/jly_sorting.hpp
MrJia1997/RenderKinect
6cc6d6a56ce6a925920e155db5aa6f5239c563e8
[ "MIT" ]
null
null
null
/******************************************************************** Sorting/Selection functions for the Go-ICP Algorithm Last modified: Jan 27, 2015 "Go-ICP: Solving 3D Registration Efficiently and Globally Optimally" Jiaolong Yang, Hongdong Li, Yunde Jia International Conference on Computer Vision (ICCV), 2013 Copyright (C) 2013 Jiaolong Yang (BIT and ANU) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *********************************************************************/ #ifndef JLY_SORING_HPP #define JLY_SORING_HPP #define INTRO_K 5 #define INSERTION_NUM 5 //sorting in ascending order template <typename T> inline size_t median_of_st_mid_en(T * data, size_t st, size_t en) { size_t mid = (st+en)/2; if(data[st] < data[en]) { if(data[mid] < data[st])//median is data[st] return st; else if(data[mid] < data[en]) //median is data[md] return mid; else //median is data[en] return en; } else // data[en] <= data[st] { if(data[mid] < data[en])//median is data[en] return en; else if(data[mid] < data[st]) //median is data[md] return mid; else //median is data[st] return st; } } //median of 3 numbers template <typename T> inline size_t median_of_3(T * data, size_t st) { T* data_ = data + st; if(data_[0] < data_[2]) { if(data_[1] < data_[0])//median is data[0] return st; else if(data_[1] < data_[2]) //median is data[1] return st + 1; else //median is data[2] return st + 2; } else // data[2] <= data[0] { if(data[1] < data[2])//median is data[2] return st + 2; else if(data[1] < data[0]) //median is data[1] return st + 1; else //median is data[0] return st; } } //median of 5 numbers with 6 comparisons template <typename T> inline size_t median_of_5(T * data, size_t st) { T* data_ = data + st; T tmp; if(data_[0] > data_[1]) { tmp = data_[0]; data_[0] = data_[1]; data_[1] = tmp; } if(data_[2] > data_[3]) { tmp = data_[2]; data_[2] = data_[3]; data_[3] = tmp; } if(data_[0] < data_[2]) { tmp = data_[4]; data_[4] = data_[0]; if(tmp < data_[1]) data_[0] = tmp; else { data_[0] = data_[1]; data_[1] = tmp; } } else { tmp = data_[4]; data_[4] = data_[2]; if(tmp < data_[3]) data_[2] = tmp; else { data_[2] = data_[3]; data_[3] = tmp; } } if(data_[0] < data_[2]) { if(data_[1] < data_[2]) return st + 1; else return st + 2; } else { if(data_[0] < data_[3]) return st; else return st + 3; } } template <typename T> size_t median_of_medians(T * data, size_t st, size_t en) { size_t l = en-st+1; size_t numof5 = l / 5; if(l % 5 != 0) numof5 ++; T tmp; size_t subst = st, suben = st + 4; size_t i, medind; //fist (numof5 - 1) groups for(i = 0; i < numof5 - 1; i++, subst += 5, suben += 5) { medind = median_of_5(data, subst); tmp = data[st+i]; data[st+i] = data[medind]; data[medind] = tmp; } //last group { switch(en-subst+1) { case 3: // 3 elements case 4: // 4 elements medind = median_of_3(data, subst); break; case 5: // 5 elements medind = median_of_5(data, subst); break; default: // 1 or 2 elements medind = subst; break; } tmp = data[st+i]; data[st+i] = data[medind]; data[medind] = tmp; } //median of medians if(numof5 > 5) return median_of_medians(data, st, st + numof5-1); else { switch(numof5) { case 3: // 3 elements case 4: // 4 elements return median_of_3(data, st); break; case 5: // 5 elements return median_of_5(data, st); break; default: // 1 or 2 elements return st; break; } } } template <typename T> void insertion_sort(T * data, size_t st, size_t en) { T tmp; size_t i, j; for(i = st+1; i <= en; i++) for(j = i; j > st && data[j-1] > data[j]; j--) { tmp = data[j-1]; data[j-1] = data[j]; data[j] = tmp; } } // Sort the given array in ascending order // Stop immediately after the array is splitted into k small numbers and n-k large numbers template <typename T> void intro_select(T * data, size_t st, size_t en, size_t k) { T pivot; T tmp; //for(; st < en && data[st] > 0; st++); size_t l_pre = en-st+1; size_t l; size_t medind; bool quickselect = true; size_t i = 0; while(1) { if(st >= en) break; if(en - st <= INSERTION_NUM) { insertion_sort(data, st, en); return; } if(quickselect && i++ == INTRO_K) { // switch to 'median of medians' if INTRO_K partations of quickselect fail to half the size l = en-st+1; if(l*2 > l_pre) quickselect = false; l_pre = l; i = 0; } if(quickselect) //medind = st; medind = median_of_st_mid_en(data, st, en); else medind = median_of_medians(data, st, en); if(medind != st) { tmp = data[st]; data[st] = data[medind]; data[medind] = tmp; } size_t p = st; size_t left = st+1; size_t right = en; pivot = data[p]; while(1) { while (left < right && pivot >= data[left]) ++left; while (left < right && pivot <= data[right]) --right; if (left >= right) break; //swap left & right tmp = data[left]; data[left] = data[right]; data[right] = tmp; } size_t s = left-1; if(data[left] < pivot) s = left; //swap p & s data[p] = data[s]; data[s] = pivot; if(s < k) st = s+1; else if(s > k) en = s-1; else //s == k break; } } #endif
18.787975
95
0.593397
MrJia1997
d23e8ce8d08e98652ed7d04b5bdfdd9855ff24b6
407
hpp
C++
include/CompareVersionNumbers.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
include/CompareVersionNumbers.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
include/CompareVersionNumbers.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#ifndef COMPARE_VERSION_NUMBERS_HPP_ #define COMPARE_VERSION_NUMBERS_HPP_ #include <string> #include <vector> using namespace std; class CompareVersionNumbers { public: int compareVersion(string version1, string version2); private: int compareDigitsString(string num1, string num2); void tokenize(const string &version, vector<string> &versions); }; #endif // COMPARE_VERSION_NUMBERS_HPP_
20.35
67
0.786241
yanzhe-chen
d23f2d248759fa2add0110a18f9f9abaa7614df5
31,150
cc
C++
src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler_unittest.cc
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
[ "BSD-3-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler_unittest.cc
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
[ "BSD-3-Clause" ]
null
null
null
src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler_unittest.cc
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
[ "BSD-3-Clause" ]
2
2020-10-25T01:13:49.000Z
2020-10-26T02:32:13.000Z
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/connectivity/bluetooth/core/bt-host/l2cap/bredr_command_handler.h" #include <lib/async/cpp/task.h> #include <memory> #include <unordered_map> #include <vector> #include "lib/gtest/test_loop_fixture.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/channel_configuration.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/fake_signaling_channel.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/l2cap_defs.h" namespace bt { namespace l2cap { namespace internal { namespace { using TestBase = ::gtest::TestLoopFixture; constexpr uint16_t kPsm = 0x0001; constexpr ChannelId kLocalCId = 0x0040; constexpr ChannelId kRemoteCId = 0x60a3; class L2CAP_BrEdrCommandHandlerTest : public TestBase { public: L2CAP_BrEdrCommandHandlerTest() = default; ~L2CAP_BrEdrCommandHandlerTest() override = default; DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(L2CAP_BrEdrCommandHandlerTest); protected: // TestLoopFixture overrides void SetUp() override { TestBase::SetUp(); signaling_channel_ = std::make_unique<testing::FakeSignalingChannel>(dispatcher()); command_handler_ = std::make_unique<BrEdrCommandHandler>( fake_sig(), fit::bind_member(this, &L2CAP_BrEdrCommandHandlerTest::OnRequestFail)); request_fail_callback_ = nullptr; failed_requests_ = 0; } void TearDown() override { request_fail_callback_ = nullptr; signaling_channel_ = nullptr; command_handler_ = nullptr; TestBase::TearDown(); } testing::FakeSignalingChannel* fake_sig() const { return signaling_channel_.get(); } BrEdrCommandHandler* cmd_handler() const { return command_handler_.get(); } size_t failed_requests() const { return failed_requests_; } void set_request_fail_callback(fit::closure request_fail_callback) { ZX_ASSERT(!request_fail_callback_); request_fail_callback_ = std::move(request_fail_callback); } private: void OnRequestFail() { failed_requests_++; if (request_fail_callback_) { request_fail_callback_(); } } std::unique_ptr<testing::FakeSignalingChannel> signaling_channel_; std::unique_ptr<BrEdrCommandHandler> command_handler_; fit::closure request_fail_callback_; size_t failed_requests_; }; TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundConnReqRej) { constexpr ChannelId kBadLocalCId = 0x0005; // Not a dynamic channel // Connection Request payload auto expected_conn_req = CreateStaticByteBuffer( // PSM LowerBits(kPsm), UpperBits(kPsm), // Source CID LowerBits(kBadLocalCId), UpperBits(kBadLocalCId)); // Command Reject payload auto rej_rsp = CreateStaticByteBuffer( // Reject Reason (invalid channel ID) LowerBits(static_cast<uint16_t>(RejectReason::kInvalidCID)), UpperBits(static_cast<uint16_t>(RejectReason::kInvalidCID)), // Local (relative to rejecter) CID LowerBits(kInvalidChannelId), UpperBits(kInvalidChannelId), // Remote (relative to rejecter) CID LowerBits(kBadLocalCId), UpperBits(kBadLocalCId)); EXPECT_OUTBOUND_REQ(*fake_sig(), kConnectionRequest, expected_conn_req.view(), {SignalingChannel::Status::kReject, rej_rsp.view()}); bool cb_called = false; auto on_conn_rsp = [&cb_called, kBadLocalCId](const BrEdrCommandHandler::ConnectionResponse& rsp) { cb_called = true; EXPECT_EQ(BrEdrCommandHandler::Status::kReject, rsp.status()); EXPECT_EQ(kInvalidChannelId, rsp.remote_cid()); EXPECT_EQ(kBadLocalCId, rsp.local_cid()); return BrEdrCommandHandler::ResponseHandlerAction::kCompleteOutboundTransaction; }; EXPECT_TRUE(cmd_handler()->SendConnectionRequest(kPsm, kBadLocalCId, std::move(on_conn_rsp))); RunLoopUntilIdle(); EXPECT_TRUE(cb_called); } TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundConnReqRejNotEnoughBytesInRejection) { constexpr ChannelId kBadLocalCId = 0x0005; // Not a dynamic channel // Connection Request payload auto expected_conn_req = CreateStaticByteBuffer( // PSM LowerBits(kPsm), UpperBits(kPsm), // Source CID LowerBits(kBadLocalCId), UpperBits(kBadLocalCId)); // Command Reject payload (the invalid channel IDs are missing) auto rej_rsp = CreateStaticByteBuffer( // Reject Reason (invalid channel ID) LowerBits(static_cast<uint16_t>(RejectReason::kInvalidCID)), UpperBits(static_cast<uint16_t>(RejectReason::kInvalidCID))); EXPECT_OUTBOUND_REQ(*fake_sig(), kConnectionRequest, expected_conn_req.view(), {SignalingChannel::Status::kReject, rej_rsp.view()}); bool cb_called = false; auto on_conn_rsp = [&cb_called](const BrEdrCommandHandler::ConnectionResponse& rsp) { cb_called = true; return BrEdrCommandHandler::ResponseHandlerAction::kCompleteOutboundTransaction; }; EXPECT_TRUE(cmd_handler()->SendConnectionRequest(kPsm, kBadLocalCId, std::move(on_conn_rsp))); RunLoopUntilIdle(); EXPECT_FALSE(cb_called); } TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundConnReqRspOk) { // Connection Request payload auto expected_conn_req = CreateStaticByteBuffer( // PSM LowerBits(kPsm), UpperBits(kPsm), // Source CID LowerBits(kLocalCId), UpperBits(kLocalCId)); // Connection Response payload auto ok_conn_rsp = CreateStaticByteBuffer( // Destination CID LowerBits(kRemoteCId), UpperBits(kRemoteCId), // Source CID LowerBits(kLocalCId), UpperBits(kLocalCId), // Result (Successful) 0x00, 0x00, // Status (No further information available) 0x00, 0x00); EXPECT_OUTBOUND_REQ(*fake_sig(), kConnectionRequest, expected_conn_req.view(), {SignalingChannel::Status::kSuccess, ok_conn_rsp.view()}); bool cb_called = false; auto on_conn_rsp = [&cb_called](const BrEdrCommandHandler::ConnectionResponse& rsp) { cb_called = true; EXPECT_EQ(BrEdrCommandHandler::Status::kSuccess, rsp.status()); EXPECT_EQ(kRemoteCId, rsp.remote_cid()); EXPECT_EQ(kLocalCId, rsp.local_cid()); EXPECT_EQ(ConnectionResult::kSuccess, rsp.result()); EXPECT_EQ(ConnectionStatus::kNoInfoAvailable, rsp.conn_status()); return SignalingChannel::ResponseHandlerAction::kCompleteOutboundTransaction; }; EXPECT_TRUE(cmd_handler()->SendConnectionRequest(kPsm, kLocalCId, std::move(on_conn_rsp))); RunLoopUntilIdle(); EXPECT_TRUE(cb_called); } TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundConnReqRspPendingAuthThenOk) { // Connection Request payload auto expected_conn_req = CreateStaticByteBuffer( // PSM LowerBits(kPsm), UpperBits(kPsm), // Source CID LowerBits(kLocalCId), UpperBits(kLocalCId)); // Connection Response payload auto pend_conn_rsp = CreateStaticByteBuffer( // Destination CID LowerBits(kRemoteCId), UpperBits(kRemoteCId), // Source CID LowerBits(kLocalCId), UpperBits(kLocalCId), // Result (Pending) 0x01, 0x00, // Status (Authorization pending) 0x02, 0x00); auto ok_conn_rsp = CreateStaticByteBuffer( // Destination CID LowerBits(kRemoteCId), UpperBits(kRemoteCId), // Source CID LowerBits(kLocalCId), UpperBits(kLocalCId), // Result (Successful) 0x00, 0x00, // Status (No further information available) 0x00, 0x00); EXPECT_OUTBOUND_REQ(*fake_sig(), kConnectionRequest, expected_conn_req.view(), {SignalingChannel::Status::kSuccess, pend_conn_rsp.view()}, {SignalingChannel::Status::kSuccess, ok_conn_rsp.view()}); int cb_count = 0; auto on_conn_rsp = [&cb_count](const BrEdrCommandHandler::ConnectionResponse& rsp) { cb_count++; EXPECT_EQ(kRemoteCId, rsp.remote_cid()); EXPECT_EQ(kLocalCId, rsp.local_cid()); if (cb_count == 1) { EXPECT_EQ(BrEdrCommandHandler::Status::kSuccess, rsp.status()); EXPECT_EQ(ConnectionResult::kPending, rsp.result()); EXPECT_EQ(ConnectionStatus::kAuthorizationPending, rsp.conn_status()); return SignalingChannel::ResponseHandlerAction::kExpectAdditionalResponse; } else if (cb_count == 2) { EXPECT_EQ(BrEdrCommandHandler::Status::kSuccess, rsp.status()); EXPECT_EQ(ConnectionResult::kSuccess, rsp.result()); EXPECT_EQ(ConnectionStatus::kNoInfoAvailable, rsp.conn_status()); } return SignalingChannel::ResponseHandlerAction::kCompleteOutboundTransaction; }; EXPECT_TRUE(cmd_handler()->SendConnectionRequest(kPsm, kLocalCId, std::move(on_conn_rsp))); RunLoopUntilIdle(); EXPECT_EQ(2, cb_count); } TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundConnReqRspTimeOut) { // Connection Request payload auto expected_conn_req = CreateStaticByteBuffer( // PSM LowerBits(kPsm), UpperBits(kPsm), // Source CID LowerBits(kLocalCId), UpperBits(kLocalCId)); EXPECT_OUTBOUND_REQ(*fake_sig(), kConnectionRequest, expected_conn_req.view(), {SignalingChannel::Status::kTimeOut, {}}); ASSERT_EQ(0u, failed_requests()); auto on_conn_rsp = [](auto&) { ADD_FAILURE(); return SignalingChannel::ResponseHandlerAction::kCompleteOutboundTransaction; }; EXPECT_TRUE(cmd_handler()->SendConnectionRequest(kPsm, kLocalCId, std::move(on_conn_rsp))); RETURN_IF_FATAL(RunLoopUntilIdle()); EXPECT_EQ(1u, failed_requests()); } TEST_F(L2CAP_BrEdrCommandHandlerTest, InboundInfoReqRspNotSupported) { BrEdrCommandHandler::InformationRequestCallback cb = [](InformationType type, auto responder) { EXPECT_EQ(InformationType::kConnectionlessMTU, type); responder->SendNotSupported(); }; cmd_handler()->ServeInformationRequest(std::move(cb)); // Information Request payload auto info_req = CreateStaticByteBuffer( // Type = Connectionless MTU 0x01, 0x00); // Information Response payload auto expected_rsp = CreateStaticByteBuffer( // Type = Connectionless MTU 0x01, 0x00, // Result = Not supported 0x01, 0x00); RETURN_IF_FATAL(fake_sig()->ReceiveExpect(kInformationRequest, info_req, expected_rsp)); } TEST_F(L2CAP_BrEdrCommandHandlerTest, InboundInfoReqRspConnlessMtu) { BrEdrCommandHandler::InformationRequestCallback cb = [](InformationType type, auto responder) { EXPECT_EQ(InformationType::kConnectionlessMTU, type); responder->SendConnectionlessMtu(0x02dc); }; cmd_handler()->ServeInformationRequest(std::move(cb)); // Information Request payload auto info_req = CreateStaticByteBuffer( // Type = Connectionless MTU 0x01, 0x00); // Information Response payload auto expected_rsp = CreateStaticByteBuffer( // Type = Connectionless MTU 0x01, 0x00, // Result = Success 0x00, 0x00, // Data (MTU) 0xdc, 0x02); RETURN_IF_FATAL(fake_sig()->ReceiveExpect(kInformationRequest, info_req, expected_rsp)); } TEST_F(L2CAP_BrEdrCommandHandlerTest, InboundInfoReqRspExtendedFeatures) { BrEdrCommandHandler::InformationRequestCallback cb = [](InformationType type, auto responder) { EXPECT_EQ(InformationType::kExtendedFeaturesSupported, type); responder->SendExtendedFeaturesSupported(0xfaceb00c); }; cmd_handler()->ServeInformationRequest(std::move(cb)); // Information Request payload auto info_req = CreateStaticByteBuffer( // Type = Features Mask 0x02, 0x00); // Information Response payload auto expected_rsp = CreateStaticByteBuffer( // Type = Features Mask 0x02, 0x00, // Result = Success 0x00, 0x00, // Data (Mask) 0x0c, 0xb0, 0xce, 0xfa); RETURN_IF_FATAL(fake_sig()->ReceiveExpect(kInformationRequest, info_req, expected_rsp)); } TEST_F(L2CAP_BrEdrCommandHandlerTest, InboundInfoReqRspFixedChannels) { BrEdrCommandHandler::InformationRequestCallback cb = [](InformationType type, auto responder) { EXPECT_EQ(InformationType::kFixedChannelsSupported, type); responder->SendFixedChannelsSupported(0xcafef00d4badc0deUL); }; cmd_handler()->ServeInformationRequest(std::move(cb)); // Information Request payload auto info_req = CreateStaticByteBuffer( // Type = Fixed Channels 0x03, 0x00); // Configuration Response payload auto expected_rsp = CreateStaticByteBuffer( // Type = Fixed Channels 0x03, 0x00, // Result = Success 0x00, 0x00, // Data (Mask) 0xde, 0xc0, 0xad, 0x4b, 0x0d, 0xf0, 0xfe, 0xca); RETURN_IF_FATAL(fake_sig()->ReceiveExpect(kInformationRequest, info_req, expected_rsp)); } TEST_F(L2CAP_BrEdrCommandHandlerTest, InboundConfigReqEmptyRspOkEmpty) { BrEdrCommandHandler::ConfigurationRequestCallback cb = [](ChannelId local_cid, uint16_t flags, ChannelConfiguration config, auto responder) { EXPECT_EQ(kLocalCId, local_cid); EXPECT_EQ(0x6006, flags); EXPECT_FALSE(config.mtu_option().has_value()); EXPECT_FALSE(config.retransmission_flow_control_option().has_value()); EXPECT_EQ(0u, config.unknown_options().size()); responder->Send(kRemoteCId, 0x0001, ConfigurationResult::kPending, ChannelConfiguration::ConfigurationOptions()); }; cmd_handler()->ServeConfigurationRequest(std::move(cb)); // Configuration Request payload auto config_req = CreateStaticByteBuffer( // Destination Channel ID LowerBits(kLocalCId), UpperBits(kLocalCId), // Flags 0x06, 0x60); // Configuration Response payload auto expected_rsp = CreateStaticByteBuffer( // Destination Channel ID LowerBits(kRemoteCId), UpperBits(kRemoteCId), // Flags 0x01, 0x00, // Result = Pending 0x04, 0x00); RETURN_IF_FATAL(fake_sig()->ReceiveExpect(kConfigurationRequest, config_req, expected_rsp)); } TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundConfigReqRspPendingEmpty) { // Configuration Request payload auto expected_config_req = CreateStaticByteBuffer( // Destination CID LowerBits(kRemoteCId), UpperBits(kRemoteCId), // Flags (non-zero to test encoding) 0x01, 0x00, // Data (Config Options) 0x01, // Type = MTU 0x02, // Length = 2 0x30, 0x00 // MTU = 48 ); // Configuration Response payload auto pending_config_req = CreateStaticByteBuffer( // Source CID LowerBits(kLocalCId), UpperBits(kLocalCId), // Flags (non-zero to test encoding) 0x04, 0x00, // Result = Pending 0x04, 0x00, // Data (Config Options) 0x01, // Type = MTU 0x02, // Length = 2 0x60, 0x00 // MTU = 96 ); EXPECT_OUTBOUND_REQ(*fake_sig(), kConfigurationRequest, expected_config_req.view(), {SignalingChannel::Status::kSuccess, pending_config_req.view()}); bool cb_called = false; BrEdrCommandHandler::ConfigurationResponseCallback on_config_rsp = [&cb_called](const BrEdrCommandHandler::ConfigurationResponse& rsp) { cb_called = true; EXPECT_EQ(SignalingChannel::Status::kSuccess, rsp.status()); EXPECT_EQ(kLocalCId, rsp.local_cid()); EXPECT_EQ(0x0004, rsp.flags()); EXPECT_EQ(ConfigurationResult::kPending, rsp.result()); EXPECT_TRUE(rsp.config().mtu_option().has_value()); EXPECT_EQ(96u, rsp.config().mtu_option()->mtu()); return SignalingChannel::ResponseHandlerAction::kCompleteOutboundTransaction; }; ChannelConfiguration config; config.set_mtu_option(ChannelConfiguration::MtuOption(48)); EXPECT_TRUE(cmd_handler()->SendConfigurationRequest(kRemoteCId, 0x0001, config.Options(), std::move(on_config_rsp))); RunLoopUntilIdle(); EXPECT_TRUE(cb_called); } TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundConfigReqRspTimeOut) { // Configuration Request payload auto expected_config_req = CreateStaticByteBuffer( // Destination CID LowerBits(kRemoteCId), UpperBits(kRemoteCId), // Flags (non-zero to test encoding) 0x01, 0xf0, // Data (Config Options) 0x01, // Type = MTU 0x02, // Length = 2 0x30, 0x00 // MTU = 48 ); // Disconnect Request payload auto expected_discon_req = CreateStaticByteBuffer( // Destination CID LowerBits(kRemoteCId), UpperBits(kRemoteCId), // Source CID LowerBits(kLocalCId), UpperBits(kLocalCId)); EXPECT_OUTBOUND_REQ(*fake_sig(), kConfigurationRequest, expected_config_req.view(), {SignalingChannel::Status::kTimeOut, {}}); EXPECT_OUTBOUND_REQ(*fake_sig(), kDisconnectionRequest, expected_discon_req.view()); set_request_fail_callback([this]() { // Should still be allowed to send requests even after one failed auto on_discon_rsp = [](auto&) {}; EXPECT_TRUE( cmd_handler()->SendDisconnectionRequest(kRemoteCId, kLocalCId, std::move(on_discon_rsp))); }); ASSERT_EQ(0u, failed_requests()); auto on_config_rsp = [](auto&) { ADD_FAILURE(); return SignalingChannel::ResponseHandlerAction::kCompleteOutboundTransaction; }; ChannelConfiguration config; config.set_mtu_option(ChannelConfiguration::MtuOption(48)); EXPECT_TRUE(cmd_handler()->SendConfigurationRequest(kRemoteCId, 0xf001, config.Options(), std::move(on_config_rsp))); RETURN_IF_FATAL(RunLoopUntilIdle()); EXPECT_EQ(1u, failed_requests()); } TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundInfoReqRspOk) { // Information Request payload auto expected_info_req = CreateStaticByteBuffer( // Information Type LowerBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported)), UpperBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported))); // Information Response payload auto ok_info_rsp = CreateStaticByteBuffer( // Information Type LowerBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported)), UpperBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported)), // Information Result LowerBits(static_cast<uint16_t>(InformationResult::kSuccess)), UpperBits(static_cast<uint16_t>(InformationResult::kSuccess)), // Data (extended features mask, 4 bytes) LowerBits(kExtendedFeaturesBitFixedChannels), 0, 0, 0); EXPECT_OUTBOUND_REQ(*fake_sig(), kInformationRequest, expected_info_req.view(), {SignalingChannel::Status::kSuccess, ok_info_rsp.view()}); bool cb_called = false; BrEdrCommandHandler::InformationResponseCallback on_info_cb = [&cb_called](const BrEdrCommandHandler::InformationResponse& rsp) { cb_called = true; EXPECT_EQ(SignalingChannel::Status::kSuccess, rsp.status()); EXPECT_EQ(InformationResult::kSuccess, rsp.result()); EXPECT_EQ(InformationType::kExtendedFeaturesSupported, rsp.type()); EXPECT_EQ(kExtendedFeaturesBitFixedChannels, rsp.extended_features()); }; EXPECT_TRUE(cmd_handler()->SendInformationRequest(InformationType::kExtendedFeaturesSupported, std::move(on_info_cb))); RunLoopUntilIdle(); EXPECT_TRUE(cb_called); } TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundInfoReqRspNotSupported) { // Information Request payload auto expected_info_req = CreateStaticByteBuffer( // Information Type LowerBits(static_cast<uint16_t>(InformationType::kConnectionlessMTU)), UpperBits(static_cast<uint16_t>(InformationType::kConnectionlessMTU))); // Information Response payload auto error_info_rsp = CreateStaticByteBuffer( // Information Type LowerBits(static_cast<uint16_t>(InformationType::kConnectionlessMTU)), UpperBits(static_cast<uint16_t>(InformationType::kConnectionlessMTU)), // Information Result LowerBits(static_cast<uint16_t>(InformationResult::kNotSupported)), UpperBits(static_cast<uint16_t>(InformationResult::kNotSupported))); EXPECT_OUTBOUND_REQ(*fake_sig(), kInformationRequest, expected_info_req.view(), {SignalingChannel::Status::kSuccess, error_info_rsp.view()}); bool cb_called = false; BrEdrCommandHandler::InformationResponseCallback on_info_cb = [&cb_called](const BrEdrCommandHandler::InformationResponse& rsp) { cb_called = true; EXPECT_EQ(SignalingChannel::Status::kSuccess, rsp.status()); EXPECT_EQ(InformationResult::kNotSupported, rsp.result()); EXPECT_EQ(InformationType::kConnectionlessMTU, rsp.type()); }; EXPECT_TRUE(cmd_handler()->SendInformationRequest(InformationType::kConnectionlessMTU, std::move(on_info_cb))); RunLoopUntilIdle(); EXPECT_TRUE(cb_called); } TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundInfoReqRspHeaderNotEnoughBytes) { // Information Request payload auto expected_info_req = CreateStaticByteBuffer( // Information Type LowerBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported)), UpperBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported))); // Information Response payload auto malformed_info_rsp = CreateStaticByteBuffer( // 1 of 4 bytes expected of an Information Response just to be able to parse it. LowerBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported))); EXPECT_OUTBOUND_REQ(*fake_sig(), kInformationRequest, expected_info_req.view(), {SignalingChannel::Status::kSuccess, malformed_info_rsp.view()}); bool cb_called = false; BrEdrCommandHandler::InformationResponseCallback on_info_cb = [&cb_called](const BrEdrCommandHandler::InformationResponse& rsp) { cb_called = true; }; EXPECT_TRUE(cmd_handler()->SendInformationRequest(InformationType::kExtendedFeaturesSupported, std::move(on_info_cb))); RunLoopUntilIdle(); EXPECT_FALSE(cb_called); } TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundInfoReqRspPayloadNotEnoughBytes) { // Information Request payload auto expected_info_req = CreateStaticByteBuffer( // Information Type LowerBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported)), UpperBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported))); // Information Response payload auto malformed_info_rsp = CreateStaticByteBuffer( // Information Type LowerBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported)), UpperBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported)), // Information Result LowerBits(static_cast<uint16_t>(InformationResult::kSuccess)), UpperBits(static_cast<uint16_t>(InformationResult::kSuccess)), // Data (2 of 4 bytes expected of an extended features mask) 0, 0); EXPECT_OUTBOUND_REQ(*fake_sig(), kInformationRequest, expected_info_req.view(), {SignalingChannel::Status::kSuccess, malformed_info_rsp.view()}); bool cb_called = false; BrEdrCommandHandler::InformationResponseCallback on_info_cb = [&cb_called](const BrEdrCommandHandler::InformationResponse& rsp) { cb_called = true; }; EXPECT_TRUE(cmd_handler()->SendInformationRequest(InformationType::kExtendedFeaturesSupported, std::move(on_info_cb))); RunLoopUntilIdle(); EXPECT_FALSE(cb_called); } // Accept and pass a valid Information Response even if it doesn't have the type // requested. TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundInfoReqRspWrongType) { // Information Request payload auto expected_info_req = CreateStaticByteBuffer( // Information Type LowerBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported)), UpperBits(static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported))); // Information Response payload auto mismatch_info_rsp = CreateStaticByteBuffer( // Information Type LowerBits(static_cast<uint16_t>(InformationType::kConnectionlessMTU)), UpperBits(static_cast<uint16_t>(InformationType::kConnectionlessMTU)), // Information Result LowerBits(static_cast<uint16_t>(InformationResult::kSuccess)), UpperBits(static_cast<uint16_t>(InformationResult::kSuccess)), // Data (connectionless broadcast MTU, 2 bytes) 0x40, 0); EXPECT_OUTBOUND_REQ(*fake_sig(), kInformationRequest, expected_info_req.view(), {SignalingChannel::Status::kSuccess, mismatch_info_rsp.view()}); bool cb_called = false; BrEdrCommandHandler::InformationResponseCallback on_info_cb = [&cb_called](const BrEdrCommandHandler::InformationResponse& rsp) { cb_called = true; EXPECT_EQ(SignalingChannel::Status::kSuccess, rsp.status()); EXPECT_EQ(InformationResult::kSuccess, rsp.result()); EXPECT_EQ(InformationType::kConnectionlessMTU, rsp.type()); EXPECT_EQ(0x40, rsp.connectionless_mtu()); }; EXPECT_TRUE(cmd_handler()->SendInformationRequest(InformationType::kExtendedFeaturesSupported, std::move(on_info_cb))); RunLoopUntilIdle(); EXPECT_TRUE(cb_called); } // Allow types of information besides those known to BrEdrCommandHandler. TEST_F(L2CAP_BrEdrCommandHandlerTest, OutboundInfoReqUnknownType) { // Information Request payload auto expected_info_req = CreateStaticByteBuffer( // Information Type 0x04, 0); // Information Response payload auto ok_info_rsp = CreateStaticByteBuffer( // Information Type 0x04, 0, // Information Result LowerBits(static_cast<uint16_t>(InformationResult::kSuccess)), UpperBits(static_cast<uint16_t>(InformationResult::kSuccess)), // Data (some payload) 't', 'e', 's', 't'); EXPECT_OUTBOUND_REQ(*fake_sig(), kInformationRequest, expected_info_req.view(), {SignalingChannel::Status::kSuccess, ok_info_rsp.view()}); bool cb_called = false; BrEdrCommandHandler::InformationResponseCallback on_info_cb = [&cb_called](const BrEdrCommandHandler::InformationResponse& rsp) { cb_called = true; EXPECT_EQ(SignalingChannel::Status::kSuccess, rsp.status()); EXPECT_EQ(InformationResult::kSuccess, rsp.result()); EXPECT_EQ(static_cast<InformationType>(0x04), rsp.type()); }; EXPECT_TRUE(cmd_handler()->SendInformationRequest(static_cast<InformationType>(0x04), std::move(on_info_cb))); RunLoopUntilIdle(); EXPECT_TRUE(cb_called); } TEST_F(L2CAP_BrEdrCommandHandlerTest, InboundConnReqRspPending) { BrEdrCommandHandler::ConnectionRequestCallback cb = [](PSM psm, ChannelId remote_cid, auto responder) { EXPECT_EQ(kPsm, psm); EXPECT_EQ(kRemoteCId, remote_cid); responder->Send(kLocalCId, ConnectionResult::kPending, ConnectionStatus::kAuthorizationPending); }; cmd_handler()->ServeConnectionRequest(std::move(cb)); // Connection Request payload auto conn_req = CreateStaticByteBuffer( // PSM LowerBits(kPsm), UpperBits(kPsm), // Source CID (relative to requester) LowerBits(kRemoteCId), UpperBits(kRemoteCId)); // Connection Response payload auto conn_rsp = CreateStaticByteBuffer( // Destination CID (relative to requester) LowerBits(kLocalCId), UpperBits(kLocalCId), // Source CID (relative to requester) LowerBits(kRemoteCId), UpperBits(kRemoteCId), // Connection Result LowerBits(static_cast<uint16_t>(ConnectionResult::kPending)), UpperBits(static_cast<uint16_t>(ConnectionResult::kPending)), // Connection Status LowerBits(static_cast<uint16_t>(ConnectionStatus::kAuthorizationPending)), UpperBits(static_cast<uint16_t>(ConnectionStatus::kAuthorizationPending))); RETURN_IF_FATAL(fake_sig()->ReceiveExpect(kConnectionRequest, conn_req, conn_rsp)); } TEST_F(L2CAP_BrEdrCommandHandlerTest, InboundConnReqBadPsm) { constexpr uint16_t kBadPsm = 0x0002; // Request callback shouldn't even be called for an invalid PSM. bool req_cb_called = false; BrEdrCommandHandler::ConnectionRequestCallback cb = [&req_cb_called](PSM psm, ChannelId remote_cid, auto responder) { req_cb_called = true; }; cmd_handler()->ServeConnectionRequest(std::move(cb)); // Connection Request payload auto conn_req = CreateStaticByteBuffer( // PSM LowerBits(kBadPsm), UpperBits(kBadPsm), // Source CID (relative to requester) LowerBits(kRemoteCId), UpperBits(kRemoteCId)); // Connection Response payload auto conn_rsp = CreateStaticByteBuffer( // Destination CID (relative to requester) LowerBits(kInvalidChannelId), UpperBits(kInvalidChannelId), // Source CID (relative to requester) LowerBits(kRemoteCId), UpperBits(kRemoteCId), // Connection Result LowerBits(static_cast<uint16_t>(ConnectionResult::kPSMNotSupported)), UpperBits(static_cast<uint16_t>(ConnectionResult::kPSMNotSupported)), // Connection Status LowerBits(static_cast<uint16_t>(ConnectionStatus::kNoInfoAvailable)), UpperBits(static_cast<uint16_t>(ConnectionStatus::kNoInfoAvailable))); RETURN_IF_FATAL(fake_sig()->ReceiveExpect(kConnectionRequest, conn_req, conn_rsp)); EXPECT_FALSE(req_cb_called); } TEST_F(L2CAP_BrEdrCommandHandlerTest, InboundConnReqNonDynamicSrcCId) { // Request callback shouldn't even be called for an invalid Source Channel ID. bool req_cb_called = false; BrEdrCommandHandler::ConnectionRequestCallback cb = [&req_cb_called](PSM psm, ChannelId remote_cid, auto responder) { req_cb_called = true; }; cmd_handler()->ServeConnectionRequest(std::move(cb)); // Connection Request payload auto conn_req = CreateStaticByteBuffer( // PSM LowerBits(kPsm), UpperBits(kPsm), // Source CID: fixed channel for Security Manager (relative to requester) LowerBits(kSMPChannelId), UpperBits(kSMPChannelId)); // Connection Response payload auto conn_rsp = CreateStaticByteBuffer( // Destination CID (relative to requester) LowerBits(kInvalidChannelId), UpperBits(kInvalidChannelId), // Source CID (relative to requester) LowerBits(kSMPChannelId), UpperBits(kSMPChannelId), // Connection Result LowerBits(static_cast<uint16_t>(ConnectionResult::kInvalidSourceCID)), UpperBits(static_cast<uint16_t>(ConnectionResult::kInvalidSourceCID)), // Connection Status LowerBits(static_cast<uint16_t>(ConnectionStatus::kNoInfoAvailable)), UpperBits(static_cast<uint16_t>(ConnectionStatus::kNoInfoAvailable))); RETURN_IF_FATAL(fake_sig()->ReceiveExpect(kConnectionRequest, conn_req, conn_rsp)); EXPECT_FALSE(req_cb_called); } } // namespace } // namespace internal } // namespace l2cap } // namespace bt
37.127533
100
0.71923
EnderNightLord-ChromeBook
d240095031c8d3e133801299163fc595b6244045
1,090
cpp
C++
tests/char_set/test_single.cpp
FrancoisChabot/abulafia
4aeefd8d388d68994f9d73bb0f586517737a5174
[ "BSL-1.0" ]
42
2017-09-21T16:51:12.000Z
2020-03-12T09:44:32.000Z
tests/char_set/test_single.cpp
FrancoisChabot/abulafia
4aeefd8d388d68994f9d73bb0f586517737a5174
[ "BSL-1.0" ]
32
2017-09-21T06:31:08.000Z
2017-10-20T00:52:58.000Z
tests/char_set/test_single.cpp
FrancoisChabot/abulafia
4aeefd8d388d68994f9d73bb0f586517737a5174
[ "BSL-1.0" ]
3
2018-10-30T11:29:18.000Z
2019-07-18T08:19:51.000Z
// Copyright 2017 Francois Chabot // (francois.chabot.dev@gmail.com) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "abulafia/abulafia.h" #include "gtest/gtest.h" using namespace abu; static_assert(char_set::is_char_set<char>::value == false); static_assert(char_set::is_char_set<char_set::Single<char>>::value == true); static_assert( char_set::is_char_set<decltype(char_set::to_char_set('a'))>::value == true); TEST(test_single, simple_test) { auto c_set = char_set::single('a'); static_assert(char_set::is_char_set<decltype(c_set)>::value, "must be a valid char set"); using char_set_type = decltype(c_set); static_assert(is_same<char_set_type::char_t, char>::value, "type inference failure"); EXPECT_TRUE(c_set.is_valid('a')); EXPECT_FALSE(c_set.is_valid('b')); EXPECT_FALSE(c_set.is_valid('g')); EXPECT_FALSE(c_set.is_valid('A')); EXPECT_FALSE(c_set.is_valid(' ')); EXPECT_FALSE(c_set.is_valid('\0')); }
31.142857
80
0.704587
FrancoisChabot
d240ed2bde9c335bdd5f4a52c127bd3a9fa677eb
4,246
hpp
C++
include/shz/math/frustum.hpp
TraxNet/ShadingZenCpp
46860da3249900259941bf64f4a46347500b65fb
[ "MIT" ]
3
2015-04-30T15:41:51.000Z
2018-12-28T05:47:18.000Z
include/shz/math/frustum.hpp
TraxNet/ShadingZenCpp
46860da3249900259941bf64f4a46347500b65fb
[ "MIT" ]
null
null
null
include/shz/math/frustum.hpp
TraxNet/ShadingZenCpp
46860da3249900259941bf64f4a46347500b65fb
[ "MIT" ]
null
null
null
#ifndef __SHZ_MATH_FRUSTUM__ #define __SHZ_MATH_FRUSTUM__ #include <array> #include <shz/math/matrix.hpp> #include <shz/math/plane.hpp> namespace shz{ namespace math{ template <typename T> struct frustum { static const size_t num_planes = 6; frustum(){} frustum(const shz::math::matrix<T, 4, 4>& clip){ generate_planes_from_projection(clip); } bool is_point_inside(T x, T y, T z){ for(size_t i=0; i < num_planes; ++i){ if(planes[i].is_point_behind(x, y, z)) return false; } } bool is_point_inside(const vector<T, 3>& p){ for(size_t i=0; i < num_planes; ++i){ if(planes[i].is_point_behind(p)) return false; } } bool is_point_inside(const vector<T, 4>& p){ for(size_t i=0; i < num_planes; ++i){ if(planes[i].is_point_behind(p)) return false; } } bool is_sphere_inside(T x, T y, T z, T radius) { for(size_t i=0; i < num_planes; ++i){ if(planes[i].is_sphere_behind(x, y, z, radius)) return false; } return true; } /* public boolean is_bbox_inside(BBox bbox) { for(int index=0; index < 6; index++){ Plane plane = planes[index]; Vector3 mins = bbox.getMins(); Vector3 maxs = bbox.getMaxs(); T x, y, z; x = mins.x; y = mins.y; z = mins.z; if(!plane.isPointBehind(x, y, z)) continue; x = maxs.x; y = mins.y; z = mins.z; if(!plane.isPointBehind(x, y, z)) continue; x = mins.x; y = maxs.y; z = mins.z; if(!plane.isPointBehind(x, y, z)) continue; x = maxs.x; y = maxs.y; z = mins.z; if(!plane.isPointBehind(x, y, z)) continue; x = mins.x; y = mins.y; z = maxs.z; if(!plane.isPointBehind(x, y, z)) continue; x = maxs.x; y = mins.y; z = maxs.z; if(!plane.isPointBehind(x, y, z)) continue; x = mins.x; y = maxs.y; z = maxs.z; if(!plane.isPointBehind(x, y, z)) continue; x = maxs.x; y = maxs.y; z = maxs.z; if(!plane.isPointBehind(x, y, z)) continue; return false; } return true; }*/ enum plane_names{ REAR = 0, FRONT, RIGHT, LEFT, TOP, BOTTOM }; void generate_planes_from_projection(const matrix<T, 4, 4>& clip){ shz::math::plane<T>* plane = &planes[plane_names::RIGHT]; plane->eq[0] = clip[3] - clip[0]; plane->eq[1] = clip[7] - clip[4]; plane->eq[2] = clip[11] - clip[8]; plane->eq[3] = clip[15] - clip[12]; T t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; plane = &planes[plane_names::LEFT]; plane->eq[0] = clip[3] + clip[0]; plane->eq[1] = clip[7] + clip[4]; plane->eq[2] = clip[11] + clip[8]; plane->eq[3] = clip[15] + clip[12]; t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; plane = &planes[plane_names::BOTTOM]; plane->eq[0] = clip[3] + clip[1]; plane->eq[1] = clip[7] + clip[5]; plane->eq[2] = clip[11] + clip[9]; plane->eq[3] = clip[15] + clip[13]; t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; plane = &planes[plane_names::TOP]; plane->eq[0] = clip[3] - clip[1]; plane->eq[1] = clip[7] - clip[5]; plane->eq[2] = clip[11] - clip[9]; plane->eq[3] = clip[15] - clip[13]; t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; plane = &planes[plane_names::FRONT]; plane->eq[0] = clip[3] - clip[2]; plane->eq[1] = clip[7] - clip[6]; plane->eq[2] = clip[11] - clip[10]; plane->eq[3] = clip[15] - clip[14]; t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; plane = &planes[plane_names::REAR]; plane->eq[0] = clip[3] + clip[2]; plane->eq[1] = clip[7] + clip[6]; plane->eq[2] = clip[11] + clip[10]; plane->eq[3] = clip[15] + clip[14]; t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; } std::array<shz::math::plane<T>, num_planes> planes; }; } } #endif // __SHZ_MATH_FRUSTUM__
20.512077
68
0.537447
TraxNet
d240f6b09f2be76740fce5c84508a4a01ed2a6e3
664
hpp
C++
higan/sfc/coprocessor/coprocessor.hpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
null
null
null
higan/sfc/coprocessor/coprocessor.hpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
null
null
null
higan/sfc/coprocessor/coprocessor.hpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
null
null
null
#include <sfc/coprocessor/icd2/icd2.hpp> #include <sfc/coprocessor/mcc/mcc.hpp> #include <sfc/coprocessor/nss/nss.hpp> #include <sfc/coprocessor/event/event.hpp> #include <sfc/coprocessor/sa1/sa1.hpp> #include <sfc/coprocessor/superfx/superfx.hpp> #include <sfc/coprocessor/armdsp/armdsp.hpp> #include <sfc/coprocessor/hitachidsp/hitachidsp.hpp> #include <sfc/coprocessor/necdsp/necdsp.hpp> #include <sfc/coprocessor/epsonrtc/epsonrtc.hpp> #include <sfc/coprocessor/sharprtc/sharprtc.hpp> #include <sfc/coprocessor/spc7110/spc7110.hpp> #include <sfc/coprocessor/sdd1/sdd1.hpp> #include <sfc/coprocessor/obc1/obc1.hpp> #include <sfc/coprocessor/msu1/msu1.hpp>
31.619048
52
0.789157
mp-lee
d243a9b2d12fb0c76112ad0168a366771c23cfbe
37,072
cpp
C++
applis/OLD-MICMAC-OLD/SaisieLiaisons.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
451
2016-11-25T09:40:28.000Z
2022-03-30T04:20:42.000Z
applis/OLD-MICMAC-OLD/SaisieLiaisons.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
143
2016-11-25T20:35:57.000Z
2022-03-01T11:58:02.000Z
applis/OLD-MICMAC-OLD/SaisieLiaisons.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
139
2016-12-02T10:26:21.000Z
2022-03-10T19:40:29.000Z
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ /* bouton 2 : geometrie (translation/homotetie) bouton 3 : menu contextuel o recal : clik (b1/b3) sur rouge puis bleu pour fixer valeur du decalage global; */ #include "general/all.h" #include "private/all.h" #if (ELISE_X11) #include "im_tpl/image.h" #include "MICMAC.h" using namespace NS_ParamMICMAC; Pt2di SzImIncr(300,300); class Incruster : public ElImIncruster { public : static const INT BrdMax = 100; static const INT DecMax = 40; static const INT StdBrd = 10; INT SzBrd() const { return ElMin(BrdMax,round_ni(StdBrd*mScale)); } Incruster ( Pt2di SzIm, Visu_ElImScr & Visu, const vector<ElImScroller*> & Scrols ) : ElImIncruster(SzIm,Pt2di(BrdMax+DecMax,BrdMax+DecMax),Visu,Scrols,3), mDec12 (0,0) { } void SetDec12(Pt2di aDec) { mDec12 = Inf(Pt2di(DecMax,DecMax),Sup(-Pt2di(DecMax,DecMax),aDec)); } Pt2di CurDec() const {return mDec12;} INT Filters ( ElSTDNS vector<ElImIncr_ScrAttr> & Attrs, ElSTDNS vector<Im2D_INT4> & ImsOut, ElSTDNS vector<Im2D_INT4> & ImsIn, Pt2di p0,Pt2di p1 ); bool PixelIndep() const { return false; } void SetScale(REAL aScale) { mScale = aScale; } private : Filtr_Incr_EqDyn_Glob mFIEG; Filtr_Incr_EqDyn_Loc mFIEL; REAL mScale; Pt2di mDec12; }; Fonc_Num AUC(Fonc_Num f) { return Max(0,Min(255,f)); } INT Incruster::Filters ( ElSTDNS vector<ElImIncr_ScrAttr> & Attrs, ElSTDNS vector<Im2D_INT4> & ImsOut, ElSTDNS vector<Im2D_INT4> & ImsIn, Pt2di p0,Pt2di p1 ) { INT fact = 2; mFIEG.Filters(Attrs,ImsOut,ImsIn,p0,p1); // mFIEL.Filters(Attrs,ImsOut,ImsIn,p0,p1,SzBrd()); Symb_FNum f1 = ImsOut[0].in(0); Symb_FNum f2 = trans(ImsOut[1].in(0),mDec12); Symb_FNum dif = fact * (f1-f2); ELISE_COPY ( rectangle(p0,p1), Virgule(AUC(f1+dif), (f1+f2)/2,AUC(f2-dif)), Virgule(ImsOut[2].out() , ImsOut[3].out() , ImsOut[4].out()) ); ELISE_COPY ( rectangle(p0,p1), Virgule(ImsOut[2].in() , ImsOut[3].in() , ImsOut[4].in()), Virgule(ImsOut[0].out() , ImsOut[1].out() , ImsOut[2].out()) ); return 3; } /***************************************************/ /***************************************************/ /*** ***/ /*** TestScroller ***/ /*** ***/ /***************************************************/ /***************************************************/ class MyBisCr : public BiScroller { public : MyBisCr ( const cAppliMICMAC & anAppli, VideoWin_Visu_ElImScr &aVisu, const std::string & Name1, const std::string & NameShrt1, cElHomographie aH1, const std::string & Name2, const std::string & NameShrt2, const std::string & NameI2GeomInit, cElHomographie aH2 ) : BiScroller ( aVisu, ElImScroller::StdPyramide(aVisu,Name1), ElImScroller::StdPyramide(aVisu,Name2,0,true,true), FusRG1B2, 0,0,"" ), mAppli (anAppli), mNameXML ( anAppli.FullDirGeom() + anAppli.PDV1()->NamePackHom(anAppli.PDV2()) /* + StdPrefixGen(NameShrt1) + std::string("_") + StdPrefixGen(NameShrt2) + "_Liaison.xml" */ ), mName1 (NameShrt1), mName2 (NameShrt2), mNameFull1 (Name1), mNameFull2 (Name2), // mNameFull1 (Name1), // mNameFull2 (Name2), mNameI2GeomInit (anAppli.WorkDir()+NameI2GeomInit), mH1 (aH1), mH2 (aH2), mH1_Inv (aH1.Inverse()), mH2_Inv (aH2.Inverse()) { std::cout << "mNameXML " << mNameXML << "\n"; if (ELISE_fp::exist_file(mNameXML)) { // cElXMLTree aTree (mNameXML); // mLiaisons = aTree.GetPackHomologues("ListeCpleHom"); mLiaisons = ElPackHomologue::FromFile(mNameXML); mLiaisons.ApplyHomographies(mH1_Inv,mH2_Inv); } } void ShowLiaison(); void ShowLiaison(ElCplePtsHomologues &); void LoadXImage(Pt2di p0W,Pt2di p1W,bool quick) { BiScroller::LoadXImage(p0W,p1W,quick); ShowLiaison(); } void write_liaison() ; void SauvGrille(); ElPackHomologue mLiaisons; const cAppliMICMAC & mAppli; std::string mNameXML; std::string mName1; std::string mName2; std::string mNameFull1; std::string mNameFull2; std::string mNameI2GeomInit; cElHomographie mH1; cElHomographie mH2; cElHomographie mH1_Inv; cElHomographie mH2_Inv; }; void MyBisCr::SauvGrille() { write_liaison() ; cGeomImage * aGeom = cGeomImage::Geom_DHD_Px ( mAppli, *((cPriseDeVue *)0), // Pas tres propre ... mAppli.PDV2()->SzIm(), mAppli.PDV1()->ReadGridDist(), mAppli.PDV2()->ReadGridDist(), mAppli.PDV1()->ReadPackHom(mAppli.PDV2()), 2 ); std::string aName = ExpendPattern ( mAppli.SL_Name_Grid_Exp().Val(), mAppli.PDV1(), mAppli.PDV2() ); double aStepG = mAppli.SL_Step_Grid().Val(); cDbleGrid aDG ( true, Pt2dr(0,0),Pt2dr(SzU()), Pt2dr(aStepG,aStepG), *aGeom, aName ); { cElXMLFileIn aFileXML ( mAppli.FullDirGeom() + aName + ".xml" ); aDG.PutXMWithData(aFileXML,mAppli.FullDirGeom()); } delete aGeom; if (0) { cDbleGrid::cXMLMode aXmlMode; cDbleGrid aGr(aXmlMode,mAppli.FullDirGeom(),aName+".xml"); while (1) { Pt2dr aP; cin >> aP.x >> aP.y; cout << "P= " << aP << "\n"; Pt2dr aQ = aGr.Direct(aP); cout << "Q= " << aQ << "\n"; Pt2dr aR = aGr.Direct(aQ); cout << "R= " << aR << "\n"; } } if (1) // Image en geometrie 1 { Im2D_U_INT1 aI1 = Im2D_U_INT1::FromFileStd(mNameFull1); Pt2di aSz = aI1.sz(); Im2D_U_INT1 aI2Init = Im2D_U_INT1::FromFileStd(mNameI2GeomInit); Im2D_U_INT1 aI2(aSz.x,aSz.y); cDbleGrid::cXMLMode aXmlMode; cDbleGrid aGr(aXmlMode,mAppli.FullDirGeom(),aName+".xml"); Pt2di aP; TIm2D<U_INT1,INT> aTI2(aI2); TIm2D<U_INT1,INT> aTI2Init(aI2Init); for ( aP.x=0 ; aP.x <aSz.x; aP.x++) for (aP.y=0 ; aP.y <aSz.y; aP.y++) { aTI2.oset(aP,aTI2Init.getr(aGr.Direct(Pt2dr(aP)),0)); } Tiff_Im::Create8BFromFonc ( mAppli.FullDirGeom()+"TestSup.tif", aSz, Virgule(aI1.in(),aI2.in(),aI2.in()) ); cout << "Done Superp\n"; } if (0) // Image en geometrie 2 { Im2D_U_INT1 aI1 = Im2D_U_INT1::FromFileStd(mNameFull1); Im2D_U_INT1 aI2Init = Im2D_U_INT1::FromFileStd(mNameI2GeomInit); double aFact = 5.0/3.0; Pt2di aSz = round_ni(Pt2dr(aI1.sz()) * aFact); Im2D_U_INT1 aI2(aSz.x,aSz.y); cDbleGrid::cXMLMode aXmlMode; cDbleGrid aGr(aXmlMode,mAppli.FullDirGeom(),aName+".xml"); Pt2di aP; TIm2D<U_INT1,INT> aTI2(aI2); TIm2D<U_INT1,INT> aTI1(aI1); // ELISE_COPY(aI1.all_pts(),((FX/10)%2)*255,aI1.out()); for ( aP.x=0 ; aP.x <aSz.x; aP.x++) for (aP.y=0 ; aP.y <aSz.y; aP.y++) { int aC1 = (int)aTI1.getr(aGr.Inverse(Pt2dr(aP)/aFact),0); aTI2.oset(aP,aC1); } Tiff_Im::Create8BFromFonc ( mAppli.FullDirGeom()+"TestSup.tif", aSz, aI2.in() ); cout << "Done Superp\n"; } } void MyBisCr::ShowLiaison(ElCplePtsHomologues & aCple) { Video_Win aW = this->W(); Pt2dr aPW1 = this->Scr1().to_win(aCple.P1()); Pt2dr aPW2 = this->Scr2().to_win(aCple.P2()); if (this->Im1Act() ) { aW.draw_circle_abs ( aPW1, 3.0, aW.pdisc()(P8COL::red) ); } if (this->Im2Act() ) { aW.draw_circle_abs ( aPW2, 3.0, aW.pdisc()(P8COL::blue) ); } if (this->Im1Act() && this->Im2Act() ) { aW.draw_seg ( aPW1, aPW2, aW.pdisc()(P8COL::magenta) ); } } void MyBisCr::ShowLiaison() { for ( ElPackHomologue::tIter itCple = mLiaisons.begin(); itCple != mLiaisons.end(); itCple++ ) ShowLiaison(itCple->ToCple()); } void MyBisCr::write_liaison() { if (StdPostfix(mNameXML)=="dat") { ELISE_fp aFP(mNameXML.c_str(),ELISE_fp::WRITE); ElPackHomologue aPackSauv = mLiaisons; aPackSauv.ApplyHomographies(mH1,mH2); aPackSauv.write(aFP); } else if (StdPostfix(mNameXML)=="xml") { cElXMLFileIn aXMLFile(mNameXML); // aXMLFile.PutString(mParam.Directory(),"Directory"); aXMLFile.PutString(mName1,"Name1"); aXMLFile.PutString(mName2,"Name2"); ElPackHomologue aPackSauv = mLiaisons; aPackSauv.ApplyHomographies(mH1,mH2); aXMLFile.PutPackHom(aPackSauv); } else { ELISE_ASSERT(false,"MyBisCr::write_liaison"); } } static const INT NbPixInitCorr = 2; class TestScroller : public Optim2DParam, private EliseStdImageInteractor, public Grab_Untill_Realeased { public : REAL Op2DParam_ComputeScore(REAL,REAL) ; virtual ~TestScroller(){}; TestScroller ( Video_Win, VideoWin_Visu_ElImScr & aVisu, MyBisCr & aScr, Pt2di aTrInit, bool IsEpip ); void GUR_query_pointer(Clik p,bool); void GUR_button_released(Clik p); void OnEndTranslate(Clik){ShowVect();} void OnEndScale(Clik aCl) { EliseStdImageInteractor::OnEndScale(aCl); ShowVect(); } Pt2dr SetTranslate(Pt2dr aP) { if (mIsEpip) aP.y = 0; mScrol.SetTranslate(aP); return aP; } Video_Win W; Video_Win * pWProf; VideoWin_Visu_ElImScr & mVisu; MyBisCr & mScrol; vector<ElImScroller*> mVScr; void IncrustFromBegin(Pt2di p0,Pt2di aDec); REAL OptimCorrelAutom(bool addLiaison,bool Optim); Pt2di mLastCl; Pt2di mLastDec; Pt2di mIncrCenter; bool mModePopUp; bool mModeIncr; INT mCptScale; Tiff_Im mTifMenu; Pt2di mSzCase; GridPopUpMenuTransp mPopUp; ChoixParmiCaseGPUMT * mCase12; ChoixParmiCaseGPUMT * mCase1; ChoixParmiCaseGPUMT * mCase2; CaseGPUMT * mCaseExit; CaseGPUMT * mCaseRecal; CaseGPUMT * mCaseFlip; CaseGPUMT * mCaseProfil; CaseGPUMT * mCasePolyg; CaseGPUMT * mCaseLiaisCorr; CaseGPUMT * mCaseLiaisTriv; CaseGPUMT * mCaseKillLiais; CaseGPUMT * mCaseSauvGrid; Incruster mIncr; ElList<Pt2di> mLpt; INT mFlagIm; bool mBlocSwapIm; INT mMaxSeg; INT mRabSeg; INT mBoxSeg; Memory_ElImDest<U_INT1> aMem; Im2D_INT1 mGX; Im2D_INT1 mGY; Im2D_U_INT1 mRhoG; ElPackHomologue & mLiaisons; bool mIsEpip; void SetFlagIm(INT aFlag); void FlipImage(); void Recal2Pt(bool BlAndW); Pt2dr GetPt1Image(bool * Shifted = 0); Pt2dr ToWScAct(Pt2dr aP) { return mScrol.TheScrAct().to_win(aP); } void KillLiaison(); void ShowVect(); void GetLiasonCorr(bool Optim); void Profil(); void Profil(Im2D_REAL4 aIm,Pt2dr aP0,Pt2dr aP1,INT aCoul); }; Pt2di aSzWP(600,200); void TestScroller::Profil(Im2D_REAL4 aIm,Pt2dr aP0,Pt2dr aP1,INT aCoul) { cout << aP0 << aP1 << aIm.sz() << "\n"; REAL aD = euclid(aP1-aP0); REAL aStep = ElMax(0.05,ElMax(1.0,aD)/600.0); INT aNb = round_ni(aD/aStep); TIm2D<REAL4,REAL> aTIm(aIm); REAL aS0 = 0; REAL aS1 = 0; REAL aS2 = 0; std::vector<REAL> aVVals; for (INT aK=0 ; aK<=aNb ; aK++) { REAL aPds = 1-(aK/REAL(aNb)); Pt2dr aP = barry(aPds,aP0,aP1); REAL aV = aTIm.getr(aP); aVVals.push_back(aV); aS0 += 1; aS1 += aV; aS2 += ElSquare(aV); } aS1 /= aS0; aS2 = sqrt(ElMax(1e-2,aS2/aS0 - ElSquare(aS1))); std::vector<Pt2dr> aVPts; for (INT aK=0 ; aK<=aNb ; aK++) { REAL aY = aSzWP.y * (0.5 + (aVVals[aK]-aS1)/aS2 * 0.3); aVPts.push_back(Pt2dr(aK,aY)); } for (INT aK=0 ; aK<aNb ; aK++) { pWProf->draw_seg(aVPts[aK],aVPts[aK+1],pWProf->pdisc()(aCoul)); } } void TestScroller::Profil() { if (pWProf == 0) { pWProf = new Video_Win(W,Video_Win::eBasG,aSzWP); } pWProf->clear(); Clik aCl = clik_press(); Pt2dr aPW = aCl._pt; W.draw_circle_abs(aPW,2.0,W.pdisc()(P8COL::green)); Pt2dr p1 = mScrol.Scr1().to_user(aPW); Pt2dr p2 = mScrol.Scr2().to_user(aPW); aCl = clik_press(); Pt2dr aQW = aCl._pt; W.draw_circle_abs(aQW,2.0,W.pdisc()(P8COL::green)); W.draw_seg(aPW,aQW,W.pdisc()(P8COL::yellow)); Pt2dr q1 = mScrol.Scr1().to_user(aQW); Pt2dr q2 = mScrol.Scr2().to_user(aQW); Pt2di aP0 = round_down(Inf(Inf(p1,q1),Inf(p2,q2))) - Pt2di(3,3); Pt2di aP1 = round_up (Sup(Sup(p1,q1),Sup(p2,q2))) + Pt2di(3,3); Tiff_Im aF1 = Tiff_Im::StdConvGen(mScrol.mNameFull1,1,false); Tiff_Im aF2 = Tiff_Im::StdConvGen(mScrol.mNameFull2,1,false); Pt2di aSzCr = aP1-aP0; Im2D_REAL4 Im1(aSzCr.x,aSzCr.y); Im2D_REAL4 Im2(aSzCr.x,aSzCr.y); p1 -= Pt2dr(aP0); p2 -= Pt2dr(aP0); q1 -= Pt2dr(aP0); q2 -= Pt2dr(aP0); ELISE_COPY(Im1.all_pts(),trans(aF1.in(),aP0),Im1.out()); ELISE_COPY(Im2.all_pts(),trans(aF2.in(),aP0),Im2.out()); Profil(Im1,p1,q1,P8COL::blue); Profil(Im2,p2,q2,P8COL::red); cout << p1 << p2 << "\n"; cout << q1 << q2 << "\n"; } void TestScroller::ShowVect() { mScrol.ShowLiaison(); // mLiaisons.Show(mScrol); } Pt2dr TestScroller::GetPt1Image(bool * shifted) { Clik aCl = clik_press(); if (shifted) *shifted = aCl.shifted(); return mScrol.TheScrAct().to_user(aCl._pt); } void TestScroller::KillLiaison() { Pt2dr aPt = mScrol.TheFirstScrAct().to_user(clik_press()._pt); aPt = mScrol.TheFirstScrAct().to_win(aPt); aPt = mScrol.Scr1().to_user(aPt); std::cout << "AV " << mLiaisons.size() << "\n"; mLiaisons.Cple_RemoveNearest(aPt,true); std::cout << "AP " << mLiaisons.size() << "\n"; } INT SensibRec = 3; void TestScroller::SetFlagIm(INT aFlag) { cout << mFlagIm << " => " << aFlag << "\n"; if (aFlag == mFlagIm) return; mFlagIm = aFlag; mScrol.SetImAct((bool)(aFlag&1),(bool)(aFlag&2)); mScrol.LoadAndVisuIm(); ShowVect(); } void TestScroller::FlipImage() { INT aCurFlag = mFlagIm; for (INT k=0 ; k<20 ; k++) SetFlagIm(1+(k%2)); SetFlagIm(aCurFlag); } void TestScroller::GUR_button_released(Clik cl) { if (cl.controled()) { SetTranslate ( Pt2dr(mScrol.CurTr() ) + ((Pt2dr(mLastDec)-cl._pt)/SensibRec) / mScr.sc() ); cout << "TR= " << mScrol.Scr1().tr() - mScrol.Scr2().tr() << "\n"; } } void TestScroller::GUR_query_pointer(Clik cl,bool) { if (mModePopUp) { mPopUp.SetPtActif( Pt2di(cl._pt)); } if (mModeIncr) { if (!cl.controled()) mLastDec = Pt2di(cl._pt); if (cl.shifted()) { INT dy = (INT) cl._pt.y-mLastCl.y; mIncr.IncrSzAndReaff(mIncrCenter,Pt2di(dy,dy),W.prgb()); } else if (cl.controled()) { IncrustFromBegin(mIncrCenter,Pt2di((Pt2dr(mLastDec)-cl._pt)/SensibRec)); } else { mIncrCenter = Pt2di(cl._pt); mIncr.IncrustCenterAtPtW(Pt2di(cl._pt),W.prgb()); } } mLastCl = Pt2di(cl._pt); } void TestScroller::Recal2Pt(bool BlackAndW) { cout << "BLW = " << BlackAndW << "\n"; INT aFlag = mFlagIm; if (BlackAndW) SetFlagIm(1); Clik cl1 = clik_press(); Pt2dr p1 = mScrol.Scr1().to_user(cl1._pt); if (BlackAndW) SetFlagIm(2); Clik cl2 = clik_press(); Pt2dr p2 = mScrol.Scr2().to_user(cl2._pt); SetFlagIm(aFlag); SetTranslate(p2-p1); ShowVect(); cout << "Translate = " << p2-p1 << "\n"; } REAL TestScroller::Op2DParam_ComputeScore(REAL xR,REAL yR) { Pt2di dec = Pt2di(Pt2dr(xR,yR) * double(NbPixInitCorr)); Symb_FNum f1 = Rconv(mScrol.Im1().in(0)); Symb_FNum f2 = trans(Rconv(mScrol.Im2().in(0)),dec); REAL S[6]; ELISE_COPY ( polygone(mLpt), Virgule(1.0,f1,f2,Square(f1),f1*f2,Square(f2)), sigma(S,6) ); REAL s = S[0]; REAL s1= S[1] /s; REAL s2= S[2] /s; REAL s11 = S[3]/s - ElSquare(s1); REAL s12 = S[4]/s - s1 * s2; REAL s22 = S[5]/s - ElSquare(s2); REAL coeff = s12 / sqrt(ElMax(s11*s22,0.1)); cout << "Coeff = " << coeff << "\n"; return coeff; } REAL TestScroller::OptimCorrelAutom(bool addLiaison,bool Optim) { mLpt = mW.GetPolyg(mW.pdisc()(P8COL::red),3); if (Optim) Optim2DParam::optim(); REAL S[3]; ELISE_COPY ( polygone(mLpt), Virgule(1.0,FX,FY), sigma(S,3) ); Pt2dr aDec = param() * NbPixInitCorr; // IncrustFromBegin(aC,aDec); Clik aCl= mW.clik_in(); Pt2dr aTrans = mScrol.CurTr()+ aDec/mScr.sc(); SetTranslate(aTrans); REAL aCor = Op2DParam_ComputeScore(0,0); if (addLiaison) { Pt2dr aC = Pt2dr(S[1],S[2])/ S[0]; Pt2dr aP0 = mScrol.Scr1().to_user(aC); Pt2dr aP1 = aP0+aTrans; cout << "P0 Pokyg" << aP0 << aP1 << "\n"; mLiaisons.Cple_Add(ElCplePtsHomologues(aP0,aP1,aCor)); } return aCor; } void TestScroller::GetLiasonCorr(bool Optim) { SetFlagIm(3); REAL aCor = OptimCorrelAutom(true,Optim); // Clik aCl = clik_press(); cout << "Cor = " << aCor << "\n"; } void TestScroller::IncrustFromBegin(Pt2di aP,Pt2di aDec) { if (mIsEpip) aDec.y = 0; mIncr.SetDec12(aDec); mIncr.SetScale(mScrol.sc()); mIncr.BeginIncrust ( Pt2dr(aP), mScr.sc() ); mIncr.IncrustCenterAtPtW(aP,W.prgb()); } TestScroller::TestScroller ( Video_Win WIN, VideoWin_Visu_ElImScr & aVisu, MyBisCr & SCROL, Pt2di aTrInit, bool IsEpip ) : Optim2DParam ( 0.9 / NbPixInitCorr, -10, 1e-5, true ), EliseStdImageInteractor(WIN,SCROL,2), W (WIN), pWProf (0), mVisu (aVisu), mScrol (SCROL), mVScr (SCROL.SubScrolls()), mCptScale (0), mTifMenu (MMIcone("Loupe")), mSzCase (mTifMenu.sz()), mPopUp ( WIN, mSzCase, Pt2di(5,5), Pt2di(1,1) ), mCase12 (0), mCase1 (0), mCase2 (0), mCaseExit (0), mCaseRecal (0), mCasePolyg (0), mCaseLiaisCorr (0), mCaseLiaisTriv (0), mCaseKillLiais (0), mCaseSauvGrid (0), mIncr (SzImIncr,aVisu,mVScr), mFlagIm (3), mBlocSwapIm (false), mMaxSeg (500), mRabSeg (20), mBoxSeg (mMaxSeg + 2 * mRabSeg), aMem (1,Pt2di(mBoxSeg,mBoxSeg)), mGX (mBoxSeg,mBoxSeg), mGY (mBoxSeg,mBoxSeg), mRhoG (mBoxSeg,mBoxSeg), mLiaisons (mScrol.mLiaisons), mIsEpip (IsEpip) { mCase12 = new ChoixParmiCaseGPUMT ( mPopUp,"1 0",Pt2di(1,0), (!MMIcone("i12").in(0)) * 255, MMIcone("i12").in(0) * 255, 3, (ChoixParmiCaseGPUMT *)0 ); mCase1 = new ChoixParmiCaseGPUMT ( mPopUp,"0 0",Pt2di(1,1), (!MMIcone("i1").in(0)) * 255, MMIcone("i1").in(0) * 255, 1, mCase12 ); mCase2 =new ChoixParmiCaseGPUMT ( mPopUp,"0 0",Pt2di(1,2), (!MMIcone("i2").in(0)) * 255, MMIcone("i2").in(0) * 255, 2, mCase12 ); mCaseKillLiais = new CaseGPUMT ( mPopUp,"0 0",Pt2di(1,3), MMIcone("TDM").in(0) *255 ); mCaseSauvGrid = new CaseGPUMT ( mPopUp,"0 0",Pt2di(3,1), MMIcone("Gr").in(0) *255 ); mCaseExit = new CaseGPUMT ( mPopUp,"0 0",Pt2di(4,4), MMIcone("Exit").in(0) *255 ); mCaseRecal = new CaseGPUMT ( mPopUp,"0 0",Pt2di(0,1), MMIcone("Recal").in(0) *255 ); mCasePolyg = new CaseGPUMT ( mPopUp,"0 0",Pt2di(0,2), MMIcone("Polyg").in(0) *255 ); mCaseLiaisCorr = new CaseGPUMT ( mPopUp,"0 0",Pt2di(2,0), MMIcone("PCor").in(0) *255 ); mCaseLiaisTriv = new CaseGPUMT ( mPopUp,"0 0",Pt2di(3,0), MMIcone("Liais").in(0) *255 ); mCaseFlip = new CaseGPUMT ( mPopUp,"0 0",Pt2di(2,1), MMIcone("Flip").in(0) *255 ); mCaseProfil = new CaseGPUMT ( mPopUp,"0 0",Pt2di(2,2), MMIcone("Profil").in(0) *255 ); // mScrol.SetTranslate(aTrInit); // mScrol.set(Pt2dr(0,0),0.2,false); mCptScale++; CaseGPUMT * aCase = 0; while (aCase != mCaseExit) { Clik cl1 = clik_press(); mLastCl = Pt2di(cl1._pt); mLastDec = Pt2di(cl1._pt); mIncrCenter = Pt2di(cl1._pt); mModePopUp = false; mModeIncr = false; switch (cl1._b ) { case 1 : { mModeIncr = true; IncrustFromBegin(Pt2di(cl1._pt),Pt2di(0,0)); W.grab(*this); mIncr.EndIncrust(); cout << "SCALE = " << mScrol.sc() << "\n"; } break; case 3 : { mModePopUp = true; mPopUp.UpCenter(Pt2di(cl1._pt)); W.grab(*this); aCase = mPopUp.PopAndGet(); if (aCase == mCaseRecal) Recal2Pt(cl1.shifted()); if (aCase == mCasePolyg) OptimCorrelAutom(false,true); if (aCase == mCaseKillLiais) KillLiaison(); if (aCase== mCaseLiaisCorr) GetLiasonCorr(true); if (aCase== mCaseLiaisTriv) GetLiasonCorr(false); if (aCase== mCaseFlip) FlipImage(); if (aCase== mCaseProfil) Profil(); if (aCase== mCaseSauvGrid) mScrol.SauvGrille() ; if ( (aCase == mCase12) || (aCase == mCase1) || (aCase == mCase2) ) SetFlagIm(mCase12->IdSelected()); cout << "Id 12 " << mCase12->IdSelected() << "\n"; } break; } } mScrol.write_liaison(); } Video_Win * BUGW=0; void TestHomographie(const cElHomographie & aH,const std::string & aMes ) { Pt2dr aP0(1000,1000); Pt2dr aQ0 = aH.Direct(aP0); Pt2dr aP1(3000,3000); Pt2dr aQ1 = aH.Direct(aP1); REAL aDP = euclid(aP0,aP1); REAL aDQ = euclid(aQ0,aQ1); cout << aMes << " ; HOMOGRAPHIE : " << aDP << " -> " << aDQ << "\n"; } bool ToImEqual ( std::string & aNameIm, cAppliMICMAC & anAppli ) { if (! anAppli.SL_FILTER().IsInit()) return false; std::vector<std::string> ArgsF= anAppli.SL_FILTER().Val(); std::string aPref; for (int aK=0 ; aK<int(ArgsF.size()) ; aK++) aPref = aPref + ArgsF[aK]; cout << "Begin Equal " << aNameIm << "\n"; std::string aNameInit = anAppli.DirImagesInit() + aNameIm; aNameIm = anAppli.TmpMEC() + StdPrefixGen(aNameIm) + aPref + std::string(".tif"); std::string aFullName = anAppli.WorkDir() +aNameIm; if (ELISE_fp::exist_file(aFullName) && (! anAppli.SL_TJS_FILTER().Val())) return true; Tiff_Im aFileInit = Tiff_Im::StdConvGen(aNameInit,1,true); Pt2di aSz = aFileInit.sz(); Tiff_Im aFileOut ( aFullName.c_str(), aSz, GenIm::u_int1, Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ); Fonc_Num aFres = FiltrageImMicMac(anAppli.SL_FILTER().Val(),aFileInit.in(0),aFileInit.inside()); aFres = Max(0,Min(255,aFres)); ELISE_COPY(aFileOut.all_pts(),aFres,aFileOut.out()); cout << "END Equal " << aNameIm << "\n"; return true; /* */ } cElHomographie ToImRedr ( bool isNameDejaModifie, std::string & aNameIm, cAppliMICMAC & anAppli, ElPackHomologue aPack, std::string & aNameImBase, bool ForceWhenExist ) { std::string aNameInit = anAppli.WorkDir() + aNameIm; Tiff_Im aTifInit = Tiff_Im::StdConvGen(aNameInit.c_str(),1,false,true); Pt2di aSz = aTifInit.sz(); cElHomographie aHom(aPack,true); // aHom = aHom.Inverse(); Pt2di aSzOut = aSz; // ====== aNameIm = (isNameDejaModifie ?"": anAppli.TmpMEC()) // anAppli.TmpMEC() + StdPrefixGen(aNameIm) + std::string("_RedrOn_") + StdPrefixGen(aNameImBase) + std::string(".tif"); if (ELISE_fp::exist_file(anAppli.WorkDir() +aNameIm) && (!ForceWhenExist)) return aHom; Im2D<U_INT1,INT> aIn = LoadFileIm(aTifInit,(U_INT1 *)0); Im2D<U_INT1,INT> aOut (aSzOut.x,aSzOut.y); // Taille a changer aussi // U_INT1 ** DIn = aIn.data(); U_INT1 ** DOut = aOut.data(); Box2di aBoxIn (Pt2di(0,0),aSz-Pt2di(1,1)); TIm2D<U_INT1,INT> aTIn(aIn); cCubicInterpKernel aKer(-0.5); for (INT x=0 ; x<aSzOut.x ; x++) { if ((x % 10) == 0 ) cout << "HOM , " << x << "\n"; for (INT y=0 ; y<aSzOut.y ; y++) { Pt2di POut(x,y); Pt2dr PIn = aHom.Direct(Pt2dr(POut)); INT aV = round_ni(aTIn.getr(aKer,PIn,0)); DOut[POut.y][POut.x] = ElMax(0,ElMin(255,aV)); } } Tiff_Im::CreateFromIm(aOut,anAppli.WorkDir()+aNameIm); return aHom; } int main(int argc,char** argv) { cAppliMICMAC & anAppli = *(cAppliMICMAC::Alloc(argc,argv,eAllocAM_Saisie)); Pt2di SzW(anAppli.SL_XSzW().Val(),anAppli.SL_YSzW().Val()); bool aRedrCur = anAppli.SL_RedrOnCur().Val(); bool aNewRC = anAppli.SL_NewRedrCur().Val(); std::string aNameCompSauvXML = anAppli.PDV1()->NamePackHom(anAppli.PDV2()); std::string aNameXMLSsDir,aDirXML; SplitDirAndFile(aDirXML,aNameXMLSsDir,aNameCompSauvXML); std::string Nameim1 = anAppli.PDV1()->Name(); std::string Nameim2 = anAppli.PDV2()->Name(); std::string NameImOri1 = Nameim1; std::string NameImOri2 = Nameim2; ToImEqual (Nameim1,anAppli); bool aModifName2 = ToImEqual (Nameim2,anAppli); bool WithEpip = anAppli.SL_Epip().Val(); cElHomographie Hom1 = cElHomographie::Id(); cElHomographie Hom2 = cElHomographie::Id(); std::string aNameH = anAppli.SL_PackHom0().Val(); std::string aNameIm2GeomInit = Nameim2; if (aRedrCur) { std::string aNameRedr = anAppli.TmpMEC() + "Redr_"+ aNameXMLSsDir; std::string aFullNR = anAppli.FullDirGeom() + aNameRedr; std::string aSys = "cp " + anAppli.FullDirGeom() + aNameCompSauvXML + " " + aFullNR; if (aNewRC) VoidSystem(aSys.c_str()); if (ELISE_fp::exist_file(aFullNR)) aNameH = aNameRedr; } if (aNameH != "") { /* cElXMLTree aTree ( anAppli.FullDirGeom() + aNameH ); ElPackHomologue aPackExtIm2 = aTree.GetPackHomologues("ListeCpleHom"); */ ElPackHomologue aPackExtIm2 = ElPackHomologue::FromFile(anAppli.FullDirGeom()+aNameH); Hom2 = ToImRedr(aModifName2,Nameim2,anAppli,aPackExtIm2,NameImOri1,aNewRC); } cout << aNameIm2GeomInit << " " << Nameim2 << "\n"; TestHomographie(Hom1,"H1"); TestHomographie(Hom2,"H2"); Gray_Pal Pgray(90); Disc_Pal Pdisc(Disc_Pal::P8COL()); RGB_Pal Prgb(3,3,3); Circ_Pal Pcirc = Circ_Pal::PCIRC6(30); Elise_Set_Of_Palette SOP(NewLElPal(Pgray)+Elise_Palette(Pdisc)+Elise_Palette(Prgb)+Elise_Palette(Pcirc)); Video_Display Ecr((char *) NULL); Video_Win W(Ecr,SOP,Pt2di(50,50),SzW); Ecr.load(SOP); VideoWin_Visu_ElImScr V(W,W.prgb(),SzImIncr); MyBisCr * aScr = new MyBisCr ( anAppli, V, NameFileStd(anAppli.WorkDir()+Nameim1,1,false,true), NameImOri1, Hom1, NameFileStd(anAppli.WorkDir()+Nameim2,1,false,true), NameImOri2, aNameIm2GeomInit, Hom2 ); // aScr->SetAlwaysQuick(); // aScr->SetTranslate(aCor0.DecEch1()); ELISE_ASSERT(aScr !=0 , "Cannot Create Scroller \n"); //V.SetUseEtalDyn(true); Pt2di aDec = WithEpip ? Pt2di(0,anAppli.SL_YDecEpip().Val()) : Pt2di(0,0); TestScroller(W,V,*aScr,aDec,WithEpip); } #else int main(int argc,char** argv) { ELISE_ASSERT(false,"No X11, no interactive program !"); } #endif /********************************************************************/ /********************************************************************/ /********************************************************************/ /********************************************************************/ /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant à la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. A cet égard l'attention de l'utilisateur est attirée sur les risques associés au chargement, à l'utilisation, à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant donné sa spécificité de logiciel libre, qui peut le rendre complexe à manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques approfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. Footer-MicMac-eLiSe-25/06/2007*/
27.178886
119
0.502563
kikislater
d2440f26f0465d0ebef1db5e21cbdd7ce5349b8a
2,725
cpp
C++
trainer/MemoryManager.cpp
thefinalstarman/DolphinTrainer
f3d615f35b21986cc2078028311306207fe00801
[ "MIT" ]
1
2017-11-19T17:02:34.000Z
2017-11-19T17:02:34.000Z
trainer/MemoryManager.cpp
thefinalstarman/DolphinTrainer
f3d615f35b21986cc2078028311306207fe00801
[ "MIT" ]
null
null
null
trainer/MemoryManager.cpp
thefinalstarman/DolphinTrainer
f3d615f35b21986cc2078028311306207fe00801
[ "MIT" ]
null
null
null
/* * MemoryManager.cpp * * Created on: Jan 24, 2018 * Author: Jordan Richards */ #include <trainer/MemoryManager.h> #include <algorithm> #include <vector> #include <exception> #include <functional> namespace xtrainer{ Page::Page(PageInfo&& p, int expiration): expirationTime(expiration){ size = p.size(); addr = (size_t)p.startAddr; data = new char[size]; } Page::~Page(){ delete [] data; } size_t Page::read(size_t addr, void* buffer, size_t n){ char* str = (char*)buffer; size_t k = 0; for(int i = addr - this->addr; i < addr - this->addr + n && i < size; i++){ str[i] = data[i]; k++; }return k; } void Page::update(Process* proc){ proc->readBytes((void*)addr, data, size); lastUpdated = time(0); } MemoryManager::MemoryManager(Process* p): parent(p) {} void MemoryManager::addPage(PageInfo&& pageInfo, int expiration){ pages.insert(Page(std::move(pageInfo),expiration)); } const Page* MemoryManager::findPage(size_t addr){ if(!pages.size())return nullptr; auto page = std::lower_bound(pages.begin(), pages.end(), addr); if(page == pages.end() || (page != pages.begin() && page->getStartAddress() > addr))page--; if(page->getStartAddress() + page->getSize() < addr)return &*page; return nullptr; } size_t MemoryManager::read(size_t addr, void* buffer, size_t n, bool forceUpdate){ Page* p = const_cast<Page*>(findPage(addr)); if(p == nullptr){ return parent->readBytes((void*)addr, buffer, n); } if(allExpired || forceUpdate || p->isExpired()) p->update(parent); allExpired = false; return p->read(addr, buffer, n); } size_t MemoryManager::write(size_t addr, void* str, size_t n){ allExpired = true; return parent->writeBytes((void*)addr, str, n); } void dfs(int i, int* visited, std::vector<Property*> in, std::function<void(Property*)> callback){ if(visited[i] == 2)return; if(visited[i] == 1)throw std::runtime_error("Circular dependency while processing property."); visited[i] = 1; if(in[i]->dependency() != nullptr){ auto it = std::find(in.begin(), in.end(), in[i]->dependency()); if(it == in.end())throw std::runtime_error("Required property not found."); dfs(it - in.begin(), visited, in, callback); } visited[i] = 2; callback(in[i]); } void MemoryManager::updateProperties(std::set<Property*> in){ std::vector<Property*> v(in.begin(), in.end()); int* visited = new int[v.size()]; for(int i = 0; i < v.size(); i++){ dfs(i, visited, v, [](Property* p){ p->update(); }); } delete [] visited; } void MemoryManager::updateModules(){ std::set<Property*> props; for(auto it = mods.begin(); it != mods.end(); it++){ it->second->getProperties(std::inserter(props,props.begin())); } updateProperties(props); } }//namespace xtrainer
24.772727
98
0.659817
thefinalstarman
d24465231e656c2308669981180c36530374d81f
14,271
cpp
C++
Unix/samples/Providers/TestClass_MethodProvider_Calc/TestClass_MethodProvider_Calc.cpp
HydAu/omi
d5329f01f826430b4148264e64aa11ebeede1bf8
[ "MIT" ]
null
null
null
Unix/samples/Providers/TestClass_MethodProvider_Calc/TestClass_MethodProvider_Calc.cpp
HydAu/omi
d5329f01f826430b4148264e64aa11ebeede1bf8
[ "MIT" ]
null
null
null
Unix/samples/Providers/TestClass_MethodProvider_Calc/TestClass_MethodProvider_Calc.cpp
HydAu/omi
d5329f01f826430b4148264e64aa11ebeede1bf8
[ "MIT" ]
null
null
null
/* **============================================================================== ** ** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE ** for license information. ** **============================================================================== */ /* @statikgen@ */ #include "MI.h" #include <iostream> #include "TestClass_MethodProvider_Calc.h" #include "CIM_Error.h" #include <vector> #include <memory> #include <stdio.h> #ifdef _MSC_VER #include <strsafe.h> #endif #include <sstream> #include <algorithm> #include <pal/palcommon.h> void MI_CALL TestClass_MethodProvider_Calc_Load( _Outptr_result_maybenull_ TestClass_MethodProvider_Calc_Self** self, _In_opt_ MI_Module_Self* selfModule, _In_ MI_Context* context) { *self = NULL; MI_PostResult(context, MI_RESULT_OK); } void MI_CALL TestClass_MethodProvider_Calc_Unload( _In_opt_ TestClass_MethodProvider_Calc_Self* self, _In_ MI_Context* context) { MI_PostResult(context, MI_RESULT_OK); } void MI_CALL TestClass_MethodProvider_Calc_EnumerateInstances( TestClass_MethodProvider_Calc_Self* self, MI_Context* context, const MI_Char* nameSpace, const MI_Char* className, const MI_PropertySet* propertySet, MI_Boolean keysOnly, const MI_Filter* filter) { MI_PostResult(context, MI_RESULT_NOT_SUPPORTED); } void MI_CALL TestClass_MethodProvider_Calc_GetInstance( TestClass_MethodProvider_Calc_Self* self, MI_Context* context, const MI_Char* nameSpace, const MI_Char* className, const TestClass_MethodProvider_Calc* instanceName, const MI_PropertySet* propertySet) { MI_PostResult(context, MI_RESULT_NOT_SUPPORTED); } void MI_CALL TestClass_MethodProvider_Calc_CreateInstance( TestClass_MethodProvider_Calc_Self* self, MI_Context* context, const MI_Char* nameSpace, const MI_Char* className, const TestClass_MethodProvider_Calc* newInstance) { MI_PostResult(context, MI_RESULT_NOT_SUPPORTED); } void MI_CALL TestClass_MethodProvider_Calc_ModifyInstance( TestClass_MethodProvider_Calc_Self* self, MI_Context* context, const MI_Char* nameSpace, const MI_Char* className, const TestClass_MethodProvider_Calc* modifiedInstance, const MI_PropertySet* propertySet) { MI_PostResult(context, MI_RESULT_NOT_SUPPORTED); } void MI_CALL TestClass_MethodProvider_Calc_DeleteInstance( TestClass_MethodProvider_Calc_Self* self, MI_Context* context, const MI_Char* nameSpace, const MI_Char* className, const TestClass_MethodProvider_Calc* instanceName) { MI_PostResult(context, MI_RESULT_NOT_SUPPORTED); } void MI_CALL TestClass_MethodProvider_Calc_Invoke_Add( _In_opt_ TestClass_MethodProvider_Calc_Self* self, _In_ MI_Context* context, _In_opt_z_ const MI_Char* nameSpace, _In_opt_z_ const MI_Char* className, _In_opt_z_ const MI_Char* methodName, _In_ const TestClass_MethodProvider_Calc* instanceName, _In_opt_ const TestClass_MethodProvider_Calc_Add* in) { MI_Result result = MI_RESULT_OK; if(in == NULL || in->Left.exists == 0 || in->Right.exists == 0) { MI_PostError(context, MI_RESULT_INVALID_PARAMETER, MI_RESULT_TYPE_MI, MI_T("In-Parameter \"left\" or \"right\" cannot be null")); return; } TestClass_MethodProvider_Calc_Add add = {{0}}; result = TestClass_MethodProvider_Calc_Add_Construct(&add, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); return; } TestClass_MethodProvider_Calc_Add_Set_sum(&add, (in->Left.value + in->Right.value)); TestClass_MethodProvider_Calc_Add_Set_MIReturn(&add, result); result = TestClass_MethodProvider_Calc_Add_Post(&add, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); TestClass_MethodProvider_Calc_Add_Destruct(&add); return; } MI_PostResult(context, result); TestClass_MethodProvider_Calc_Add_Destruct(&add); } void MI_CALL TestClass_MethodProvider_Calc_Invoke_Subtract( _In_opt_ TestClass_MethodProvider_Calc_Self* self, _In_ MI_Context* context, _In_opt_z_ const MI_Char* nameSpace, _In_opt_z_ const MI_Char* className, _In_opt_z_ const MI_Char* methodName, _In_ const TestClass_MethodProvider_Calc* instanceName, _In_opt_ const TestClass_MethodProvider_Calc_Subtract* in) { MI_Result result = MI_RESULT_OK; if(in == NULL || in->Left.exists == 0 || in->Right.exists == 0) { MI_PostError(context, MI_RESULT_INVALID_PARAMETER, MI_RESULT_TYPE_MI, MI_T("In-Parameter \"left\" or \"right\" cannot be null")); return; } TestClass_MethodProvider_Calc_Subtract sub = {{0}}; result = TestClass_MethodProvider_Calc_Subtract_Construct(&sub, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); return; } TestClass_MethodProvider_Calc_Subtract_Set_difference(&sub, ( in->Left.value - in->Right.value)); TestClass_MethodProvider_Calc_Subtract_Set_MIReturn(&sub, result); result = TestClass_MethodProvider_Calc_Subtract_Post(&sub, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); TestClass_MethodProvider_Calc_Subtract_Destruct(&sub); return; } MI_PostResult(context, result); TestClass_MethodProvider_Calc_Subtract_Destruct(&sub); } void MI_CALL TestClass_MethodProvider_Calc_Invoke_Divide( _In_opt_ TestClass_MethodProvider_Calc_Self* self, _In_ MI_Context* context, _In_opt_z_ const MI_Char* nameSpace, _In_opt_z_ const MI_Char* className, _In_opt_z_ const MI_Char* methodName, _In_ const TestClass_MethodProvider_Calc* instanceName, _In_opt_ const TestClass_MethodProvider_Calc_Divide* in) { MI_Result result = MI_RESULT_OK; if(in == NULL || in->Denominator.exists == 0 || in->Numerator.exists == 0) { MI_PostError(context, MI_RESULT_INVALID_PARAMETER, MI_RESULT_TYPE_MI, MI_T("In-Parameter \"Denominator\" or \"Numerator\" cannot be null")); return; } TestClass_MethodProvider_Calc_Divide div = {{0}}; result = TestClass_MethodProvider_Calc_Divide_Construct(&div, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); return; } TestClass_MethodProvider_Calc_Divide_Set_quotient(&div, ( in->Numerator.value / in->Denominator.value)); TestClass_MethodProvider_Calc_Divide_Set_MIReturn(&div, result); result = TestClass_MethodProvider_Calc_Divide_Post(&div, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); TestClass_MethodProvider_Calc_Divide_Destruct(&div); return; } MI_PostResult(context, result); TestClass_MethodProvider_Calc_Divide_Destruct(&div); } void MI_CALL TestClass_MethodProvider_Calc_Invoke_Multiply( _In_opt_ TestClass_MethodProvider_Calc_Self* self, _In_ MI_Context* context, _In_opt_z_ const MI_Char* nameSpace, _In_opt_z_ const MI_Char* className, _In_opt_z_ const MI_Char* methodName, _In_ const TestClass_MethodProvider_Calc* instanceName, _In_opt_ const TestClass_MethodProvider_Calc_Multiply* in) { MI_Result result = MI_RESULT_OK; if(in == NULL || in->Left.exists == 0 || in->Right.exists == 0) { MI_PostError(context, MI_RESULT_INVALID_PARAMETER, MI_RESULT_TYPE_MI, MI_T("In-Parameter \"Denominator\" or \"Numerator\" cannot be null")); return; } TestClass_MethodProvider_Calc_Multiply mult = {{0}}; result = TestClass_MethodProvider_Calc_Multiply_Construct(&mult, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); return; } TestClass_MethodProvider_Calc_Multiply_Set_product(&mult, ( in->Left.value * in->Right.value)); TestClass_MethodProvider_Calc_Multiply_Set_MIReturn(&mult, result); result = TestClass_MethodProvider_Calc_Multiply_Post(&mult, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); TestClass_MethodProvider_Calc_Multiply_Destruct(&mult); return; } MI_PostResult(context, result); TestClass_MethodProvider_Calc_Multiply_Destruct(&mult); } void MI_CALL TestClass_MethodProvider_Calc_Invoke_AddNumbers( _In_opt_ TestClass_MethodProvider_Calc_Self* self, _In_ MI_Context* context, _In_opt_z_ const MI_Char* nameSpace, _In_opt_z_ const MI_Char* className, _In_opt_z_ const MI_Char* methodName, _In_ const TestClass_MethodProvider_Calc* instanceName, _In_opt_ const TestClass_MethodProvider_Calc_AddNumbers* in) { MI_Result result = MI_RESULT_OK; if(in == NULL || in->numbers.exists == 0) { MI_PostError(context, MI_RESULT_INVALID_PARAMETER, MI_RESULT_TYPE_MI, MI_T("In-Parameter \"numbers\" cannot be null")); return; } MI_Uint32 count = in->numbers.value->count.value; const Numbers* inParams = in->numbers.value; TestClass_MethodProvider_Calc_AddNumbers addNum = {{0}}; result = TestClass_MethodProvider_Calc_AddNumbers_Construct(&addNum, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); return; } MI_Sint64 sum = 0; for(MI_Uint32 i = 0; i < count; i++) { sum += inParams->numbers.value.data[i]; } TestClass_MethodProvider_Calc_AddNumbers_Set_sum(&addNum, sum); result = TestClass_MethodProvider_Calc_AddNumbers_Set_MIReturn(&addNum, result); if(result != MI_RESULT_OK) { MI_PostResult(context, result); TestClass_MethodProvider_Calc_AddNumbers_Destruct(&addNum); return; } result = TestClass_MethodProvider_Calc_AddNumbers_Post(&addNum, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); TestClass_MethodProvider_Calc_AddNumbers_Destruct(&addNum); return; } MI_PostResult(context, result); TestClass_MethodProvider_Calc_AddNumbers_Destruct(&addNum); } bool isPrime(MI_Sint64 number) { for(MI_Sint64 i=2; i <= number / 2; i++) { if(number % i == 0) return false; } return true; } void factors(MI_Uint64 number, MI_Uint64 iteration, std::vector<MI_Sint64> &primeFactors) { if(number % iteration == 0) { if(isPrime(iteration)) primeFactors.push_back(iteration); } if(number == iteration) return; factors(number, iteration+1, primeFactors); } void MI_CALL TestClass_MethodProvider_Calc_Invoke_PrimeFactors( _In_opt_ TestClass_MethodProvider_Calc_Self* self, _In_ MI_Context* context, _In_opt_z_ const MI_Char* nameSpace, _In_opt_z_ const MI_Char* className, _In_opt_z_ const MI_Char* methodName, _In_ const TestClass_MethodProvider_Calc* instanceName, _In_opt_ const TestClass_MethodProvider_Calc_PrimeFactors* in) { std::vector<MI_Sint64> primeFactors; MI_Result result = MI_RESULT_OK; if(in == NULL || in->number.exists == 0) { MI_PostError(context, MI_RESULT_INVALID_PARAMETER, MI_RESULT_TYPE_MI, MI_T("In-Parameter \"number\" cannot be null")); return; } factors(in->number.value, 2, primeFactors); TestClass_MethodProvider_Calc_PrimeFactors primeFac = {{0}}; result = TestClass_MethodProvider_Calc_PrimeFactors_Construct(&primeFac, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); return; } Numbers fac = {{0}}; result = Numbers_Construct(&fac, context); if(result != MI_RESULT_OK) { MI_PostResult(context, result); TestClass_MethodProvider_Calc_PrimeFactors_Destruct(&primeFac); return; } MI_Sint64* answer; answer = (MI_Sint64 *) PAL_Malloc(sizeof (MI_Sint64) * primeFactors.size()); for(MI_Uint64 i=0; i < primeFactors.size(); i++) { answer[i] = primeFactors[i]; } Numbers_Set_count(&fac, primeFactors.size()); Numbers_Set_numbers(&fac, answer, primeFactors.size()); TestClass_MethodProvider_Calc_PrimeFactors_Set_factors(&primeFac, &fac); TestClass_MethodProvider_Calc_PrimeFactors_Set_MIReturn(&primeFac, result); result = TestClass_MethodProvider_Calc_PrimeFactors_Post(&primeFac, context); PAL_Free(answer); Numbers_Destruct(&fac); if(result != MI_RESULT_OK) { MI_PostResult(context, result); TestClass_MethodProvider_Calc_PrimeFactors_Destruct(&primeFac); return; } MI_PostResult(context, result); TestClass_MethodProvider_Calc_PrimeFactors_Destruct(&primeFac); } MI_EXTERN_C void MI_CALL TestClass_MethodProvider_Calc_Invoke_HardError( _In_opt_ TestClass_MethodProvider_Calc_Self* self, _In_ MI_Context* context, _In_opt_z_ const MI_Char* nameSpace, _In_opt_z_ const MI_Char* className, _In_opt_z_ const MI_Char* methodName, _In_ const TestClass_MethodProvider_Calc* instanceName, _In_opt_ const TestClass_MethodProvider_Calc_HardError* in) { if (in->postError.value) { CIM_Error error = {{0}}; CIM_Error_Construct(&error, context); CIM_Error_Set_PerceivedSeverity(&error, in->perceivedSeverity.value); CIM_Error_Set_Message(&error, MI_T("Hard error message")); CIM_Error_Set_CIMStatusCode(&error, 1); CIM_Error_Set_ErrorType(&error, 3); CIM_Error_Set_MessageID(&error, MI_T("HardError")); MI_Context_PostCimError(context, &(error.__instance)); } else { TestClass_MethodProvider_Calc_HardError hardError = {{0}}; TestClass_MethodProvider_Calc_HardError_Construct(&hardError, context); TestClass_MethodProvider_Calc_HardError_Set_MIReturn(&hardError, 0);\ MI_PostInstance(context, &(hardError.__instance)); MI_PostResult(context, MI_RESULT_OK); TestClass_MethodProvider_Calc_HardError_Destruct(&hardError); } }
32.731651
148
0.701563
HydAu
d2447e0884454edf39881ca6dfc42381c63e3d72
16,498
cpp
C++
src/main.cpp
Faaux/DingoEngine
05c8ae59816befaaa203e8d5310c4e17da89bb7b
[ "MIT" ]
null
null
null
src/main.cpp
Faaux/DingoEngine
05c8ae59816befaaa203e8d5310c4e17da89bb7b
[ "MIT" ]
null
null
null
src/main.cpp
Faaux/DingoEngine
05c8ae59816befaaa203e8d5310c4e17da89bb7b
[ "MIT" ]
null
null
null
/** * @file main.cpp * @author Faaux (github.com/Faaux) * @date 11 February 2018 */ #include "main.h" #include <ImGuizmo.h> #include <SDL.h> #include "components/SceneComponent.h" #include "components/StaticMeshComponent.h" #include "engine/Messaging.h" #include "engine/Types.h" #include "engine/WorldEditor.h" #include "graphics/FrameData.h" #include "graphics/GameWorldWindow.h" #include "graphics/GraphicsSystem.h" #include "graphics/Renderer.h" #include "imgui/DG_Imgui.h" #include "imgui/imgui_dock.h" #include "imgui/imgui_impl_sdl_gl3.h" #include "memory/Memory.h" #include "physics/Physics.h" #include "platform/ConditionVariable.h" #include "platform/InputSystem.h" #include "platform/Job.h" #include "platform/SDLHelper.h" #include "platform/StringIdCRC32.h" namespace DG { #if _DEBUG StringHashTable<2048> g_StringHashTable; #endif GameMemory Memory; GameState* Game; Managers* g_Managers; bool InitWindow() { Game->RenderState->Window = SDL_CreateWindow("Dingo", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1280, 720, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if (Game->RenderState->Window == nullptr) { SDL_LogCritical(SDL_LOG_CATEGORY_VIDEO, "Window could not be created! SDL Error: %s\n", SDL_GetError()); return false; } return true; } bool InitImgui() { ImGui_ImplSdlGL3_Init(Game->RenderState->Window); ImGui::StyleColorsDark(); ImGui::LoadDock(); InitInternalImgui(); return true; } bool InitWorkerThreads() { // Register Main Thread JobSystem::RegisterWorker(); // Create Worker Threads for (int i = 0; i < SDL_GetCPUCount() - 1; ++i) { JobSystem::CreateAndRegisterWorker(); } return true; } bool InitMemory() { // Grab a 1GB of memory const u32 TotalMemorySize = 1 * 1024 * 1024 * 1024; // 1 GB // ToDo: Get rid of this! u8* memory = (u8*)VirtualAlloc(0, TotalMemorySize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!memory) { SDL_LogError(0, "Couldn't allocate game memory."); return false; } // Assign 50 MB to Persistent, rest is transient const u32 PersistentMemorySize = 50 * 1024 * 1024; // 50 MB Memory.PersistentMemory.Init(memory, PersistentMemorySize); const u32 TransientMemorySize = TotalMemorySize - PersistentMemorySize; Memory.TransientMemory.Init(memory + PersistentMemorySize, TransientMemorySize); return true; } void Cleanup() { // PhysX Cleanup Game->WorldEdit->Shutdown(); ShutdownPhysics(); ImGui_ImplSdlGL3_Shutdown(); SDL_Quit(); } void AttachDebugListenersToMessageSystem() {} u64 GetFrameBufferIndex(u64 frameIndex, u64 size) { s64 index = (s64)frameIndex; if (index < 0) { return (size - (-index % size)); } return frameIndex % size; } template <typename T> void CopyImVector(ImVector<T>* dest, ImVector<T>* src, StackAllocator& allocator) { dest->Size = src->Size; dest->Capacity = src->Capacity; u32 memSize = src->Capacity * sizeof(T); dest->Data = (T*)allocator.Push(memSize, 4); memcpy(dest->Data, src->Data, memSize); } } // namespace DG int main(int, char* []) { using namespace DG; if (!InitMemory()) return -1; if (!InitSDL()) return -1; if (!InitWorkerThreads()) return -1; InitClocks(); // Initialize Resource Managers g_Managers = Memory.TransientMemory.PushAndConstruct<Managers>(); g_Managers->ModelManager = Memory.TransientMemory.PushAndConstruct<ModelManager>(); g_Managers->GLTFSceneManager = Memory.TransientMemory.PushAndConstruct<graphics::GLTFSceneManager>(); g_Managers->ShaderManager = Memory.TransientMemory.PushAndConstruct<graphics::ShaderManager>(); // Initialize Game const u32 playModeSize = 4 * 1024 * 1024; // 4MB Game = Memory.PersistentMemory.Push<GameState>(); Game->GameIsRunning = true; Game->PlayModeStack.Init(Memory.TransientMemory.Push(playModeSize, 4), playModeSize); Game->RawInputSystem = Memory.TransientMemory.PushAndConstruct<RawInputSystem>(); // Init Messaging // ToDo(Faaux)(Messaging): Messaging runs on real time clock? What if we pause the game? g_MessagingSystem.Initialize(&Memory.TransientMemory, &g_RealTimeClock); // Init RenderState Game->RenderState = Memory.TransientMemory.PushAndConstruct<graphics::RenderState>(); Game->RenderState->RenderMemory.Init(Memory.TransientMemory.Push(playModeSize, 4), playModeSize); // Create Window on main thread if (!InitWindow()) return -1; // This will boot up opengl on another thread if (!graphics::StartRenderThread(Game->RenderState)) return -1; if (!InitImgui()) return -1; if (!InitPhysics()) return -1; Game->WorldEdit = Memory.TransientMemory.PushAndConstruct<WorldEdit>(); Game->WorldEdit->Startup(&Memory.TransientMemory); Game->ActiveWorld = Game->WorldEdit->GetWorld(); AttachDebugListenersToMessageSystem(); u64 currentTime = SDL_GetPerformanceCounter(); f32 cpuFrequency = (f32)(SDL_GetPerformanceFrequency()); // Init FrameRingBuffer graphics::FrameData* frames = Memory.TransientMemory.Push<graphics::FrameData>(5); for (int i = 0; i < 5; ++i) { const u32 frameDataSize = 16 * 1024 * 1024; // 16MB u8* base = Memory.TransientMemory.Push(frameDataSize, 4); frames[i].FrameMemory.Init(base, frameDataSize); frames[i].Reset(); frames[i].IsPreRenderDone = true; frames[i].RenderDone.Create(); frames[i].DoubleBufferDone.Create(); } // Signal once, this opens the gate for the first frame to pass! frames[4].RenderDone.Signal(); // Stop clocks depending on edit mode if (Game->Mode == GameState::GameMode::EditMode) g_InGameClock.SetPaused(true); else if (Game->Mode == GameState::GameMode::PlayMode) g_EditingClock.SetPaused(true); // ToDo: This is not the right place for this to live.... graphics::GameWorldWindow mainGameWindow; mainGameWindow.Initialize("EditWindow", Game->WorldEdit->GetWorld()); while (!Game->RawInputSystem->IsQuitRequested()) { static bool isWireframe = false; TWEAKER_CAT("OpenGL", CB, "Wireframe", &isWireframe); // Frame Data Setup graphics::FrameData& previousFrameData = frames[GetFrameBufferIndex(Game->CurrentFrameIdx - 1, 5)]; graphics::FrameData& currentFrameData = frames[GetFrameBufferIndex(Game->CurrentFrameIdx, 5)]; currentFrameData.Reset(); // For now assume one world only currentFrameData.WorldRenderDataCount = 1; currentFrameData.WorldRenderData = currentFrameData.FrameMemory.PushAndConstruct<graphics::WorldRenderData*>(); currentFrameData.WorldRenderData[0] = currentFrameData.FrameMemory.PushAndConstruct<graphics::WorldRenderData>(); currentFrameData.WorldRenderData[0]->RenderCTX = currentFrameData.FrameMemory.PushAndConstruct<graphics::RenderContext>(); currentFrameData.WorldRenderData[0]->DebugRenderCTX = currentFrameData.FrameMemory.PushAndConstruct<graphics::DebugRenderContext>(); graphics::g_DebugRenderContext = currentFrameData.WorldRenderData[0]->DebugRenderCTX; currentFrameData.WorldRenderData[0]->RenderCTX->IsWireframe = isWireframe; // Update Phase! { // Poll Events and Update Input accordingly Game->RawInputSystem->Update(); // Measure time and update clocks! const u64 lastTime = currentTime; currentTime = SDL_GetPerformanceCounter(); f32 dtSeconds = (f32)(currentTime - lastTime) / cpuFrequency; // This usually happens once we hit a breakpoint when debugging if (dtSeconds > 0.25f) dtSeconds = 1.0f / TargetFrameRate; // Update Clocks g_RealTimeClock.Update(dtSeconds); g_EditingClock.Update(dtSeconds); g_InGameClock.Update(dtSeconds); // Imgui ImGui_ImplSdlGL3_NewFrame(Game->RenderState->Window); ImGuizmo::BeginFrame(); ImVec2 mainBarSize; // Main Menu Bar if (ImGui::BeginMainMenuBar()) { mainBarSize = ImGui::GetWindowSize(); if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Save layout")) { ImGui::SaveDock(); } if (ImGui::MenuItem("Exit")) { Game->RawInputSystem->RequestClose(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Shader")) { if (ImGui::MenuItem("Reload changed shaders")) { auto it = g_Managers->ShaderManager->begin(); auto end = g_Managers->ShaderManager->end(); while (it != end) { it->ReloadShader(); ++it; } } ImGui::EndMenu(); } if (Game->Mode == GameState::GameMode::EditMode) { if (ImGui::MenuItem("Start Playmode")) { Game->Mode = GameState::GameMode::PlayMode; g_EditingClock.SetPaused(true); g_InGameClock.SetPaused(false); // Cleanup PlayMode stack Game->PlayModeStack.Reset(); Game->ActiveWorld = Game->PlayModeStack.Push<GameWorld>(); // Copy World from Edit mode over // CopyGameWorld(Game->ActiveWorld, Game->WorldEdit->GetWorld()); } } else if (Game->Mode == GameState::GameMode::PlayMode) { if (ImGui::MenuItem("Stop Playmode")) { Game->Mode = GameState::GameMode::EditMode; g_EditingClock.SetPaused(false); g_InGameClock.SetPaused(true); Game->ActiveWorld->Shutdown(); Game->ActiveWorld->~GameWorld(); Game->ActiveWorld = Game->WorldEdit->GetWorld(); } } if (ImGui::MenuItem("Spawn Duck Actor")) { auto actor = Game->ActiveWorld->CreateActor<Actor>(); auto staticMesh = actor->RegisterComponent<StaticMeshComponent>("DuckModel", Transform()); /*std::ofstream o("pretty.json"); nlohmann::json j; actor->Serialize(j); o << std::setw(4) << j << std::endl;*/ } // Shift all the way to the right ImGui::SameLine(ImGui::GetWindowWidth() - 200); ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::EndMainMenuBar(); } // Create Main Window vec2 adjustedDisplaySize = ImGui::GetIO().DisplaySize; adjustedDisplaySize.y -= mainBarSize.y; ImGui::SetNextWindowPos(ImVec2(0, mainBarSize.y)); ImGui::SetNextWindowSize(adjustedDisplaySize, ImGuiCond_Always); bool isContentVisible = ImGui::Begin("###content", 0, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoInputs); Assert(isContentVisible); ImGui::BeginDockspace(); // Imgui Window for MainViewport mainGameWindow.AddToImgui(); // Game Logic g_MessagingSystem.Update(); mainGameWindow.Update(dtSeconds); // Also updates the world Game->WorldEdit->Update(); AddImguiTweakers(); ImGui::EndDockspace(); ImGui::End(); ImGui::Render(); // Just generates statements to be rendered, doesnt actually render! } // PreRender Phase! { // Copying imgui render data to context ImDrawData* drawData = currentFrameData.FrameMemory.Push<ImDrawData>(); *drawData = *ImGui::GetDrawData(); ImDrawList** newList = currentFrameData.FrameMemory.Push<ImDrawList*>(drawData->CmdListsCount); // Create copies of cmd lists for (int i = 0; i < drawData->CmdListsCount; ++i) { // Copy this list! ImDrawList* drawList = drawData->CmdLists[i]; newList[i] = currentFrameData.FrameMemory.Push<ImDrawList>(); ImDrawList* copiedDrawList = newList[i]; // Create copies of copiedDrawList->CmdBuffer = ImVector<ImDrawCmd>(); CopyImVector<ImDrawCmd>(&copiedDrawList->CmdBuffer, &drawList->CmdBuffer, currentFrameData.FrameMemory); copiedDrawList->IdxBuffer = ImVector<ImDrawIdx>(); CopyImVector<ImDrawIdx>(&copiedDrawList->IdxBuffer, &drawList->IdxBuffer, currentFrameData.FrameMemory); copiedDrawList->VtxBuffer = ImVector<ImDrawVert>(); CopyImVector<ImDrawVert>(&copiedDrawList->VtxBuffer, &drawList->VtxBuffer, currentFrameData.FrameMemory); } drawData->CmdLists = newList; // Set Imgui Render Data currentFrameData.ImOverlayDrawData = drawData; graphics::RenderQueue* rq = currentFrameData.FrameMemory.Push<graphics::RenderQueue>(); // ToDo(Faaux)(Graphics): This needs to be a dynamic amount of renderables rq->Renderables = currentFrameData.FrameMemory.Push<graphics::Renderable>(250); rq->Count = 0; // Get all actors that need to be drawn for (auto& actor : Game->ActiveWorld->GetAllActors()) { // Check if we have a Mesh associated auto staticMeshes = actor->GetComponentsOfType(StaticMeshComponent::GetClassType()); for (auto& sm : staticMeshes) { auto staticMesh = (StaticMeshComponent*)sm; auto model = g_Managers->ModelManager->Exists(staticMesh->GetRenderable()); Assert(model); Assert(!rq->Shader || rq->Shader == &model->shader); rq->Shader = &model->shader; rq->Renderables[rq->Count].Model = model; rq->Renderables[rq->Count].ModelMatrix = staticMesh->GetGlobalModelMatrix(); rq->Count++; } } if (rq->Count != 0) currentFrameData.WorldRenderData[0]->RenderCTX->AddRenderQueue(rq); currentFrameData.WorldRenderData[0]->Window = &mainGameWindow; currentFrameData.IsPreRenderDone = true; } // Render Phase { previousFrameData.RenderDone.WaitAndReset(); Game->RenderState->FrameDataToRender = &currentFrameData; Game->RenderState->RenderCondition.Signal(); currentFrameData.DoubleBufferDone.WaitAndReset(); } Game->CurrentFrameIdx++; } Game->GameIsRunning = false; g_JobQueueShutdownRequested = true; Cleanup(); return 0; }
35.403433
100
0.582798
Faaux
d244ca6df6310dae68ec5d4d358bbb96b796fe5e
7,257
hxx
C++
src/mirrage/asset/include/mirrage/asset/asset_manager.hxx
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
14
2017-10-26T08:45:54.000Z
2021-04-06T11:44:17.000Z
src/mirrage/asset/include/mirrage/asset/asset_manager.hxx
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
17
2017-10-09T20:11:58.000Z
2018-11-08T22:05:14.000Z
src/mirrage/asset/include/mirrage/asset/asset_manager.hxx
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
1
2018-09-26T23:10:06.000Z
2018-09-26T23:10:06.000Z
#pragma once #ifndef MIRRAGE_ASSETMANAGER_INCLUDED #include "asset_manager.hpp" #endif #ifndef __clang_analyzer__ #include <async++.h> #endif namespace mirrage::asset { template <class R> auto Ptr<R>::get_blocking() const -> const R& { if(_cached_result) return *_cached_result; return *(_cached_result = &_task.get()); } template <class R> auto Ptr<R>::get_if_ready() const -> util::maybe<const R&> { if(_cached_result) return util::justPtr(_cached_result); return ready() ? util::nothing : util::maybe<const R&>(get_blocking()); } template <class R> auto Ptr<R>::ready() const -> bool { return _task.valid() && _task.ready(); } template <class R> void Ptr<R>::reset() { _aid = {}; _task = {}; _cached_result = nullptr; } namespace detail { template <class T> struct has_reload { private: typedef char one; typedef long two; template <typename C> static one test(decltype(std::declval<Loader<C>>().reload(std::declval<istream>(), std::declval<C&>()))*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(nullptr)) == sizeof(char) }; }; template <class T> constexpr auto has_reload_v = has_reload<T>::value; template <class TaskType, class T> constexpr auto is_task_v = std::is_same_v<T, ::async::task<TaskType>> || std::is_same_v<T, ::async::shared_task<TaskType>>; template <typename T> auto Asset_container<T>::load(AID aid, const std::string& path, bool cache) -> Ptr<T> { auto lock = std::scoped_lock{_container_mutex}; auto found = _assets.find(path); if(found != _assets.end()) return {aid, found->second.task}; // not found => load // clang-format off auto loading = async::spawn([path = std::string(path), aid, this] { return Loader<T>::load(_manager._open(aid, path)); }).share(); // clang-format on if(cache) _assets.try_emplace(path, Asset{aid, loading, _manager._last_modified(path)}); return {aid, loading}; } template <typename T> void Asset_container<T>::save(const AID& aid, const std::string& name, const T& obj) { auto lock = std::scoped_lock{_container_mutex}; Loader<T>::save(_manager._open_rw(aid, name), obj); auto found = _assets.find(name); if(found != _assets.end() && &found.value().task.get() != &obj) { _reload_asset(found.value(), found.key()); // replace existing value } } template <typename T> void Asset_container<T>::shrink_to_fit() noexcept { auto lock = std::scoped_lock{_container_mutex}; util::erase_if(_assets, [](const auto& v) { return v.second.task.refcount() <= 1; }); } template <typename T> void Asset_container<T>::reload() { auto lock = std::scoped_lock{_container_mutex}; for(auto&& entry : _assets) { auto last_mod = _manager._last_modified(entry.first); if(last_mod > entry.second.last_modified) { _reload_asset(const_cast<Asset&>(entry.second), entry.first); } } } // TODO: test if this actually works template <typename T> void Asset_container<T>::_reload_asset(Asset& asset, const std::string& path) { auto& old_value = const_cast<T&>(asset.task.get()); asset.last_modified = _manager._last_modified(path); if constexpr(has_reload_v<T>) { Loader<T>::reload(_manager._open(asset.aid, path), old_value); } else { auto new_value = Loader<T>::load(_manager._open(asset.aid, path)); if constexpr(std::is_same_v<decltype(new_value), async::task<T>>) { old_value = std::move(new_value.get()); } else if constexpr(std::is_same_v<decltype(new_value), async::shared_task<T>>) { old_value = std::move(const_cast<T&>(new_value.get())); } else { old_value = std::move(new_value); } } // TODO: notify other systems about change } } // namespace detail template <typename T> auto Asset_manager::load(const AID& id, bool cache) -> Ptr<T> { auto path = resolve(id); if(path.is_nothing()) throw std::system_error(Asset_error::resolve_failed, id.str()); auto&& container = _find_container<T>(); if(container.is_nothing()) throw std::system_error(Asset_error::stateful_loader_not_initialized, util::type_name<T>()); return container.get_or_throw().load(id, path.get_or_throw(), cache); } template <typename T> auto Asset_manager::load_maybe(const AID& id, bool cache) -> util::maybe<Ptr<T>> { auto path = resolve(id); if(path.is_nothing()) return util::nothing; return _find_container<T>().process([&](detail::Asset_container<T>& container) { return container.load(id, path.get_or_throw(), cache); }); } template <typename T> void Asset_manager::save(const AID& id, const T& asset) { auto path = resolve(id, false); if(path.is_nothing()) throw std::system_error(Asset_error::resolve_failed, id.str()); auto container = _find_container<T>(); if(container.is_nothing()) throw std::system_error(Asset_error::stateful_loader_not_initialized, id.str()); container.get_or_throw().save(id, path.get_or_throw(), asset); } template <typename T> void Asset_manager::save(const Ptr<T>& asset) { save(asset.aid(), *asset); } template <typename T, typename... Args> void Asset_manager::create_stateful_loader(Args&&... args) { auto key = util::type_uid_of<T>(); auto lock = std::scoped_lock{_containers_mutex}; auto container = _containers.find(key); if(container == _containers.end()) { _containers.emplace( key, std::make_unique<detail::Asset_container<T>>(*this, std::forward<Args>(args)...)); } } template <typename T> void Asset_manager::remove_stateful_loader() { auto lock = std::scoped_lock{_containers_mutex}; _containers.erase(util::type_uid_of<T>()); } template <typename T> auto Asset_manager::load_stream(asset::istream stream) -> Ptr<T> { auto container = _find_container<T>(); if(container.is_nothing()) throw std::system_error(Asset_error::stateful_loader_not_initialized, util::type_name<T>()); auto new_value = container.get_or_throw().load(std::move(stream)); if constexpr(std::is_same_v<decltype(new_value), async::task<T>>) return Ptr<T>(stream.aid(), new_value.share()); else if constexpr(std::is_same_v<decltype(new_value), async::shared_task<T>>) return Ptr<T>(stream.aid(), std::move(new_value)); else return Ptr<T>(stream.aid(), async::make_task(std::move(new_value)).share()); } template <typename T> auto Asset_manager::_find_container() -> util::maybe<detail::Asset_container<T>&> { auto key = util::type_uid_of<T>(); auto lock = std::scoped_lock{_containers_mutex}; auto container = _containers.find(key); if(container != _containers.end()) { return util::justPtr(static_cast<detail::Asset_container<T>*>(&*container->second)); } // no container for T, yet if constexpr(std::is_default_constructible_v<Loader<T>>) { container = _containers.emplace(key, std::make_unique<detail::Asset_container<T>>(*this)).first; return util::justPtr(static_cast<detail::Asset_container<T>*>(&*container->second)); } else { return util::nothing; } } } // namespace mirrage::asset
27.384906
103
0.668596
lowkey42
d248323b3cd912d5d4b11c311addd99d0b59a569
593
hpp
C++
multiview/multiview_cpp/src/perceive/calibration/position-scene-cameras/config.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
5
2021-09-03T23:12:08.000Z
2022-03-04T21:43:32.000Z
multiview/multiview_cpp/src/perceive/calibration/position-scene-cameras/config.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
3
2021-09-08T02:57:46.000Z
2022-02-26T05:33:02.000Z
multiview/multiview_cpp/src/perceive/calibration/position-scene-cameras/config.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
2
2021-09-26T03:14:40.000Z
2022-01-26T06:42:52.000Z
#pragma once namespace perceive::calibration::position_scene_cameras { // ---------------------------------------------------------------------- config struct Config { bool show_help = false; bool has_error = false; string outdir = "/tmp"s; string scene_id = ""s; string manifest_fname = ""s; string cube_key = ""s; string cube_filename = ""s; bool use_fast_distort = false; }; void show_help(string argv0); Config parse_command_line(int argc, char** argv) noexcept; } // namespace perceive::calibration::position_scene_cameras
23.72
80
0.58516
prcvlabs
d24aa6ef3cc44a99bd9fb72d93286b63ff625193
2,605
cpp
C++
Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/TestEuropeanOptionPriceCurve.cpp
bondxue/Option-Pricing-Model
5f22df0ff31e90fd536eb216c5af19c697fb87b2
[ "MIT" ]
null
null
null
Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/TestEuropeanOptionPriceCurve.cpp
bondxue/Option-Pricing-Model
5f22df0ff31e90fd536eb216c5af19c697fb87b2
[ "MIT" ]
null
null
null
Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/TestEuropeanOptionPriceCurve.cpp
bondxue/Option-Pricing-Model
5f22df0ff31e90fd536eb216c5af19c697fb87b2
[ "MIT" ]
null
null
null
//TestEuropeanOptionPriceCurve.cpp //purpose: source file to display European Put and Call option prices on one Excel sheet //author: bondxue //version: 1.0 21/01/2017 #include <iostream> #include <cmath> #include <list> #include <string> #include <iostream> #include "EuropeanOption.hpp" #include "Mesher.hpp" #include "ExcelDriverLite.hpp" #include "Utilities.hpp" using namespace std; using namespace OPTION; using namespace OPTION::EUROPEANOPTION; int main() { //// Batch 1 data //double T = 0.25; //double K = 65.0; //double sig = 0.30; //double r = 0.08; //double b = r; // b = r for stock option model //double S = 60.0; //// Batch 2 data //double T = 1.0; //double K = 100.0; //double sig = 0.20; //double r = 0.0; //double b = r; // b = r for stock option model //double S = 100.0; //// Batch 3 data //double T = 1.0; //double K = 10.0; //double sig = 0.50; //double r = 0.12; //double b = r; // b = r for stock option model //double S = 5.0; // Batch 4 data double T = 30.0; double K = 100.0; double sig = 0.30; double r = 0.08; double b = r; // b = r for stock option model double S = 100.0; EuropeanOption Batch(Euro_OptionData(S, K, T, r, sig, b), EuroCall); // create an European call option object double start_S = Batch.S() * 0.5; // set the start value as 0.05 times of stock price of the batch double end_S = start_S * 5.0; // set the end value as 5 times of initial value int num_S = 40; // set the number of stock prices we need vector<double> S_vec = CreateMesh(start_S, end_S, num_S); // create a vector of of monotonically increasing stock prices cout << "stock price vector: " << endl; print(S_vec); // print the stock price vector cout << endl; vector<double> C_vec = Batch.Price_S(S_vec); // create a vector to store a sequence of call prices Batch.Type(EuroPut); // set the option type as European put vector<double> P_vec = Batch.Price_S(S_vec); // create a vector to store a sequence of put prices long N = 40; ExcelDriver xl; xl.MakeVisible(true); xl.CreateChart(S_vec, C_vec, "Call price"); xl.CreateChart(S_vec, P_vec, "Put price"); // C++11 style initializer lists // std::list<std::string> labels{ "Call price", "Put price" }; std::list<std::string> labels; labels.push_back("Call price"); labels.push_back("Put price"); // C++11 style initializer lists // std::list<std::vector<double>> curves{ C_vec, P_vec }; std::list<std::vector<double>> curves; curves.push_back(C_vec); curves.push_back(P_vec); xl.CreateChart(S_vec, labels, curves, "Option Prices", "S", "V"); return 0; }
28.626374
121
0.667946
bondxue
d24c668e49c2c6fadf027cfe75345dc94e38326a
1,000
cpp
C++
SDL/Game9/SpriteComponent.cpp
blAs1N/C-programming
3ab83a00dab6e3d9cfe97c514115308ad2333387
[ "MIT" ]
4
2018-06-17T11:47:16.000Z
2018-10-01T14:01:55.000Z
SDL/Game9/SpriteComponent.cpp
blAs1N/TIL
3ab83a00dab6e3d9cfe97c514115308ad2333387
[ "MIT" ]
null
null
null
SDL/Game9/SpriteComponent.cpp
blAs1N/TIL
3ab83a00dab6e3d9cfe97c514115308ad2333387
[ "MIT" ]
null
null
null
#include "SpriteComponent.h" #include "Actor.h" #include "Game.h" #include "Renderer.h" #include "Shader.h" #include "Texture.h" SpriteComponent::SpriteComponent(Actor* inOwner, const int inDrawOrder) : Component(inOwner), texture(nullptr), drawOrder(inDrawOrder), width(0), height(0) { owner->GetGame()->GetRenderer()->AddSpriteComponent(this); } SpriteComponent::~SpriteComponent() { owner->GetGame()->GetRenderer()->RemoveSpriteComponent(this); } void SpriteComponent::Draw(Shader* shader) { if (texture) { const auto imageScale = Matrix4::CreateScale( static_cast<float>(width), static_cast<float>(height), 1.0f ); const auto transform = imageScale * owner->GetWorldTransform(); shader->SetUniformValue("uWorldTransform", transform); texture->SetActive(); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr); } } void SpriteComponent::SetTexture(Texture* inTexture) { texture = inTexture; width = texture->GetWidth(); height = texture->GetHeight(); }
23.809524
71
0.73
blAs1N
d24d90941574c88a92f21570307214a2bf5acb18
4,903
cpp
C++
path.cpp
Ocisra/file_manager
cfb88aac368a789c1330b5d9fc8c3d0703b60c2b
[ "MIT" ]
null
null
null
path.cpp
Ocisra/file_manager
cfb88aac368a789c1330b5d9fc8c3d0703b60c2b
[ "MIT" ]
null
null
null
path.cpp
Ocisra/file_manager
cfb88aac368a789c1330b5d9fc8c3d0703b60c2b
[ "MIT" ]
null
null
null
#include "path.hpp" #include "config.hpp" #include "miller.hpp" #include <filesystem> #include <set> #include <ncurses.h> #include "libft-detect.hpp" /** * Populate the content of a directory * * @param content: content to populate * @param path: path tracked by the content */ static void populateContent(Content *content, const fs::path &path) { if (fs::is_empty(path)) { content->addVirtual("empty"); return; } for (auto &p : fs::directory_iterator(path)) { Entry *entry = new Entry; entry->path = p.path(); entry->filetype = ft_finder->getFiletype(p.path()); content->entries.emplace(entry); } } Entry::~Entry() { delete filetype; } void Content::addVirtual(std::string text) { Entry *entry = new Entry; entry->filetype = nullptr; entry->isVirtual = true; entry->path = text; entries.emplace(entry); } /** * Get the filetype of the Nth element * * @param n: element of which to find the filetype */ lft::filetype *Content::getFileType(unsigned int n) { return ft_finder->getFiletype(getNthElement(entries, n)->path); } /** * Get the file at a specific line */ Entry *Content::getFileByLine(unsigned int line) { return getNthElement(entries, line); } /** * Get the Nth element of a set * * @param s: set to query * @param n: number of the element */ Entry *Content::getNthElement(std::set<Entry *, decltype(contentSort)> &s, unsigned int n) { typename std::set<Entry *>::iterator it = s.begin(); for (unsigned i = 0; i < n; i++) it++; return *it; } Content::~Content() { for (auto &e : entries) { delete e; } } Path::Path(fs::path start_path) { if (start_path.string().ends_with('/') && start_path.string() != "/") setPath(start_path.parent_path()); else setPath(start_path); setCurrent(new Content); setChild(new Content); populateContent(current(), path()); populateContent(child(), current()->getFileByLine(0)->path); if (path().string() != "/") { setParent(new Content); populateContent(parent(), path().parent_path()); } else setParent(nullptr); } Path::~Path() { if (parent() != nullptr) delete parent(); delete current(); delete child(); } /** * Go up a directory */ bool Path::goUp() { setPath(path().parent_path()); delete child(); setChild(current()); setCurrent(parent()); if (path().string() != "/") { setParent(new Content); populateContent(parent(), path().parent_path()); return true; } else { setParent(nullptr); return false; } } /** * Go down a directory */ void Path::goDown() { setPath(current()->getFileByLine(miller->middle()->line())->path); Content *tmp = parent(); setParent(current()); setCurrent(child()); setChild(new Content); try { // This line is dangerous because the function need access to the content of a // directory we are not sure exists or is readable populateContent(child(), path()); delete tmp; } catch (const fs::filesystem_error &e) { log->debug(e.what()); setPath(path().parent_path()); delete child(); setChild(current()); setCurrent(parent()); setParent(tmp); } } /** * Preview the child directory in the right panel * * @param win: window in which to preview */ void Path::previewChild(Window *win) { wclear(win->win); delete child(); setChild(new Content); auto setWindow = [](Window *win, int sizey, int startx, int starty) { win->sizey = sizey; win->startx = startx; win->starty = starty; wresize(win->win, win->sizey > win->vsizey ? win->sizey : win->vsizey + 1, win->sizex > win->vsizex ? win->sizex : win->vsizex); }; try { if (fs::is_directory(current()->getFileByLine(miller->middle()->line())->path)) { populateContent(child(), current()->getFileByLine(miller->middle()->line())->path); } } catch (const fs::filesystem_error &e) { child()->addVirtual("not accessible"); log->debug(e.what()); } setWindow(win, child()->numOfEntries(), 0, 0); win->display(child()); prefresh(win->win, win->starty, win->startx, win->posy, win->posx, win->vsizey + win->posy, win->vsizex + win->posx); } /** * Find the index of the specified path */ int Path::find(Content *content, fs::path p) { return getIndex(content->entries, p); } /** * Get the index of an element * * @param s: set to query * @param p: element to find */ int Path::getIndex(std::set<Entry *, decltype(contentSort)> &s, fs::path p) { int c = 0; for (auto &e : s) { if (e->path == p) return c; c++; } return -1; }
24.034314
95
0.587599
Ocisra
d2523be15dde118f8aa468c90dec363da08d3d01
12,971
cpp
C++
ContextNotify/src/Drawer.cpp
crutchwalkfactory/jaikuengine-mobile-client
c47100ec009d47a4045b3d98addc9b8ad887b132
[ "MIT" ]
null
null
null
ContextNotify/src/Drawer.cpp
crutchwalkfactory/jaikuengine-mobile-client
c47100ec009d47a4045b3d98addc9b8ad887b132
[ "MIT" ]
null
null
null
ContextNotify/src/Drawer.cpp
crutchwalkfactory/jaikuengine-mobile-client
c47100ec009d47a4045b3d98addc9b8ad887b132
[ "MIT" ]
null
null
null
// Copyright (c) 2007-2009 Google Inc. // Copyright (c) 2006-2007 Jaiku Ltd. // Copyright (c) 2002-2006 Mika Raento and Renaud Petit // // This software is licensed at your choice under either 1 or 2 below. // // 1. MIT License // // 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. // // 2. Gnu General Public license 2.0 // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // // This file is part of the JaikuEngine mobile client. #include "drawer.h" #include "symbian_auto_ptr.h" #include "break.h" #include "app_context.h" #include "juik_layout_impl.h" #include "jaiku_layoutids.hrh" #include <e32std.h> #include <w32std.h> #include <coedef.h> #include <apgwgnam.h> #ifndef __S80__ #include <aknkeylock.h> #else class RAknKeyLock { public: TInt Connect() { return 0; } void Close() { } TBool IsKeyLockEnabled() { return EFalse; } }; #endif #include <aknsbasicbackgroundcontrolcontext.h> #include <aknsdrawutils.h> #include <aknsutils.h> /* * Concepts: * !Drawing on top of Phone screen! * !UI in EXE! */ const TUid KUidPhone = { 0x100058b3 }; const TUid KUidIdle = { 0x101fd64c }; const TUid KUidMenu = { 0x101f4cd2 }; const TInt KIconSep = 1; class CDrawerImpl : public CDrawer { public: virtual TInt AddIconL(CFbsBitmap* data, CFbsBitmap* mask); virtual void RemoveIcon(TInt Id); virtual void ChangeIconL(CFbsBitmap* data, CFbsBitmap* mask, TInt Id); virtual void GetIcons(TInt* aIds, TInt aSize); virtual void SetBackgroundL(TInt aHandle); CDrawerImpl(RWsSession& aWsSession); virtual ~CDrawerImpl(); virtual void ForegroundChanged(CApaWindowGroupName* gn); virtual void ScreenChanged(); void ConstructL(); void StartL(); void Listen(); void Release(); void Draw(const TRect& aRect); void ReadLayoutL(); void RunL(); TInt RunError(TInt aError); void DoCancel(); void ReadSize(); TBool reception_bar_on_screen(); void CopyBackground(); RWsSession& iWsSession; CWindowGc* gc; CWsScreenDevice* screen; RWindowGroup wg; bool wg_is_open; RWindow w; bool w_is_open; RAknKeyLock iKeyLock; bool kl_is_open; TUid iCurrentAppUid, iPreviousAppUid, iSecondPreviousAppUid; RPointerArray<CFbsBitmap> iIcons; RPointerArray<CFbsBitmap> iMasks; bool full_redraw; CFbsBitmap* iBackground; //CFbsBitmap* iBackgroundCopy; CJuikLayout* iLayout; CAknsBasicBackgroundControlContext* iBackgroundControlContext; TSize iScreenSize; // cached screensize, because reading it from CWsScreenDevice causes flush }; CDrawer::CDrawer(CActive::TPriority aPriority) : CActive(aPriority) { } CDrawer::~CDrawer() { } void CDrawerImpl::GetIcons(TInt* aIds, TInt aSize) { TInt i=0, j=0; while (i<iIcons.Count() && j<aSize) { if (iIcons[i] && iMasks[i]) { aIds[j]=iIcons[i]->Handle(); j++; aIds[j]=iMasks[i]->Handle(); j++; } i++; } } void CDrawerImpl::ReadSize() { TSize s(0, 0); TInt i=0; while (i<iIcons.Count()) { if (iIcons[i]) { TSize is=iIcons[i]->SizeInPixels(); s.iWidth+=is.iWidth+KIconSep; if (is.iHeight > s.iHeight) s.iHeight=is.iHeight; } i++; } w.SetSize(s); } CDrawer* CDrawer::NewL(RWsSession& aWsSession) { auto_ptr<CDrawerImpl> ret(new (ELeave) CDrawerImpl(aWsSession)); ret->ConstructL(); return ret.release(); } TInt CDrawerImpl::AddIconL(CFbsBitmap* aIcon, CFbsBitmap* aMask) { User::LeaveIfError(iIcons.Append(aIcon)); TInt err=iMasks.Append(aMask); if (err!=KErrNone) { iIcons.Remove(iIcons.Count()-1); User::Leave(err); } ReadSize(); full_redraw=true; Draw(TRect()); return iIcons.Count()-1; } void CDrawerImpl::SetBackgroundL(TInt aHandle) { if (!iBackground) { iBackground=new (ELeave) CFbsBitmap; } iBackground->Reset(); User::LeaveIfError(iBackground->Duplicate(aHandle)); } void CDrawerImpl::RemoveIcon(TInt Id) { if (Id<0 || Id >= iIcons.Count()) return; delete iIcons[Id]; iIcons[Id]=0; delete iMasks[Id]; iMasks[Id]=0; ReadSize(); full_redraw=true; Draw(TRect()); } void CDrawerImpl::ChangeIconL(CFbsBitmap* data, CFbsBitmap* aMask, TInt Id) { if (Id<0 || Id >= iIcons.Count()) User::Leave(KErrNotFound); delete iIcons[Id]; iIcons[Id]=data; delete iMasks[Id]; iMasks[Id]=aMask; ReadSize(); full_redraw=true; Draw(TRect()); } CDrawerImpl::CDrawerImpl(RWsSession& aWsSession) : CDrawer(EPriorityHigh), iWsSession(aWsSession) { } void CDrawerImpl::ReadLayoutL() { TInt mode=screen->CurrentScreenMode(); TPixelsAndRotation sz_and_rot; screen->GetScreenModeSizeAndRotation(mode, sz_and_rot); iScreenSize=sz_and_rot.iPixelSize; iLayout->UpdateLayoutDataL(iScreenSize); TJuikLayoutItem l = iLayout->GetLayoutItemL( LG_idleview_connection_icon, LI_idleview_connection_icon__icon ); TSize ws=w.Size(); w.SetExtent( l.Rect().iTl, ws ); } void CDrawerImpl::ScreenChanged() { ReadLayoutL(); TRect screenRect( TPoint(0,0), iScreenSize ); delete iBackgroundControlContext; iBackgroundControlContext = NULL; iBackgroundControlContext = CAknsBasicBackgroundControlContext::NewL(KAknsIIDQsnBgScreenIdle, screenRect, EFalse); // if ( iBackgroundCopy ) // { // delete iBackgroundCopy; // iBackgroundCopy = NULL; // } // iBackgroundCopy = new (ELeave) CFbsBitmap(); // User::LeaveIfError(iBackgroundCopy->Create(screenSize, displayMode)); full_redraw=true; Draw(TRect()); } void CDrawerImpl::ConstructL() { iLayout = CJuikLayout::NewL(EFalse); AknsUtils::InitSkinSupportL(); screen=new (ELeave) CWsScreenDevice(iWsSession); User::LeaveIfError(screen->Construct()); User::LeaveIfError(screen->CreateContext(gc)); wg=RWindowGroup(iWsSession); User::LeaveIfError(wg.Construct((TUint32)&wg, EFalse)); wg_is_open=true; wg.SetOrdinalPosition(1, ECoeWinPriorityAlwaysAtFront+1); wg.EnableReceiptOfFocus(EFalse); CApaWindowGroupName* wn=CApaWindowGroupName::NewLC(iWsSession); wn->SetHidden(ETrue); wn->SetWindowGroupName(wg); CleanupStack::PopAndDestroy(); w=RWindow(iWsSession); User::LeaveIfError(w.Construct(wg, (TUint32)&w)); w_is_open=true; w.Activate(); w.SetExtent( TPoint(0, 0), TSize(0, 0) ); ReadLayoutL(); TRect screenRect( TPoint(0,0), MJuikLayout::ScreenSize()); iBackgroundControlContext = CAknsBasicBackgroundControlContext::NewL(KAknsIIDQsnBgScreenIdle, screenRect, EFalse); // TSize screenSize = screen->SizeInPixels(); // TDisplayMode displayMode = screen->DisplayMode(); // if ( iBackgroundCopy ) // { // delete iBackgroundCopy; // iBackgroundCopy = NULL; // } // iBackgroundCopy = new (ELeave) CFbsBitmap(); // User::LeaveIfError(iBackgroundCopy->Create(screenSize, displayMode)); // CopyBackground(); w.SetOrdinalPosition(1, ECoeWinPriorityAlwaysAtFront+1); w.SetNonFading(EFalse); TInt wgid=iWsSession.GetFocusWindowGroup(); CApaWindowGroupName* gn; gn=CApaWindowGroupName::NewLC(iWsSession, wgid); ForegroundChanged(gn); CleanupStack::PopAndDestroy(); TInt err=iKeyLock.Connect(); if (err==KErrNone) kl_is_open=true; CActiveScheduler::Add(this); Listen(); } CDrawerImpl::~CDrawerImpl() { Cancel(); int i; for (i=0; i<iIcons.Count(); i++) { delete iIcons[i]; delete iMasks[i]; } iIcons.Close(); iMasks.Close(); delete gc; delete screen; if (w_is_open) w.Close(); if (wg_is_open) wg.Close(); if (kl_is_open) iKeyLock.Close(); delete iBackground; delete iBackgroundControlContext; // delete iBackgroundCopy; delete iLayout; } void CDrawerImpl::StartL() { } void CDrawerImpl::Listen() { iStatus=KRequestPending; iWsSession.RedrawReady(&iStatus); SetActive(); } void CDrawerImpl::Release() { } void CDrawerImpl::RunL() { TWsRedrawEvent e; iWsSession.GetRedraw(e); CopyBackground(); Draw(e.Rect()); Listen(); } void CDrawerImpl::CopyBackground() { // if ( iBackgroundCopy ) // { // TInt err = screen->CopyScreenToBitmap( iBackgroundCopy ); // } } void CDrawerImpl::Draw(const TRect& serverRect) { TRect aRect=serverRect; gc->Activate(w); if (full_redraw) { aRect=TRect(TPoint(0,0), w.Size()); } full_redraw=false; //w.HandleTransparencyUpdate(); //TInt err = w.SetTransparencyAlphaChannel(); w.Invalidate(aRect); w.BeginRedraw(); // Draw background if ( iBackground ) { TRect sourceRect( aRect ); gc->BitBlt(TPoint(0,0), iBackground, sourceRect); } else if ( iBackgroundControlContext ) { TPoint dstPosInCanvas(0,0); TRect partOfBackground( w.AbsPosition(), w.Size() ); TBool skinBackgroundDrawn = AknsDrawUtils::DrawBackground( AknsUtils::SkinInstance(), iBackgroundControlContext, NULL, *gc, dstPosInCanvas, partOfBackground, KAknsDrawParamLimitToFirstLevel); // KAknsDrawParamDefault); } // else if ( iBackgroundCopy ) // { // TPoint p = w.AbsPosition(); // TSize s = w.Size(); // TRect sourceRect( p, s ); // gc->BitBlt(TPoint(0,0), iBackgroundCopy, sourceRect); // } else { // gc->SetPenStyle(CGraphicsContext::ENullPen); // gc->SetBrushColor(KRgbWhite); // gc->SetBrushStyle(CGraphicsContext::ESolidBrush); // gc->DrawRect(aRect); TRgb backgroundColour(100,100,100); // backgroundColour.SetAlpha(0x50); gc->SetBrushStyle(CGraphicsContext::ESolidBrush); gc->SetBrushColor(backgroundColour); gc->Clear(); } gc->SetBrushStyle(CGraphicsContext::ENullBrush); int xpos=0, i; for (i=0; i<iIcons.Count(); i++) { if (iIcons[i]!=0 && iMasks[i]!=0) { xpos+=KIconSep; TRect r( TPoint(0, 0), iIcons[i]->SizeInPixels()); gc->BitBltMasked(TPoint(xpos, 0), iIcons[i], r, iMasks[i], ETrue); xpos+=r.Width(); } } w.EndRedraw(); gc->Deactivate(); iWsSession.Flush(); } TInt CDrawerImpl::RunError(TInt aError) { return aError; } void CDrawerImpl::DoCancel() { iWsSession.RedrawReadyCancel(); } void CDrawerImpl::ForegroundChanged(CApaWindowGroupName* gn) { TUid AppUid=gn->AppUid(); RDebug::Print(_L("%u"), AppUid.iUid); iSecondPreviousAppUid = iPreviousAppUid; iPreviousAppUid = iCurrentAppUid; iCurrentAppUid = AppUid; #ifdef __WINS__ if ( iCurrentAppUid==KUidMenu || iCurrentAppUid==KUidPhone || iCurrentAppUid==KUidIdle ) { w.SetVisible(ETrue); } else { w.SetVisible(EFalse); } #else if (iCurrentAppUid==KUidPhone #ifdef __S60V3__ || iCurrentAppUid==KUidIdle #endif ) { w.SetVisible(ETrue); } else if (iCurrentAppUid==KNullUid) { //First, getting keylock status if (!kl_is_open) { TInt err=iKeyLock.Connect(); if (err==KErrNone) kl_is_open=true; } // Then many cases: if ( kl_is_open && iKeyLock.IsKeyLockEnabled() ) { // Keyboard is closed if (iPreviousAppUid == KUidPhone) { // we locked the screen on the phone app -> display indicators // even if the screensaver goes on, no new uid event is generated, // so looking at the first previous one should be enough. w.SetVisible(ETrue); } else if ( (iPreviousAppUid == KNullUid) && (iSecondPreviousAppUid == KUidPhone) ) { w.SetVisible(ETrue); } else { w.SetVisible(EFalse); } } else { // Keyboard is not closed w.SetVisible(EFalse); // we are displaying either the app menu, or the power menu, // but both have KNullUid, so no difference possible -> no display } } else { w.SetVisible(EFalse); } #endif }
24.24486
97
0.704726
crutchwalkfactory
d25542995768c153bea9ec40493608959bf66467
11,764
hpp
C++
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSail_Parent_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSail_Parent_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSail_Parent_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItem_Spawner_HoverSail_Parent_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass PrimalItem_Spawner_HoverSail_Parent.PrimalItem_Spawner_HoverSail_Parent_C // 0x0180 (0x0E68 - 0x0CE8) class UPrimalItem_Spawner_HoverSail_Parent_C : public UPrimalItem_DinoSpawner_Base_C { public: int NumSpawnAttempts; // 0x0CE8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData00[0x4]; // 0x0CEC(0x0004) MISSED OFFSET class AShooterCharacter* CraftingShooterChar; // 0x0CF0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData01[0x8]; // 0x0CF8(0x0008) MISSED OFFSET struct UObject_FTransform SpawnTransform; // 0x0D00(0x0030) (Edit, BlueprintVisible, DisableEditOnInstance, IsPlainOldData) class FString SkiffSpawnString; // 0x0D30(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) class APrimalDinoCharacter* spawned_dino; // 0x0D40(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData) float allowed_distance_to_despawn_hoversail; // 0x0D48(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool should_have_a_spawned_dino; // 0x0D4C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, SaveGame, IsPlainOldData) unsigned char UnknownData02[0x3]; // 0x0D4D(0x0003) MISSED OFFSET class FString lost_reference_string; // 0x0D50(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) bool could_find_a_valid_location_next_to_target; // 0x0D60(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData03[0x7]; // 0x0D61(0x0007) MISSED OFFSET class FString usetofollowstring; // 0x0D68(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) class FString use_to_deploy_string; // 0x0D78(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) class FString use_to_put_away_string; // 0x0D88(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) bool show_appropriate_item_description_based_on_state___not_working_on_dedi;// 0x0D98(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool CallFunc_GetDinoColorizationData_HasAnyColorData; // 0x0D99(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData04[0x6]; // 0x0D9A(0x0006) MISSED OFFSET TArray<unsigned char> CallFunc_GetDinoColorizationData_ColorData; // 0x0DA0(0x0010) (ZeroConstructor, Transient, DuplicateTransient) int Temp_int_Variable; // 0x0DB0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char CallFunc_Conv_IntToByte_ReturnValue; // 0x0DB4(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_IsValid_ReturnValue; // 0x0DB5(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char CallFunc_GetValidIndex_ReturnValue; // 0x0DB6(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) TEnumAsByte<ENetworkModeResult> CallFunc_IsRunningOnServer_OutNetworkMode; // 0x0DB7(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) int CallFunc_Conv_ByteToInt_ReturnValue; // 0x0DB8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool K2Node_SwitchEnum_CmpSuccess; // 0x0DBC(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_LessEqual_IntInt_ReturnValue; // 0x0DBD(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData05[0x2]; // 0x0DBE(0x0002) MISSED OFFSET int CallFunc_GetDinoStat_NumDinoLevels; // 0x0DC0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) int CallFunc_GetDinoStat_StatMapIndexUsed; // 0x0DC4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_GetDinoStat_Success; // 0x0DC8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData06[0x3]; // 0x0DC9(0x0003) MISSED OFFSET int CallFunc_Add_IntInt_ReturnValue; // 0x0DCC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) int CallFunc_MakeLiteralInt_ReturnValue; // 0x0DD0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FVector CallFunc_BreakTransform_Location; // 0x0DD4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FRotator CallFunc_BreakTransform_Rotation; // 0x0DE0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FVector CallFunc_BreakTransform_Scale; // 0x0DEC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_Less_IntInt_ReturnValue; // 0x0DF8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData07[0x7]; // 0x0DF9(0x0007) MISSED OFFSET class UWorld* CallFunc_K2_GetWorld_ReturnValue; // 0x0E00(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class AController* CallFunc_GetCharacterController_ReturnValue; // 0x0E08(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class AShooterPlayerController* K2Node_DynamicCast_AsShooterPlayerController; // 0x0E10(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool K2Node_DynamicCast_CastSuccess; // 0x0E18(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData08[0x7]; // 0x0E19(0x0007) MISSED OFFSET class AActor* CallFunc_GetOwner_ReturnValue; // 0x0E20(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class APrimalDinoCharacter* CallFunc_SpawnCustomDino_ReturnValue; // 0x0E28(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class AGameState* CallFunc_GetGameState_ReturnValue; // 0x0E30(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FVector CallFunc_K2_GetActorLocation_ReturnValue; // 0x0E38(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_IsValid_ReturnValue2; // 0x0E44(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData09[0x3]; // 0x0E45(0x0003) MISSED OFFSET struct FVector CallFunc_FindValidLocationNextToTarget_OutLocation; // 0x0E48(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_FindValidLocationNextToTarget_ReturnValue; // 0x0E54(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_K2_SetActorLocation_ReturnValue; // 0x0E55(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData10[0x2]; // 0x0E56(0x0002) MISSED OFFSET float CallFunc_RandomFloatInRange_ReturnValue; // 0x0E58(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FRotator CallFunc_MakeRot_ReturnValue; // 0x0E5C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass PrimalItem_Spawner_HoverSail_Parent.PrimalItem_Spawner_HoverSail_Parent_C"); return ptr; } class FString BPGetItemDescription(class FString* InDescription, bool* bGetLongDescription, class AShooterPlayerController** ForPC); void notify_hoversail_destroyed(); void Delaymount(); bool BPCanUse(bool* bIgnoreCooldown); void SpawnCraftedSkiff(); void ExecuteUbergraph_PrimalItem_Spawner_HoverSail_Parent(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
116.475248
231
0.562734
2bite
d259620e891f8515d136f8a63fab93fdf75ca5c7
902
cpp
C++
NativeLibrary/WriteStream.cpp
Const-me/ComLightInterop
3968aee5e1b61c71cb70245c93a1b05f00df2cb8
[ "MIT" ]
22
2019-08-27T13:59:26.000Z
2022-02-18T07:40:36.000Z
NativeLibrary/WriteStream.cpp
Const-me/ComLightInterop
3968aee5e1b61c71cb70245c93a1b05f00df2cb8
[ "MIT" ]
2
2021-04-14T13:07:48.000Z
2021-10-16T16:32:20.000Z
NativeLibrary/WriteStream.cpp
Const-me/ComLightInterop
3968aee5e1b61c71cb70245c93a1b05f00df2cb8
[ "MIT" ]
2
2019-10-10T00:14:08.000Z
2022-02-03T03:42:36.000Z
#include "stdafx.h" #include "WriteStream.h" HRESULT WriteStream::write( const void* lpBuffer, int nNumberOfBytesToWrite ) { if( nullptr == m_file ) return OLE_E_BLANK; if( nNumberOfBytesToWrite < 0 ) return E_INVALIDARG; const size_t cb = (size_t)nNumberOfBytesToWrite; const size_t written = fwrite( lpBuffer, 1, cb, m_file ); if( cb == written ) return S_OK; return CTL_E_DEVICEIOERROR; } HRESULT WriteStream::flush() { if( nullptr == m_file ) return OLE_E_BLANK; if( 0 == fflush( m_file ) ) return S_OK; return CTL_E_DEVICEIOERROR; } HRESULT WriteStream::createFile( LPCTSTR path ) { if( nullptr != m_file ) { fclose( m_file ); m_file = nullptr; } #ifdef _MSC_VER const auto e = _wfopen_s( &m_file, path, L"wb" ); return ( 0 == e ) ? S_OK : CTL_E_DEVICEIOERROR; #else m_file = fopen( path, "wb" ); return ( nullptr != m_file ) ? S_OK : CTL_E_DEVICEIOERROR; #endif }
22.55
77
0.694013
Const-me
d25c22d9c0902ad11ab22ba6494471bb44d17a26
1,077
cpp
C++
src/quiz/quiz01a.cpp
msu-csc232-fa20/lectures
194a93cef456e29099c99147fbb1f645df07fc69
[ "MIT" ]
null
null
null
src/quiz/quiz01a.cpp
msu-csc232-fa20/lectures
194a93cef456e29099c99147fbb1f645df07fc69
[ "MIT" ]
null
null
null
src/quiz/quiz01a.cpp
msu-csc232-fa20/lectures
194a93cef456e29099c99147fbb1f645df07fc69
[ "MIT" ]
null
null
null
/** * CSC232 - Data Structures * Missouri State University, Fall 2020 * * Quiz 1 * * @author Jim Daehn <jdaehn@missouristate.edu> * @file quiz01.cpp */ #include <cstdlib> #include <iostream> #define FALSE 0 #define TRUE 1 #define USE_CODE_ON_QUIZ TRUE #define USE_ANSWER FALSE int main() { // These were the assumptions listed in Question 1 const int ARRAY_SIZE = 4; int i; int n; int data[ARRAY_SIZE]; #if USE_CODE_ON_QUIZ // To reveal the answer to Question 1, we repeat the code // in Question 2 here... for (i = 0, n = 4; i < n; ++i) { std::cout << "Enter data[" << i << "]: "; std::cin >> data[i]; } #endif // the following macro-guard is not part of the answer; it's // just here prevent this code from executing #if USE_ANSWER // an equivalent while loop is shown below (Question 2) i = 0; n = 4; while (i < n) { std::cout << "Enter data[" << i << "]: "; std::cin >> data[i]; ++i; } #endif // And now we're done return EXIT_SUCCESS; }
18.568966
61
0.581244
msu-csc232-fa20
d25e979d9a463a3a6bc35fa187d2422758fffb77
1,067
cc
C++
third_party/blink/renderer/core/execution_context/agent.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/execution_context/agent.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/execution_context/agent.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 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 "third_party/blink/renderer/core/execution_context/agent.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/mutation_observer.h" #include "third_party/blink/renderer/platform/scheduler/public/event_loop.h" namespace blink { Agent::Agent(v8::Isolate* isolate, const base::UnguessableToken& cluster_id, std::unique_ptr<v8::MicrotaskQueue> microtask_queue) : event_loop_(base::AdoptRef( new scheduler::EventLoop(isolate, std::move(microtask_queue)))), cluster_id_(cluster_id) {} Agent::~Agent() = default; void Agent::Trace(Visitor* visitor) {} void Agent::AttachDocument(Document* document) { event_loop_->AttachScheduler(document->GetScheduler()); } void Agent::DetachDocument(Document* document) { event_loop_->DetachScheduler(document->GetScheduler()); } } // namespace blink
32.333333
76
0.743205
sarang-apps
d25f4202a845b7f46bcef8f818fcce2d9267fe50
21,886
cpp
C++
apiwznm/PnlWznmSteAAction.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
3
2020-09-20T16:24:48.000Z
2021-12-01T19:44:51.000Z
apiwznm/PnlWznmSteAAction.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
apiwznm/PnlWznmSteAAction.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
/** * \file PnlWznmSteAAction.cpp * API code for job PnlWznmSteAAction (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 5 Dec 2020 */ // IP header --- ABOVE #include "PnlWznmSteAAction.h" using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class PnlWznmSteAAction::VecVDo ******************************************************************************/ uint PnlWznmSteAAction::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butnewclick") return BUTNEWCLICK; if (s == "butduplicateclick") return BUTDUPLICATECLICK; if (s == "butdeleteclick") return BUTDELETECLICK; if (s == "butrefreshclick") return BUTREFRESHCLICK; return(0); }; string PnlWznmSteAAction::VecVDo::getSref( const uint ix ) { if (ix == BUTNEWCLICK) return("ButNewClick"); if (ix == BUTDUPLICATECLICK) return("ButDuplicateClick"); if (ix == BUTDELETECLICK) return("ButDeleteClick"); if (ix == BUTREFRESHCLICK) return("ButRefreshClick"); return(""); }; /****************************************************************************** class PnlWznmSteAAction::ContInf ******************************************************************************/ PnlWznmSteAAction::ContInf::ContInf( const uint numFCsiQst ) : Block() { this->numFCsiQst = numFCsiQst; mask = {NUMFCSIQST}; }; bool PnlWznmSteAAction::ContInf::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContInfWznmSteAAction"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemInfWznmSteAAction"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFCsiQst", numFCsiQst)) add(NUMFCSIQST); }; return basefound; }; set<uint> PnlWznmSteAAction::ContInf::comm( const ContInf* comp ) { set<uint> items; if (numFCsiQst == comp->numFCsiQst) insert(items, NUMFCSIQST); return(items); }; set<uint> PnlWznmSteAAction::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {NUMFCSIQST}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmSteAAction::StatApp ******************************************************************************/ PnlWznmSteAAction::StatApp::StatApp( const uint ixWznmVExpstate ) : Block() { this->ixWznmVExpstate = ixWznmVExpstate; mask = {IXWZNMVEXPSTATE}; }; bool PnlWznmSteAAction::StatApp::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string srefIxWznmVExpstate; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppWznmSteAAction"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemAppWznmSteAAction"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "srefIxWznmVExpstate", srefIxWznmVExpstate)) { ixWznmVExpstate = VecWznmVExpstate::getIx(srefIxWznmVExpstate); add(IXWZNMVEXPSTATE); }; }; return basefound; }; set<uint> PnlWznmSteAAction::StatApp::comm( const StatApp* comp ) { set<uint> items; if (ixWznmVExpstate == comp->ixWznmVExpstate) insert(items, IXWZNMVEXPSTATE); return(items); }; set<uint> PnlWznmSteAAction::StatApp::diff( const StatApp* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {IXWZNMVEXPSTATE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmSteAAction::StatShr ******************************************************************************/ PnlWznmSteAAction::StatShr::StatShr( const bool ButNewAvail , const bool ButDuplicateAvail , const bool ButDuplicateActive , const bool ButDeleteAvail , const bool ButDeleteActive ) : Block() { this->ButNewAvail = ButNewAvail; this->ButDuplicateAvail = ButDuplicateAvail; this->ButDuplicateActive = ButDuplicateActive; this->ButDeleteAvail = ButDeleteAvail; this->ButDeleteActive = ButDeleteActive; mask = {BUTNEWAVAIL, BUTDUPLICATEAVAIL, BUTDUPLICATEACTIVE, BUTDELETEAVAIL, BUTDELETEACTIVE}; }; bool PnlWznmSteAAction::StatShr::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrWznmSteAAction"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemShrWznmSteAAction"; if (basefound) { if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButNewAvail", ButNewAvail)) add(BUTNEWAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDuplicateAvail", ButDuplicateAvail)) add(BUTDUPLICATEAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDuplicateActive", ButDuplicateActive)) add(BUTDUPLICATEACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDeleteAvail", ButDeleteAvail)) add(BUTDELETEAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDeleteActive", ButDeleteActive)) add(BUTDELETEACTIVE); }; return basefound; }; set<uint> PnlWznmSteAAction::StatShr::comm( const StatShr* comp ) { set<uint> items; if (ButNewAvail == comp->ButNewAvail) insert(items, BUTNEWAVAIL); if (ButDuplicateAvail == comp->ButDuplicateAvail) insert(items, BUTDUPLICATEAVAIL); if (ButDuplicateActive == comp->ButDuplicateActive) insert(items, BUTDUPLICATEACTIVE); if (ButDeleteAvail == comp->ButDeleteAvail) insert(items, BUTDELETEAVAIL); if (ButDeleteActive == comp->ButDeleteActive) insert(items, BUTDELETEACTIVE); return(items); }; set<uint> PnlWznmSteAAction::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {BUTNEWAVAIL, BUTDUPLICATEAVAIL, BUTDUPLICATEACTIVE, BUTDELETEAVAIL, BUTDELETEACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmSteAAction::StgIac ******************************************************************************/ PnlWznmSteAAction::StgIac::StgIac( const uint TcoSctWidth , const uint TcoTypWidth , const uint TcoTrjWidth , const uint TcoVecWidth , const uint TcoVitWidth , const uint TcoSnxWidth , const uint TcoSeqWidth , const uint TcoTr1Width , const uint TcoIp1Width , const uint TcoTr2Width , const uint TcoIp2Width , const uint TcoTr3Width , const uint TcoIp3Width , const uint TcoTr4Width , const uint TcoIp4Width ) : Block() { this->TcoSctWidth = TcoSctWidth; this->TcoTypWidth = TcoTypWidth; this->TcoTrjWidth = TcoTrjWidth; this->TcoVecWidth = TcoVecWidth; this->TcoVitWidth = TcoVitWidth; this->TcoSnxWidth = TcoSnxWidth; this->TcoSeqWidth = TcoSeqWidth; this->TcoTr1Width = TcoTr1Width; this->TcoIp1Width = TcoIp1Width; this->TcoTr2Width = TcoTr2Width; this->TcoIp2Width = TcoIp2Width; this->TcoTr3Width = TcoTr3Width; this->TcoIp3Width = TcoIp3Width; this->TcoTr4Width = TcoTr4Width; this->TcoIp4Width = TcoIp4Width; mask = {TCOSCTWIDTH, TCOTYPWIDTH, TCOTRJWIDTH, TCOVECWIDTH, TCOVITWIDTH, TCOSNXWIDTH, TCOSEQWIDTH, TCOTR1WIDTH, TCOIP1WIDTH, TCOTR2WIDTH, TCOIP2WIDTH, TCOTR3WIDTH, TCOIP3WIDTH, TCOTR4WIDTH, TCOIP4WIDTH}; }; bool PnlWznmSteAAction::StgIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StgIacWznmSteAAction"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StgitemIacWznmSteAAction"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoSctWidth", TcoSctWidth)) add(TCOSCTWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoTypWidth", TcoTypWidth)) add(TCOTYPWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoTrjWidth", TcoTrjWidth)) add(TCOTRJWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoVecWidth", TcoVecWidth)) add(TCOVECWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoVitWidth", TcoVitWidth)) add(TCOVITWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoSnxWidth", TcoSnxWidth)) add(TCOSNXWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoSeqWidth", TcoSeqWidth)) add(TCOSEQWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoTr1Width", TcoTr1Width)) add(TCOTR1WIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoIp1Width", TcoIp1Width)) add(TCOIP1WIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoTr2Width", TcoTr2Width)) add(TCOTR2WIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoIp2Width", TcoIp2Width)) add(TCOIP2WIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoTr3Width", TcoTr3Width)) add(TCOTR3WIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoIp3Width", TcoIp3Width)) add(TCOIP3WIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoTr4Width", TcoTr4Width)) add(TCOTR4WIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoIp4Width", TcoIp4Width)) add(TCOIP4WIDTH); }; return basefound; }; void PnlWznmSteAAction::StgIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StgIacWznmSteAAction"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StgitemIacWznmSteAAction"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "TcoSctWidth", TcoSctWidth); writeUintAttr(wr, itemtag, "sref", "TcoTypWidth", TcoTypWidth); writeUintAttr(wr, itemtag, "sref", "TcoTrjWidth", TcoTrjWidth); writeUintAttr(wr, itemtag, "sref", "TcoVecWidth", TcoVecWidth); writeUintAttr(wr, itemtag, "sref", "TcoVitWidth", TcoVitWidth); writeUintAttr(wr, itemtag, "sref", "TcoSnxWidth", TcoSnxWidth); writeUintAttr(wr, itemtag, "sref", "TcoSeqWidth", TcoSeqWidth); writeUintAttr(wr, itemtag, "sref", "TcoTr1Width", TcoTr1Width); writeUintAttr(wr, itemtag, "sref", "TcoIp1Width", TcoIp1Width); writeUintAttr(wr, itemtag, "sref", "TcoTr2Width", TcoTr2Width); writeUintAttr(wr, itemtag, "sref", "TcoIp2Width", TcoIp2Width); writeUintAttr(wr, itemtag, "sref", "TcoTr3Width", TcoTr3Width); writeUintAttr(wr, itemtag, "sref", "TcoIp3Width", TcoIp3Width); writeUintAttr(wr, itemtag, "sref", "TcoTr4Width", TcoTr4Width); writeUintAttr(wr, itemtag, "sref", "TcoIp4Width", TcoIp4Width); xmlTextWriterEndElement(wr); }; set<uint> PnlWznmSteAAction::StgIac::comm( const StgIac* comp ) { set<uint> items; if (TcoSctWidth == comp->TcoSctWidth) insert(items, TCOSCTWIDTH); if (TcoTypWidth == comp->TcoTypWidth) insert(items, TCOTYPWIDTH); if (TcoTrjWidth == comp->TcoTrjWidth) insert(items, TCOTRJWIDTH); if (TcoVecWidth == comp->TcoVecWidth) insert(items, TCOVECWIDTH); if (TcoVitWidth == comp->TcoVitWidth) insert(items, TCOVITWIDTH); if (TcoSnxWidth == comp->TcoSnxWidth) insert(items, TCOSNXWIDTH); if (TcoSeqWidth == comp->TcoSeqWidth) insert(items, TCOSEQWIDTH); if (TcoTr1Width == comp->TcoTr1Width) insert(items, TCOTR1WIDTH); if (TcoIp1Width == comp->TcoIp1Width) insert(items, TCOIP1WIDTH); if (TcoTr2Width == comp->TcoTr2Width) insert(items, TCOTR2WIDTH); if (TcoIp2Width == comp->TcoIp2Width) insert(items, TCOIP2WIDTH); if (TcoTr3Width == comp->TcoTr3Width) insert(items, TCOTR3WIDTH); if (TcoIp3Width == comp->TcoIp3Width) insert(items, TCOIP3WIDTH); if (TcoTr4Width == comp->TcoTr4Width) insert(items, TCOTR4WIDTH); if (TcoIp4Width == comp->TcoIp4Width) insert(items, TCOIP4WIDTH); return(items); }; set<uint> PnlWznmSteAAction::StgIac::diff( const StgIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TCOSCTWIDTH, TCOTYPWIDTH, TCOTRJWIDTH, TCOVECWIDTH, TCOVITWIDTH, TCOSNXWIDTH, TCOSEQWIDTH, TCOTR1WIDTH, TCOIP1WIDTH, TCOTR2WIDTH, TCOIP2WIDTH, TCOTR3WIDTH, TCOIP3WIDTH, TCOTR4WIDTH, TCOIP4WIDTH}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmSteAAction::Tag ******************************************************************************/ PnlWznmSteAAction::Tag::Tag( const string& Cpt , const string& TxtRecord1 , const string& TxtRecord2 , const string& Trs , const string& TxtShowing1 , const string& TxtShowing2 , const string& TcoSct , const string& TcoTyp , const string& TcoTrj , const string& TcoVec , const string& TcoVit , const string& TcoSnx , const string& TcoSeq , const string& TcoTr1 , const string& TcoIp1 , const string& TcoTr2 , const string& TcoIp2 , const string& TcoTr3 , const string& TcoIp3 , const string& TcoTr4 , const string& TcoIp4 ) : Block() { this->Cpt = Cpt; this->TxtRecord1 = TxtRecord1; this->TxtRecord2 = TxtRecord2; this->Trs = Trs; this->TxtShowing1 = TxtShowing1; this->TxtShowing2 = TxtShowing2; this->TcoSct = TcoSct; this->TcoTyp = TcoTyp; this->TcoTrj = TcoTrj; this->TcoVec = TcoVec; this->TcoVit = TcoVit; this->TcoSnx = TcoSnx; this->TcoSeq = TcoSeq; this->TcoTr1 = TcoTr1; this->TcoIp1 = TcoIp1; this->TcoTr2 = TcoTr2; this->TcoIp2 = TcoIp2; this->TcoTr3 = TcoTr3; this->TcoIp3 = TcoIp3; this->TcoTr4 = TcoTr4; this->TcoIp4 = TcoIp4; mask = {CPT, TXTRECORD1, TXTRECORD2, TRS, TXTSHOWING1, TXTSHOWING2, TCOSCT, TCOTYP, TCOTRJ, TCOVEC, TCOVIT, TCOSNX, TCOSEQ, TCOTR1, TCOIP1, TCOTR2, TCOIP2, TCOTR3, TCOIP3, TCOTR4, TCOIP4}; }; bool PnlWznmSteAAction::Tag::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagWznmSteAAction"); else basefound = checkXPath(docctx, basexpath); string itemtag = "TagitemWznmSteAAction"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Cpt", Cpt)) add(CPT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtRecord1", TxtRecord1)) add(TXTRECORD1); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtRecord2", TxtRecord2)) add(TXTRECORD2); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Trs", Trs)) add(TRS); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtShowing1", TxtShowing1)) add(TXTSHOWING1); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtShowing2", TxtShowing2)) add(TXTSHOWING2); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoSct", TcoSct)) add(TCOSCT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoTyp", TcoTyp)) add(TCOTYP); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoTrj", TcoTrj)) add(TCOTRJ); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoVec", TcoVec)) add(TCOVEC); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoVit", TcoVit)) add(TCOVIT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoSnx", TcoSnx)) add(TCOSNX); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoSeq", TcoSeq)) add(TCOSEQ); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoTr1", TcoTr1)) add(TCOTR1); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoIp1", TcoIp1)) add(TCOIP1); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoTr2", TcoTr2)) add(TCOTR2); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoIp2", TcoIp2)) add(TCOIP2); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoTr3", TcoTr3)) add(TCOTR3); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoIp3", TcoIp3)) add(TCOIP3); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoTr4", TcoTr4)) add(TCOTR4); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoIp4", TcoIp4)) add(TCOIP4); }; return basefound; }; /****************************************************************************** class PnlWznmSteAAction::DpchAppData ******************************************************************************/ PnlWznmSteAAction::DpchAppData::DpchAppData( const string& scrJref , StgIac* stgiac , QryWznmSteAAction::StgIac* stgiacqry , const set<uint>& mask ) : DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMSTEAACTIONDATA, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, STGIAC, STGIACQRY}; else this->mask = mask; if (find(this->mask, STGIAC) && stgiac) this->stgiac = *stgiac; if (find(this->mask, STGIACQRY) && stgiacqry) this->stgiacqry = *stgiacqry; }; string PnlWznmSteAAction::DpchAppData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(STGIAC)) ss.push_back("stgiac"); if (has(STGIACQRY)) ss.push_back("stgiacqry"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmSteAAction::DpchAppData::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmSteAActionData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(STGIAC)) stgiac.writeXML(wr); if (has(STGIACQRY)) stgiacqry.writeXML(wr); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWznmSteAAction::DpchAppDo ******************************************************************************/ PnlWznmSteAAction::DpchAppDo::DpchAppDo( const string& scrJref , const uint ixVDo , const set<uint>& mask ) : DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMSTEAACTIONDO, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO}; else this->mask = mask; this->ixVDo = ixVDo; }; string PnlWznmSteAAction::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmSteAAction::DpchAppDo::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmSteAActionDo"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo)); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWznmSteAAction::DpchEngData ******************************************************************************/ PnlWznmSteAAction::DpchEngData::DpchEngData() : DpchEngWznm(VecWznmVDpch::DPCHENGWZNMSTEAACTIONDATA) { feedFCsiQst.tag = "FeedFCsiQst"; }; string PnlWznmSteAAction::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(CONTINF)) ss.push_back("continf"); if (has(FEEDFCSIQST)) ss.push_back("feedFCsiQst"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(STGIAC)) ss.push_back("stgiac"); if (has(TAG)) ss.push_back("tag"); if (has(RST)) ss.push_back("rst"); if (has(STATAPPQRY)) ss.push_back("statappqry"); if (has(STATSHRQRY)) ss.push_back("statshrqry"); if (has(STGIACQRY)) ss.push_back("stgiacqry"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmSteAAction::DpchEngData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngWznmSteAActionData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF); if (continf.readXML(docctx, basexpath, true)) add(CONTINF); if (feedFCsiQst.readXML(docctx, basexpath, true)) add(FEEDFCSIQST); if (statapp.readXML(docctx, basexpath, true)) add(STATAPP); if (statshr.readXML(docctx, basexpath, true)) add(STATSHR); if (stgiac.readXML(docctx, basexpath, true)) add(STGIAC); if (tag.readXML(docctx, basexpath, true)) add(TAG); if (rst.readXML(docctx, basexpath, true)) add(RST); if (statappqry.readXML(docctx, basexpath, true)) add(STATAPPQRY); if (statshrqry.readXML(docctx, basexpath, true)) add(STATSHRQRY); if (stgiacqry.readXML(docctx, basexpath, true)) add(STGIACQRY); } else { continf = ContInf(); feedFCsiQst.clear(); statapp = StatApp(); statshr = StatShr(); stgiac = StgIac(); tag = Tag(); rst.clear(); statappqry = QryWznmSteAAction::StatApp(); statshrqry = QryWznmSteAAction::StatShr(); stgiacqry = QryWznmSteAAction::StgIac(); }; };
33.984472
209
0.674861
mpsitech
d25f7144b9c0a7df5bf6730782097d00adeb27ee
779
cpp
C++
TabGraph/src/Common.cpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
1
2020-08-28T09:35:18.000Z
2020-08-28T09:35:18.000Z
TabGraph/src/Common.cpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
null
null
null
TabGraph/src/Common.cpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
1
2020-10-08T11:21:13.000Z
2020-10-08T11:21:13.000Z
/* * @Author: gpinchon * @Date: 2020-08-27 18:48:19 * @Last Modified by: gpinchon * @Last Modified time: 2021-01-11 08:42:39 */ #include "Common.hpp" #include <glm/vec3.hpp> static glm::vec3 s_up(0, 1, 0); static glm::vec3 s_forward(0, 0, -1); static glm::vec3 s_right(1, 0, 0); static glm::vec3 s_gravity(0, -9.81, 0); glm::vec3 Common::Up() { return s_up; } void Common::SetUp(glm::vec3 up) { s_up = up; } glm::vec3 Common::Forward() { return s_forward; } void Common::SetForward(glm::vec3 up) { s_forward = up; } glm::vec3 Common::Right() { return s_right; } void Common::SetRight(glm::vec3 up) { s_right = up; } glm::vec3 Common::Gravity() { return s_gravity; } void Common::SetGravity(glm::vec3 gravity) { s_gravity = gravity; }
14.425926
42
0.634146
Gpinchon
d26095c87fa7d7e53d68bdb03faed399795558f5
81,548
cpp
C++
Source/ThirdParty/ANGLE/src/libANGLE/renderer/glslang_wrapper_utils.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/ThirdParty/ANGLE/src/libANGLE/renderer/glslang_wrapper_utils.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/ThirdParty/ANGLE/src/libANGLE/renderer/glslang_wrapper_utils.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
// // Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Wrapper for Khronos glslang compiler. // #include "libANGLE/renderer/glslang_wrapper_utils.h" // glslang has issues with some specific warnings. ANGLE_DISABLE_EXTRA_SEMI_WARNING ANGLE_DISABLE_SHADOWING_WARNING // glslang's version of ShaderLang.h, not to be confused with ANGLE's. #include <glslang/Public/ShaderLang.h> // Other glslang includes. #include <SPIRV/GlslangToSpv.h> #include <StandAlone/ResourceLimits.h> ANGLE_REENABLE_SHADOWING_WARNING ANGLE_REENABLE_EXTRA_SEMI_WARNING // SPIR-V headers include for AST transformation. #include <spirv/unified1/spirv.hpp> // SPIR-V tools include for AST validation. #include <spirv-tools/libspirv.hpp> #include <array> #include <numeric> #include "common/FixedVector.h" #include "common/string_utils.h" #include "common/utilities.h" #include "libANGLE/Caps.h" #include "libANGLE/ProgramLinkedResources.h" #include "libANGLE/trace.h" #define ANGLE_GLSLANG_CHECK(CALLBACK, TEST, ERR) \ do \ { \ if (ANGLE_UNLIKELY(!(TEST))) \ { \ return CALLBACK(ERR); \ } \ \ } while (0) namespace rx { namespace { constexpr char kXfbDeclMarker[] = "@@ XFB-DECL @@"; constexpr char kXfbOutMarker[] = "@@ XFB-OUT @@;"; constexpr char kXfbBuiltInPrefix[] = "xfbANGLE"; template <size_t N> constexpr size_t ConstStrLen(const char (&)[N]) { static_assert(N > 0, "C++ shouldn't allow N to be zero"); // The length of a string defined as a char array is the size of the array minus 1 (the // terminating '\0'). return N - 1; } void GetBuiltInResourcesFromCaps(const gl::Caps &caps, TBuiltInResource *outBuiltInResources) { outBuiltInResources->maxDrawBuffers = caps.maxDrawBuffers; outBuiltInResources->maxAtomicCounterBindings = caps.maxAtomicCounterBufferBindings; outBuiltInResources->maxAtomicCounterBufferSize = caps.maxAtomicCounterBufferSize; outBuiltInResources->maxClipPlanes = caps.maxClipPlanes; outBuiltInResources->maxCombinedAtomicCounterBuffers = caps.maxCombinedAtomicCounterBuffers; outBuiltInResources->maxCombinedAtomicCounters = caps.maxCombinedAtomicCounters; outBuiltInResources->maxCombinedImageUniforms = caps.maxCombinedImageUniforms; outBuiltInResources->maxCombinedTextureImageUnits = caps.maxCombinedTextureImageUnits; outBuiltInResources->maxCombinedShaderOutputResources = caps.maxCombinedShaderOutputResources; outBuiltInResources->maxComputeWorkGroupCountX = caps.maxComputeWorkGroupCount[0]; outBuiltInResources->maxComputeWorkGroupCountY = caps.maxComputeWorkGroupCount[1]; outBuiltInResources->maxComputeWorkGroupCountZ = caps.maxComputeWorkGroupCount[2]; outBuiltInResources->maxComputeWorkGroupSizeX = caps.maxComputeWorkGroupSize[0]; outBuiltInResources->maxComputeWorkGroupSizeY = caps.maxComputeWorkGroupSize[1]; outBuiltInResources->maxComputeWorkGroupSizeZ = caps.maxComputeWorkGroupSize[2]; outBuiltInResources->minProgramTexelOffset = caps.minProgramTexelOffset; outBuiltInResources->maxFragmentUniformVectors = caps.maxFragmentUniformVectors; outBuiltInResources->maxFragmentInputComponents = caps.maxFragmentInputComponents; outBuiltInResources->maxGeometryInputComponents = caps.maxGeometryInputComponents; outBuiltInResources->maxGeometryOutputComponents = caps.maxGeometryOutputComponents; outBuiltInResources->maxGeometryOutputVertices = caps.maxGeometryOutputVertices; outBuiltInResources->maxGeometryTotalOutputComponents = caps.maxGeometryTotalOutputComponents; outBuiltInResources->maxLights = caps.maxLights; outBuiltInResources->maxProgramTexelOffset = caps.maxProgramTexelOffset; outBuiltInResources->maxVaryingComponents = caps.maxVaryingComponents; outBuiltInResources->maxVaryingVectors = caps.maxVaryingVectors; outBuiltInResources->maxVertexAttribs = caps.maxVertexAttributes; outBuiltInResources->maxVertexOutputComponents = caps.maxVertexOutputComponents; outBuiltInResources->maxVertexUniformVectors = caps.maxVertexUniformVectors; outBuiltInResources->maxClipDistances = caps.maxClipDistances; } // Run at startup to warm up glslang's internals to avoid hitches on first shader compile. void GlslangWarmup() { ANGLE_TRACE_EVENT0("gpu.angle,startup", "GlslangWarmup"); EShMessages messages = static_cast<EShMessages>(EShMsgSpvRules | EShMsgVulkanRules); // EShMessages messages = EShMsgDefault; TBuiltInResource builtInResources(glslang::DefaultTBuiltInResource); glslang::TShader dummyShader(EShLangVertex); const char *kShaderString = R"(#version 450 core void main(){} )"; const int kShaderLength = static_cast<int>(strlen(kShaderString)); dummyShader.setStringsWithLengths(&kShaderString, &kShaderLength, 1); dummyShader.setEntryPoint("main"); bool result = dummyShader.parse(&builtInResources, 450, ECoreProfile, false, false, messages); ASSERT(result); } // Test if there are non-zero indices in the uniform name, returning false in that case. This // happens for multi-dimensional arrays, where a uniform is created for every possible index of the // array (except for the innermost dimension). When assigning decorations (set/binding/etc), only // the indices corresponding to the first element of the array should be specified. This function // is used to skip the other indices. // // If useOldRewriteStructSamplers, there are multiple samplers extracted out of struct arrays // though, so the above only applies to the sampler array defined in the struct. bool UniformNameIsIndexZero(const std::string &name, bool excludeCheckForOwningStructArrays) { size_t lastBracketClose = 0; if (excludeCheckForOwningStructArrays) { size_t lastDot = name.find_last_of('.'); if (lastDot != std::string::npos) { lastBracketClose = lastDot; } } while (true) { size_t openBracket = name.find('[', lastBracketClose); if (openBracket == std::string::npos) { break; } size_t closeBracket = name.find(']', openBracket); // If the index between the brackets is not zero, ignore this uniform. if (name.substr(openBracket + 1, closeBracket - openBracket - 1) != "0") { return false; } lastBracketClose = closeBracket; } return true; } bool MappedSamplerNameNeedsUserDefinedPrefix(const std::string &originalName) { return originalName.find('.') == std::string::npos; } template <typename OutputIter, typename ImplicitIter> uint32_t CountExplicitOutputs(OutputIter outputsBegin, OutputIter outputsEnd, ImplicitIter implicitsBegin, ImplicitIter implicitsEnd) { auto reduce = [implicitsBegin, implicitsEnd](uint32_t count, const sh::ShaderVariable &var) { bool isExplicit = std::find(implicitsBegin, implicitsEnd, var.name) == implicitsEnd; return count + isExplicit; }; return std::accumulate(outputsBegin, outputsEnd, 0, reduce); } ShaderInterfaceVariableInfo *AddShaderInterfaceVariable(ShaderInterfaceVariableInfoMap *infoMap, const std::string &varName) { ASSERT(infoMap->find(varName) == infoMap->end()); return &(*infoMap)[varName]; } ShaderInterfaceVariableInfo *GetShaderInterfaceVariable(ShaderInterfaceVariableInfoMap *infoMap, const std::string &varName) { ASSERT(infoMap->find(varName) != infoMap->end()); return &(*infoMap)[varName]; } ShaderInterfaceVariableInfo *AddResourceInfoToAllStages(ShaderInterfaceVariableInfoMap *infoMap, const std::string &varName, uint32_t descriptorSet, uint32_t binding) { gl::ShaderBitSet allStages; allStages.set(); ShaderInterfaceVariableInfo *info = AddShaderInterfaceVariable(infoMap, varName); info->descriptorSet = descriptorSet; info->binding = binding; info->activeStages = allStages; return info; } ShaderInterfaceVariableInfo *AddResourceInfo(ShaderInterfaceVariableInfoMap *infoMap, const std::string &varName, uint32_t descriptorSet, uint32_t binding, const gl::ShaderType shaderType) { gl::ShaderBitSet stages; stages.set(shaderType); ShaderInterfaceVariableInfo *info = AddShaderInterfaceVariable(infoMap, varName); info->descriptorSet = descriptorSet; info->binding = binding; info->activeStages = stages; return info; } // Add location information for an in/out variable. ShaderInterfaceVariableInfo *AddLocationInfo(ShaderInterfaceVariableInfoMap *infoMap, const std::string &varName, uint32_t location, uint32_t component, gl::ShaderType stage) { // The info map for this name may or may not exist already. This function merges the // location/component information. ShaderInterfaceVariableInfo *info = &(*infoMap)[varName]; ASSERT(info->descriptorSet == ShaderInterfaceVariableInfo::kInvalid); ASSERT(info->binding == ShaderInterfaceVariableInfo::kInvalid); ASSERT(info->location == ShaderInterfaceVariableInfo::kInvalid); ASSERT(info->component == ShaderInterfaceVariableInfo::kInvalid); info->location = location; info->component = component; info->activeStages.set(stage); return info; } // Modify an existing out variable and add transform feedback information. ShaderInterfaceVariableInfo *SetXfbInfo(ShaderInterfaceVariableInfoMap *infoMap, const std::string &varName, uint32_t xfbBuffer, uint32_t xfbOffset, uint32_t xfbStride) { ShaderInterfaceVariableInfo *info = GetShaderInterfaceVariable(infoMap, varName); ASSERT(info->xfbBuffer == ShaderInterfaceVariableInfo::kInvalid); ASSERT(info->xfbOffset == ShaderInterfaceVariableInfo::kInvalid); ASSERT(info->xfbStride == ShaderInterfaceVariableInfo::kInvalid); info->xfbBuffer = xfbBuffer; info->xfbOffset = xfbOffset; info->xfbStride = xfbStride; return info; } std::string SubstituteTransformFeedbackMarkers(const std::string &originalSource, const std::string &xfbDecl, const std::string &xfbOut) { const size_t xfbDeclMarkerStart = originalSource.find(kXfbDeclMarker); const size_t xfbDeclMarkerEnd = xfbDeclMarkerStart + ConstStrLen(kXfbDeclMarker); const size_t xfbOutMarkerStart = originalSource.find(kXfbOutMarker, xfbDeclMarkerStart); const size_t xfbOutMarkerEnd = xfbOutMarkerStart + ConstStrLen(kXfbOutMarker); // The shader is the following form: // // ..part1.. // @@ XFB-DECL @@ // ..part2.. // @@ XFB-OUT @@; // ..part3.. // // Construct the string by concatenating these five pieces, replacing the markers with the given // values. std::string result; result.append(&originalSource[0], &originalSource[xfbDeclMarkerStart]); result.append(xfbDecl); result.append(&originalSource[xfbDeclMarkerEnd], &originalSource[xfbOutMarkerStart]); result.append(xfbOut); result.append(&originalSource[xfbOutMarkerEnd], &originalSource[originalSource.size()]); return result; } std::string GenerateTransformFeedbackVaryingOutput(const gl::TransformFeedbackVarying &varying, const gl::UniformTypeInfo &info, size_t strideBytes, size_t offset, const std::string &bufferIndex) { std::ostringstream result; ASSERT(strideBytes % 4 == 0); size_t stride = strideBytes / 4; const size_t arrayIndexStart = varying.arrayIndex == GL_INVALID_INDEX ? 0 : varying.arrayIndex; const size_t arrayIndexEnd = arrayIndexStart + varying.size(); for (size_t arrayIndex = arrayIndexStart; arrayIndex < arrayIndexEnd; ++arrayIndex) { for (int col = 0; col < info.columnCount; ++col) { for (int row = 0; row < info.rowCount; ++row) { result << "xfbOut" << bufferIndex << "[" << sh::vk::kDriverUniformsVarName << ".xfbBufferOffsets[" << bufferIndex << "] + (gl_VertexIndex + gl_InstanceIndex * " << sh::vk::kDriverUniformsVarName << ".xfbVerticesPerDraw) * " << stride << " + " << offset << "] = " << info.glslAsFloat << "(" << varying.mappedName; if (varying.isArray()) { result << "[" << arrayIndex << "]"; } if (info.columnCount > 1) { result << "[" << col << "]"; } if (info.rowCount > 1) { result << "[" << row << "]"; } result << ");\n"; ++offset; } } } return result.str(); } void GenerateTransformFeedbackEmulationOutputs(GlslangSourceOptions &options, const gl::ProgramState &programState, GlslangProgramInterfaceInfo *programInterfaceInfo, std::string *vertexShader, ShaderInterfaceVariableInfoMap *variableInfoMapOut) { const std::vector<gl::TransformFeedbackVarying> &varyings = programState.getLinkedTransformFeedbackVaryings(); const std::vector<GLsizei> &bufferStrides = programState.getTransformFeedbackStrides(); const bool isInterleaved = programState.getTransformFeedbackBufferMode() == GL_INTERLEAVED_ATTRIBS; const size_t bufferCount = isInterleaved ? 1 : varyings.size(); const std::string xfbSet = Str(programInterfaceInfo->uniformsAndXfbDescriptorSetIndex); std::vector<std::string> xfbIndices(bufferCount); std::string xfbDecl; for (uint32_t bufferIndex = 0; bufferIndex < bufferCount; ++bufferIndex) { const std::string xfbBinding = Str(programInterfaceInfo->currentUniformBindingIndex); xfbIndices[bufferIndex] = Str(bufferIndex); std::string bufferName = GetXfbBufferName(bufferIndex); xfbDecl += "layout(set = " + xfbSet + ", binding = " + xfbBinding + ") buffer " + bufferName + " { float xfbOut" + Str(bufferIndex) + "[]; };\n"; // Add this entry to the info map, so we can easily assert that every resource has an entry // in this map. AddResourceInfo(variableInfoMapOut, bufferName, programInterfaceInfo->uniformsAndXfbDescriptorSetIndex, programInterfaceInfo->currentUniformBindingIndex, gl::ShaderType::Vertex); ++programInterfaceInfo->currentUniformBindingIndex; } std::string xfbOut = "if (" + std::string(sh::vk::kDriverUniformsVarName) + ".xfbActiveUnpaused != 0)\n{\n"; size_t outputOffset = 0; for (size_t varyingIndex = 0; varyingIndex < varyings.size(); ++varyingIndex) { const size_t bufferIndex = isInterleaved ? 0 : varyingIndex; const gl::TransformFeedbackVarying &varying = varyings[varyingIndex]; // For every varying, output to the respective buffer packed. If interleaved, the output is // always to the same buffer, but at different offsets. const gl::UniformTypeInfo &info = gl::GetUniformTypeInfo(varying.type); xfbOut += GenerateTransformFeedbackVaryingOutput(varying, info, bufferStrides[bufferIndex], outputOffset, xfbIndices[bufferIndex]); if (isInterleaved) { outputOffset += info.columnCount * info.rowCount * varying.size(); } } xfbOut += "}\n"; *vertexShader = SubstituteTransformFeedbackMarkers(*vertexShader, xfbDecl, xfbOut); } bool IsFirstRegisterOfVarying(const gl::PackedVaryingRegister &varyingReg) { const gl::PackedVarying &varying = *varyingReg.packedVarying; // In Vulkan GLSL, struct fields are not allowed to have location assignments. The varying of a // struct type is thus given a location equal to the one assigned to its first field. if (varying.isStructField() && varying.fieldIndex > 0) { return false; } // Similarly, assign array varying locations to the assigned location of the first element. if (varyingReg.varyingArrayIndex != 0 || (varying.isArrayElement() && varying.arrayIndex != 0)) { return false; } // Similarly, assign matrix varying locations to the assigned location of the first row. if (varyingReg.varyingRowIndex != 0) { return false; } return true; } // Calculates XFB layout qualifier arguments for each tranform feedback varying. Stores calculated // values for the SPIR-V transformation. void GenerateTransformFeedbackExtensionOutputs(const gl::ProgramState &programState, const gl::ProgramLinkedResources &resources, std::string *vertexShader, uint32_t *locationsUsedForXfbExtensionOut) { const std::vector<gl::TransformFeedbackVarying> &tfVaryings = programState.getLinkedTransformFeedbackVaryings(); std::string xfbDecl; std::string xfbOut; for (uint32_t varyingIndex = 0; varyingIndex < tfVaryings.size(); ++varyingIndex) { const gl::TransformFeedbackVarying &tfVarying = tfVaryings[varyingIndex]; const std::string &tfVaryingName = tfVarying.mappedName; if (tfVarying.isBuiltIn()) { // For simplicity, create a copy of every builtin that's captured so xfb qualifiers // could be added to that instead. This allows the SPIR-V transformation to ignore // OpMemberName and OpMemberDecorate instructions. Note that capturing gl_Position // already requires such a copy, since the translator modifies this value at the end of // main. Capturing the rest of the built-ins are niche enough that the inefficiency // involved in doing this is not a concern. uint32_t xfbVaryingLocation = resources.varyingPacking.getMaxSemanticIndex() + ++(*locationsUsedForXfbExtensionOut); std::string xfbVaryingName = kXfbBuiltInPrefix + tfVaryingName; // Add declaration and initialization code for the new varying. std::string varyingType = gl::GetGLSLTypeString(tfVarying.type); xfbDecl += "layout(location = " + Str(xfbVaryingLocation) + ") out " + varyingType + " " + xfbVaryingName + ";\n"; xfbOut += xfbVaryingName + " = " + tfVaryingName + ";\n"; } } *vertexShader = SubstituteTransformFeedbackMarkers(*vertexShader, xfbDecl, xfbOut); } void AssignAttributeLocations(const gl::ProgramExecutable &programExecutable, gl::ShaderType stage, ShaderInterfaceVariableInfoMap *variableInfoMapOut) { // Assign attribute locations for the vertex shader. for (const sh::ShaderVariable &attribute : programExecutable.getProgramInputs()) { ASSERT(attribute.active); AddLocationInfo(variableInfoMapOut, attribute.mappedName, attribute.location, ShaderInterfaceVariableInfo::kInvalid, stage); } } void AssignOutputLocations(const gl::ProgramExecutable &programExecutable, const gl::ShaderType shaderType, ShaderInterfaceVariableInfoMap *variableInfoMapOut) { // Assign output locations for the fragment shader. ASSERT(shaderType == gl::ShaderType::Fragment); // TODO(syoussefi): Add support for EXT_blend_func_extended. http://anglebug.com/3385 const auto &outputLocations = programExecutable.getOutputLocations(); const auto &outputVariables = programExecutable.getOutputVariables(); const std::array<std::string, 3> implicitOutputs = {"gl_FragDepth", "gl_SampleMask", "gl_FragStencilRefARB"}; for (const gl::VariableLocation &outputLocation : outputLocations) { if (outputLocation.arrayIndex == 0 && outputLocation.used() && !outputLocation.ignored) { const sh::ShaderVariable &outputVar = outputVariables[outputLocation.index]; uint32_t location = 0; if (outputVar.location != -1) { location = outputVar.location; } else if (std::find(implicitOutputs.begin(), implicitOutputs.end(), outputVar.name) == implicitOutputs.end()) { // If there is only one output, it is allowed not to have a location qualifier, in // which case it defaults to 0. GLSL ES 3.00 spec, section 4.3.8.2. ASSERT(CountExplicitOutputs(outputVariables.begin(), outputVariables.end(), implicitOutputs.begin(), implicitOutputs.end()) == 1); } AddLocationInfo(variableInfoMapOut, outputVar.mappedName, location, ShaderInterfaceVariableInfo::kInvalid, shaderType); } } // When no fragment output is specified by the shader, the translator outputs webgl_FragColor or // webgl_FragData. Add an entry for these. Even though the translator is already assigning // location 0 to these entries, adding an entry for them here allows us to ASSERT that every // shader interface variable is processed during the SPIR-V transformation. This is done when // iterating the ids provided by OpEntryPoint. AddLocationInfo(variableInfoMapOut, "webgl_FragColor", 0, 0, shaderType); AddLocationInfo(variableInfoMapOut, "webgl_FragData", 0, 0, shaderType); } void AssignVaryingLocations(const GlslangSourceOptions &options, const gl::ProgramExecutable &programExecutable, const gl::ShaderType shaderType, GlslangProgramInterfaceInfo *programInterfaceInfo, ShaderMapInterfaceVariableInfoMap *variableInfoMapOut) { uint32_t locationsUsedForEmulation = programInterfaceInfo->locationsUsedForXfbExtension; // Substitute layout and qualifier strings for the position varying added for line raster // emulation. if (options.emulateBresenhamLines) { uint32_t lineRasterEmulationPositionLocation = locationsUsedForEmulation++; AddLocationInfo(&(*variableInfoMapOut)[shaderType], sh::vk::kLineRasterEmulationPosition, lineRasterEmulationPositionLocation, ShaderInterfaceVariableInfo::kInvalid, shaderType); } // Assign varying locations. for (const gl::PackedVaryingRegister &varyingReg : programExecutable.getResources().varyingPacking.getRegisterList()) { if (!IsFirstRegisterOfVarying(varyingReg)) { continue; } const gl::PackedVarying &varying = *varyingReg.packedVarying; uint32_t location = varyingReg.registerRow + locationsUsedForEmulation; uint32_t component = ShaderInterfaceVariableInfo::kInvalid; if (varyingReg.registerColumn > 0) { ASSERT(!varying.varying().isStruct()); ASSERT(!gl::IsMatrixType(varying.varying().type)); component = varyingReg.registerColumn; } // In the following: // // struct S { vec4 field; }; // out S varStruct; // // "_uvarStruct" is found through |parentStructMappedName|, with |varying->mappedName| // being "_ufield". In such a case, use |parentStructMappedName|. if (varying.frontVarying.varying && (varying.frontVarying.stage == shaderType)) { const std::string &name = varying.isStructField() ? varying.frontVarying.parentStructMappedName : varying.frontVarying.varying->mappedName; AddLocationInfo(&(*variableInfoMapOut)[varying.frontVarying.stage], name, location, component, varying.frontVarying.stage); } if (varying.backVarying.varying && (varying.backVarying.stage == shaderType)) { const std::string &name = varying.isStructField() ? varying.backVarying.parentStructMappedName : varying.backVarying.varying->mappedName; AddLocationInfo(&(*variableInfoMapOut)[varying.backVarying.stage], name, location, component, varying.backVarying.stage); } } // Add an entry for inactive varyings. const gl::ShaderMap<std::vector<std::string>> &inactiveVaryingMappedNames = programExecutable.getResources().varyingPacking.getInactiveVaryingMappedNames(); for (const std::string &varyingName : inactiveVaryingMappedNames[shaderType]) { bool isBuiltin = angle::BeginsWith(varyingName, "gl_"); if (isBuiltin) { continue; } // If name is already in the map, it will automatically have marked all other stages // inactive. if ((*variableInfoMapOut)[shaderType].find(varyingName) != (*variableInfoMapOut)[shaderType].end()) { continue; } // Otherwise, add an entry for it with all locations inactive. ShaderInterfaceVariableInfo *info = &(*variableInfoMapOut)[shaderType][varyingName]; ASSERT(info->location == ShaderInterfaceVariableInfo::kInvalid); } } // Calculates XFB layout qualifier arguments for each tranform feedback varying. Stores calculated // values for the SPIR-V transformation. void AssignTransformFeedbackExtensionQualifiers(const gl::ProgramExecutable &programExecutable, uint32_t locationsUsedForXfbExtension, const gl::ShaderType shaderType, ShaderInterfaceVariableInfoMap *variableInfoMapOut) { const std::vector<gl::TransformFeedbackVarying> &tfVaryings = programExecutable.getLinkedTransformFeedbackVaryings(); const std::vector<GLsizei> &varyingStrides = programExecutable.getTransformFeedbackStrides(); const bool isInterleaved = programExecutable.getTransformFeedbackBufferMode() == GL_INTERLEAVED_ATTRIBS; std::string xfbDecl; std::string xfbOut; uint32_t currentOffset = 0; uint32_t currentStride = 0; uint32_t bufferIndex = 0; uint32_t currentBuiltinLocation = 0; for (uint32_t varyingIndex = 0; varyingIndex < tfVaryings.size(); ++varyingIndex) { if (isInterleaved) { bufferIndex = 0; if (varyingIndex > 0) { const gl::TransformFeedbackVarying &prev = tfVaryings[varyingIndex - 1]; currentOffset += prev.size() * gl::VariableExternalSize(prev.type); } currentStride = varyingStrides[0]; } else { bufferIndex = varyingIndex; currentOffset = 0; currentStride = varyingStrides[varyingIndex]; } const gl::TransformFeedbackVarying &tfVarying = tfVaryings[varyingIndex]; const std::string &tfVaryingName = tfVarying.mappedName; if (tfVarying.isBuiltIn()) { uint32_t xfbVaryingLocation = currentBuiltinLocation++; std::string xfbVaryingName = kXfbBuiltInPrefix + tfVaryingName; ASSERT(xfbVaryingLocation < locationsUsedForXfbExtension); AddLocationInfo(variableInfoMapOut, xfbVaryingName, xfbVaryingLocation, ShaderInterfaceVariableInfo::kInvalid, shaderType); SetXfbInfo(variableInfoMapOut, xfbVaryingName, bufferIndex, currentOffset, currentStride); } else if (!tfVarying.isArray() || tfVarying.arrayIndex == GL_INVALID_INDEX) { // Note: capturing individual array elements using the Vulkan transform feedback // extension is not supported, and it unlikely to be ever supported (on the contrary, it // may be removed from the GLES spec). http://anglebug.com/4140 // ANGLE should support capturing the whole array. // Find the varying with this name. If a struct is captured, we would be iterating over // its fields, and the name of the varying is found through parentStructMappedName. Not // only that, but also we should only do this for the first field of the struct. const gl::PackedVarying *originalVarying = nullptr; for (const gl::PackedVaryingRegister &varyingReg : programExecutable.getResources().varyingPacking.getRegisterList()) { if (!IsFirstRegisterOfVarying(varyingReg)) { continue; } const gl::PackedVarying *varying = varyingReg.packedVarying; if (varying->frontVarying.varying->name == tfVarying.name) { originalVarying = varying; break; } } if (originalVarying) { const std::string &mappedName = originalVarying->isStructField() ? originalVarying->frontVarying.parentStructMappedName : originalVarying->frontVarying.varying->mappedName; // Set xfb info for this varying. AssignVaryingLocations should have already added // location information for these varyings. SetXfbInfo(variableInfoMapOut, mappedName, bufferIndex, currentOffset, currentStride); } } } } void AssignUniformBindings(GlslangSourceOptions &options, const gl::ProgramExecutable &programExecutable, const gl::ShaderType shaderType, GlslangProgramInterfaceInfo *programInterfaceInfo, ShaderMapInterfaceVariableInfoMap *variableInfoMapOut) { if (programExecutable.hasLinkedShaderStage(shaderType)) { AddResourceInfo(&(*variableInfoMapOut)[shaderType], kDefaultUniformNames[shaderType], programInterfaceInfo->uniformsAndXfbDescriptorSetIndex, programInterfaceInfo->currentUniformBindingIndex, shaderType); ++programInterfaceInfo->currentUniformBindingIndex; // Assign binding to the driver uniforms block AddResourceInfoToAllStages(&(*variableInfoMapOut)[shaderType], sh::vk::kDriverUniformsBlockName, programInterfaceInfo->driverUniformsDescriptorSetIndex, 0); } } // TODO: http://anglebug.com/4512: Need to combine descriptor set bindings across // shader stages. void AssignInterfaceBlockBindings(GlslangSourceOptions &options, const gl::ProgramExecutable &programExecutable, const std::vector<gl::InterfaceBlock> &blocks, const gl::ShaderType shaderType, GlslangProgramInterfaceInfo *programInterfaceInfo, ShaderMapInterfaceVariableInfoMap *variableInfoMapOut) { for (const gl::InterfaceBlock &block : blocks) { if (!block.isArray || block.arrayElement == 0) { // TODO: http://anglebug.com/4523: All blocks should be active if (programExecutable.hasLinkedShaderStage(shaderType) && block.isActive(shaderType)) { AddResourceInfo(&(*variableInfoMapOut)[shaderType], block.mappedName, programInterfaceInfo->shaderResourceDescriptorSetIndex, programInterfaceInfo->currentShaderResourceBindingIndex, shaderType); ++programInterfaceInfo->currentShaderResourceBindingIndex; } } } } // TODO: http://anglebug.com/4512: Need to combine descriptor set bindings across // shader stages. void AssignAtomicCounterBufferBindings(GlslangSourceOptions &options, const gl::ProgramExecutable &programExecutable, const std::vector<gl::AtomicCounterBuffer> &buffers, const gl::ShaderType shaderType, GlslangProgramInterfaceInfo *programInterfaceInfo, ShaderMapInterfaceVariableInfoMap *variableInfoMapOut) { if (buffers.size() == 0) { return; } if (programExecutable.hasLinkedShaderStage(shaderType)) { AddResourceInfo(&(*variableInfoMapOut)[shaderType], sh::vk::kAtomicCountersBlockName, programInterfaceInfo->shaderResourceDescriptorSetIndex, programInterfaceInfo->currentShaderResourceBindingIndex, shaderType); ++programInterfaceInfo->currentShaderResourceBindingIndex; } } // TODO: http://anglebug.com/4512: Need to combine descriptor set bindings across // shader stages. void AssignImageBindings(GlslangSourceOptions &options, const gl::ProgramExecutable &programExecutable, const std::vector<gl::LinkedUniform> &uniforms, const gl::RangeUI &imageUniformRange, const gl::ShaderType shaderType, GlslangProgramInterfaceInfo *programInterfaceInfo, ShaderMapInterfaceVariableInfoMap *variableInfoMapOut) { for (unsigned int uniformIndex : imageUniformRange) { const gl::LinkedUniform &imageUniform = uniforms[uniformIndex]; std::string name = imageUniform.mappedName; if (GetImageNameWithoutIndices(&name)) { if (programExecutable.hasLinkedShaderStage(shaderType)) { AddResourceInfo(&(*variableInfoMapOut)[shaderType], name, programInterfaceInfo->shaderResourceDescriptorSetIndex, programInterfaceInfo->currentShaderResourceBindingIndex, shaderType); ++programInterfaceInfo->currentShaderResourceBindingIndex; } } } } void AssignNonTextureBindings(GlslangSourceOptions &options, const gl::ProgramExecutable &programExecutable, const gl::ShaderType shaderType, GlslangProgramInterfaceInfo *programInterfaceInfo, ShaderMapInterfaceVariableInfoMap *variableInfoMapOut) { const std::vector<gl::InterfaceBlock> &uniformBlocks = programExecutable.getUniformBlocks(); AssignInterfaceBlockBindings(options, programExecutable, uniformBlocks, shaderType, programInterfaceInfo, variableInfoMapOut); const std::vector<gl::InterfaceBlock> &storageBlocks = programExecutable.getShaderStorageBlocks(); AssignInterfaceBlockBindings(options, programExecutable, storageBlocks, shaderType, programInterfaceInfo, variableInfoMapOut); const std::vector<gl::AtomicCounterBuffer> &atomicCounterBuffers = programExecutable.getAtomicCounterBuffers(); AssignAtomicCounterBufferBindings(options, programExecutable, atomicCounterBuffers, shaderType, programInterfaceInfo, variableInfoMapOut); const std::vector<gl::LinkedUniform> &uniforms = programExecutable.getUniforms(); const gl::RangeUI &imageUniformRange = programExecutable.getImageUniformRange(); AssignImageBindings(options, programExecutable, uniforms, imageUniformRange, shaderType, programInterfaceInfo, variableInfoMapOut); } // TODO: http://anglebug.com/4512: Need to combine descriptor set bindings across // shader stages. void AssignTextureBindings(GlslangSourceOptions &options, const gl::ProgramExecutable &programExecutable, const gl::ShaderType shaderType, GlslangProgramInterfaceInfo *programInterfaceInfo, ShaderMapInterfaceVariableInfoMap *variableInfoMapOut) { // Assign textures to a descriptor set and binding. const std::vector<gl::LinkedUniform> &uniforms = programExecutable.getUniforms(); for (unsigned int uniformIndex : programExecutable.getSamplerUniformRange()) { const gl::LinkedUniform &samplerUniform = uniforms[uniformIndex]; if (!options.useOldRewriteStructSamplers && gl::SamplerNameContainsNonZeroArrayElement(samplerUniform.name)) { continue; } if (UniformNameIsIndexZero(samplerUniform.name, options.useOldRewriteStructSamplers)) { // Samplers in structs are extracted and renamed. const std::string samplerName = options.useOldRewriteStructSamplers ? GetMappedSamplerNameOld(samplerUniform.name) : GlslangGetMappedSamplerName(samplerUniform.name); // TODO: http://anglebug.com/4523: All uniforms should be active if (programExecutable.hasLinkedShaderStage(shaderType) && samplerUniform.isActive(shaderType)) { AddResourceInfo(&(*variableInfoMapOut)[shaderType], samplerName, programInterfaceInfo->textureDescriptorSetIndex, programInterfaceInfo->currentTextureBindingIndex, shaderType); ++programInterfaceInfo->currentTextureBindingIndex; } } } } constexpr gl::ShaderMap<EShLanguage> kShLanguageMap = { {gl::ShaderType::Vertex, EShLangVertex}, {gl::ShaderType::Geometry, EShLangGeometry}, {gl::ShaderType::Fragment, EShLangFragment}, {gl::ShaderType::Compute, EShLangCompute}, }; void ValidateSpirvMessage(spv_message_level_t level, const char *source, const spv_position_t &position, const char *message) { WARN() << "Level" << level << ": " << message; } bool ValidateSpirv(const std::vector<uint32_t> &spirvBlob) { spvtools::SpirvTools spirvTools(SPV_ENV_VULKAN_1_1); spirvTools.SetMessageConsumer(ValidateSpirvMessage); bool result = spirvTools.Validate(spirvBlob); if (!result) { std::string readableSpirv; spirvTools.Disassemble(spirvBlob, &readableSpirv, SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES); WARN() << "Invalid SPIR-V:\n" << readableSpirv; } return result; } // A SPIR-V transformer. It walks the instructions and modifies them as necessary, for example to // assign bindings or locations. class SpirvTransformer final : angle::NonCopyable { public: SpirvTransformer(const std::vector<uint32_t> &spirvBlobIn, bool removeEarlyFragmentTestsOptimization, bool removeDebugInfo, const ShaderInterfaceVariableInfoMap &variableInfoMap, gl::ShaderType shaderType, SpirvBlob *spirvBlobOut) : mSpirvBlobIn(spirvBlobIn), mShaderType(shaderType), mHasTransformFeedbackOutput(false), mVariableInfoMap(variableInfoMap), mSpirvBlobOut(spirvBlobOut) { gl::ShaderBitSet allStages; allStages.set(); mRemoveEarlyFragmentTestsOptimization = removeEarlyFragmentTestsOptimization; mRemoveDebugInfo = removeDebugInfo; mBuiltinVariableInfo.activeStages = allStages; } bool transform(); private: // SPIR-V 1.0 Table 1: First Words of Physical Layout enum HeaderIndex { kHeaderIndexMagic = 0, kHeaderIndexVersion = 1, kHeaderIndexGenerator = 2, kHeaderIndexIndexBound = 3, kHeaderIndexSchema = 4, kHeaderIndexInstructions = 5, }; // A prepass to resolve interesting ids: void resolveVariableIds(); // Transform instructions: void transformInstruction(); // Instructions that are purely informational: void visitName(const uint32_t *instruction); void visitTypeHelper(const uint32_t *instruction, size_t idIndex, size_t typeIdIndex); void visitTypeArray(const uint32_t *instruction); void visitTypePointer(const uint32_t *instruction); void visitVariable(const uint32_t *instruction); // Instructions that potentially need transformation. They return true if the instruction is // transformed. If false is returned, the instruction should be copied as-is. bool transformAccessChain(const uint32_t *instruction, size_t wordCount); bool transformCapability(const uint32_t *instruction, size_t wordCount); bool transformEntryPoint(const uint32_t *instruction, size_t wordCount); bool transformDecorate(const uint32_t *instruction, size_t wordCount); bool transformTypePointer(const uint32_t *instruction, size_t wordCount); bool transformVariable(const uint32_t *instruction, size_t wordCount); bool transformExecutionMode(const uint32_t *instruction, size_t wordCount); // Any other instructions: size_t copyInstruction(const uint32_t *instruction, size_t wordCount); uint32_t getNewId(); // SPIR-V to transform: const std::vector<uint32_t> &mSpirvBlobIn; const gl::ShaderType mShaderType; bool mHasTransformFeedbackOutput; bool mRemoveEarlyFragmentTestsOptimization; bool mRemoveDebugInfo; // Input shader variable info map: const ShaderInterfaceVariableInfoMap &mVariableInfoMap; ShaderInterfaceVariableInfo mBuiltinVariableInfo; // Transformed SPIR-V: SpirvBlob *mSpirvBlobOut; // Traversal state: size_t mCurrentWord = 0; bool mIsInFunctionSection = false; // Transformation state: // Names associated with ids through OpName. The same name may be assigned to multiple ids, but // not all names are interesting (for example function arguments). When the variable // declaration is met (OpVariable), the variable info is matched with the corresponding id's // name based on the Storage Class. std::vector<const char *> mNamesById; // Shader variable info per id, if id is a shader variable. std::vector<const ShaderInterfaceVariableInfo *> mVariableInfoById; // Each OpTypePointer instruction that defines a type with the Output storage class is // duplicated with a similar instruction but which defines a type with the Private storage // class. If inactive varyings are encountered, its type is changed to the Private one. The // following vector maps the Output type id to the corresponding Private one. std::vector<uint32_t> mTypePointerTransformedId; }; bool SpirvTransformer::transform() { // Glslang succeeded in outputting SPIR-V, so we assume it's valid. ASSERT(mSpirvBlobIn.size() >= kHeaderIndexInstructions); // Since SPIR-V comes from a local call to glslang, it necessarily has the same endianness as // the running architecture, so no byte-swapping is necessary. ASSERT(mSpirvBlobIn[kHeaderIndexMagic] == spv::MagicNumber); // Make sure the transformer is not reused to avoid having to reinitialize it here. ASSERT(mCurrentWord == 0); ASSERT(mIsInFunctionSection == false); // Make sure the SpirvBlob is not reused. ASSERT(mSpirvBlobOut->empty()); // First, find all necessary ids and associate them with the information required to transform // their decorations. resolveVariableIds(); // Copy the header to SpirvBlob mSpirvBlobOut->assign(mSpirvBlobIn.begin(), mSpirvBlobIn.begin() + kHeaderIndexInstructions); mCurrentWord = kHeaderIndexInstructions; while (mCurrentWord < mSpirvBlobIn.size()) { transformInstruction(); } return true; } // SPIR-V 1.0 Table 2: Instruction Physical Layout uint32_t GetSpirvInstructionLength(const uint32_t *instruction) { return instruction[0] >> 16; } uint32_t GetSpirvInstructionOp(const uint32_t *instruction) { constexpr uint32_t kOpMask = 0xFFFFu; return instruction[0] & kOpMask; } void SetSpirvInstructionLength(uint32_t *instruction, size_t length) { ASSERT(length < 0xFFFFu); constexpr uint32_t kLengthMask = 0xFFFF0000u; instruction[0] &= ~kLengthMask; instruction[0] |= length << 16; } void SetSpirvInstructionOp(uint32_t *instruction, uint32_t op) { constexpr uint32_t kOpMask = 0xFFFFu; instruction[0] &= ~kOpMask; instruction[0] |= op; } void SpirvTransformer::resolveVariableIds() { size_t indexBound = mSpirvBlobIn[kHeaderIndexIndexBound]; // Allocate storage for id-to-name map. Used to associate ShaderInterfaceVariableInfo with ids // based on name, but only when it's determined that the name corresponds to a shader interface // variable. mNamesById.resize(indexBound + 1, nullptr); // Allocate storage for id-to-info map. If %i is the id of a name in mVariableInfoMap, index i // in this vector will hold a pointer to the ShaderInterfaceVariableInfo object associated with // that name in mVariableInfoMap. mVariableInfoById.resize(indexBound + 1, nullptr); // Allocate storage for Output type pointer map. At index i, this vector holds the identical // type as %i except for its storage class turned to Private. mTypePointerTransformedId.resize(indexBound + 1, 0); size_t currentWord = kHeaderIndexInstructions; while (currentWord < mSpirvBlobIn.size()) { const uint32_t *instruction = &mSpirvBlobIn[currentWord]; const uint32_t wordCount = GetSpirvInstructionLength(instruction); const uint32_t opCode = GetSpirvInstructionOp(instruction); switch (opCode) { case spv::OpName: visitName(instruction); break; case spv::OpTypeArray: visitTypeArray(instruction); break; case spv::OpTypePointer: visitTypePointer(instruction); break; case spv::OpVariable: visitVariable(instruction); break; case spv::OpFunction: // SPIR-V is structured in sections (SPIR-V 1.0 Section 2.4 Logical Layout of a // Module). Names appear before decorations, which are followed by type+variables // and finally functions. We are only interested in name and variable declarations // (as well as type declarations for the sake of nameless interface blocks). Early // out when the function declaration section is met. return; default: break; } currentWord += wordCount; } } void SpirvTransformer::transformInstruction() { const uint32_t *instruction = &mSpirvBlobIn[mCurrentWord]; const uint32_t wordCount = GetSpirvInstructionLength(instruction); const uint32_t opCode = GetSpirvInstructionOp(instruction); // Since glslang succeeded in producing SPIR-V, we assume it to be valid. ASSERT(mCurrentWord + wordCount <= mSpirvBlobIn.size()); if (opCode == spv::OpFunction) { // SPIR-V is structured in sections. Function declarations come last. Only Op*Access* // opcodes inside functions need to be inspected. mIsInFunctionSection = true; } // Only look at interesting instructions. bool transformed = false; if (mIsInFunctionSection) { // Look at in-function opcodes. switch (opCode) { case spv::OpAccessChain: case spv::OpInBoundsAccessChain: case spv::OpPtrAccessChain: case spv::OpInBoundsPtrAccessChain: transformed = transformAccessChain(instruction, wordCount); break; default: break; } } else { // Look at global declaration opcodes. switch (opCode) { case spv::OpSourceContinued: case spv::OpSource: case spv::OpSourceExtension: case spv::OpName: case spv::OpMemberName: case spv::OpString: case spv::OpLine: case spv::OpNoLine: case spv::OpModuleProcessed: if (mRemoveDebugInfo) { // Strip debug info to reduce binary size. transformed = true; } break; case spv::OpCapability: transformed = transformCapability(instruction, wordCount); break; case spv::OpEntryPoint: transformed = transformEntryPoint(instruction, wordCount); break; case spv::OpDecorate: transformed = transformDecorate(instruction, wordCount); break; case spv::OpTypePointer: transformed = transformTypePointer(instruction, wordCount); break; case spv::OpVariable: transformed = transformVariable(instruction, wordCount); break; case spv::OpExecutionMode: transformed = transformExecutionMode(instruction, wordCount); break; default: break; } } // If the instruction was not transformed, copy it to output as is. if (!transformed) { copyInstruction(instruction, wordCount); } // Advance to next instruction. mCurrentWord += wordCount; } void SpirvTransformer::visitName(const uint32_t *instruction) { // We currently don't have any big-endian devices in the list of supported platforms. Literal // strings in SPIR-V are stored little-endian (SPIR-V 1.0 Section 2.2.1, Literal String), so if // a big-endian device is to be supported, the string matching here should be specialized. ASSERT(IsLittleEndian()); // SPIR-V 1.0 Section 3.32 Instructions, OpName constexpr size_t kIdIndex = 1; constexpr size_t kNameIndex = 2; const uint32_t id = instruction[kIdIndex]; const char *name = reinterpret_cast<const char *>(&instruction[kNameIndex]); // The names and ids are unique ASSERT(id < mNamesById.size()); ASSERT(mNamesById[id] == nullptr); mNamesById[id] = name; } void SpirvTransformer::visitTypeHelper(const uint32_t *instruction, const size_t idIndex, const size_t typeIdIndex) { const uint32_t id = instruction[idIndex]; const uint32_t typeId = instruction[typeIdIndex]; // Every type id is declared only once. ASSERT(id < mNamesById.size()); ASSERT(mNamesById[id] == nullptr); // Carry the name forward from the base type. This is only necessary for interface blocks, // as the variable info is associated with the block name instead of the variable name (to // support nameless interface blocks). When the variable declaration is met, either the // type name or the variable name is used to associate with info based on the variable's // storage class. ASSERT(typeId < mNamesById.size()); mNamesById[id] = mNamesById[typeId]; } void SpirvTransformer::visitTypeArray(const uint32_t *instruction) { // SPIR-V 1.0 Section 3.32 Instructions, OpTypeArray constexpr size_t kIdIndex = 1; constexpr size_t kElementTypeIdIndex = 2; visitTypeHelper(instruction, kIdIndex, kElementTypeIdIndex); } void SpirvTransformer::visitTypePointer(const uint32_t *instruction) { // SPIR-V 1.0 Section 3.32 Instructions, OpTypePointer constexpr size_t kIdIndex = 1; constexpr size_t kTypeIdIndex = 3; visitTypeHelper(instruction, kIdIndex, kTypeIdIndex); } void SpirvTransformer::visitVariable(const uint32_t *instruction) { // SPIR-V 1.0 Section 3.32 Instructions, OpVariable constexpr size_t kTypeIdIndex = 1; constexpr size_t kIdIndex = 2; constexpr size_t kStorageClassIndex = 3; // All resources that take set/binding should be transformed. const uint32_t typeId = instruction[kTypeIdIndex]; const uint32_t id = instruction[kIdIndex]; const uint32_t storageClass = instruction[kStorageClassIndex]; ASSERT(typeId < mNamesById.size()); ASSERT(id < mNamesById.size()); // If storage class indicates that this is not a shader interface variable, ignore it. const bool isInterfaceBlockVariable = storageClass == spv::StorageClassUniform || storageClass == spv::StorageClassStorageBuffer; const bool isOpaqueUniform = storageClass == spv::StorageClassUniformConstant; const bool isInOut = storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput; if (!isInterfaceBlockVariable && !isOpaqueUniform && !isInOut) { return; } // The ids are unique. ASSERT(id < mVariableInfoById.size()); ASSERT(mVariableInfoById[id] == nullptr); // For interface block variables, the name that's used to associate info is the block name // rather than the variable name. const char *name = mNamesById[isInterfaceBlockVariable ? typeId : id]; ASSERT(name != nullptr); // Handle builtins, which all start with "gl_". Either the variable name could be an indication // of a builtin variable (such as with gl_FragCoord) or the type name (such as with // gl_PerVertex). const bool isNameBuiltin = isInOut && angle::BeginsWith(name, "gl_"); const bool isTypeBuiltin = isInOut && mNamesById[typeId] != nullptr && angle::BeginsWith(mNamesById[typeId], "gl_"); if (isNameBuiltin || isTypeBuiltin) { // Make all builtins point to this no-op info. Adding this entry allows us to ASSERT that // every shader interface variable is processed during the SPIR-V transformation. This is // done when iterating the ids provided by OpEntryPoint. mVariableInfoById[id] = &mBuiltinVariableInfo; return; } // Every shader interface variable should have an associated data. auto infoIter = mVariableInfoMap.find(name); ASSERT(infoIter != mVariableInfoMap.end()); const ShaderInterfaceVariableInfo *info = &infoIter->second; // Associate the id of this name with its info. mVariableInfoById[id] = info; // Note if the variable is captured by transform feedback. In that case, the TransformFeedback // capability needs to be added. if (mShaderType != gl::ShaderType::Fragment && info->xfbBuffer != ShaderInterfaceVariableInfo::kInvalid && info->activeStages[mShaderType]) { mHasTransformFeedbackOutput = true; } } bool SpirvTransformer::transformDecorate(const uint32_t *instruction, size_t wordCount) { // SPIR-V 1.0 Section 3.32 Instructions, OpDecorate constexpr size_t kIdIndex = 1; constexpr size_t kDecorationIndex = 2; constexpr size_t kDecorationValueIndex = 3; uint32_t id = instruction[kIdIndex]; uint32_t decoration = instruction[kDecorationIndex]; const ShaderInterfaceVariableInfo *info = mVariableInfoById[id]; // If variable is not a shader interface variable that needs modification, there's nothing to // do. if (info == nullptr) { return false; } // If it's an inactive varying, remove the decoration altogether. if (!info->activeStages[mShaderType]) { return true; } uint32_t newDecorationValue = ShaderInterfaceVariableInfo::kInvalid; switch (decoration) { case spv::DecorationLocation: newDecorationValue = info->location; break; case spv::DecorationBinding: newDecorationValue = info->binding; break; case spv::DecorationDescriptorSet: newDecorationValue = info->descriptorSet; break; default: break; } // If the decoration is not something we care about modifying, there's nothing to do. if (newDecorationValue == ShaderInterfaceVariableInfo::kInvalid) { return false; } // Copy the decoration declaration and modify it. const size_t instructionOffset = copyInstruction(instruction, wordCount); (*mSpirvBlobOut)[instructionOffset + kDecorationValueIndex] = newDecorationValue; // If there are decorations to be added, add them right after the Location decoration is // encountered. if (decoration != spv::DecorationLocation) { return true; } // Add component decoration, if any. if (info->component != ShaderInterfaceVariableInfo::kInvalid) { // Copy the location decoration declaration and modify it to contain the Component // decoration. const size_t instOffset = copyInstruction(instruction, wordCount); (*mSpirvBlobOut)[instOffset + kDecorationIndex] = spv::DecorationComponent; (*mSpirvBlobOut)[instOffset + kDecorationValueIndex] = info->component; } // Add Xfb decorations, if any. if (mShaderType != gl::ShaderType::Fragment && info->xfbBuffer != ShaderInterfaceVariableInfo::kInvalid) { ASSERT(info->xfbStride != ShaderInterfaceVariableInfo::kInvalid); ASSERT(info->xfbOffset != ShaderInterfaceVariableInfo::kInvalid); constexpr size_t kXfbDecorationCount = 3; constexpr uint32_t xfbDecorations[kXfbDecorationCount] = { spv::DecorationXfbBuffer, spv::DecorationXfbStride, spv::DecorationOffset, }; const uint32_t xfbDecorationValues[kXfbDecorationCount] = { info->xfbBuffer, info->xfbStride, info->xfbOffset, }; // Copy the location decoration declaration three times, and modify them to contain the // XfbBuffer, XfbStride and Offset decorations. for (size_t i = 0; i < kXfbDecorationCount; ++i) { const size_t xfbInstructionOffset = copyInstruction(instruction, wordCount); (*mSpirvBlobOut)[xfbInstructionOffset + kDecorationIndex] = xfbDecorations[i]; (*mSpirvBlobOut)[xfbInstructionOffset + kDecorationValueIndex] = xfbDecorationValues[i]; } } return true; } bool SpirvTransformer::transformCapability(const uint32_t *instruction, size_t wordCount) { if (!mHasTransformFeedbackOutput) { return false; } // SPIR-V 1.0 Section 3.32 Instructions, OpCapability constexpr size_t kCapabilityIndex = 1; uint32_t capability = instruction[kCapabilityIndex]; // Transform feedback capability shouldn't have already been specified. ASSERT(capability != spv::CapabilityTransformFeedback); // Vulkan shaders have either Shader, Geometry or Tessellation capability. We find this // capability, and add the TransformFeedback capability after it. if (capability != spv::CapabilityShader && capability != spv::CapabilityGeometry && capability != spv::CapabilityTessellation) { return false; } // Copy the original capability declaration. copyInstruction(instruction, wordCount); // Create the TransformFeedback capability declaration. // SPIR-V 1.0 Section 3.32 Instructions, OpCapability constexpr size_t kCapabilityInstructionLength = 2; std::array<uint32_t, kCapabilityInstructionLength> newCapabilityDeclaration = { instruction[0], // length+opcode is identical }; // Fill the fields. newCapabilityDeclaration[kCapabilityIndex] = spv::CapabilityTransformFeedback; copyInstruction(newCapabilityDeclaration.data(), kCapabilityInstructionLength); return true; } bool SpirvTransformer::transformEntryPoint(const uint32_t *instruction, size_t wordCount) { // Remove inactive varyings from the shader interface declaration. // SPIR-V 1.0 Section 3.32 Instructions, OpEntryPoint constexpr size_t kNameIndex = 3; // Calculate the length of entry point name in words. Note that endianness of the string // doesn't matter, since we are looking for the '\0' character and rounding up to the word size. // This calculates (strlen(name)+1+3) / 4, which is equal to strlen(name)/4+1. const size_t nameLength = strlen(reinterpret_cast<const char *>(&instruction[kNameIndex])) / 4 + 1; const uint32_t instructionLength = GetSpirvInstructionLength(instruction); const size_t interfaceStart = kNameIndex + nameLength; const size_t interfaceCount = instructionLength - interfaceStart; // Create a copy of the entry point for modification. std::vector<uint32_t> filteredEntryPoint(instruction, instruction + wordCount); // Filter out inactive varyings from entry point interface declaration. size_t writeIndex = interfaceStart; for (size_t index = 0; index < interfaceCount; ++index) { uint32_t id = instruction[interfaceStart + index]; const ShaderInterfaceVariableInfo *info = mVariableInfoById[id]; ASSERT(info); if (!info->activeStages[mShaderType]) { continue; } filteredEntryPoint[writeIndex] = id; ++writeIndex; } // Update the length of the instruction. const size_t newLength = writeIndex; SetSpirvInstructionLength(filteredEntryPoint.data(), newLength); // Copy to output. copyInstruction(filteredEntryPoint.data(), newLength); // Add an OpExecutionMode Xfb instruction if necessary. if (!mHasTransformFeedbackOutput) { return true; } // SPIR-V 1.0 Section 3.32 Instructions, OpEntryPoint constexpr size_t kEntryPointIdIndex = 2; // SPIR-V 1.0 Section 3.32 Instructions, OpExecutionMode constexpr size_t kExecutionModeInstructionLength = 3; constexpr size_t kExecutionModeIdIndex = 1; constexpr size_t kExecutionModeExecutionModeIndex = 2; std::array<uint32_t, kExecutionModeInstructionLength> newExecutionModeDeclaration = {}; // Fill the fields. SetSpirvInstructionOp(newExecutionModeDeclaration.data(), spv::OpExecutionMode); SetSpirvInstructionLength(newExecutionModeDeclaration.data(), kExecutionModeInstructionLength); newExecutionModeDeclaration[kExecutionModeIdIndex] = instruction[kEntryPointIdIndex]; newExecutionModeDeclaration[kExecutionModeExecutionModeIndex] = spv::ExecutionModeXfb; copyInstruction(newExecutionModeDeclaration.data(), kExecutionModeInstructionLength); return true; } bool SpirvTransformer::transformTypePointer(const uint32_t *instruction, size_t wordCount) { // SPIR-V 1.0 Section 3.32 Instructions, OpTypePointer constexpr size_t kIdIndex = 1; constexpr size_t kStorageClassIndex = 2; constexpr size_t kTypeIdIndex = 3; const uint32_t id = instruction[kIdIndex]; const uint32_t storageClass = instruction[kStorageClassIndex]; const uint32_t typeId = instruction[kTypeIdIndex]; // If the storage class is output, this may be used to create a variable corresponding to an // inactive varying, or if that varying is a struct, an Op*AccessChain retrieving a field of // that inactive varying. // // Unfortunately, SPIR-V specifies the storage class both on the type and the variable // declaration. Otherwise it would have been sufficient to modify the OpVariable instruction. // For simplicty, copy every "OpTypePointer Output" instruction except with the Private storage // class, in case it may be necessary later. if (storageClass != spv::StorageClassOutput) { return false; } // Cannot create a Private type declaration from builtins such as gl_PerVertex. if (mNamesById[typeId] != nullptr && angle::BeginsWith(mNamesById[typeId], "gl_")) { return false; } // Copy the type declaration for modification. const size_t instructionOffset = copyInstruction(instruction, wordCount); const uint32_t newTypeId = getNewId(); (*mSpirvBlobOut)[instructionOffset + kIdIndex] = newTypeId; (*mSpirvBlobOut)[instructionOffset + kStorageClassIndex] = spv::StorageClassPrivate; // Remember the id of the replacement. ASSERT(id < mTypePointerTransformedId.size()); mTypePointerTransformedId[id] = newTypeId; // The original instruction should still be present as well. At this point, we don't know // whether we will need the Output or Private type. return false; } bool SpirvTransformer::transformVariable(const uint32_t *instruction, size_t wordCount) { // SPIR-V 1.0 Section 3.32 Instructions, OpVariable constexpr size_t kTypeIdIndex = 1; constexpr size_t kIdIndex = 2; constexpr size_t kStorageClassIndex = 3; const uint32_t id = instruction[kIdIndex]; const uint32_t typeId = instruction[kTypeIdIndex]; const uint32_t storageClass = instruction[kStorageClassIndex]; const ShaderInterfaceVariableInfo *info = mVariableInfoById[id]; // If variable is not a shader interface variable that needs modification, there's nothing to // do. if (info == nullptr) { return false; } // Furthermore, if it's not an inactive varying output, there's nothing to do. Note that // inactive varying inputs are already pruned by the translator. ASSERT(storageClass != spv::StorageClassInput || info->activeStages[mShaderType]); if (info->activeStages[mShaderType]) { return false; } ASSERT(storageClass == spv::StorageClassOutput); // Copy the variable declaration for modification. Change its type to the corresponding type // with the Private storage class, as well as changing the storage class respecified in this // instruction. const size_t instructionOffset = copyInstruction(instruction, wordCount); ASSERT(typeId < mTypePointerTransformedId.size()); ASSERT(mTypePointerTransformedId[typeId] != 0); (*mSpirvBlobOut)[instructionOffset + kTypeIdIndex] = mTypePointerTransformedId[typeId]; (*mSpirvBlobOut)[instructionOffset + kStorageClassIndex] = spv::StorageClassPrivate; return true; } bool SpirvTransformer::transformAccessChain(const uint32_t *instruction, size_t wordCount) { // SPIR-V 1.0 Section 3.32 Instructions, OpAccessChain, OpInBoundsAccessChain, OpPtrAccessChain, // OpInBoundsPtrAccessChain constexpr size_t kTypeIdIndex = 1; constexpr size_t kBaseIdIndex = 3; const uint32_t typeId = instruction[kTypeIdIndex]; const uint32_t baseId = instruction[kBaseIdIndex]; // If not accessing an inactive output varying, nothing to do. const ShaderInterfaceVariableInfo *info = mVariableInfoById[baseId]; if (info == nullptr || info->activeStages[mShaderType]) { return false; } // Copy the instruction for modification. const size_t instructionOffset = copyInstruction(instruction, wordCount); ASSERT(typeId < mTypePointerTransformedId.size()); ASSERT(mTypePointerTransformedId[typeId] != 0); (*mSpirvBlobOut)[instructionOffset + kTypeIdIndex] = mTypePointerTransformedId[typeId]; return true; } bool SpirvTransformer::transformExecutionMode(const uint32_t *instruction, size_t wordCount) { // SPIR-V 1.0 Section 3.32 Instructions, OpAccessChain, OpInBoundsAccessChain, OpPtrAccessChain, // OpInBoundsPtrAccessChain constexpr size_t kModeIndex = 2; const uint32_t executionMode = instruction[kModeIndex]; if (executionMode == spv::ExecutionModeEarlyFragmentTests && mRemoveEarlyFragmentTestsOptimization) { // skip the copy return true; } return false; } size_t SpirvTransformer::copyInstruction(const uint32_t *instruction, size_t wordCount) { size_t instructionOffset = mSpirvBlobOut->size(); mSpirvBlobOut->insert(mSpirvBlobOut->end(), instruction, instruction + wordCount); return instructionOffset; } uint32_t SpirvTransformer::getNewId() { return (*mSpirvBlobOut)[kHeaderIndexIndexBound]++; } } // anonymous namespace const uint32_t ShaderInterfaceVariableInfo::kInvalid; ShaderInterfaceVariableInfo::ShaderInterfaceVariableInfo() {} void GlslangInitialize() { int result = ShInitialize(); ASSERT(result != 0); GlslangWarmup(); } void GlslangRelease() { int result = ShFinalize(); ASSERT(result != 0); } // Strip indices from the name. If there are non-zero indices, return false to indicate that this // image uniform doesn't require set/binding. That is done on index 0. bool GetImageNameWithoutIndices(std::string *name) { if (name->back() != ']') { return true; } if (!UniformNameIsIndexZero(*name, false)) { return false; } // Strip all indices *name = name->substr(0, name->find('[')); return true; } std::string GetMappedSamplerNameOld(const std::string &originalName) { std::string samplerName = gl::ParseResourceName(originalName, nullptr); // Samplers in structs are extracted. std::replace(samplerName.begin(), samplerName.end(), '.', '_'); // Samplers in arrays of structs are also extracted. std::replace(samplerName.begin(), samplerName.end(), '[', '_'); samplerName.erase(std::remove(samplerName.begin(), samplerName.end(), ']'), samplerName.end()); if (MappedSamplerNameNeedsUserDefinedPrefix(originalName)) { samplerName = sh::kUserDefinedNamePrefix + samplerName; } return samplerName; } std::string GlslangGetMappedSamplerName(const std::string &originalName) { std::string samplerName = originalName; // Samplers in structs are extracted. std::replace(samplerName.begin(), samplerName.end(), '.', '_'); // Remove array elements auto out = samplerName.begin(); for (auto in = samplerName.begin(); in != samplerName.end(); in++) { if (*in == '[') { while (*in != ']') { in++; ASSERT(in != samplerName.end()); } } else { *out++ = *in; } } samplerName.erase(out, samplerName.end()); if (MappedSamplerNameNeedsUserDefinedPrefix(originalName)) { samplerName = sh::kUserDefinedNamePrefix + samplerName; } return samplerName; } std::string GetXfbBufferName(const uint32_t bufferIndex) { return "xfbBuffer" + Str(bufferIndex); } void GlslangAssignLocations(GlslangSourceOptions &options, const gl::ProgramExecutable &programExecutable, const gl::ShaderType shaderType, GlslangProgramInterfaceInfo *programInterfaceInfo, ShaderMapInterfaceVariableInfoMap *variableInfoMapOut) { // Assign outputs to the fragment shader, if any. if ((shaderType == gl::ShaderType::Fragment) && programExecutable.hasLinkedShaderStage(gl::ShaderType::Fragment)) { AssignOutputLocations(programExecutable, gl::ShaderType::Fragment, &(*variableInfoMapOut)[gl::ShaderType::Fragment]); } // Assign attributes to the vertex shader, if any. if ((shaderType == gl::ShaderType::Vertex) && programExecutable.hasLinkedShaderStage(gl::ShaderType::Vertex)) { AssignAttributeLocations(programExecutable, gl::ShaderType::Vertex, &(*variableInfoMapOut)[gl::ShaderType::Vertex]); } if (!programExecutable.hasLinkedShaderStage(gl::ShaderType::Compute)) { // Assign varying locations. AssignVaryingLocations(options, programExecutable, shaderType, programInterfaceInfo, variableInfoMapOut); if (!programExecutable.getLinkedTransformFeedbackVaryings().empty() && options.supportsTransformFeedbackExtension && (shaderType == gl::ShaderType::Vertex)) { AssignTransformFeedbackExtensionQualifiers( programExecutable, programInterfaceInfo->locationsUsedForXfbExtension, gl::ShaderType::Vertex, &(*variableInfoMapOut)[gl::ShaderType::Vertex]); } } AssignUniformBindings(options, programExecutable, shaderType, programInterfaceInfo, variableInfoMapOut); AssignTextureBindings(options, programExecutable, shaderType, programInterfaceInfo, variableInfoMapOut); AssignNonTextureBindings(options, programExecutable, shaderType, programInterfaceInfo, variableInfoMapOut); } void GlslangGetShaderSource(GlslangSourceOptions &options, const gl::ProgramState &programState, const gl::ProgramLinkedResources &resources, GlslangProgramInterfaceInfo *programInterfaceInfo, gl::ShaderMap<std::string> *shaderSourcesOut, ShaderMapInterfaceVariableInfoMap *variableInfoMapOut) { for (const gl::ShaderType shaderType : gl::AllShaderTypes()) { gl::Shader *glShader = programState.getAttachedShader(shaderType); (*shaderSourcesOut)[shaderType] = glShader ? glShader->getTranslatedSource() : ""; } std::string *vertexSource = &(*shaderSourcesOut)[gl::ShaderType::Vertex]; // Write transform feedback output code. if (!vertexSource->empty()) { if (programState.getLinkedTransformFeedbackVaryings().empty()) { *vertexSource = SubstituteTransformFeedbackMarkers(*vertexSource, "", ""); } else { if (options.supportsTransformFeedbackExtension) { GenerateTransformFeedbackExtensionOutputs( programState, resources, vertexSource, &programInterfaceInfo->locationsUsedForXfbExtension); } else if (options.emulateTransformFeedback) { GenerateTransformFeedbackEmulationOutputs( options, programState, programInterfaceInfo, vertexSource, &(*variableInfoMapOut)[gl::ShaderType::Vertex]); } } } for (const gl::ShaderType shaderType : programState.getExecutable().getLinkedShaderStages()) { GlslangAssignLocations(options, programState.getExecutable(), shaderType, programInterfaceInfo, variableInfoMapOut); } } angle::Result GlslangTransformSpirvCode(const GlslangErrorCallback &callback, const gl::ShaderType shaderType, bool removeEarlyFragmentTestsOptimization, bool removeDebugInfo, const ShaderInterfaceVariableInfoMap &variableInfoMap, const SpirvBlob &initialSpirvBlob, SpirvBlob *spirvBlobOut) { if (initialSpirvBlob.empty()) { return angle::Result::Continue; } // Transform the SPIR-V code by assigning location/set/binding values. SpirvTransformer transformer(initialSpirvBlob, removeEarlyFragmentTestsOptimization, removeDebugInfo, variableInfoMap, shaderType, spirvBlobOut); ANGLE_GLSLANG_CHECK(callback, transformer.transform(), GlslangError::InvalidSpirv); ASSERT(ValidateSpirv(*spirvBlobOut)); return angle::Result::Continue; } angle::Result GlslangGetShaderSpirvCode(const GlslangErrorCallback &callback, const gl::ShaderBitSet &linkedShaderStages, const gl::Caps &glCaps, const gl::ShaderMap<std::string> &shaderSources, const ShaderMapInterfaceVariableInfoMap &variableInfoMap, gl::ShaderMap<SpirvBlob> *spirvBlobsOut) { // Enable SPIR-V and Vulkan rules when parsing GLSL EShMessages messages = static_cast<EShMessages>(EShMsgSpvRules | EShMsgVulkanRules); TBuiltInResource builtInResources(glslang::DefaultTBuiltInResource); GetBuiltInResourcesFromCaps(glCaps, &builtInResources); glslang::TShader vertexShader(EShLangVertex); glslang::TShader fragmentShader(EShLangFragment); glslang::TShader geometryShader(EShLangGeometry); glslang::TShader computeShader(EShLangCompute); gl::ShaderMap<glslang::TShader *> shaders = { {gl::ShaderType::Vertex, &vertexShader}, {gl::ShaderType::Fragment, &fragmentShader}, {gl::ShaderType::Geometry, &geometryShader}, {gl::ShaderType::Compute, &computeShader}, }; glslang::TProgram program; for (const gl::ShaderType shaderType : gl::AllShaderTypes()) { if (shaderSources[shaderType].empty()) { continue; } ANGLE_TRACE_EVENT0("gpu.angle", "GlslangGetShaderSpirvCode TShader::parse"); const char *shaderString = shaderSources[shaderType].c_str(); int shaderLength = static_cast<int>(shaderSources[shaderType].size()); glslang::TShader *shader = shaders[shaderType]; shader->setStringsWithLengths(&shaderString, &shaderLength, 1); shader->setEntryPoint("main"); bool result = shader->parse(&builtInResources, 450, ECoreProfile, false, false, messages); if (!result) { ERR() << "Internal error parsing Vulkan shader corresponding to " << shaderType << ":\n" << shader->getInfoLog() << "\n" << shader->getInfoDebugLog() << "\n"; ANGLE_GLSLANG_CHECK(callback, false, GlslangError::InvalidShader); } program.addShader(shader); } bool linkResult = program.link(messages); if (!linkResult) { ERR() << "Internal error linking Vulkan shaders:\n" << program.getInfoLog() << "\n"; ANGLE_GLSLANG_CHECK(callback, false, GlslangError::InvalidShader); } for (const gl::ShaderType shaderType : gl::AllShaderTypes()) { if (shaderSources[shaderType].empty()) { continue; } glslang::TIntermediate *intermediate = program.getIntermediate(kShLanguageMap[shaderType]); glslang::GlslangToSpv(*intermediate, (*spirvBlobsOut)[shaderType]); } return angle::Result::Continue; } } // namespace rx
40.591339
100
0.646969
jacadcaps
d921e987a4979cd17b7dbbe1bed47efc0f2d1827
9,434
cc
C++
src/Scanner.cc
avartak/KAZM
4b08bf47bf5412f435eb7b129f4aa6eeddb31a42
[ "MIT" ]
null
null
null
src/Scanner.cc
avartak/KAZM
4b08bf47bf5412f435eb7b129f4aa6eeddb31a42
[ "MIT" ]
null
null
null
src/Scanner.cc
avartak/KAZM
4b08bf47bf5412f435eb7b129f4aa6eeddb31a42
[ "MIT" ]
null
null
null
// src/Scanner.cc generated by reflex 2.1.5 from src/lexer.l #define REFLEX_VERSION "2.1.5" //////////////////////////////////////////////////////////////////////////////// // // // OPTIONS USED // // // //////////////////////////////////////////////////////////////////////////////// #define REFLEX_OPTION_header_file "include/Scanner.h" #define REFLEX_OPTION_lex scan #define REFLEX_OPTION_lexer Scanner #define REFLEX_OPTION_namespace kazm #define REFLEX_OPTION_noline true #define REFLEX_OPTION_outfile "src/Scanner.cc" #define REFLEX_OPTION_token_type kazm::Token //////////////////////////////////////////////////////////////////////////////// // // // SECTION 1: %top user code // // // //////////////////////////////////////////////////////////////////////////////// #include <Token.h> //////////////////////////////////////////////////////////////////////////////// // // // REGEX MATCHER // // // //////////////////////////////////////////////////////////////////////////////// #include <reflex/matcher.h> //////////////////////////////////////////////////////////////////////////////// // // // ABSTRACT LEXER CLASS // // // //////////////////////////////////////////////////////////////////////////////// #include <reflex/abslexer.h> //////////////////////////////////////////////////////////////////////////////// // // // LEXER CLASS // // // //////////////////////////////////////////////////////////////////////////////// namespace kazm { class Scanner : public reflex::AbstractLexer<reflex::Matcher> { public: typedef reflex::AbstractLexer<reflex::Matcher> AbstractBaseLexer; Scanner( const reflex::Input& input = reflex::Input(), std::ostream& os = std::cout) : AbstractBaseLexer(input, os) { } static const int INITIAL = 0; virtual kazm::Token scan(void); kazm::Token scan(const reflex::Input& input) { in(input); return scan(); } kazm::Token scan(const reflex::Input& input, std::ostream *os) { in(input); if (os) out(*os); return scan(); } }; } // namespace kazm //////////////////////////////////////////////////////////////////////////////// // // // SECTION 1: %{ user code %} // // // //////////////////////////////////////////////////////////////////////////////// #include <iostream> #define RETURN(x) return Token(x, str(), lineno()) //////////////////////////////////////////////////////////////////////////////// // // // SECTION 2: rules // // // //////////////////////////////////////////////////////////////////////////////// kazm::Token kazm::Scanner::scan(void) { static const char *REGEX_INITIAL = "(?m)((?:[\\x09-\\x0d\\x20])+)|((?:\\Q//\\E).*)|((?:\\QOPENQASM\\E)(?:[\\x09\\x20])+(?:(?:(?:\\Q0\\E)|[1-9]+(?:[0-9])*))(?:\\Q.\\E)(?:(?:(?:\\Q0\\E)|[1-9]+(?:[0-9])*))(?:[\\x09\\x20])*(?:\\Q;\\E))|((?:\\Q{\\E))|((?:\\Q}\\E))|((?:\\Q[\\E))|((?:\\Q]\\E))|((?:\\Q(\\E))|((?:\\Q)\\E))|((?:\\Q,\\E))|((?:\\Q;\\E))|((?:\\Q+\\E))|((?:\\Q-\\E))|((?:\\Q*\\E))|((?:\\Q/\\E))|((?:\\Q^\\E))|((?:\\Q->\\E))|((?:\\Q==\\E))|((?:\\Qif\\E))|((?:\\Qpi\\E))|((?:\\Qsin\\E))|((?:\\Qcos\\E))|((?:\\Qtan\\E))|((?:\\Qexp\\E))|((?:\\Qln\\E))|((?:\\Qsqrt\\E))|((?:\\Qqreg\\E))|((?:\\Qcreg\\E))|((?:\\Qgate\\E))|((?:\\Qopaque\\E))|((?:\\Qbarrier\\E))|((?:\\Qmeasure\\E))|((?:\\Qreset\\E))|((?:\\QU\\E))|((?:\\QCX\\E))|((?:\\Qinclude\\E))|((?:(?:(?:\\Q0\\E)|[1-9]+(?:[0-9])*)))|((?:[0-9])+(?:(?:[Ee][\\x2b\\x2d]?(?:[0-9])+)))|((?:[0-9])+(?:\\Q.\\E)(?:[0-9])*(?:(?:[Ee][\\x2b\\x2d]?(?:[0-9])+))?)|((?:[0-9])*(?:\\Q.\\E)(?:[0-9])+(?:(?:[Ee][\\x2b\\x2d]?(?:[0-9])+))?)|([a-z][0-9A-Z_a-z]*)|(\"[^\"]+\")|(.)"; static const reflex::Pattern PATTERN_INITIAL(REGEX_INITIAL); if (!has_matcher()) { matcher(new Matcher(PATTERN_INITIAL, stdinit(), this)); } while (true) { switch (matcher().scan()) { case 0: if (matcher().at_end()) { { RETURN(0); } } else { out().put(matcher().input()); } break; case 1: // rule src/lexer.l:21: {W}+ : break; case 2: // rule src/lexer.l:22: "//".* : break; case 3: // rule src/lexer.l:24: "OPENQASM"{S}+{I}"."{I}{S}*";" : { RETURN(T_HEADER); } break; case 4: // rule src/lexer.l:26: "{" : { RETURN('{'); } break; case 5: // rule src/lexer.l:27: "}" : { RETURN('}'); } break; case 6: // rule src/lexer.l:28: "[" : { RETURN('['); } break; case 7: // rule src/lexer.l:29: "]" : { RETURN(']'); } break; case 8: // rule src/lexer.l:30: "(" : { RETURN('('); } break; case 9: // rule src/lexer.l:31: ")" : { RETURN(')'); } break; case 10: // rule src/lexer.l:32: "," : { RETURN(','); } break; case 11: // rule src/lexer.l:33: ";" : { RETURN(';'); } break; case 12: // rule src/lexer.l:34: "+" : { RETURN('+'); } break; case 13: // rule src/lexer.l:35: "-" : { RETURN('-'); } break; case 14: // rule src/lexer.l:36: "*" : { RETURN('*'); } break; case 15: // rule src/lexer.l:37: "/" : { RETURN('/'); } break; case 16: // rule src/lexer.l:38: "^" : { RETURN('^'); } break; case 17: // rule src/lexer.l:39: "->" : { RETURN(T_YIELDS); } break; case 18: // rule src/lexer.l:40: "==" : { RETURN(T_EQUALS); } break; case 19: // rule src/lexer.l:41: "if" : { RETURN(T_IF); } break; case 20: // rule src/lexer.l:42: "pi" : { RETURN(T_PI); } break; case 21: // rule src/lexer.l:43: "sin" : { RETURN(T_SIN); } break; case 22: // rule src/lexer.l:44: "cos" : { RETURN(T_COS); } break; case 23: // rule src/lexer.l:45: "tan" : { RETURN(T_TAN); } break; case 24: // rule src/lexer.l:46: "exp" : { RETURN(T_EXP); } break; case 25: // rule src/lexer.l:47: "ln" : { RETURN(T_LN); } break; case 26: // rule src/lexer.l:48: "sqrt" : { RETURN(T_SQRT); } break; case 27: // rule src/lexer.l:49: "qreg" : { RETURN(T_QREG); } break; case 28: // rule src/lexer.l:50: "creg" : { RETURN(T_CREG); } break; case 29: // rule src/lexer.l:51: "gate" : { RETURN(T_GATE); } break; case 30: // rule src/lexer.l:52: "opaque" : { RETURN(T_OPAQUE); } break; case 31: // rule src/lexer.l:53: "barrier" : { RETURN(T_BARRIER); } break; case 32: // rule src/lexer.l:54: "measure" : { RETURN(T_MEASURE); } break; case 33: // rule src/lexer.l:55: "reset" : { RETURN(T_RESET); } break; case 34: // rule src/lexer.l:56: "U" : { RETURN(T_U); } break; case 35: // rule src/lexer.l:57: "CX" : { RETURN(T_CX); } break; case 36: // rule src/lexer.l:58: "include" : { RETURN(T_INCLUDE); } break; case 37: // rule src/lexer.l:60: {I} : { RETURN(T_NNINTEGER); } break; case 38: // rule src/lexer.l:61: {D}+{E} : { RETURN(T_REAL); } break; case 39: // rule src/lexer.l:62: {D}+"."{D}*{E}? : { RETURN(T_REAL); } break; case 40: // rule src/lexer.l:63: {D}*"."{D}+{E}? : { RETURN(T_REAL); } break; case 41: // rule src/lexer.l:64: [a-z][a-zA-Z_0-9]* : { RETURN(T_ID); } break; case 42: // rule src/lexer.l:65: \"[^\"]+\" : { RETURN(T_FILENAME); } break; case 43: // rule src/lexer.l:67: . : { RETURN(T_UNDEF); } break; } } }
36.42471
1,015
0.321391
avartak
d92409824eee962a1b00965b618371f31ac842cf
5,311
cpp
C++
octopi/library/tests_octopus/t_entity.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
2
2019-01-22T23:34:37.000Z
2021-10-31T15:44:15.000Z
octopi/library/tests_octopus/t_entity.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
2
2020-06-01T16:35:46.000Z
2021-10-05T21:02:09.000Z
octopi/library/tests_octopus/t_entity.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
null
null
null
/*****************************************************************************\ * * * Name : octopus_entity tester * * Author : Chris Koeritz * * * * Purpose: * * * * Checks that the octopus_entity class is behaving as expected. * * * ******************************************************************************* * Copyright (c) 2002-$now By Author. This program is free software; you can * * redistribute it and/or modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either version 2 of * * the License or (at your option) any later version. This is online at: * * http://www.fsf.org/copyleft/gpl.html * * Please send any updates to: fred@gruntose.com * \*****************************************************************************/ #include <basis/byte_array.h> #include <mathematics/chaos.h> #include <basis/guards.h> #include <basis/astring.h> #include <octopus/entity_defs.h> #include <application/application_shell.h> #include <loggers/console_logger.h> #include <loggers/file_logger.h> #include <structures/static_memory_gremlin.h> #include <sockets/tcpip_stack.h> #include <textual/string_manipulation.h> #ifdef __WIN32__ #include <process.h> #else #include <unistd.h> #endif const int ITERATE_EACH_TEST = 1000; // the number of times to repeat each test operation. class test_entity : public application_shell { public: test_entity() : application_shell(class_name()) {} DEFINE_CLASS_NAME("test_entity"); virtual int execute(); }; int test_entity::execute() { chaos rando; SET_DEFAULT_COMBO_LOGGER; tcpip_stack stack; octopus_entity blankie; if (!blankie.blank()) deadly_error(class_name(), "emptiness test", "the blank entity was not seen as empty."); octopus_entity fullish("gurp", 28, 39, 4); if (fullish.blank()) deadly_error(class_name(), "emptiness test", "the non-blank entity was seen as empty."); for (int i = 0; i < ITERATE_EACH_TEST; i++) { // test the basic filling of the values in an entity. octopus_entity blank_ent; int sequencer = rando.inclusive(1, MAXINT - 10); int add_in = rando.inclusive(0, MAXINT - 10); octopus_entity filled_ent(stack.hostname(), application_configuration::process_id(), sequencer, add_in); blank_ent = octopus_entity(stack.hostname(), application_configuration::process_id(), sequencer, add_in); if (blank_ent != filled_ent) deadly_error(class_name(), "simple reset test", "failed to resolve to same id"); astring text1 = filled_ent.to_text(); astring text2 = blank_ent.to_text(); if (text1 != text2) deadly_error(class_name(), "to_text test", "strings are different"); ///log(text1); octopus_entity georgio = octopus_entity::from_text(text2); ///log(georgio.to_text()); if (georgio != filled_ent) deadly_error(class_name(), "from_text test", "entity is different after from_text"); octopus_request_id fudnix(filled_ent, 8232390); astring text3 = fudnix.to_text(); octopus_request_id resur = octopus_request_id::from_text(text3); if (resur != fudnix) deadly_error(class_name(), "from_text test", "request id is different after from_text"); blank_ent = octopus_entity(); // reset it again forcefully. blank_ent = octopus_entity(filled_ent.hostname(), filled_ent.process_id(), filled_ent.sequencer(), filled_ent.add_in()); if (blank_ent != filled_ent) deadly_error(class_name(), "reset from attribs test", "failed to resolve to same id"); // log(a_sprintf("%d: ", i + 1) + filled_ent.mangled_form()); byte_array chunk1; filled_ent.pack(chunk1); octopus_entity unpacked1; unpacked1.unpack(chunk1); if (unpacked1 != filled_ent) deadly_error(class_name(), "pack/unpack test", "failed to return same values"); // test of entity packing and size calculation. octopus_entity ent(string_manipulation::make_random_name(1, 428), randomizer().inclusive(0, MAXINT/2), randomizer().inclusive(0, MAXINT/2), randomizer().inclusive(0, MAXINT/2)); octopus_request_id bobo(ent, randomizer().inclusive(0, MAXINT/2)); int packed_estimate = bobo.packed_size(); byte_array packed_bobo; bobo.pack(packed_bobo); if (packed_bobo.length() != packed_estimate) deadly_error(class_name(), "entity packed_size test", "calculated incorrect packed size"); } log("octopus_entity:: works for those functions tested."); return 0; } //hmmm: tests the octopus entity object, // can do exact text check if want but that's not guaranteed to be useful // in the future. HOOPLE_MAIN(test_entity, )
39.634328
100
0.588778
fredhamster
d928f48d649ebe372fe54378d0f88e54c952de03
576
cpp
C++
ABC/ABC247/A/abc247-a.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
ABC/ABC247/A/abc247-a.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
ABC/ABC247/A/abc247-a.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
/** * @file abc247-a.cpp * @brief ABC247 Problem A - Move Right * @author Keitaro Naruse * @date 2022-04-10 * @copyright MIT License * @details https://atcoder.jp/contests/abc247/tasks/abc247_a */ // # Solution #include <iostream> #include <string> int main() { // Read | S | = [ 1, 10^6 ] std::string S; std::cin >> S; // Main const int N = 4; std::string T( N, ' ' ); T.at( 0 ) = '0'; T.at( 1 ) = S.at( 0 ); T.at( 2 ) = S.at( 1 ); T.at( 3 ) = S.at( 2 ); std::cout << T << std::endl; // Finalize return( 0 ); }
17.454545
60
0.508681
keitaronaruse
d92a44e01d39b0743eb29ac2627ba0403bbe3358
1,155
cpp
C++
NPSVisor/tools/svMaker/source/pObject/svmHistory.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/tools/svMaker/source/pObject/svmHistory.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/tools/svMaker/source/pObject/svmHistory.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
//-------------------- svmHistory.cpp -------------------------- //----------------------------------------------------------- #include "precHeader.h" //----------------------------------------------------------- #include "svmHistory.h" #include "svmObject.h" //----------------------------------------------------------- static PRect getObjRect(svmBaseObject* obj) { svmObject* o = dynamic_cast<svmObject*>(obj); if(o) return o->getRect(); return PRect(); } //----------------------------------------------------------- static int getObjId(svmBaseObject* obj) { svmObject* o = dynamic_cast<svmObject*>(obj); if(o) return o->getId(); return 0; } //----------------------------------------------------------- svmObjHistory::svmObjHistory(svmBaseObject* obj, svmObjHistory::typeOfAction action, svmBaseObject* prev) : Curr(obj), Action(action), Prev(prev), Rect(getObjRect(obj)), Id(getObjId(obj)), Next(0), Cloned(0) {} //----------------------------------------------------------- svmObjHistory::~svmObjHistory() { if(Group != Action) delete Cloned; } //-----------------------------------------------------------
35
84
0.401732
NPaolini
d92a876c94c41878cba040efe46b2fcd5c82c175
40,970
cc
C++
chrome/browser/views/toolbar_view.cc
zachlatta/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
1
2021-09-24T22:49:10.000Z
2021-09-24T22:49:10.000Z
chrome/browser/views/toolbar_view.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/views/toolbar_view.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2009 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/views/toolbar_view.h" #include <string> #include "app/drag_drop_types.h" #include "app/gfx/canvas.h" #include "app/l10n_util.h" #include "app/os_exchange_data.h" #include "app/resource_bundle.h" #include "base/command_line.h" #include "base/logging.h" #include "base/path_service.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/back_forward_menu_model_views.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/character_encoding.h" #include "chrome/browser/encoding_menu_controller.h" #include "chrome/browser/metrics/user_metrics.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/navigation_controller.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/browser_theme_provider.h" #include "chrome/browser/user_data_manager.h" #include "chrome/browser/views/bookmark_menu_button.h" #include "chrome/browser/views/event_utils.h" #include "chrome/browser/views/go_button.h" #include "chrome/browser/views/location_bar_view.h" #include "chrome/browser/views/toolbar_star_toggle.h" #include "chrome/browser/view_ids.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_service.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #ifdef CHROME_PERSONALIZATION #include "chrome/personalization/personalization.h" #endif #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/net_util.h" #include "views/background.h" #include "views/controls/button/button_dropdown.h" #include "views/controls/label.h" #if defined(OS_WIN) #include "views/drag_utils.h" #include "views/widget/tooltip_manager.h" #endif #include "views/window/non_client_view.h" #include "views/window/window.h" static const int kControlHorizOffset = 4; static const int kControlVertOffset = 6; static const int kControlIndent = 3; static const int kStatusBubbleWidth = 480; // Separation between the location bar and the menus. static const int kMenuButtonOffset = 3; // Padding to the right of the location bar static const int kPaddingRight = 2; static const int kPopupTopSpacingNonGlass = 3; static const int kPopupBottomSpacingNonGlass = 2; static const int kPopupBottomSpacingGlass = 1; // The vertical distance between the bottom of the omnibox and the top of the // popup. static const int kOmniboxPopupVerticalSpacing = 2; // The number of pixels of margin on the buttons on either side of the omnibox. // We use this value to inset the bounds returned for the omnibox popup, since // we want the popup to be only as wide as the visible frame of the omnibox. static const int kOmniboxButtonsHorizontalMargin = 2; static SkBitmap* kPopupBackgroundEdge = NULL; //////////////////////////////////////////////////////////////////////////////// // EncodingMenuModel EncodingMenuModel::EncodingMenuModel(Browser* browser) : SimpleMenuModel(this), browser_(browser) { Build(); } void EncodingMenuModel::Build() { EncodingMenuController::EncodingMenuItemList encoding_menu_items; EncodingMenuController encoding_menu_controller; encoding_menu_controller.GetEncodingMenuItems(browser_->profile(), &encoding_menu_items); int group_id = 0; EncodingMenuController::EncodingMenuItemList::iterator it = encoding_menu_items.begin(); for (; it != encoding_menu_items.end(); ++it) { int id = it->first; std::wstring& label = it->second; if (id == 0) { AddSeparator(); } else { if (id == IDC_ENCODING_AUTO_DETECT) { AddCheckItem(id, WideToUTF16Hack(label)); } else { // Use the id of the first radio command as the id of the group. if (group_id <= 0) group_id = id; AddRadioItem(id, WideToUTF16Hack(label), group_id); } } } } bool EncodingMenuModel::IsCommandIdChecked(int command_id) const { TabContents* current_tab = browser_->GetSelectedTabContents(); EncodingMenuController controller; return controller.IsItemChecked(browser_->profile(), current_tab->encoding(), command_id); } bool EncodingMenuModel::IsCommandIdEnabled(int command_id) const { return browser_->command_updater()->IsCommandEnabled(command_id); } bool EncodingMenuModel::GetAcceleratorForCommandId( int command_id, views::Accelerator* accelerator) { return false; } void EncodingMenuModel::ExecuteCommand(int command_id) { browser_->ExecuteCommand(command_id); } //////////////////////////////////////////////////////////////////////////////// // EncodingMenuModel ZoomMenuModel::ZoomMenuModel(views::SimpleMenuModel::Delegate* delegate) : SimpleMenuModel(delegate) { Build(); } void ZoomMenuModel::Build() { AddItemWithStringId(IDC_ZOOM_PLUS, IDS_ZOOM_PLUS); AddItemWithStringId(IDC_ZOOM_NORMAL, IDS_ZOOM_NORMAL); AddItemWithStringId(IDC_ZOOM_MINUS, IDS_ZOOM_MINUS); } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, public: ToolbarView::ToolbarView(Browser* browser) : model_(browser->toolbar_model()), acc_focused_view_(NULL), back_(NULL), forward_(NULL), reload_(NULL), home_(NULL), star_(NULL), location_bar_(NULL), go_(NULL), page_menu_(NULL), app_menu_(NULL), bookmark_menu_(NULL), profile_(NULL), browser_(browser), profiles_menu_contents_(NULL), ALLOW_THIS_IN_INITIALIZER_LIST( profiles_helper_(new GetProfilesHelper(this))) { browser_->command_updater()->AddCommandObserver(IDC_BACK, this); browser_->command_updater()->AddCommandObserver(IDC_FORWARD, this); browser_->command_updater()->AddCommandObserver(IDC_RELOAD, this); browser_->command_updater()->AddCommandObserver(IDC_HOME, this); browser_->command_updater()->AddCommandObserver(IDC_STAR, this); if (browser->type() == Browser::TYPE_NORMAL) display_mode_ = DISPLAYMODE_NORMAL; else display_mode_ = DISPLAYMODE_LOCATION; if (!kPopupBackgroundEdge) { kPopupBackgroundEdge = ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_LOCATIONBG_POPUPMODE_EDGE); } } ToolbarView::~ToolbarView() { profiles_helper_->OnDelegateDeleted(); } void ToolbarView::Init(Profile* profile) { back_menu_model_.reset(new BackForwardMenuModelViews( browser_, BackForwardMenuModel::BACKWARD_MENU, GetWidget())); forward_menu_model_.reset(new BackForwardMenuModelViews( browser_, BackForwardMenuModel::FORWARD_MENU, GetWidget())); // Create all the individual Views in the Toolbar. CreateLeftSideControls(); CreateCenterStack(profile); CreateRightSideControls(profile); show_home_button_.Init(prefs::kShowHomeButton, profile->GetPrefs(), this); SetProfile(profile); } void ToolbarView::SetProfile(Profile* profile) { if (profile == profile_) return; profile_ = profile; location_bar_->SetProfile(profile); } void ToolbarView::Update(TabContents* tab, bool should_restore_state) { if (location_bar_) location_bar_->Update(should_restore_state ? tab : NULL); } int ToolbarView::GetNextAccessibleViewIndex(int view_index, bool nav_left) { int modifier = 1; if (nav_left) modifier = -1; int current_view_index = view_index + modifier; while ((current_view_index >= 0) && (current_view_index < GetChildViewCount())) { // Skip the location bar, as it has its own keyboard navigation. Also skip // any views that cannot be interacted with. if (current_view_index == GetChildIndex(location_bar_) || !GetChildViewAt(current_view_index)->IsEnabled() || !GetChildViewAt(current_view_index)->IsVisible()) { current_view_index += modifier; continue; } // Update view_index with the available button index found. view_index = current_view_index; break; } // Returns the next available button index, or if no button is available in // the specified direction, remains where it was. return view_index; } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, Menu::BaseControllerDelegate overrides: bool ToolbarView::GetAcceleratorInfo(int id, views::Accelerator* accel) { return GetWidget()->GetAccelerator(id, accel); } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, views::MenuDelegate implementation: void ToolbarView::RunMenu(views::View* source, const gfx::Point& pt, gfx::NativeView parent) { switch (source->GetID()) { case VIEW_ID_PAGE_MENU: RunPageMenu(pt, parent); break; case VIEW_ID_APP_MENU: RunAppMenu(pt, parent); break; default: NOTREACHED() << "Invalid source menu."; } } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, GetProfilesHelper::Delegate implementation: void ToolbarView::OnGetProfilesDone( const std::vector<std::wstring>& profiles) { // Nothing to do if the menu has gone away. if (!profiles_menu_contents_.get()) return; // Store the latest list of profiles in the browser. browser_->set_user_data_dir_profiles(profiles); // Add direct sub menu items for profiles. std::vector<std::wstring>::const_iterator iter = profiles.begin(); for (int i = IDC_NEW_WINDOW_PROFILE_0; (i <= IDC_NEW_WINDOW_PROFILE_LAST) && (iter != profiles.end()); ++i, ++iter) profiles_menu_contents_->AddItem(i, WideToUTF16Hack(*iter)); // If there are more profiles then show "Other" link. if (iter != profiles.end()) { profiles_menu_contents_->AddSeparator(); profiles_menu_contents_->AddItemWithStringId(IDC_SELECT_PROFILE, IDS_SELECT_PROFILE); } // Always show a link to select a new profile. profiles_menu_contents_->AddSeparator(); profiles_menu_contents_->AddItemWithStringId( IDC_NEW_PROFILE, IDS_SELECT_PROFILE_DIALOG_NEW_PROFILE_ENTRY); } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, LocationBarView::Delegate implementation: TabContents* ToolbarView::GetTabContents() { return browser_->GetSelectedTabContents(); } void ToolbarView::OnInputInProgress(bool in_progress) { // The edit should make sure we're only notified when something changes. DCHECK(model_->input_in_progress() != in_progress); model_->set_input_in_progress(in_progress); location_bar_->Update(NULL); } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, CommandUpdater::CommandObserver implementation: void ToolbarView::EnabledStateChangedForCommand(int id, bool enabled) { views::Button* button = NULL; switch (id) { case IDC_BACK: button = back_; break; case IDC_FORWARD: button = forward_; break; case IDC_RELOAD: button = reload_; break; case IDC_HOME: button = home_; break; case IDC_STAR: button = star_; break; } if (button) button->SetEnabled(enabled); } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, views::Button::ButtonListener implementation: void ToolbarView::ButtonPressed(views::Button* sender) { browser_->ExecuteCommandWithDisposition( sender->tag(), event_utils::DispositionFromEventFlags(sender->mouse_event_flags())); } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, AutocompletePopupPositioner implementation: gfx::Rect ToolbarView::GetPopupBounds() const { gfx::Point origin; views::View::ConvertPointToScreen(star_, &origin); origin.set_y(origin.y() + star_->height() + kOmniboxPopupVerticalSpacing); gfx::Rect popup_bounds(origin.x(), origin.y(), star_->width() + location_bar_->width() + go_->width(), 0); if (UILayoutIsRightToLeft()) { popup_bounds.set_x( popup_bounds.x() - location_bar_->width() - go_->width()); } else { popup_bounds.set_x(popup_bounds.x()); } popup_bounds.set_y(popup_bounds.y()); popup_bounds.set_width(popup_bounds.width()); // Inset the bounds a little, since the buttons on either edge of the omnibox // have invisible padding that makes the popup appear too wide. popup_bounds.Inset(kOmniboxButtonsHorizontalMargin, 0); return popup_bounds; } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, NotificationObserver implementation: void ToolbarView::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::PREF_CHANGED) { std::wstring* pref_name = Details<std::wstring>(details).ptr(); if (*pref_name == prefs::kShowHomeButton) { Layout(); SchedulePaint(); } } } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, views::SimpleMenuModel::Delegate implementation: bool ToolbarView::IsCommandIdChecked(int command_id) const { if (command_id == IDC_SHOW_BOOKMARK_BAR) return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar); return false; } bool ToolbarView::IsCommandIdEnabled(int command_id) const { return browser_->command_updater()->IsCommandEnabled(command_id); } bool ToolbarView::GetAcceleratorForCommandId(int command_id, views::Accelerator* accelerator) { // The standard Ctrl-X, Ctrl-V and Ctrl-C are not defined as accelerators // anywhere so we need to check for them explicitly here. // TODO(cpu) Bug 1109102. Query WebKit land for the actual bindings. switch (command_id) { case IDC_CUT: *accelerator = views::Accelerator(L'X', false, true, false); return true; case IDC_COPY: *accelerator = views::Accelerator(L'C', false, true, false); return true; case IDC_PASTE: *accelerator = views::Accelerator(L'V', false, true, false); return true; } // Else, we retrieve the accelerator information from the frame. return GetWidget()->GetAccelerator(command_id, accelerator); } void ToolbarView::ExecuteCommand(int command_id) { browser_->ExecuteCommand(command_id); } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, views::View overrides: gfx::Size ToolbarView::GetPreferredSize() { if (IsDisplayModeNormal()) { int min_width = kControlIndent + back_->GetPreferredSize().width() + forward_->GetPreferredSize().width() + kControlHorizOffset + reload_->GetPreferredSize().width() + (show_home_button_.GetValue() ? (home_->GetPreferredSize().width() + kControlHorizOffset) : 0) + star_->GetPreferredSize().width() + go_->GetPreferredSize().width() + kMenuButtonOffset + (bookmark_menu_ ? bookmark_menu_->GetPreferredSize().width() : 0) + page_menu_->GetPreferredSize().width() + app_menu_->GetPreferredSize().width() + kPaddingRight; static SkBitmap normal_background; if (normal_background.isNull()) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); normal_background = *rb.GetBitmapNamed(IDR_CONTENT_TOP_CENTER); } return gfx::Size(min_width, normal_background.height()); } int vertical_spacing = PopupTopSpacing() + (GetWindow()->GetNonClientView()->UseNativeFrame() ? kPopupBottomSpacingGlass : kPopupBottomSpacingNonGlass); return gfx::Size(0, location_bar_->GetPreferredSize().height() + vertical_spacing); } void ToolbarView::Layout() { // If we have not been initialized yet just do nothing. if (back_ == NULL) return; if (!IsDisplayModeNormal()) { int edge_width = (browser_->window() && browser_->window()->IsMaximized()) ? 0 : kPopupBackgroundEdge->width(); // See Paint(). location_bar_->SetBounds(edge_width, PopupTopSpacing(), width() - (edge_width * 2), location_bar_->GetPreferredSize().height()); return; } int child_y = std::min(kControlVertOffset, height()); // We assume all child elements are the same height. int child_height = std::min(go_->GetPreferredSize().height(), height() - child_y); // If the window is maximized, we extend the back button to the left so that // clicking on the left-most pixel will activate the back button. // TODO(abarth): If the window becomes maximized but is not resized, // then Layout() might not be called and the back button // will be slightly the wrong size. We should force a // Layout() in this case. // http://crbug.com/5540 int back_width = back_->GetPreferredSize().width(); if (browser_->window() && browser_->window()->IsMaximized()) back_->SetBounds(0, child_y, back_width + kControlIndent, child_height); else back_->SetBounds(kControlIndent, child_y, back_width, child_height); forward_->SetBounds(back_->x() + back_->width(), child_y, forward_->GetPreferredSize().width(), child_height); reload_->SetBounds(forward_->x() + forward_->width() + kControlHorizOffset, child_y, reload_->GetPreferredSize().width(), child_height); if (show_home_button_.GetValue()) { home_->SetVisible(true); home_->SetBounds(reload_->x() + reload_->width() + kControlHorizOffset, child_y, home_->GetPreferredSize().width(), child_height); } else { home_->SetVisible(false); home_->SetBounds(reload_->x() + reload_->width(), child_y, 0, child_height); } star_->SetBounds(home_->x() + home_->width() + kControlHorizOffset, child_y, star_->GetPreferredSize().width(), child_height); int go_button_width = go_->GetPreferredSize().width(); int page_menu_width = page_menu_->GetPreferredSize().width(); int app_menu_width = app_menu_->GetPreferredSize().width(); int bookmark_menu_width = bookmark_menu_ ? bookmark_menu_->GetPreferredSize().width() : 0; int location_x = star_->x() + star_->width(); int available_width = width() - kPaddingRight - bookmark_menu_width - app_menu_width - page_menu_width - kMenuButtonOffset - go_button_width - location_x; location_bar_->SetBounds(location_x, child_y, std::max(available_width, 0), child_height); go_->SetBounds(location_bar_->x() + location_bar_->width(), child_y, go_button_width, child_height); int next_menu_x = go_->x() + go_->width() + kMenuButtonOffset; if (bookmark_menu_) { bookmark_menu_->SetBounds(next_menu_x, child_y, bookmark_menu_width, child_height); next_menu_x += bookmark_menu_width; } page_menu_->SetBounds(next_menu_x, child_y, page_menu_width, child_height); next_menu_x += page_menu_width; app_menu_->SetBounds(next_menu_x, child_y, app_menu_width, child_height); } void ToolbarView::Paint(gfx::Canvas* canvas) { View::Paint(canvas); if (IsDisplayModeNormal()) return; // In maximized mode, we don't draw the endcaps on the location bar, because // when they're flush against the edge of the screen they just look glitchy. if (!browser_->window() || !browser_->window()->IsMaximized()) { int top_spacing = PopupTopSpacing(); canvas->DrawBitmapInt(*kPopupBackgroundEdge, 0, top_spacing); canvas->DrawBitmapInt(*kPopupBackgroundEdge, width() - kPopupBackgroundEdge->width(), top_spacing); } // For glass, we need to draw a black line below the location bar to separate // it from the content area. For non-glass, the NonClientView draws the // toolbar background below the location bar for us. if (GetWindow()->GetNonClientView()->UseNativeFrame()) canvas->FillRectInt(SK_ColorBLACK, 0, height() - 1, width(), 1); } void ToolbarView::ThemeChanged() { LoadLeftSideControlsImages(); LoadCenterStackImages(); LoadRightSideControlsImages(); } void ToolbarView::ShowContextMenu(int x, int y, bool is_mouse_gesture) { if (acc_focused_view_) acc_focused_view_->ShowContextMenu(x, y, is_mouse_gesture); } void ToolbarView::DidGainFocus() { #if defined(OS_WIN) // Check to see if MSAA focus should be restored to previously focused button, // and if button is an enabled, visibled child of toolbar. if (!acc_focused_view_ || (acc_focused_view_->GetParent()->GetID() != VIEW_ID_TOOLBAR) || !acc_focused_view_->IsEnabled() || !acc_focused_view_->IsVisible()) { // Find first accessible child (-1 to start search at parent). int first_acc_child = GetNextAccessibleViewIndex(-1, false); // No buttons enabled or visible. if (first_acc_child == -1) return; set_acc_focused_view(GetChildViewAt(first_acc_child)); } // Default focus is on the toolbar. int view_index = VIEW_ID_TOOLBAR; // Set hot-tracking for child, and update focused_view for MSAA focus event. if (acc_focused_view_) { acc_focused_view_->SetHotTracked(true); // Show the tooltip for the view that got the focus. if (GetWidget()->GetTooltipManager()) GetWidget()->GetTooltipManager()->ShowKeyboardTooltip(acc_focused_view_); // Update focused_view with MSAA-adjusted child id. view_index = acc_focused_view_->GetID(); } gfx::NativeView wnd = GetWidget()->GetNativeView(); // Notify Access Technology that there was a change in keyboard focus. ::NotifyWinEvent(EVENT_OBJECT_FOCUS, wnd, OBJID_CLIENT, static_cast<LONG>(view_index)); #else // TODO(port): deal with toolbar a11y focus. NOTIMPLEMENTED(); #endif } void ToolbarView::WillLoseFocus() { #if defined(OS_WIN) if (acc_focused_view_) { // Resetting focus state. acc_focused_view_->SetHotTracked(false); } // Any tooltips that are active should be hidden when toolbar loses focus. if (GetWidget() && GetWidget()->GetTooltipManager()) GetWidget()->GetTooltipManager()->HideKeyboardTooltip(); #else // TODO(port): deal with toolbar a11y focus. NOTIMPLEMENTED(); #endif } bool ToolbarView::OnKeyPressed(const views::KeyEvent& e) { #if defined(OS_WIN) // Paranoia check, button should be initialized upon toolbar gaining focus. if (!acc_focused_view_) return false; int focused_view = GetChildIndex(acc_focused_view_); int next_view = focused_view; switch (e.GetCharacter()) { case VK_LEFT: next_view = GetNextAccessibleViewIndex(focused_view, true); break; case VK_RIGHT: next_view = GetNextAccessibleViewIndex(focused_view, false); break; case VK_DOWN: case VK_RETURN: // VK_SPACE is already handled by the default case. if (acc_focused_view_->GetID() == VIEW_ID_PAGE_MENU || acc_focused_view_->GetID() == VIEW_ID_APP_MENU) { // If a menu button in toolbar is activated and its menu is displayed, // then active tooltip should be hidden. if (GetWidget()->GetTooltipManager()) GetWidget()->GetTooltipManager()->HideKeyboardTooltip(); // Safe to cast, given to above view id check. static_cast<views::MenuButton*>(acc_focused_view_)->Activate(); if (!acc_focused_view_) { // Activate triggered a focus change, don't try to change focus. return true; } // Re-enable hot-tracking, as Activate() will disable it. acc_focused_view_->SetHotTracked(true); break; } default: // If key is not handled explicitly, pass it on to view. return acc_focused_view_->OnKeyPressed(e); } // No buttons enabled or visible. if (next_view == -1) return false; // Only send an event if focus moved. if (next_view != focused_view) { // Remove hot-tracking from old focused button. acc_focused_view_->SetHotTracked(false); // All is well, update the focused child member variable. acc_focused_view_ = GetChildViewAt(next_view); // Hot-track new focused button. acc_focused_view_->SetHotTracked(true); // Retrieve information to generate an MSAA focus event. int view_id = acc_focused_view_->GetID(); gfx::NativeView wnd = GetWidget()->GetNativeView(); // Show the tooltip for the view that got the focus. if (GetWidget()->GetTooltipManager()) { GetWidget()->GetTooltipManager()-> ShowKeyboardTooltip(GetChildViewAt(next_view)); } // Notify Access Technology that there was a change in keyboard focus. ::NotifyWinEvent(EVENT_OBJECT_FOCUS, wnd, OBJID_CLIENT, static_cast<LONG>(view_id)); return true; } #else // TODO(port): deal with toolbar a11y focus. NOTIMPLEMENTED(); #endif return false; } bool ToolbarView::OnKeyReleased(const views::KeyEvent& e) { // Paranoia check, button should be initialized upon toolbar gaining focus. if (!acc_focused_view_) return false; // Have keys be handled by the views themselves. return acc_focused_view_->OnKeyReleased(e); } bool ToolbarView::GetAccessibleName(std::wstring* name) { if (!accessible_name_.empty()) { (*name).assign(accessible_name_); return true; } return false; } bool ToolbarView::GetAccessibleRole(AccessibilityTypes::Role* role) { DCHECK(role); *role = AccessibilityTypes::ROLE_TOOLBAR; return true; } void ToolbarView::SetAccessibleName(const std::wstring& name) { accessible_name_.assign(name); } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, views::DragController implementation: void ToolbarView::WriteDragData(views::View* sender, int press_x, int press_y, OSExchangeData* data) { DCHECK( GetDragOperations(sender, press_x, press_y) != DragDropTypes::DRAG_NONE); UserMetrics::RecordAction(L"Toolbar_DragStar", profile_); #if defined(OS_WIN) // If there is a bookmark for the URL, add the bookmark drag data for it. We // do this to ensure the bookmark is moved, rather than creating an new // bookmark. TabContents* tab = browser_->GetSelectedTabContents(); if (tab) { if (profile_ && profile_->GetBookmarkModel()) { const BookmarkNode* node = profile_->GetBookmarkModel()-> GetMostRecentlyAddedNodeForURL(tab->GetURL()); if (node) { BookmarkDragData bookmark_data(node); bookmark_data.Write(profile_, data); } } drag_utils::SetURLAndDragImage(tab->GetURL(), UTF16ToWideHack(tab->GetTitle()), tab->GetFavIcon(), data); } #else // TODO(port): do bookmark item drag & drop NOTIMPLEMENTED(); #endif } int ToolbarView::GetDragOperations(views::View* sender, int x, int y) { DCHECK(sender == star_); TabContents* tab = browser_->GetSelectedTabContents(); if (!tab || !tab->ShouldDisplayURL() || !tab->GetURL().is_valid()) { return DragDropTypes::DRAG_NONE; } if (profile_ && profile_->GetBookmarkModel() && profile_->GetBookmarkModel()->IsBookmarked(tab->GetURL())) { return DragDropTypes::DRAG_MOVE | DragDropTypes::DRAG_COPY | DragDropTypes::DRAG_LINK; } return DragDropTypes::DRAG_COPY | DragDropTypes::DRAG_LINK; } //////////////////////////////////////////////////////////////////////////////// // ToolbarView, private: int ToolbarView::PopupTopSpacing() const { return GetWindow()->GetNonClientView()->UseNativeFrame() ? 0 : kPopupTopSpacingNonGlass; } void ToolbarView::CreateLeftSideControls() { back_ = new views::ButtonDropDown(this, back_menu_model_.get()); back_->set_triggerable_event_flags(views::Event::EF_LEFT_BUTTON_DOWN | views::Event::EF_MIDDLE_BUTTON_DOWN); back_->set_tag(IDC_BACK); back_->SetImageAlignment(views::ImageButton::ALIGN_RIGHT, views::ImageButton::ALIGN_TOP); back_->SetTooltipText(l10n_util::GetString(IDS_TOOLTIP_BACK)); back_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_BACK)); back_->SetID(VIEW_ID_BACK_BUTTON); forward_ = new views::ButtonDropDown(this, forward_menu_model_.get()); forward_->set_triggerable_event_flags(views::Event::EF_LEFT_BUTTON_DOWN | views::Event::EF_MIDDLE_BUTTON_DOWN); forward_->set_tag(IDC_FORWARD); forward_->SetTooltipText(l10n_util::GetString(IDS_TOOLTIP_FORWARD)); forward_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_FORWARD)); forward_->SetID(VIEW_ID_FORWARD_BUTTON); reload_ = new views::ImageButton(this); reload_->set_tag(IDC_RELOAD); reload_->SetTooltipText(l10n_util::GetString(IDS_TOOLTIP_RELOAD)); reload_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_RELOAD)); reload_->SetID(VIEW_ID_RELOAD_BUTTON); home_ = new views::ImageButton(this); home_->set_triggerable_event_flags(views::Event::EF_LEFT_BUTTON_DOWN | views::Event::EF_MIDDLE_BUTTON_DOWN); home_->set_tag(IDC_HOME); home_->SetTooltipText(l10n_util::GetString(IDS_TOOLTIP_HOME)); home_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_HOME)); home_->SetID(VIEW_ID_HOME_BUTTON); LoadLeftSideControlsImages(); AddChildView(back_); AddChildView(forward_); AddChildView(reload_); AddChildView(home_); } void ToolbarView::CreateCenterStack(Profile *profile) { star_ = new ToolbarStarToggle(this, this); star_->set_tag(IDC_STAR); star_->SetDragController(this); star_->SetTooltipText(l10n_util::GetString(IDS_TOOLTIP_STAR)); star_->SetToggledTooltipText(l10n_util::GetString(IDS_TOOLTIP_STARRED)); star_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_STAR)); star_->SetID(VIEW_ID_STAR_BUTTON); AddChildView(star_); location_bar_ = new LocationBarView(profile, browser_->command_updater(), model_, this, display_mode_ == DISPLAYMODE_LOCATION, this); // The Go button. go_ = new GoButton(location_bar_, browser_); go_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_GO)); go_->SetID(VIEW_ID_GO_BUTTON); LoadCenterStackImages(); AddChildView(location_bar_); location_bar_->Init(); AddChildView(go_); } void ToolbarView::CreateRightSideControls(Profile* profile) { page_menu_ = new views::MenuButton(NULL, std::wstring(), this, false); page_menu_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_PAGE)); page_menu_->SetTooltipText(l10n_util::GetString(IDS_PAGEMENU_TOOLTIP)); page_menu_->SetID(VIEW_ID_PAGE_MENU); app_menu_ = new views::MenuButton(NULL, std::wstring(), this, false); app_menu_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_APP)); app_menu_->SetTooltipText(l10n_util::GetStringF(IDS_APPMENU_TOOLTIP, l10n_util::GetString(IDS_PRODUCT_NAME))); app_menu_->SetID(VIEW_ID_APP_MENU); LoadRightSideControlsImages(); AddChildView(page_menu_); AddChildView(app_menu_); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kBookmarkMenu)) { bookmark_menu_ = new BookmarkMenuButton(browser_); AddChildView(bookmark_menu_); } else { bookmark_menu_ = NULL; } } void ToolbarView::LoadLeftSideControlsImages() { ThemeProvider* tp = GetThemeProvider(); SkColor color = tp->GetColor(BrowserThemeProvider::COLOR_BUTTON_BACKGROUND); SkBitmap* background = tp->GetBitmapNamed(IDR_THEME_BUTTON_BACKGROUND); back_->SetImage(views::CustomButton::BS_NORMAL, tp->GetBitmapNamed(IDR_BACK)); back_->SetImage(views::CustomButton::BS_HOT, tp->GetBitmapNamed(IDR_BACK_H)); back_->SetImage(views::CustomButton::BS_PUSHED, tp->GetBitmapNamed(IDR_BACK_P)); back_->SetImage(views::CustomButton::BS_DISABLED, tp->GetBitmapNamed(IDR_BACK_D)); back_->SetBackground(color, background, tp->GetBitmapNamed(IDR_BACK_MASK)); forward_->SetImage(views::CustomButton::BS_NORMAL, tp->GetBitmapNamed(IDR_FORWARD)); forward_->SetImage(views::CustomButton::BS_HOT, tp->GetBitmapNamed(IDR_FORWARD_H)); forward_->SetImage(views::CustomButton::BS_PUSHED, tp->GetBitmapNamed(IDR_FORWARD_P)); forward_->SetImage(views::CustomButton::BS_DISABLED, tp->GetBitmapNamed(IDR_FORWARD_D)); forward_->SetBackground(color, background, tp->GetBitmapNamed(IDR_FORWARD_MASK)); reload_->SetImage(views::CustomButton::BS_NORMAL, tp->GetBitmapNamed(IDR_RELOAD)); reload_->SetImage(views::CustomButton::BS_HOT, tp->GetBitmapNamed(IDR_RELOAD_H)); reload_->SetImage(views::CustomButton::BS_PUSHED, tp->GetBitmapNamed(IDR_RELOAD_P)); reload_->SetBackground(color, background, tp->GetBitmapNamed(IDR_BUTTON_MASK)); home_->SetImage(views::CustomButton::BS_NORMAL, tp->GetBitmapNamed(IDR_HOME)); home_->SetImage(views::CustomButton::BS_HOT, tp->GetBitmapNamed(IDR_HOME_H)); home_->SetImage(views::CustomButton::BS_PUSHED, tp->GetBitmapNamed(IDR_HOME_P)); home_->SetBackground(color, background, tp->GetBitmapNamed(IDR_BUTTON_MASK)); } void ToolbarView::LoadCenterStackImages() { ThemeProvider* tp = GetThemeProvider(); SkColor color = tp->GetColor(BrowserThemeProvider::COLOR_BUTTON_BACKGROUND); SkBitmap* background = tp->GetBitmapNamed(IDR_THEME_BUTTON_BACKGROUND); star_->SetImage(views::CustomButton::BS_NORMAL, tp->GetBitmapNamed(IDR_STAR)); star_->SetImage(views::CustomButton::BS_HOT, tp->GetBitmapNamed(IDR_STAR_H)); star_->SetImage(views::CustomButton::BS_PUSHED, tp->GetBitmapNamed(IDR_STAR_P)); star_->SetImage(views::CustomButton::BS_DISABLED, tp->GetBitmapNamed(IDR_STAR_D)); star_->SetToggledImage(views::CustomButton::BS_NORMAL, tp->GetBitmapNamed(IDR_STARRED)); star_->SetToggledImage(views::CustomButton::BS_HOT, tp->GetBitmapNamed(IDR_STARRED_H)); star_->SetToggledImage(views::CustomButton::BS_PUSHED, tp->GetBitmapNamed(IDR_STARRED_P)); star_->SetBackground(color, background, tp->GetBitmapNamed(IDR_STAR_MASK)); go_->SetImage(views::CustomButton::BS_NORMAL, tp->GetBitmapNamed(IDR_GO)); go_->SetImage(views::CustomButton::BS_HOT, tp->GetBitmapNamed(IDR_GO_H)); go_->SetImage(views::CustomButton::BS_PUSHED, tp->GetBitmapNamed(IDR_GO_P)); go_->SetToggledImage(views::CustomButton::BS_NORMAL, tp->GetBitmapNamed(IDR_STOP)); go_->SetToggledImage(views::CustomButton::BS_HOT, tp->GetBitmapNamed(IDR_STOP_H)); go_->SetToggledImage(views::CustomButton::BS_PUSHED, tp->GetBitmapNamed(IDR_STOP_P)); go_->SetBackground(color, background, tp->GetBitmapNamed(IDR_GO_MASK)); } void ToolbarView::LoadRightSideControlsImages() { ThemeProvider* tp = GetThemeProvider(); // We use different menu button images if the locale is right-to-left. if (UILayoutIsRightToLeft()) page_menu_->SetIcon(*tp->GetBitmapNamed(IDR_MENU_PAGE_RTL)); else page_menu_->SetIcon(*tp->GetBitmapNamed(IDR_MENU_PAGE)); if (UILayoutIsRightToLeft()) app_menu_->SetIcon(*tp->GetBitmapNamed(IDR_MENU_CHROME_RTL)); else app_menu_->SetIcon(*tp->GetBitmapNamed(IDR_MENU_CHROME)); } void ToolbarView::RunPageMenu(const gfx::Point& pt, gfx::NativeView parent) { CreatePageMenu(); page_menu_menu_->RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT); } void ToolbarView::RunAppMenu(const gfx::Point& pt, gfx::NativeView parent) { CreateAppMenu(); app_menu_menu_->RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT); } void ToolbarView::CreatePageMenu() { if (page_menu_contents_.get()) return; page_menu_contents_.reset(new views::SimpleMenuModel(this)); page_menu_contents_->AddItemWithStringId(IDC_CREATE_SHORTCUTS, IDS_CREATE_SHORTCUTS); page_menu_contents_->AddSeparator(); page_menu_contents_->AddItemWithStringId(IDC_CUT, IDS_CUT); page_menu_contents_->AddItemWithStringId(IDC_COPY, IDS_COPY); page_menu_contents_->AddItemWithStringId(IDC_PASTE, IDS_PASTE); page_menu_contents_->AddSeparator(); page_menu_contents_->AddItemWithStringId(IDC_FIND, IDS_FIND); page_menu_contents_->AddItemWithStringId(IDC_SAVE_PAGE, IDS_SAVE_PAGE); page_menu_contents_->AddItemWithStringId(IDC_PRINT, IDS_PRINT); page_menu_contents_->AddSeparator(); zoom_menu_contents_.reset(new ZoomMenuModel(this)); page_menu_contents_->AddSubMenuWithStringId( IDS_ZOOM_MENU, zoom_menu_contents_.get()); encoding_menu_contents_.reset(new EncodingMenuModel(browser_)); page_menu_contents_->AddSubMenuWithStringId( IDS_ENCODING_MENU, encoding_menu_contents_.get()); #if defined(OS_WIN) CreateDevToolsMenuContents(); page_menu_contents_->AddSeparator(); page_menu_contents_->AddSubMenuWithStringId( IDS_DEVELOPER_MENU, devtools_menu_contents_.get()); #endif page_menu_contents_->AddSeparator(); page_menu_contents_->AddItemWithStringId(IDC_REPORT_BUG, IDS_REPORT_BUG); page_menu_menu_.reset(new views::Menu2(page_menu_contents_.get())); } #if defined(OS_WIN) void ToolbarView::CreateDevToolsMenuContents() { devtools_menu_contents_.reset(new views::SimpleMenuModel(this)); devtools_menu_contents_->AddItem(IDC_VIEW_SOURCE, l10n_util::GetString(IDS_VIEW_SOURCE)); devtools_menu_contents_->AddItem(IDC_JS_CONSOLE, l10n_util::GetString(IDS_JS_CONSOLE)); devtools_menu_contents_->AddItem(IDC_TASK_MANAGER, l10n_util::GetString(IDS_TASK_MANAGER)); } #endif void ToolbarView::CreateAppMenu() { if (app_menu_contents_.get()) return; app_menu_contents_.reset(new views::SimpleMenuModel(this)); app_menu_contents_->AddItemWithStringId(IDC_NEW_TAB, IDS_NEW_TAB); app_menu_contents_->AddItemWithStringId(IDC_NEW_WINDOW, IDS_NEW_WINDOW); app_menu_contents_->AddItemWithStringId(IDC_NEW_INCOGNITO_WINDOW, IDS_NEW_INCOGNITO_WINDOW); // Enumerate profiles asynchronously and then create the parent menu item. // We will create the child menu items for this once the asynchronous call is // done. See OnGetProfilesDone(). const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableUserDataDirProfiles)) { profiles_helper_->GetProfiles(NULL); profiles_menu_contents_.reset(new views::SimpleMenuModel(this)); app_menu_contents_->AddSubMenuWithStringId(IDS_PROFILE_MENU, profiles_menu_contents_.get()); } app_menu_contents_->AddSeparator(); app_menu_contents_->AddCheckItemWithStringId(IDC_SHOW_BOOKMARK_BAR, IDS_SHOW_BOOKMARK_BAR); app_menu_contents_->AddItemWithStringId(IDC_FULLSCREEN, IDS_FULLSCREEN); app_menu_contents_->AddSeparator(); app_menu_contents_->AddItemWithStringId(IDC_SHOW_HISTORY, IDS_SHOW_HISTORY); app_menu_contents_->AddItemWithStringId(IDC_SHOW_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER); app_menu_contents_->AddItemWithStringId(IDC_SHOW_DOWNLOADS, IDS_SHOW_DOWNLOADS); app_menu_contents_->AddSeparator(); #ifdef CHROME_PERSONALIZATION if (!Personalization::IsP13NDisabled(profile_)) { app_menu_contents_->AddItem( IDC_P13N_INFO, Personalization::GetMenuItemInfoText(browser())); } #endif app_menu_contents_->AddItemWithStringId(IDC_CLEAR_BROWSING_DATA, IDS_CLEAR_BROWSING_DATA); app_menu_contents_->AddItemWithStringId(IDC_IMPORT_SETTINGS, IDS_IMPORT_SETTINGS); app_menu_contents_->AddSeparator(); app_menu_contents_->AddItem(IDC_OPTIONS, l10n_util::GetStringFUTF16( IDS_OPTIONS, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME))); app_menu_contents_->AddItem(IDC_ABOUT, l10n_util::GetStringFUTF16( IDS_ABOUT, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME))); app_menu_contents_->AddItemWithStringId(IDC_HELP_PAGE, IDS_HELP_PAGE); app_menu_contents_->AddSeparator(); app_menu_contents_->AddItemWithStringId(IDC_EXIT, IDS_EXIT); app_menu_menu_.reset(new views::Menu2(app_menu_contents_.get())); }
37.144152
80
0.689041
zachlatta
d92c489965639b23cace54c0d5c25c0e87a5cb4f
16,839
cpp
C++
mainapp/Classes/Games/Counting/CountingScene.cpp
JaagaLabs/GLEXP-Team-KitkitSchool
f94ea3e53bd05fdeb2a9edcc574bc054e575ecc0
[ "Apache-2.0" ]
45
2019-05-16T20:49:31.000Z
2021-11-05T21:40:54.000Z
mainapp/Classes/Games/Counting/CountingScene.cpp
rdsmarketing/GLEXP-Team-KitkitSchool
6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e
[ "Apache-2.0" ]
123
2019-05-28T14:03:04.000Z
2019-07-12T04:23:26.000Z
pehlaschool/Classes/Games/Counting/CountingScene.cpp
maqsoftware/Pehla-School-Hindi
61aeae0f1d91952b44eaeaff5d2f6ec1d5aa3c43
[ "Apache-2.0" ]
29
2019-05-16T17:49:26.000Z
2021-12-30T16:36:24.000Z
// // CountingScene.cpp // // Created by Gunho Lee on 6/26/16. // // #include "CountingScene.hpp" #include <string> #include <vector> #include <numeric> #include <algorithm> #include "ui/CocosGUI.h" #include "Managers/GameSoundManager.h" #include "Managers/LanguageManager.hpp" #include "Managers/StrictLogManager.h" #include "Utils/TodoUtil.h" #include "Common/Controls/TodoSchoolBackButton.hpp" #include "Common/Controls/CompletePopup.hpp" #include "Common/Basic/AARect.h" #include "Common/Repr/AllRepr.h" #include "CCAppController.hpp" using namespace cocos2d::ui; using namespace std; using namespace todoschool::counting; namespace CountingSceneSpace { const char* solveEffect = "Common/Sounds/Effect/UI_Star_Collected.m4a"; const char* missEffect = "Common/Sounds/Effect/Help.m4a"; const char* hintEffect = "Common/Sounds/Effect/tokenappear.m4a"; const char* touchEffect = "Common/Sounds/Effect/tokenappear.m4a"; const char* dropEffect = "Common/Sounds/Effect/panelput.m4a"; const int tagForMissAction = 100; } using namespace CountingSceneSpace; Scene* CountingScene::createScene(int levelID) { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = CountingScene::create(); layer->setLevel(levelID); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } bool CountingScene::init() { if (!Layer::init()) { return false; } _touchEnabled = false; GameSoundManager::getInstance()->preloadEffect(solveEffect); GameSoundManager::getInstance()->preloadEffect(missEffect); GameSoundManager::getInstance()->preloadEffect(touchEffect); GameSoundManager::getInstance()->preloadEffect(dropEffect); auto winSize = getContentSize(); auto bg = Sprite::create("Counting/counting_image_bg.jpg"); auto bgSize = bg->getContentSize(); float bgScale = MAX(winSize.width/bgSize.width, winSize.height/bgSize.height); bg->setScale(bgScale); bg->setPosition(winSize/2); addChild(bg); _gameNode = Node::create(); auto gameSize = Size(2560, 1800); _gameNode->setContentSize(gameSize); float gameScale = MIN(winSize.width/gameSize.width, winSize.height/gameSize.height); _gameNode->setScale(gameScale); _gameNode->setAnchorPoint(Vec2::ANCHOR_MIDDLE); _gameNode->setPosition(winSize/2); addChild(_gameNode); _answerPad = AnswerPadMulti::create(); _answerPad->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT); _answerPadPos = Point(gameSize.width-82, gameSize.height/2); _answerPad->setPosition(_answerPadPos); _answerPad->setAnswerCallback([this](int answer) { // NB(xenosoz, 2018): Log for future analysis auto workPath = [this] { stringstream ss; ss << "/" << "Counting"; ss << "/" << "level-" << _currentLevel << "-" << _currentSheetID; ss << "/" << "work-" << _currentProblemID; return ss.str(); }(); StrictLogManager::shared()->game_Peek_Answer("Counting", workPath, TodoUtil::itos(answer), TodoUtil::itos(_currentProblem.totalCount)); if (_currentProblem.totalCount == answer) { onSolve(); } else { onMiss(); } }); _answerPad->setVisible(false); _gameNode->addChild(_answerPad); _answerPadOutPos = _gameNode->convertToNodeSpace( Point(winSize.width, winSize.height/2) ) + _answerPad->getContentSize(); _answerPadOutPos.y = gameSize.height/2; _objectNode = Node::create(); _objectNode->setContentSize(Size(gameSize.width/2, gameSize.height-50)); _gameNode->addChild(_objectNode); auto backButton = TodoSchoolBackButton::create(); backButton->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); backButton->setPosition(Vec2(25, winSize.height-25)); addChild(backButton); _progressBar = ProgressIndicator::create(); _progressBar->setPosition(Vec2(winSize.width/2, winSize.height - _progressBar->getContentSize().height)); addChild(_progressBar); if (CCAppController::sharedAppController()->isDebug()) { auto skip = ui::Button::create(); skip->setTitleText("CLEAR"); skip->setTitleFontSize(50); skip->setPosition(Vec2(winSize.width-200, winSize.height-100)); skip->addClickEventListener([this](Ref*) { _currentProblemID = _currentWorksheet.endProblemID()-1; onSolve(); }); addChild(skip); } return true; } void CountingScene::onEnter() { Layer::onEnter(); auto data = LevelData::defaultData(); auto lang = LanguageManager::getInstance()->getCurrentLanguageTag(); auto sheet = data.randomSheetFor(lang, _currentLevel, &_currentSheetID); _progressBar->setMax((int)sheet.size()); _currentWorksheet = sheet; _currentProblemID = sheet.beginProblemID(); _currentProblem = sheet.problemByID(_currentProblemID); } void CountingScene::onEnterTransitionDidFinish() { onStart(); } void attachNumber(Node* object, int number) { auto n = Button::create(); n->loadTextureNormal("Counting/counting_image_digit_common_countNumber_BG.png"); n->setTitleText(TodoUtil::itos(number)); n->setTitleFontSize(70); n->setAnchorPoint(Vec2::ANCHOR_MIDDLE); n->setPosition(object->getContentSize()/2); object->addChild(n, 10, "Number"); } void detachNumber(Node* object) { object->removeChildByName("Number"); } void CountingScene::onStart() { _objectNode->removeAllChildren(); _progressBar->setCurrent(_currentProblemID - _currentWorksheet.beginProblemID() + 1); _answerPad->setAnswerDigitCount((int)TodoUtil::itos(_currentProblem.totalCount).size()); setTouchEnabled(true); _objects.clear(); _touchedObjects = 0; _touchedValue = 0; float appearTime = 0; putObjects(appearTime); _answerPad->setPosition(_answerPadOutPos); _answerPad->setVisible(true); auto seq = Sequence::create(DelayTime::create(appearTime+0.2), EaseIn::create(MoveTo::create(0.2, _answerPadPos), 3.0), nullptr); //auto seq = Sequence::create(EaseBounceOut::create(MoveTo::create(0.3, _answerPadPos)), nullptr); _answerPad->runAction(seq); } void CountingScene::onSolve() { setTouchEnabled(false); GameSoundManager::getInstance()->playAdultVoice(_currentProblem.totalCount); scheduleOnce([](float) { // Sound delay GameSoundManager::getInstance()->playEffectSound(solveEffect); }, 1.0, "number"); if (_currentProblemID + 1 == _currentWorksheet.endProblemID()) { _progressBar->setCurrent(_currentProblemID - _currentWorksheet.beginProblemID() + 1, true); CompletePopup::create()->show(2.0, [](){ CCAppController::sharedAppController()->handleGameComplete(1); }); } else { _progressBar->setCurrent(_currentProblemID - _currentWorksheet.beginProblemID() + 1, true); _currentProblemID++; _currentProblem = _currentWorksheet.problemByID(_currentProblemID); auto seq = Sequence::create( DelayTime::create(2.0), EaseOut::create(MoveTo::create(0.2, _answerPadOutPos), 3.0), DelayTime::create(0.2), CallFunc::create([this]{ _answerPad->clearAnswer(); this->onStart(); }), nullptr); _answerPad->runAction(seq); } } void CountingScene::onMiss() { setTouchEnabled(false); GameSoundManager::getInstance()->playEffectSound(missEffect); const float countDelay = .2f; //int remainCount = (int)_objects.size(); //const float countDuration = countDelay * remainCount; int tempCount = _touchedObjects; int tempValue = _touchedValue; Vector<FiniteTimeAction*> actions; actions.pushBack(DelayTime::create(.5f)); // NB(xenosoz, 2016): Clear all children first. actions.pushBack(CallFunc::create([this] { for (auto object : _objects) detachNumber(object); })); actions.pushBack(DelayTime::create(.5f)); // NB(xenosoz, 2016): Relabel all objects respecting the following rules: // 1. keep the user input ordering // 2. y-pos of the object (top to bottom) // 3. x-pos of the object (left to right) vector<size_t> ordering(_objects.size()); iota(ordering.begin(), ordering.end(), 0); sort(ordering.begin(), ordering.end(), [&](size_t lhs, size_t rhs) { auto intMax = numeric_limits<int>::max(); auto valueFn = [&](int t) { return (t != 0 ? t : intMax); }; auto lvalue = valueFn(_objects[lhs]->value()); auto rvalue = valueFn(_objects[rhs]->value()); if (lvalue != rvalue) { return lvalue < rvalue; } auto lpos = _objects[lhs]->getPosition(); auto rpos = _objects[rhs]->getPosition(); if (lpos.y != rpos.y) { return lpos.y > rpos.y; } return lpos.x < rpos.x; }); for (size_t index : ordering) { auto object = _objects[index]; int label = object->value(); if (object->value() == 0) { tempCount += 1; tempValue += object->weight(); label = tempValue; } actions.pushBack(CallFunc::create([this, object, label] { GameSoundManager::getInstance()->playEffectSound(hintEffect); attachNumber(object, label); })); actions.pushBack(DelayTime::create(countDelay)); } // NB(xenosoz, 2016): Remove children for all nodes and clear the user input. actions.pushBack(DelayTime::create(1.5f - countDelay)); actions.pushBack(CallFunc::create([this] { _answerPad->clearAnswer(); setTouchEnabled(true); for (auto object : _objects) { object->setValue(0); detachNumber(object); } _touchedObjects = 0; _touchedValue = 0; })); auto seq = Sequence::create(actions); seq->setTag(tagForMissAction); stopActionByTag(seq->getTag()); runAction(seq); } void CountingScene::setLevel(int level) { _currentLevel = level; } void CountingScene::setTouchEnabled(bool enabled) { _touchEnabled = enabled; _answerPad->setTouchEnabled(enabled); } void CountingScene::putObjects(float& appearTime) { auto areaSize = _objectNode->getContentSize(); vector<AARect> occupied; auto putObject = [&](const string& objectSkin, const string& shadowSkin, int weight, int areaLimitIndex = 0, int areaLimitNum = 0) { auto localAreaSize = areaSize; auto localAreaBottom = 0; if (areaLimitNum>0) { localAreaSize.height = areaSize.height/areaLimitNum; localAreaBottom = localAreaSize.height*(areaLimitNum-areaLimitIndex-1); } auto shadow = Sprite::create(shadowSkin); // Nullable auto object = CountingObject::create(objectSkin, weight); auto objectSize = object->getContentSize(); float bestScore = -numeric_limits<float>::infinity(); Point bestPos; Rect bestRect; for (int trial = 0; trial < 10; ++trial) { auto& os = objectSize; float x = random<float>(os.width / 2.f, localAreaSize.width - os.width / 2.f); float y = random<float>(os.height / 2.f, localAreaSize.height - os.height / 2.f); auto pos = Point(x, y + localAreaBottom); AARect rect(pos.x - os.width / 2.f, pos.y - os.height / 2.f, os.width, os.height); float score = 0.f; for (auto obstacle : occupied) score -= rect.intersection(obstacle).area(); if (bestScore <= score) { bestScore = score; bestPos = pos; bestRect = rect; } } auto pos = bestPos; auto p0 = Point(pos.x, pos.y+300); occupied.push_back(bestRect); // if (shadow) { shadow->setScale(0.5); shadow->setPosition(pos); shadow->setOpacity(0); _objectNode->addChild(shadow); } object->setValue(0); object->onTouchEvent = [this, object](Widget::TouchEventType event) { if (!_touchEnabled || !object) { return; } object->getParent()->reorderChild(object, object->getLocalZOrder()); if (object->value() != 0) { // NB(xenosoz, 2016): Nonzero value // -> We already finished counting. return; } if (event != Widget::TouchEventType::BEGAN) { return; } _touchedObjects++; _touchedValue += object->weight(); object->setValue(_touchedValue); attachNumber(object, _touchedValue); GameSoundManager::getInstance()->playEffectSound(touchEffect); }; object->setAnchorPoint(Vec2::ANCHOR_MIDDLE); object->setPosition(p0); object->setOpacity(0); _objects.push_back(object); _objectNode->addChild(object); // auto delay = random(0.05, 0.2); const float actionTime = 0.3; appearTime+=delay; if (shadow) { shadow->runAction(Sequence::create( DelayTime::create(appearTime), Spawn::create(FadeIn::create(actionTime), EaseBounceOut::create(ScaleTo::create(actionTime, 1.0)), nullptr), nullptr)); } object->runAction(Sequence::create( DelayTime::create(appearTime), Spawn::create(FadeIn::create(actionTime), EaseBounceOut::create(MoveTo::create(actionTime, pos)), nullptr), CallFunc::create([](){ GameSoundManager::getInstance()->playEffectSound(dropEffect); }), nullptr )); }; // NB(xenosoz, 2016): Tallies (W=5, W=1) int talliesToGo = _currentProblem.tallyCount; int tallyVari5 = 1; int tallyVari1 = random(1, 2); auto tallyObject5 = StringUtils::format("Counting/branch_five_%02d.png", tallyVari5); auto tallyObject1 = StringUtils::format("Counting/branch_one_%02d.png", tallyVari1); auto tallyShadow5 = StringUtils::format("Counting/branch_five_%02d_shadow.png", tallyVari5); auto tallyShadow1 = StringUtils::format("Counting/branch_one_%02d_shadow.png", tallyVari1); int talliesAreaLimitNum = ((talliesToGo%5==0) || (talliesToGo<5)) ? 0 : 2; while (talliesToGo >= 5) { putObject(tallyObject5, tallyShadow5, 5, 0, talliesAreaLimitNum); talliesToGo -= 5; } while (talliesToGo >= 1) { putObject(tallyObject1, tallyShadow1, 1, 1, talliesAreaLimitNum); talliesToGo -= 1; } // NB(xenosoz, 2016): Stones int stonesCount = _currentProblem.stoneCount; int stoneVariVector[5] = { 1, 2, 3, 4, 5}; random_shuffle(std::begin(stoneVariVector), std::end(stoneVariVector)); int stoneVari = random(0, 4); int areaLimitNum = (stonesCount<=5) ? 0 : (stonesCount+4)/5; int areaLimitIndex = 0; while (stonesCount>0) { int stoneStyle = stoneVariVector[stoneVari]; string stoneObjectSkin = "Counting/stone_0"+TodoUtil::itos(stoneStyle)+".png"; string stoneShadowSkin = "Counting/stone_0"+TodoUtil::itos(stoneStyle)+"_shadow.png"; int thisStoneCount = MIN(5, stonesCount); for (int i = 0; i < thisStoneCount; i++) putObject(stoneObjectSkin, stoneShadowSkin, 1, areaLimitIndex, areaLimitNum); stonesCount -= thisStoneCount; stoneVari++; if (stoneVari>4) stoneVari = 0; areaLimitIndex++; } }
31.952562
155
0.59285
JaagaLabs
d92ca35877a6024fce9849069d63a77850dcb12c
11,476
cpp
C++
Arch(C&C++)/eb189527d6ecb920cd6dc02651c9af01/DevconCmd.cpp
bhbk/3as8kpsf
7da56a0f125c59104bc80950792c1c904b2a12f1
[ "Apache-2.0" ]
1
2019-01-12T15:30:46.000Z
2019-01-12T15:30:46.000Z
Arch(C&C++)/eb189527d6ecb920cd6dc02651c9af01/DevconCmd.cpp
bhbk/3as8kpsf
7da56a0f125c59104bc80950792c1c904b2a12f1
[ "Apache-2.0" ]
null
null
null
Arch(C&C++)/eb189527d6ecb920cd6dc02651c9af01/DevconCmd.cpp
bhbk/3as8kpsf
7da56a0f125c59104bc80950792c1c904b2a12f1
[ "Apache-2.0" ]
null
null
null
#include "Devcon.h" #include "DevconDump.h" #include "DevconDumpMsg.h" #include "DevconCmd.h" int CmdClassDeviceList(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[], LPTSTR* rslts[]) /*++ Routine Description: LISTCLASS <name>.... lists all devices for each specified class there can be more than one physical class for a class name (shouldn't be though) in such cases, list each class if machine given, list devices for that machine Arguments: BaseName - name of executable Machine - if non-NULL, remote machine argc/argv - remaining parameters - list of class names Return Value: EXIT_xxxx --*/ { BOOL classListed = FALSE; BOOL devListed = FALSE; DWORD reqGuids = 16; int argIndex; int failcode = EXIT_FAIL; LPGUID guids = NULL; HDEVINFO devs = INVALID_HANDLE_VALUE; if(!argc) { return EXIT_USAGE; } guids = new GUID[reqGuids]; if(!guids) { goto final; } for(argIndex = 0; argIndex < argc; argIndex++) { DWORD numGuids; DWORD index; if(!(argv[argIndex] && argv[argIndex][0])) { continue; } // there could be one to many name to GUID mapping while(!SetupDiClassGuidsFromNameEx(argv[argIndex],guids,reqGuids,&numGuids,Machine,NULL)) { if(GetLastError() != ERROR_INSUFFICIENT_BUFFER) { goto final; } delete [] guids; reqGuids = numGuids; guids = new GUID[reqGuids]; if(!guids) { goto final; } } if(numGuids == 0) { FormatToStream(stdout,Machine?MSG_LISTCLASS_NOCLASS:MSG_LISTCLASS_NOCLASS_LOCAL,argv[argIndex],Machine); continue; } for(index = 0; index < numGuids; index++) { TCHAR className[MAX_CLASS_NAME_LEN]; TCHAR classDesc[LINE_LEN]; DWORD devCount = 0; SP_DEVINFO_DATA devInfo; DWORD devIndex; devs = SetupDiGetClassDevsEx(&guids[index],NULL,NULL,DIGCF_PRESENT,NULL,Machine,NULL); if(devs != INVALID_HANDLE_VALUE) { // count number of devices devInfo.cbSize = sizeof(devInfo); while(SetupDiEnumDeviceInfo(devs, devCount, &devInfo)) { devCount++; } } if(!SetupDiClassNameFromGuidEx(&guids[index], className, MAX_CLASS_NAME_LEN, NULL, Machine, NULL)) { lstrcpyn(className,TEXT("?"),MAX_CLASS_NAME_LEN); } if(!SetupDiGetClassDescriptionEx(&guids[index], classDesc, LINE_LEN, NULL, Machine, NULL)) { lstrcpyn(classDesc,className,LINE_LEN); } // how many devices? if (!devCount) { FormatToStream(stdout,Machine?MSG_LISTCLASS_HEADER_NONE:MSG_LISTCLASS_HEADER_NONE_LOCAL,className,classDesc,Machine); } else { FormatToStream(stdout,Machine?MSG_LISTCLASS_HEADER:MSG_LISTCLASS_HEADER_LOCAL,devCount,className,classDesc,Machine); for(devIndex = 0; SetupDiEnumDeviceInfo(devs, devIndex, &devInfo); devIndex++) { rslts[devIndex] = (LPTSTR*)GetDeviceWithInfo(devs, &devInfo); // DumpDevice(devs, &devInfo); } } if(devs != INVALID_HANDLE_VALUE) { SetupDiDestroyDeviceInfoList(devs); devs = INVALID_HANDLE_VALUE; } } } failcode = 0; final: if(guids) { delete [] guids; } if(devs != INVALID_HANDLE_VALUE) { SetupDiDestroyDeviceInfoList(devs); } return failcode; } int CmdClasses(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[], LPTSTR* rslts[]) /*++ Routine Description: CLASSES command lists classes on (optionally) specified machine format as <name>: <destination> Arguments: BaseName - name of executable Machine - if non-NULL, remote machine argc/argv - remaining parameters - ignored Return Value: EXIT_xxxx --*/ { DWORD reqGuids = 128; DWORD numGuids; LPGUID guids = NULL; DWORD index; int failcode = EXIT_FAIL; guids = new GUID[reqGuids]; if(!guids) { goto final; } if(!SetupDiBuildClassInfoListEx(0, guids, reqGuids, &numGuids, Machine, NULL)) { do { if(GetLastError() != ERROR_INSUFFICIENT_BUFFER) { goto final; } delete [] guids; reqGuids = numGuids; guids = new GUID[reqGuids]; if(!guids) { goto final; } } while(!SetupDiBuildClassInfoListEx(0, guids, reqGuids, &numGuids, Machine, NULL)); } FormatToStream(stdout,Machine?MSG_CLASSES_HEADER:MSG_CLASSES_HEADER_LOCAL,numGuids,Machine); for(index = 0; index < numGuids; index++) { TCHAR className[MAX_CLASS_NAME_LEN]; TCHAR classDesc[LINE_LEN]; if(!SetupDiClassNameFromGuidEx(&guids[index], className, MAX_CLASS_NAME_LEN, NULL, Machine, NULL)) { lstrcpyn(className,TEXT("?"),MAX_CLASS_NAME_LEN); } if(!SetupDiGetClassDescriptionEx(&guids[index], classDesc, LINE_LEN, NULL, Machine, NULL)) { lstrcpyn(classDesc,className,LINE_LEN); } _tprintf(TEXT("%-20s: %s\n"), className, classDesc); } failcode = EXIT_OK; final: if(guids) { delete [] guids; } return failcode; } int CmdDeviceEnable(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[]) /*++ Routine Description: ENABLE <id> ... use EnumerateDevices to do hardwareID matching for each match, attempt to enable global, and if needed, config specific Arguments: BaseName - name of executable Machine - must be NULL (local machine only) argc/argv - remaining parameters - passed into EnumerateDevices Return Value: EXIT_xxxx (EXIT_REBOOT if reboot is required) --*/ { GenericContext context; TCHAR strEnable[80]; TCHAR strReboot[80]; TCHAR strFail[80]; int failcode = EXIT_FAIL; if(!argc) { // arguments required return EXIT_USAGE; } if(Machine) { // must be local machine as we need to involve class/co installers return EXIT_USAGE; } /* if(!LoadString(NULL,IDS_ENABLED,strEnable,ARRAYSIZE(strEnable))) { return EXIT_FAIL; } if(!LoadString(NULL,IDS_ENABLED_REBOOT,strReboot,ARRAYSIZE(strReboot))) { return EXIT_FAIL; } if(!LoadString(NULL,IDS_ENABLE_FAILED,strFail,ARRAYSIZE(strFail))) { return EXIT_FAIL; } */ context.control = DICS_ENABLE; // DICS_PROPCHANGE DICS_ENABLE DICS_DISABLE context.reboot = FALSE; context.count = 0; context.strReboot = strReboot; context.strSuccess = strEnable; context.strFail = strFail; failcode = EnumerateDevices(BaseName,Machine,DIGCF_PRESENT,argc,argv,ControlCallback,&context); if(failcode == EXIT_OK) { if(!context.count) { FormatToStream(stdout,MSG_ENABLE_TAIL_NONE); } else if(!context.reboot) { FormatToStream(stdout,MSG_ENABLE_TAIL,context.count); } else { FormatToStream(stdout,MSG_ENABLE_TAIL_REBOOT,context.count); failcode = EXIT_REBOOT; } } return failcode; } int CmdDeviceDisable(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[]) /*++ Routine Description: DISABLE <id> ... use EnumerateDevices to do hardwareID matching for each match, attempt to disable global Arguments: BaseName - name of executable Machine - must be NULL (local machine only) argc/argv - remaining parameters - passed into EnumerateDevices Return Value: EXIT_xxxx (EXIT_REBOOT if reboot is required) --*/ { GenericContext context; TCHAR strDisable[80]; TCHAR strReboot[80]; TCHAR strFail[80]; int failcode = EXIT_FAIL; // UNREFERENCED_PARAMETER(Flags); if(!argc) { // arguments required return EXIT_USAGE; } if(Machine) { // must be local machine as we need to involve class/co installers return EXIT_USAGE; } /* if(!LoadString(NULL,IDS_DISABLED,strDisable,ARRAYSIZE(strDisable))) { return EXIT_FAIL; } if(!LoadString(NULL,IDS_DISABLED_REBOOT,strReboot,ARRAYSIZE(strReboot))) { return EXIT_FAIL; } if(!LoadString(NULL,IDS_DISABLE_FAILED,strFail,ARRAYSIZE(strFail))) { return EXIT_FAIL; } */ context.control = DICS_DISABLE; // DICS_PROPCHANGE DICS_ENABLE DICS_DISABLE context.reboot = FALSE; context.count = 0; context.strReboot = strReboot; context.strSuccess = strDisable; context.strFail = strFail; failcode = EnumerateDevices(BaseName,Machine,DIGCF_PRESENT,argc,argv,ControlCallback,&context); if(failcode == EXIT_OK) { if(!context.count) { FormatToStream(stdout,MSG_DISABLE_TAIL_NONE); } else if(!context.reboot) { FormatToStream(stdout,MSG_DISABLE_TAIL,context.count); } else { FormatToStream(stdout,MSG_DISABLE_TAIL_REBOOT,context.count); failcode = EXIT_REBOOT; } } return failcode; } int CmdDeviceStatus(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[]) /*++ Routine Description: STATUS <id> ... use EnumerateDevices to do hardwareID matching for each match, dump status to stdout note that we only enumerate present devices Arguments: BaseName - name of executable Machine - if non-NULL, remote machine argc/argv - remaining parameters - passed into EnumerateDevices Return Value: EXIT_xxxx --*/ { GenericContext context; int failcode; if(!argc) { return EXIT_USAGE; } context.count = 0; context.control = FIND_DEVICE | FIND_STATUS; failcode = EnumerateDevices(BaseName,Machine,DIGCF_PRESENT,argc,argv,FindCallback,&context); if(failcode == EXIT_OK) { if(!context.count) { FormatToStream(stdout,Machine?MSG_FIND_TAIL_NONE:MSG_FIND_TAIL_NONE_LOCAL,Machine); } else { FormatToStream(stdout,Machine?MSG_FIND_TAIL:MSG_FIND_TAIL_LOCAL,context.count,Machine); } } return failcode; } int CmdFind(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[], LPTSTR* rslts[]) /*++ Routine Description: FIND <id> ... use EnumerateDevices to do hardwareID matching for each match, dump to stdout note that we only enumerate present devices Arguments: BaseName - name of executable Machine - if non-NULL, remote machine argc/argv - remaining parameters - passed into EnumerateDevices Return Value: EXIT_xxxx --*/ { GenericContext context; int failcode; if(!argc) { return EXIT_USAGE; } context.count = 0; context.control = 0; failcode = EnumerateDevices(BaseName, Machine, DIGCF_PRESENT, argc, argv, FindCallback, &context); if(failcode == EXIT_OK) { if(!context.count) { FormatToStream(stdout,Machine?MSG_FIND_TAIL_NONE:MSG_FIND_TAIL_NONE_LOCAL,Machine); } else { FormatToStream(stdout,Machine?MSG_FIND_TAIL:MSG_FIND_TAIL_LOCAL,context.count,Machine); } } return failcode; }
28.834171
133
0.629313
bhbk
d92ef2f2876440f6b057ff0051e235de10df37d9
6,724
cpp
C++
src/renderer.cpp
baines/engine
d26339c780e4c9accec0ed7a60d2c3bcc33171d3
[ "WTFPL" ]
4
2015-03-04T19:22:55.000Z
2020-01-06T02:31:48.000Z
src/renderer.cpp
baines/engine
d26339c780e4c9accec0ed7a60d2c3bcc33171d3
[ "WTFPL" ]
null
null
null
src/renderer.cpp
baines/engine
d26339c780e4c9accec0ed7a60d2c3bcc33171d3
[ "WTFPL" ]
null
null
null
#include "renderer.h" #include "engine.h" #include "enums.h" #include "config.h" #include "cli.h" #include "texture.h" #include "sampler.h" #include <math.h> #include <climits> #define GLM_FORCE_RADIANS #include <glm/gtc/matrix_transform.hpp> Renderer::Renderer(Engine& e, const char* name) : renderables () , render_state () , gl_debug (e.cfg->addVar<CVarBool> ("gl_debug", true)) , gl_fwd_compat (e.cfg->addVar<CVarBool> ("gl_fwd_compat", true)) , gl_core_profile (e.cfg->addVar<CVarBool> ("gl_core_profile", true)) , libgl (e.cfg->addVar<CVarString> ("gl_library", "")) , window_width (e.cfg->addVar<CVarInt> ("vid_width" , 640, 320, INT_MAX)) , window_height (e.cfg->addVar<CVarInt> ("vid_height", 480, 240, INT_MAX)) , vsync (e.cfg->addVar<CVarInt> ("vid_vsync", 1, -2, 2)) , fov (e.cfg->addVar<CVarInt> ("vid_fov", 90, 45, 135)) , display_index (e.cfg->addVar<CVarInt> ("vid_display_index", 0, 0, 100)) , fullscreen (e.cfg->addVar<CVarBool> ("vid_fullscreen", false)) , resizable (e.cfg->addVar<CVarBool> ("vid_resizable", true)) , window_title (name) , window (nullptr) , main_uniforms () , window_w (window_width->val) , window_h (window_height->val) { SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); if(SDL_InitSubSystem(SDL_INIT_VIDEO) != 0){ log(logging::fatal, "Couldn't initialize SDL video subsystem (%s).", SDL_GetError()); } e.cfg->addVar<CVarFunc>("vid_reload", [&](const alt::StrRef&){ reload(e); return true; }); std::initializer_list<CVar*> reload_vars = { gl_debug, gl_fwd_compat, gl_core_profile, libgl, window_width, window_height, vsync, fov, display_index, fullscreen, resizable }; for(auto* v : reload_vars){ v->setReloadVar("vid_reload"); } e.cfg->addVar<CVarFunc>("vid_display_info", [&](const alt::StrRef&){ char buf[80] = {}; SDL_Rect r; e.cli->echo("Displays:"); int num_disp = SDL_GetNumVideoDisplays(); for(int i = 0; i < num_disp; ++i){ SDL_GetDisplayBounds(i, &r); const char* name = SDL_GetDisplayName(i); snprintf(buf, sizeof(buf), " %d: [%dx%d+%d+%d] '%s'", i, r.w, r.h, r.x, r.y, name ? name : "(no name)" ); e.cli->echo(reinterpret_cast<const char*>(buf)); } return true; }, "Show info about available displays / monitors"); reload(e); } void Renderer::reload(Engine& e){ //TODO: check if we can get away with just using SDL_SetWindow{Size, Position} e.t.c. // instead of destroying the window & GL context. gl.deleteContext(); if(window){ SDL_DestroyWindow(window); window = nullptr; } SDL_GL_UnloadLibrary(); if(SDL_GL_LoadLibrary(libgl->str.empty() ? nullptr : libgl->str.c_str()) < 0){ log(logging::fatal, "Couldn't load OpenGL library! (%s).", SDL_GetError()); } render_state = {}; SDL_GL_SetAttribute(SDL_GL_RED_SIZE , 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE , 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE , 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE , 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER , 1); constexpr struct glversion { int maj, min; } ctx_versions[] = { { 4, 5 }, { 4, 4 }, { 4, 3 }, { 4, 2 }, { 4, 1 }, { 4, 0 }, { 3, 3 }, { 3, 2 }, { 3, 1 }, { 3, 0 }, { 2, 1 }, { 2, 0 } }; bool created = false; for(auto& v : ctx_versions){ #ifndef __EMSCRIPTEN__ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, v.maj); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, v.min); if(gl_core_profile->val && v.maj >= 3){ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); } else { SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); } int ctx_flags = 0; if(gl_debug->val){ ctx_flags |= SDL_GL_CONTEXT_DEBUG_FLAG; } if(gl_fwd_compat->val && v.maj >= 3){ ctx_flags |= SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, ctx_flags); #endif int window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN; if(fullscreen->val){ window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; } if(resizable->val){ window_flags |= SDL_WINDOW_RESIZABLE; } display_index->val = std::min(display_index->val, SDL_GetNumVideoDisplays()-1); window = SDL_CreateWindow( window_title, SDL_WINDOWPOS_CENTERED_DISPLAY(display_index->val), SDL_WINDOWPOS_CENTERED_DISPLAY(display_index->val), window_width->val, window_height->val, window_flags ); if((created = gl.createContext(e, window))){ break; } else { if(window) SDL_DestroyWindow(window); } } if(!created){ log(logging::fatal, "Couldn't get an OpenGL context of any version!"); } SDL_SetWindowMinimumSize(window, window_width->min, window_height->min); SDL_ShowWindow(window); gl.Enable(GL_BLEND); SDL_GL_SetSwapInterval(vsync->val); handleResize(window_width->val, window_height->val); } void Renderer::handleResize(float w, float h){ window_width->val = w; window_height->val = h; if(gl.initialized()){ gl.Viewport(0, 0, w, h); main_uniforms.setUniform("u_ortho", { glm::ortho(0.f, w, h, 0.f) }); const float half_angle = (fov->val / 360.f) * M_PI; const float x_dist = tan(half_angle); const float y_dist = x_dist * (h/w); main_uniforms.setUniform("u_perspective", { glm::frustum(-x_dist, x_dist, -y_dist, y_dist, 1.0f, 1000.0f) }); } } void Renderer::drawFrame(){ gl.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); for(auto i = renderables.begin(), j = renderables.end(); i != j; ++i){ auto* r = *i; VertexState* v = r->vertex_state; if(!v) continue; r->blend_mode.bind(render_state); if(ShaderProgram* s = r->shader){ s->bind(render_state); s->setAttribs(render_state, *v); s->setUniforms(main_uniforms); if(ShaderUniforms* u = r->uniforms){ s->setUniforms(*u); } } for(size_t i = 0; i < r->textures.size(); ++i){ if(const Texture* t = r->textures[i]){ t->bind(i, render_state); } if(const Sampler* s = r->samplers[i]){ s->bind(i, render_state); } } v->bind(render_state); if(IndexBuffer* ib = v->getIndexBuffer()){ gl.DrawElements(r->prim_type, r->count, ib->getType(), reinterpret_cast<GLvoid*>(r->offset)); } else { gl.DrawArrays(r->prim_type, r->offset, r->count); } } SDL_GL_SwapWindow(window); renderables.clear(); } void Renderer::addRenderable(Renderable& r){ renderables.push_back(&r); } Renderer::~Renderer(){ gl.deleteContext(); if(window){ SDL_DestroyWindow(window); } SDL_GL_UnloadLibrary(); SDL_QuitSubSystem(SDL_INIT_VIDEO); }
26.896
96
0.654819
baines
d930dfa0ae50ab72dc0a28bebcfb5395332b81d0
3,029
hh
C++
src/bugengine/filesystem/api/bugengine/filesystem/file.script.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
4
2015-05-13T16:28:36.000Z
2017-05-24T15:34:14.000Z
src/bugengine/filesystem/api/bugengine/filesystem/file.script.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
null
null
null
src/bugengine/filesystem/api/bugengine/filesystem/file.script.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
1
2017-03-21T08:28:07.000Z
2017-03-21T08:28:07.000Z
/* BugEngine <bugengine.devel@gmail.com> see LICENSE for detail */ #ifndef BE_FILESYSTEM_FILE_FILE_SCRIPT_HH_ #define BE_FILESYSTEM_FILE_FILE_SCRIPT_HH_ /**************************************************************************************************/ #include <bugengine/filesystem/stdafx.h> #include <bugengine/core/string/istring.hh> #include <bugengine/kernel/interlocked_stack.hh> #include <bugengine/minitl/intrusive_list.hh> namespace BugEngine { class Folder; class be_api(FILESYSTEM) File : public minitl::refcountable { friend class Folder; public: class Ticket; friend class Ticket; public: struct Media { enum Type { Disk, Network, Dvd, Package, Unknown }; Type type; u32 index; u64 offset; Media(Type t, u32 i, u64 o) : type(t), index(i), offset(o) { } }; protected: const ifilename m_filename; const Media m_media; u64 m_size; u64 m_state; protected: File(ifilename filename, Media media, u64 size, u64 state); public: ~File(); public: class Ticket : public minitl::refcountable { friend class File; public: enum Action { Read, Write }; Action const action; weak< const File > file; minitl::Allocator::Block< u8 > buffer; i_u32 processed; const i64 offset; const u32 total; i_bool error; bool text; inline bool done() const { return error || processed == total; } public: Ticket(minitl::Allocator& arena, weak< const File > file, i64 offset, u32 size, bool text); Ticket(minitl::Allocator& arena, weak< const File > file, i64 offset, u32 size, bool text, const void* data); ~Ticket(); private: Ticket(const Ticket&); Ticket& operator=(const Ticket&); }; ref< const Ticket > beginRead(u32 size = 0, i64 offset = 0, bool text = false, minitl::Allocator& arena = Arena::temporary()) const; ref< const Ticket > beginWrite(const void* data, u32 size, i64 offset = -1); void fillBuffer(weak< Ticket > ticket) const; void writeBuffer(weak< Ticket > ticket) const; u64 getState() const; bool isDeleted() const; bool isReloadable() const; ifilename getFileName() const { return m_filename; } private: virtual void doFillBuffer(weak< Ticket > ticket) const = 0; virtual void doWriteBuffer(weak< Ticket > ticket) const = 0; protected: void refresh(u64 fileSize, u64 state); }; } // namespace BugEngine /**************************************************************************************************/ #endif
25.453782
100
0.522615
bugengine
d9317204781e2433c47d7c13b28a2a0544a4f8d9
3,049
cc
C++
ui/app_list/views/contents_switcher_view.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-16T03:57:28.000Z
2021-01-23T15:29:45.000Z
ui/app_list/views/contents_switcher_view.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/app_list/views/contents_switcher_view.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-04-17T13:19:09.000Z
2021-10-21T12:55:15.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/app_list/views/contents_switcher_view.h" #include "ui/app_list/app_list_constants.h" #include "ui/app_list/views/contents_view.h" #include "ui/gfx/canvas.h" #include "ui/views/controls/button/custom_button.h" #include "ui/views/layout/box_layout.h" namespace app_list { namespace { const int kPreferredHeight = 36; const int kButtonSpacing = 4; const int kButtonWidth = 36; const int kButtonHeight = 36; class ContentsSwitcherButton : public views::CustomButton { public: explicit ContentsSwitcherButton(views::ButtonListener* listener, ContentsView::ShowState show_state) : views::CustomButton(listener) { set_tag(show_state); } virtual ~ContentsSwitcherButton() {} // Overridden from views::View: virtual gfx::Size GetPreferredSize() OVERRIDE { return gfx::Size(kButtonWidth, kButtonHeight); } virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE { PaintButton( canvas, state() == STATE_HOVERED ? kPagerHoverColor : kPagerNormalColor); } private: // Paints a rectangular button. void PaintButton(gfx::Canvas* canvas, SkColor base_color) { gfx::Rect rect(GetContentsBounds()); rect.ClampToCenteredSize(gfx::Size(kButtonWidth, kButtonHeight)); SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); paint.setColor(base_color); canvas->DrawRect(rect, paint); } DISALLOW_COPY_AND_ASSIGN(ContentsSwitcherButton); }; } // namespace ContentsSwitcherView::ContentsSwitcherView(ContentsView* contents_view) : contents_view_(contents_view), buttons_(new views::View) { AddChildView(buttons_); buttons_->SetLayoutManager(new views::BoxLayout( views::BoxLayout::kHorizontal, 0, 0, kButtonSpacing)); buttons_->AddChildView( new ContentsSwitcherButton(this, ContentsView::SHOW_APPS)); buttons_->AddChildView( new ContentsSwitcherButton(this, ContentsView::SHOW_SEARCH_RESULTS)); } ContentsSwitcherView::~ContentsSwitcherView() {} gfx::Size ContentsSwitcherView::GetPreferredSize() { return gfx::Size(buttons_->GetPreferredSize().width(), kPreferredHeight); } void ContentsSwitcherView::Layout() { gfx::Rect rect(GetContentsBounds()); // Makes |buttons_| horizontally center and vertically fill. gfx::Size buttons_size(buttons_->GetPreferredSize()); gfx::Rect buttons_bounds(rect.CenterPoint().x() - buttons_size.width() / 2, rect.y(), buttons_size.width(), rect.height()); buttons_->SetBoundsRect(gfx::IntersectRects(rect, buttons_bounds)); } void ContentsSwitcherView::ButtonPressed(views::Button* sender, const ui::Event& event) { contents_view_->SetShowState( static_cast<ContentsView::ShowState>(sender->tag())); } } // namespace app_list
30.79798
77
0.706789
shaochangbin
d931b4bb767b99e5cae981643443bc7174c7d905
14,119
cc
C++
chrome/browser/ui/popup_browsertest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
chrome/browser/ui/popup_browsertest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
chrome/browser/ui/popup_browsertest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 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 <string> #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/embedder_support/switches.h" #include "components/permissions/permission_request_manager.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/display/screen_base.h" #include "ui/display/test/scoped_screen_override.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" #include "url/gurl.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/shell.h" #include "ui/display/test/display_manager_test_api.h" #endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace { // Tests of window placement for popup browser windows. Test fixtures are run // with and without the experimental WindowPlacement blink feature. class PopupBrowserTest : public InProcessBrowserTest, public ::testing::WithParamInterface<bool> { protected: PopupBrowserTest() = default; ~PopupBrowserTest() override = default; void SetUpCommandLine(base::CommandLine* command_line) override { InProcessBrowserTest::SetUpCommandLine(command_line); base::CommandLine::ForCurrentProcess()->AppendSwitch( embedder_support::kDisablePopupBlocking); const bool enable_window_placement = GetParam(); base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( enable_window_placement ? switches::kEnableBlinkFeatures : switches::kDisableBlinkFeatures, "WindowPlacement"); } display::Display GetDisplayNearestBrowser(const Browser* browser) const { return display::Screen::GetScreen()->GetDisplayNearestWindow( browser->window()->GetNativeWindow()); } Browser* OpenPopup(Browser* browser, const std::string& script) const { auto* contents = browser->tab_strip_model()->GetActiveWebContents(); content::ExecuteScriptAsync(contents, script); Browser* popup = ui_test_utils::WaitForBrowserToOpen(); EXPECT_NE(popup, browser); auto* popup_contents = popup->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(WaitForRenderFrameReady(popup_contents->GetMainFrame())); return popup; } private: DISALLOW_COPY_AND_ASSIGN(PopupBrowserTest); }; INSTANTIATE_TEST_SUITE_P(All, PopupBrowserTest, ::testing::Bool()); // A helper class to wait for widget bounds changes beyond given thresholds. class WidgetBoundsChangeWaiter final : public views::WidgetObserver { public: WidgetBoundsChangeWaiter(views::Widget* widget, int move_by, int resize_by) : widget_(widget), move_by_(move_by), resize_by_(resize_by), initial_bounds_(widget->GetWindowBoundsInScreen()) { widget_->AddObserver(this); } WidgetBoundsChangeWaiter(const WidgetBoundsChangeWaiter&) = delete; WidgetBoundsChangeWaiter& operator=(const WidgetBoundsChangeWaiter&) = delete; ~WidgetBoundsChangeWaiter() final { widget_->RemoveObserver(this); } // views::WidgetObserver: void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& rect) final { if (BoundsChangeMeetsThreshold(rect)) { widget_->RemoveObserver(this); run_loop_.Quit(); } } // Wait for changes to occur, or return immediately if they already have. void Wait() { if (!BoundsChangeMeetsThreshold(widget_->GetWindowBoundsInScreen())) run_loop_.Run(); } private: bool BoundsChangeMeetsThreshold(const gfx::Rect& rect) const { return (std::abs(rect.x() - initial_bounds_.x()) >= move_by_ || std::abs(rect.y() - initial_bounds_.y()) >= move_by_) && (std::abs(rect.width() - initial_bounds_.width()) >= resize_by_ || std::abs(rect.height() - initial_bounds_.height()) >= resize_by_); } views::Widget* const widget_; const int move_by_, resize_by_; const gfx::Rect initial_bounds_; base::RunLoop run_loop_; }; // Ensure popups are opened in the available space of the opener's display. // TODO(crbug.com/1211516): Flaky. IN_PROC_BROWSER_TEST_P(PopupBrowserTest, DISABLED_OpenClampedToCurrentDisplay) { const auto display = GetDisplayNearestBrowser(browser()); EXPECT_TRUE(display.work_area().Contains(browser()->window()->GetBounds())) << "The browser window should be contained by its display's work area"; // Attempt to open a popup outside the bounds of the opener's display. const char* const open_scripts[] = { "open('.', '', 'left=' + (screen.availLeft - 50));", "open('.', '', 'left=' + (screen.availLeft + screen.availWidth + 50));", "open('.', '', 'top=' + (screen.availTop - 50));", "open('.', '', 'top=' + (screen.availTop + screen.availHeight + 50));", "open('.', '', 'left=' + (screen.availLeft - 50) + " "',top=' + (screen.availTop - 50));", "open('.', '', 'left=' + (screen.availLeft - 50) + " "',top=' + (screen.availTop - 50) + " "',width=300,height=300');", "open('.', '', 'left=' + (screen.availLeft + screen.availWidth + 50) + " "',top=' + (screen.availTop + screen.availHeight + 50) + " "',width=300,height=300');", "open('.', '', 'left=' + screen.availLeft + ',top=' + screen.availTop + " "',width=' + (screen.availWidth + 300) + ',height=300');", "open('.', '', 'left=' + screen.availLeft + ',top=' + screen.availTop + " "',width=300,height='+ (screen.availHeight + 300));", "open('.', '', 'left=' + screen.availLeft + ',top=' + screen.availTop + " "',width=' + (screen.availWidth + 300) + " "',height='+ (screen.availHeight + 300));", }; for (auto* const script : open_scripts) { Browser* popup = OpenPopup(browser(), script); // The popup should be constrained to the opener's available display space. // TODO(crbug.com/897300): Wait for the final window placement to occur; // this is flakily checking initial or intermediate window placement bounds. EXPECT_EQ(display, GetDisplayNearestBrowser(popup)); EXPECT_TRUE(display.work_area().Contains(popup->window()->GetBounds())) << " script: " << script << " work_area: " << display.work_area().ToString() << " popup: " << popup->window()->GetBounds().ToString(); } } // Ensure popups cannot be moved beyond the available display space by script. IN_PROC_BROWSER_TEST_P(PopupBrowserTest, MoveClampedToCurrentDisplay) { const auto display = GetDisplayNearestBrowser(browser()); const char kOpenPopup[] = "open('.', '', 'left=' + (screen.availLeft + 50) + " "',top=' + (screen.availTop + 50) + " "',width=150,height=100');"; const char* const kMoveScripts[] = { "moveBy(screen.availWidth * 2, 0);", "moveBy(screen.availWidth * -2, 0);", "moveBy(0, screen.availHeight * 2);", "moveBy(0, screen.availHeight * -2);", "moveBy(screen.availWidth * 2, screen.availHeight * 2);", "moveBy(screen.availWidth * -2, screen.availHeight * -2);", "moveTo(screen.availLeft + screen.availWidth + 50, screen.availTop);", "moveTo(screen.availLeft - 50, screen.availTop);", "moveTo(screen.availLeft, screen.availTop + screen.availHeight + 50);", "moveTo(screen.availLeft, screen.availTop - 50);", ("moveTo(screen.availLeft + screen.availWidth + 50, " "screen.availTop + screen.availHeight + 50);"), "moveTo(screen.availLeft - 50, screen.availTop - 50);", }; for (auto* const script : kMoveScripts) { Browser* popup = OpenPopup(browser(), kOpenPopup); auto popup_bounds = popup->window()->GetBounds(); auto* popup_contents = popup->tab_strip_model()->GetActiveWebContents(); auto* widget = views::Widget::GetWidgetForNativeWindow( popup->window()->GetNativeWindow()); content::ExecuteScriptAsync(popup_contents, script); // Wait for the substantial move, widgets may move during initialization. WidgetBoundsChangeWaiter(widget, /*move_by=*/40, /*resize_by=*/0).Wait(); EXPECT_NE(popup_bounds.origin(), popup->window()->GetBounds().origin()); EXPECT_EQ(popup_bounds.size(), popup->window()->GetBounds().size()); EXPECT_TRUE(display.work_area().Contains(popup->window()->GetBounds())) << " script: " << script << " work_area: " << display.work_area().ToString() << " popup: " << popup_bounds.ToString(); } } // Ensure popups cannot be resized beyond the available display space by script. IN_PROC_BROWSER_TEST_P(PopupBrowserTest, ResizeClampedToCurrentDisplay) { const auto display = GetDisplayNearestBrowser(browser()); const char kOpenPopup[] = "open('.', '', 'left=' + (screen.availLeft + 50) + " "',top=' + (screen.availTop + 50) + " "',width=150,height=100');"; // The popup cannot be resized beyond the current screen by script. const char* const kResizeScripts[] = { "resizeBy(screen.availWidth * 2, 0);", "resizeBy(0, screen.availHeight * 2);", "resizeTo(screen.availWidth + 200, 200);", "resizeTo(200, screen.availHeight + 200);", "resizeTo(screen.availWidth + 200, screen.availHeight + 200);", }; for (auto* const script : kResizeScripts) { Browser* popup = OpenPopup(browser(), kOpenPopup); auto popup_bounds = popup->window()->GetBounds(); auto* popup_contents = popup->tab_strip_model()->GetActiveWebContents(); auto* widget = views::Widget::GetWidgetForNativeWindow( popup->window()->GetNativeWindow()); content::ExecuteScriptAsync(popup_contents, script); // Wait for the substantial resize, widgets may move during initialization. WidgetBoundsChangeWaiter(widget, /*move_by=*/0, /*resize_by=*/100).Wait(); EXPECT_NE(popup_bounds.size(), popup->window()->GetBounds().size()); EXPECT_TRUE(display.work_area().Contains(popup->window()->GetBounds())) << " script: " << script << " work_area: " << display.work_area().ToString() << " popup: " << popup_bounds.ToString(); } } // TODO(crbug.com/1183791): Disabled on non-ChromeOS because of races with // SetScreenInstance and observers not being notified. #if !BUILDFLAG(IS_CHROMEOS_ASH) #define MAYBE_AboutBlankCrossScreenPlacement \ DISABLED_AboutBlankCrossScreenPlacement #else #define MAYBE_AboutBlankCrossScreenPlacement AboutBlankCrossScreenPlacement #endif // Tests that an about:blank popup can be moved across screens with permission. IN_PROC_BROWSER_TEST_P(PopupBrowserTest, MAYBE_AboutBlankCrossScreenPlacement) { #if BUILDFLAG(IS_CHROMEOS_ASH) display::test::DisplayManagerTestApi(ash::Shell::Get()->display_manager()) .UpdateDisplay("100+100-801x802,901+100-802x802"); #else display::ScreenBase test_screen; test_screen.display_list().AddDisplay({1, gfx::Rect(100, 100, 801, 802)}, display::DisplayList::Type::PRIMARY); test_screen.display_list().AddDisplay( {2, gfx::Rect(901, 100, 802, 802)}, display::DisplayList::Type::NOT_PRIMARY); display::test::ScopedScreenOverride screen_override(&test_screen); #endif // BUILDFLAG(IS_CHROMEOS_ASH) display::Screen* screen = display::Screen::GetScreen(); ASSERT_EQ(2, screen->GetNumDisplays()); ASSERT_TRUE(embedded_test_server()->Start()); const GURL url(embedded_test_server()->GetURL("/empty.html")); EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); auto* opener = browser()->tab_strip_model()->GetActiveWebContents(); // TODO(crbug.com/1119974): this test could be in content_browsertests // and not browser_tests if permission controls were supported. if (GetParam()) { // Check whether the WindowPlacement feature is enabled. // Request and auto-accept the Window Placement permission request. permissions::PermissionRequestManager* permission_request_manager = permissions::PermissionRequestManager::FromWebContents(opener); permission_request_manager->set_auto_response_for_test( permissions::PermissionRequestManager::ACCEPT_ALL); constexpr char kGetScreensLength[] = R"( (async () => { try { return (await getScreens()).screens.length; } catch { return 0; } })(); )"; EXPECT_EQ(2, EvalJs(opener, kGetScreensLength)); // Do not auto-accept any other permission requests. permission_request_manager->set_auto_response_for_test( permissions::PermissionRequestManager::NONE); } // Open an about:blank popup. It should start on the same screen as browser(). Browser* popup = OpenPopup( browser(), "w = open('about:blank', '', 'width=200,height=200');"); const auto opener_display = GetDisplayNearestBrowser(browser()); auto original_popup_display = GetDisplayNearestBrowser(popup); EXPECT_EQ(opener_display, original_popup_display); // Have the opener try to move the popup to the second screen. content::ExecuteScriptAsync(opener, "w.moveTo(999, 199);"); // Wait for the substantial move, widgets may move during initialization. auto* widget = views::Widget::GetWidgetForNativeWindow( popup->window()->GetNativeWindow()); WidgetBoundsChangeWaiter(widget, /*move_by=*/40, /*resize_by=*/0).Wait(); auto new_popup_display = GetDisplayNearestBrowser(popup); // The popup only moves to the second screen with Window Placement permission. EXPECT_EQ(GetParam(), original_popup_display != new_popup_display); // The popup is always constrained to the bounds of the target display. auto popup_bounds = popup->window()->GetBounds(); EXPECT_TRUE(new_popup_display.work_area().Contains(popup_bounds)) << " work_area: " << new_popup_display.work_area().ToString() << " popup: " << popup_bounds.ToString(); } } // namespace
45.692557
80
0.69148
DamieFC
d936b766a505e6cd6421edc87ac30e7780876df4
2,501
cpp
C++
shiva20rapidjson/Plugins/com.tris.rjson/Sources/Plugin.cpp
broozar/ShiVaRapidJSON
ab54f2bdfe9cd5a4e32406b550a625b1c00d19be
[ "Apache-2.0" ]
null
null
null
shiva20rapidjson/Plugins/com.tris.rjson/Sources/Plugin.cpp
broozar/ShiVaRapidJSON
ab54f2bdfe9cd5a4e32406b550a625b1c00d19be
[ "Apache-2.0" ]
null
null
null
shiva20rapidjson/Plugins/com.tris.rjson/Sources/Plugin.cpp
broozar/ShiVaRapidJSON
ab54f2bdfe9cd5a4e32406b550a625b1c00d19be
[ "Apache-2.0" ]
null
null
null
//----------------------------------------------------------------------------- #include "PrecompiledHeader.h" //----------------------------------------------------------------------------- #include <string.h> //----------------------------------------------------------------------------- S3DX_IMPLEMENT_AIVARIABLE_STRING_POOL ( 524288 ) ; S3DX_IMPLEMENT_AIENGINEAPI ( RapidJSON ) ; S3DX_IMPLEMENT_PLUGIN ( RapidJSON ) ; //----------------------------------------------------------------------------- // AI Packages //----------------------------------------------------------------------------- #include "rjson.h" //----------------------------------------------------------------------------- // Constructor / Destructor //----------------------------------------------------------------------------- RapidJSON::RapidJSON ( ) { S3DX_REGISTER_PLUGIN ( "com.tris.rjson" ) ; aContentsDirectory[0] = '\0' ; //Instanciate AI Packages S3DX::uint32 iAIPackageIndex = 0 ; if ( iAIPackageIndex < PLUGIN_AIPACKAGES_COUNT ) aAIPackages [iAIPackageIndex++] = new rjsonPackage ( ) ; for ( ; iAIPackageIndex < PLUGIN_AIPACKAGES_COUNT; iAIPackageIndex ++ ) { aAIPackages[iAIPackageIndex] = NULL ; } } //----------------------------------------------------------------------------- RapidJSON::~RapidJSON ( ) { for ( S3DX::uint32 iAIPackageIndex = 0 ; iAIPackageIndex < PLUGIN_AIPACKAGES_COUNT; iAIPackageIndex ++ ) { if ( aAIPackages [iAIPackageIndex] ) { delete aAIPackages [iAIPackageIndex] ; aAIPackages[iAIPackageIndex] = NULL ; } } } //----------------------------------------------------------------------------- // Plugin content directory //----------------------------------------------------------------------------- void RapidJSON::SetContentsDirectory ( const char *_pDirectory ) { strcpy ( aContentsDirectory, _pDirectory ) ; } //----------------------------------------------------------------------------- // AI packages //----------------------------------------------------------------------------- S3DX::uint32 RapidJSON::GetAIPackageCount ( ) const { return PLUGIN_AIPACKAGES_COUNT ; } const S3DX::AIPackage *RapidJSON::GetAIPackageAt ( S3DX::uint32 _iIndex ) const { return (_iIndex < PLUGIN_AIPACKAGES_COUNT) ? aAIPackages[_iIndex] : NULL ; }
39.698413
175
0.390244
broozar
d9377566991fcc98197f718a02819e663ee27093
855
cpp
C++
src/main/native/cpp/Util.cpp
KyleQ1/Characterization-Robot-2020
f28bb07fab05587e7462937ce3e0f9fe40a5f014
[ "BSD-3-Clause" ]
null
null
null
src/main/native/cpp/Util.cpp
KyleQ1/Characterization-Robot-2020
f28bb07fab05587e7462937ce3e0f9fe40a5f014
[ "BSD-3-Clause" ]
null
null
null
src/main/native/cpp/Util.cpp
KyleQ1/Characterization-Robot-2020
f28bb07fab05587e7462937ce3e0f9fe40a5f014
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "sysid/Util.h" #include <sstream> #include <string> #include <vector> #include <imgui.h> void sysid::CreateTooltip(const char* text) { ImGui::SameLine(); ImGui::TextDisabled(" (?)"); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); ImGui::TextUnformatted(text); ImGui::PopTextWrapPos(); ImGui::EndTooltip(); } } std::vector<std::string> sysid::Split(const std::string& s, char c) { std::vector<std::string> result; std::stringstream ss(s); std::string item; while (std::getline(ss, item, c)) { result.push_back(item); } return result; }
23.108108
74
0.676023
KyleQ1
d937915bb1a35782e9a8914bb04dc600518feb56
6,423
cpp
C++
reference/matrix/hybrid_kernels.cpp
JakubTrzcskni/ginkgo
8a9988b9c3f8c4ff59fae30050575311f230065e
[ "BSD-3-Clause" ]
null
null
null
reference/matrix/hybrid_kernels.cpp
JakubTrzcskni/ginkgo
8a9988b9c3f8c4ff59fae30050575311f230065e
[ "BSD-3-Clause" ]
null
null
null
reference/matrix/hybrid_kernels.cpp
JakubTrzcskni/ginkgo
8a9988b9c3f8c4ff59fae30050575311f230065e
[ "BSD-3-Clause" ]
null
null
null
/*******************************<GINKGO LICENSE>****************************** Copyright (c) 2017-2022, the Ginkgo authors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************<GINKGO LICENSE>*******************************/ #include "core/matrix/hybrid_kernels.hpp" #include <ginkgo/core/base/exception_helpers.hpp> #include <ginkgo/core/base/math.hpp> #include <ginkgo/core/matrix/coo.hpp> #include <ginkgo/core/matrix/csr.hpp> #include <ginkgo/core/matrix/dense.hpp> #include <ginkgo/core/matrix/ell.hpp> #include "core/components/format_conversion_kernels.hpp" #include "core/components/prefix_sum_kernels.hpp" #include "core/matrix/ell_kernels.hpp" namespace gko { namespace kernels { namespace reference { /** * @brief The Hybrid matrix format namespace. * @ref Hybrid * @ingroup hybrid */ namespace hybrid { void compute_coo_row_ptrs(std::shared_ptr<const DefaultExecutor> exec, const Array<size_type>& row_nnz, size_type ell_lim, int64* coo_row_ptrs) { for (size_type row = 0; row < row_nnz.get_num_elems(); row++) { if (row_nnz.get_const_data()[row] <= ell_lim) { coo_row_ptrs[row] = 0; } else { coo_row_ptrs[row] = row_nnz.get_const_data()[row] - ell_lim; } } components::prefix_sum(exec, coo_row_ptrs, row_nnz.get_num_elems() + 1); } void compute_row_nnz(std::shared_ptr<const DefaultExecutor> exec, const Array<int64>& row_ptrs, size_type* row_nnzs) { for (size_type i = 0; i < row_ptrs.get_num_elems() - 1; i++) { row_nnzs[i] = row_ptrs.get_const_data()[i + 1] - row_ptrs.get_const_data()[i]; } } template <typename ValueType, typename IndexType> void fill_in_matrix_data(std::shared_ptr<const DefaultExecutor> exec, const device_matrix_data<ValueType, IndexType>& data, const int64* row_ptrs, const int64*, matrix::Hybrid<ValueType, IndexType>* result) { const auto num_rows = result->get_size()[0]; const auto ell_max_nnz = result->get_ell_num_stored_elements_per_row(); const auto values = data.get_const_values(); const auto row_idxs = data.get_const_row_idxs(); const auto col_idxs = data.get_const_col_idxs(); size_type coo_nz{}; for (size_type row = 0; row < num_rows; row++) { size_type ell_nz{}; for (auto nz = row_ptrs[row]; nz < row_ptrs[row + 1]; nz++) { if (ell_nz < ell_max_nnz) { result->ell_col_at(row, ell_nz) = col_idxs[nz]; result->ell_val_at(row, ell_nz) = values[nz]; ell_nz++; } else { result->get_coo_row_idxs()[coo_nz] = row_idxs[nz]; result->get_coo_col_idxs()[coo_nz] = col_idxs[nz]; result->get_coo_values()[coo_nz] = values[nz]; coo_nz++; } } for (; ell_nz < ell_max_nnz; ell_nz++) { result->ell_col_at(row, ell_nz) = 0; result->ell_val_at(row, ell_nz) = zero<ValueType>(); } } } GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_HYBRID_FILL_IN_MATRIX_DATA_KERNEL); template <typename ValueType, typename IndexType> void convert_to_csr(std::shared_ptr<const ReferenceExecutor> exec, const matrix::Hybrid<ValueType, IndexType>* source, const IndexType*, const IndexType*, matrix::Csr<ValueType, IndexType>* result) { auto csr_val = result->get_values(); auto csr_col_idxs = result->get_col_idxs(); auto csr_row_ptrs = result->get_row_ptrs(); const auto ell = source->get_ell(); const auto max_nnz_per_row = ell->get_num_stored_elements_per_row(); const auto coo_val = source->get_const_coo_values(); const auto coo_col = source->get_const_coo_col_idxs(); const auto coo_row = source->get_const_coo_row_idxs(); const auto coo_nnz = source->get_coo_num_stored_elements(); csr_row_ptrs[0] = 0; size_type csr_idx = 0; size_type coo_idx = 0; for (IndexType row = 0; row < source->get_size()[0]; row++) { // Ell part for (IndexType col = 0; col < max_nnz_per_row; col++) { const auto val = ell->val_at(row, col); if (is_nonzero(val)) { csr_val[csr_idx] = val; csr_col_idxs[csr_idx] = ell->col_at(row, col); csr_idx++; } } // Coo part (row should be ascending) while (coo_idx < coo_nnz && coo_row[coo_idx] == row) { csr_val[csr_idx] = coo_val[coo_idx]; csr_col_idxs[csr_idx] = coo_col[coo_idx]; csr_idx++; coo_idx++; } csr_row_ptrs[row + 1] = csr_idx; } } GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_HYBRID_CONVERT_TO_CSR_KERNEL); } // namespace hybrid } // namespace reference } // namespace kernels } // namespace gko
38.005917
78
0.656391
JakubTrzcskni
d93834ddbaa5d939a8a4385aa2883b48255053a7
3,367
cpp
C++
TAO/examples/AMI/FL_Callback/progress.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/examples/AMI/FL_Callback/progress.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/examples/AMI/FL_Callback/progress.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: progress.cpp 97190 2013-06-05 20:13:29Z mesnier_p $ #include "Progress_i.h" #include "ace/Get_Opt.h" #include "ace/OS_NS_stdio.h" #include "tao/FlResource/FlResource_Loader.h" #include <FL/Fl.H> #include <FL/Fl_Window.H> const ACE_TCHAR *ior_output_file = ACE_TEXT("progress.ior"); int n_iterations = 1000; int n_peers = 1; int parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("o:p:i:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'o': ior_output_file = get_opts.opt_arg (); break; case 'p': n_peers = ACE_OS::atoi (get_opts.opt_arg ()); break; case 'i': n_iterations = ACE_OS::atoi (get_opts.opt_arg ()); break; case '?': default: ACE_ERROR_RETURN ((LM_ERROR, "usage: %s " "-o <iorfile>" "-p <peers>" "-i <iterations>" "\n", argv [0]), -1); } // Indicates successful parsing of the command line return 0; } int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { TAO::FlResource_Loader fl_loader; try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); if (parse_args (argc, argv) != 0) return 1; int w = 320; int h = 30 * n_peers + 20; Fl_Window window(w, h); Progress_Window sw (n_peers, n_iterations, 10, 10, window.w () - 20, window.h () - 20); window.resizable (&sw); window.end (); char* targv[] = { ACE_TEXT_ALWAYS_CHAR (argv[0]) }; window.show (1, targv); sw.show (); CORBA::Object_var poa_object = orb->resolve_initial_references("RootPOA"); if (CORBA::is_nil (poa_object.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Unable to initialize the POA.\n"), 1); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (poa_object.in ()); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); poa_manager->activate (); Progress_i server_impl (&sw); Progress_var server = server_impl._this (); CORBA::String_var ior = orb->object_to_string (server.in ()); ACE_DEBUG ((LM_DEBUG, "Activated as <%C>\n", ior.in ())); // If the ior_output_file exists, output the ior to it if (ior_output_file != 0) { FILE *output_file= ACE_OS::fopen (ior_output_file, "w"); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", ior_output_file), 1); ACE_OS::fprintf (output_file, "%s", ior.in ()); ACE_OS::fclose (output_file); } if (Fl::run () == -1) ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "Fl::run"), -1); ACE_DEBUG ((LM_DEBUG, "event loop finished\n")); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Caught exception:"); return 1; } return 0; }
25.70229
77
0.50995
cflowe
d938e18befaae9e3bd7f86f42559caa27dbb0250
36,655
cpp
C++
inetsrv/iis/svcs/cmp/asp/debugger.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/svcs/cmp/asp/debugger.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/svcs/cmp/asp/debugger.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*=================================================================== Microsoft Denali Microsoft Confidential. Copyright 1997 Microsoft Corporation. All Rights Reserved. Component: misc File: util.cpp Owner: DGottner This file contains debugger utility functions ===================================================================*/ #include "denpre.h" #pragma hdrstop #include "vector.h" #include "debugger.h" #include "iiscnfg.h" #include "mdcommsg.h" // for RETURNCODETOHRESULT macro #include "memchk.h" #include "vecimpl.h" /* Win64: This struct is used to package data passed to the thread handler. * (3 DWORDs are too small in 64 bit world.) */ struct DebugThreadCallArgs { DWORD dwMethod; IDebugApplication * pDebugAppln; void * pvArg; DebugThreadCallArgs(DWORD dwMethod = 0, IDebugApplication *pDebugAppln = 0, void *pvArg = 0) { this->dwMethod = dwMethod; this->pDebugAppln = pDebugAppln; this->pvArg = pvArg; } }; // Published globals IProcessDebugManager * g_pPDM = NULL; // instance of debugger for this process. IDebugApplication * g_pDebugApp = NULL; // Root ASP application IDebugApplicationNode * g_pDebugAppRoot = NULL; // used to create hierarchy tree CViperActivity * g_pDebugActivity = NULL; // Debugger's activity DWORD g_dwDebugThreadId = 0; // Thread ID of viper activity // Globals for debugging static DWORD g_dwDenaliAppCookie; // Cookie to use to remove app static HANDLE g_hPDMTermEvent; // PDM terminate event static vector<DebugThreadCallArgs> *g_prgThreadCallArgs; // for new 64 bit interface. // This hash structure & CS is used by GetServerDebugRoot() struct CDebugNodeElem : CLinkElem { IDebugApplicationNode *m_pServerRoot; HRESULT Init(char *szKey, int cchKey) { char *szKeyAlloc = new char [cchKey + 1]; if (!szKeyAlloc) return E_OUTOFMEMORY; return CLinkElem::Init(memcpy(szKeyAlloc, szKey, cchKey + 1), cchKey); } ~CDebugNodeElem() { if (m_pKey) delete m_pKey; } }; static CHashTable g_HashMDPath2DebugRoot; static CRITICAL_SECTION g_csDebugLock; // Lock for g_hashMDPath2DebugRoot /*=================================================================== InvokeDebuggerWithThreadSwitch Invoke Debugger (or Debugger UI) method from a correct thread using IDebugThreadCall. Parameters IDebugApplication *pDebugAppln to get to debugger UI DWORD iMethod which method to call void *Arg call argument Returns HRESULT ===================================================================*/ // GUIDs for debugger events static const GUID DEBUGNOTIFY_ONPAGEBEGIN = { 0xfd6806c0, 0xdb89, 0x11d0, { 0x8f, 0x81, 0x0, 0x80, 0xc7, 0x3d, 0x6d, 0x96 } }; static const GUID DEBUGNOTIFY_ONPAGEEND = { 0xfd6806c1, 0xdb89, 0x11d0, { 0x8f, 0x81, 0x0, 0x80, 0xc7, 0x3d, 0x6d, 0x96 } }; static const GUID DEBUGNOTIFY_ON_REFRESH_BREAKPOINT = { 0xffcf4b38, 0xfa12, 0x11d0, { 0x8f, 0x3b, 0x0, 0xc0, 0x4f, 0xc3, 0x4d, 0xcc } }; // Local class that implements IDebugCallback class CDebugThreadDebuggerCall : public IDebugThreadCall { public: STDMETHODIMP QueryInterface(const GUID &, void **); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); STDMETHODIMP ThreadCallHandler(DWORD_PTR, DWORD_PTR, DWORD_PTR); }; HRESULT CDebugThreadDebuggerCall::QueryInterface ( const GUID &iid, void **ppv ) { if (iid == IID_IUnknown || iid == IID_IDebugThreadCall) { *ppv = this; return S_OK; } else { *ppv = NULL; return E_NOINTERFACE; } } ULONG CDebugThreadDebuggerCall::AddRef() { return 1; } ULONG CDebugThreadDebuggerCall::Release() { return 1; } HRESULT CDebugThreadDebuggerCall::ThreadCallHandler ( DWORD_PTR iArg, DWORD_PTR , DWORD_PTR ) { // Get arguments DebugThreadCallArgs *pThreadCallArgs = &(*g_prgThreadCallArgs)[(int)iArg]; IDebugApplication * pDebugAppln = pThreadCallArgs->pDebugAppln; DWORD dwMethod = pThreadCallArgs->dwMethod; void * pvArg = pThreadCallArgs->pvArg; // we won't reference the argument block again, so free it up now. pThreadCallArgs->dwMethod |= DEBUGGER_UNUSED_RECORD; BOOL fForceDebugger = (dwMethod & (DEBUGGER_UI_BRING_DOCUMENT_TO_TOP|DEBUGGER_UI_BRING_DOC_CONTEXT_TO_TOP)) != 0; BOOL fNeedDebuggerUI = (dwMethod & (DEBUGGER_UI_BRING_DOCUMENT_TO_TOP|DEBUGGER_UI_BRING_DOC_CONTEXT_TO_TOP)) != 0; BOOL fNeedNodeEvents = (dwMethod & DEBUGGER_ON_REMOVE_CHILD) != 0; BOOL fNeedDebugger = (dwMethod & ~DEBUGGER_ON_DESTROY) != 0; HRESULT hr = S_OK; IApplicationDebugger *pDebugger = NULL; IApplicationDebuggerUI *pDebuggerUI = NULL; IDebugApplicationNodeEvents *pNodeEvents = NULL; if (pDebugAppln == NULL) return E_POINTER; // Get the debugger if (fNeedDebugger) { hr = pDebugAppln->GetDebugger(&pDebugger); if (FAILED(hr)) { // Debugger is not currently debugging our application. if (!fForceDebugger) return E_FAIL; // no debugger // Start the debugger and try again. hr = pDebugAppln->StartDebugSession(); if (SUCCEEDED(hr)) hr = pDebugAppln->GetDebugger(&pDebugger); } // Debugger UI is needed only for some methods if (SUCCEEDED(hr) && fNeedDebuggerUI) { hr = pDebugger->QueryInterface ( IID_IApplicationDebuggerUI, reinterpret_cast<void **>(&pDebuggerUI) ); } // Debugger UI is needed only for some methods if (SUCCEEDED(hr) && fNeedNodeEvents) { hr = pDebugger->QueryInterface ( IID_IDebugApplicationNodeEvents, reinterpret_cast<void **>(&pNodeEvents) ); } } // Call the desired method if (SUCCEEDED(hr)) { switch (dwMethod) { case DEBUGGER_EVENT_ON_PAGEBEGIN: { hr = pDebugger->onDebuggerEvent ( DEBUGNOTIFY_ONPAGEBEGIN, static_cast<IUnknown *>(pvArg) ); break; } case DEBUGGER_EVENT_ON_PAGEEND: { hr = pDebugger->onDebuggerEvent ( DEBUGNOTIFY_ONPAGEEND, static_cast<IUnknown *>(pvArg) ); break; } case DEBUGGER_EVENT_ON_REFRESH_BREAKPOINT: { hr = pDebugger->onDebuggerEvent ( DEBUGNOTIFY_ON_REFRESH_BREAKPOINT, static_cast<IUnknown *>(pvArg) ); break; } case DEBUGGER_ON_REMOVE_CHILD: { hr = pNodeEvents->onRemoveChild ( static_cast<IDebugApplicationNode *>(pvArg) ); break; } case DEBUGGER_ON_DESTROY: { hr = static_cast<IDebugDocumentTextEvents *>(pvArg)->onDestroy(); break; } case DEBUGGER_UI_BRING_DOCUMENT_TO_TOP: { hr = pDebuggerUI->BringDocumentToTop ( static_cast<IDebugDocumentText *>(pvArg) ); break; } case DEBUGGER_UI_BRING_DOC_CONTEXT_TO_TOP: { hr = pDebuggerUI->BringDocumentContextToTop ( static_cast<IDebugDocumentContext *>(pvArg) ); break; } default: hr = E_FAIL; break; } } // Cleanup if (pDebuggerUI) pDebuggerUI->Release(); if (pNodeEvents) pNodeEvents->Release(); if (pDebugger) pDebugger->Release(); return hr; } // The function calls using IDebugThreadCall HRESULT InvokeDebuggerWithThreadSwitch ( IDebugApplication *pDebugAppln, DWORD dwMethod, void *pvArg ) { // take these arguments and package them up in the array. We will pass the // index to the callback handler. // // first look for a freed up element before creating a new one. for (int i = g_prgThreadCallArgs->length() - 1; i >= 0; --i) { DebugThreadCallArgs *pThreadCallArgs = &(*g_prgThreadCallArgs)[i]; if (pThreadCallArgs->dwMethod & DEBUGGER_UNUSED_RECORD) { pThreadCallArgs->dwMethod = dwMethod; pThreadCallArgs->pDebugAppln = pDebugAppln; pThreadCallArgs->pvArg = pvArg; break; } } if (i < 0) { HRESULT hr = g_prgThreadCallArgs->append(DebugThreadCallArgs(dwMethod, pDebugAppln, pvArg)); if (FAILED(hr)) return hr; i = g_prgThreadCallArgs->length() - 1; } CDebugThreadDebuggerCall Call; return pDebugAppln->SynchronousCallInDebuggerThread ( &Call, i, 0, 0 ); } /*=================================================================== FCaesars Query registry to determine if default debugger is Caesar's (Script Debugger) ===================================================================*/ BOOL FCaesars() { static BOOL fCaesars = 0xBADF00D; HKEY hKey = NULL; char szRegPath[_MAX_PATH]; DWORD dwSize = sizeof szRegPath; // Check to see if Ceasers is registered as the JIT debugger on this machine. if (fCaesars == 0xBADF00D) { fCaesars = FALSE; if (RegOpenKey(HKEY_CLASSES_ROOT, _T("CLSID\\{834128A2-51F4-11D0-8F20-00805F2CD064}\\LocalServer32"), &hKey) == ERROR_SUCCESS) { if (RegQueryValueEx(hKey, NULL, NULL, NULL, (LPBYTE) szRegPath, &dwSize) == ERROR_SUCCESS) { char szFile[_MAX_FNAME]; _splitpath(szRegPath, NULL, NULL, szFile, NULL); if (_stricmp(szFile, "msscrdbg") == 0) fCaesars = TRUE; } CloseHandle (hKey); } } return fCaesars; } /*=================================================================== DestroyDocumentTree Recursively release all the nodes in a document tree. Parameters IDebugApplication *pDocRoot root of hierarchy to destroy ===================================================================*/ void DestroyDocumentTree(IDebugApplicationNode *pDocRoot) { IEnumDebugApplicationNodes *pEnum; if (SUCCEEDED(pDocRoot->EnumChildren(&pEnum)) && pEnum != NULL) { IDebugApplicationNode *pDocNode; while (pEnum->Next(1, &pDocNode, NULL) == S_OK) DestroyDocumentTree(pDocNode); pEnum->Release(); } // See if this is a directory node // IFileNode *pFileNode; if (SUCCEEDED(pDocRoot->QueryInterface(IID_IFileNode, reinterpret_cast<void **>(&pFileNode)))) { // This is a directory node, only detach when its document count vanishes) if (pFileNode->DecrementDocumentCount() == 0) { pDocRoot->Detach(); pDocRoot->Close(); pDocRoot->Release(); } pFileNode->Release(); } else { // This node is a CTemplate (or one of its include files) pDocRoot->Detach(); pDocRoot->Close(); pDocRoot->Release(); } } /*=================================================================== CreateDocumentTree Takes a path to be rooted at a node "pDocRoot", parses the path, and creates a node for each component of the path. Returns the leaf (Since the root is known) as its value. This function is called from contexts where part of the document tree may already exist, so EnumChildren is called and nodes are only created when a child does not exist. When a node exists, we merely descend into the tree. NOTE: The intermediate nodes are created with a CFileNode document implementation. The leaf node is not given a document provider - the caller must provide one. Parameters wchar_t * szDocPath path of the document IDebugApplication *pDocParent parent to attach the application tree to IDebugApplication **ppDocRoot returns root of document hierarchy IDebugApplication **ppDocLeaf returns document leaf node. wchar_t ** pwszLeaf name of the leaf node Returns HRESULT ===================================================================*/ HRESULT CreateDocumentTree ( wchar_t *wszDocPath, IDebugApplicationNode *pDocParent, IDebugApplicationNode **ppDocRoot, IDebugApplicationNode **ppDocLeaf, wchar_t **pwszLeaf ) { HRESULT hr; BOOL fCreateOnly = FALSE; // Set to TRUE when there is no need to check for duplicate node *ppDocRoot = *ppDocLeaf = NULL; // Ignore initial delimiters while (wszDocPath[0] == '/') ++wszDocPath; // Now loop over every component in the path, adding a node for each while (wszDocPath != NULL) { // Get next path component *pwszLeaf = wszDocPath; wszDocPath = wcschr(wszDocPath, L'/'); if (wszDocPath) *wszDocPath++ = L'\0'; // Check to see if this component is already a child or not BOOL fNodeExists = FALSE; if (!fCreateOnly) { IEnumDebugApplicationNodes *pEnum; if (SUCCEEDED(pDocParent->EnumChildren(&pEnum)) && pEnum != NULL) { IDebugApplicationNode *pDocChild; while (!fNodeExists && pEnum->Next(1, &pDocChild, NULL) == S_OK) { BSTR bstrName = NULL; if (FAILED(hr = pDocChild->GetName(DOCUMENTNAMETYPE_APPNODE, &bstrName))) return hr; if (wcscmp(bstrName, *pwszLeaf) == 0) { // The name of this node is equal to the component. Instead of // creating a new node, descend into the tree. // fNodeExists = TRUE; *ppDocLeaf = pDocChild; // If '*ppDocRoot' hasn't been assigned to yet, this means that // this is the first node found (and hence the root of the tree) // if (*ppDocRoot == NULL) { *ppDocRoot = pDocChild; (*ppDocRoot)->AddRef(); } // If this node is a CFileNode structure (we don't require it to be) // then increment its (recursive) containing document count. // IFileNode *pFileNode; if (SUCCEEDED(pDocChild->QueryInterface(IID_IFileNode, reinterpret_cast<void **>(&pFileNode)))) { pFileNode->IncrementDocumentCount(); pFileNode->Release(); } } SysFreeString(bstrName); pDocChild->Release(); } pEnum->Release(); } } // Create a new node if the node was not found above. Also, at this point, // to save time, we always set "fCreateOnly" to TRUE because if we are // forced to create a node at this level, we will need to create nodes at // all other levels further down // if (!fNodeExists) { fCreateOnly = TRUE; // Create the node if (FAILED(hr = g_pDebugApp->CreateApplicationNode(ppDocLeaf))) return hr; // Create a doc provider for the node - for intermediate nodes only if (wszDocPath != NULL) // intermediate node { CFileNode *pFileNode = new CFileNode; if (pFileNode == NULL || FAILED(hr = pFileNode->Init(*pwszLeaf)) || FAILED(hr = (*ppDocLeaf)->SetDocumentProvider(pFileNode))) { (*ppDocLeaf)->Release(); return E_OUTOFMEMORY; } // New node, only one document (count started at 0, so this will set to 1) pFileNode->IncrementDocumentCount(); // SetDocumentProvider() AddRef'ed pFileNode->Release(); } // If '*ppDocRoot' hasn't been assigned to yet, this means that // this is the first node created (and hence the root of the tree) // if (*ppDocRoot == NULL) { *ppDocRoot = *ppDocLeaf; (*ppDocRoot)->AddRef(); } // Attach the node if (FAILED(hr = (*ppDocLeaf)->Attach(pDocParent))) return hr; } // Descend pDocParent = *ppDocLeaf; } if (*ppDocLeaf) (*ppDocLeaf)->AddRef(); return S_OK; } /*=================================================================== Debugger The purpose of this thread is to create an execution environment for the Process Debug Manager (PDM). There is only one PDM per process, and this does not really fit in other threads, so we dedicate a thread to this. Parameters: LPVOID params Points to a BOOL* which will be set to 1 when this thread is completely initialized. Returns: 0 ===================================================================*/ void __cdecl Debugger(void *pvInit) { HRESULT hr; if (FAILED(hr = CoInitializeEx(NULL, COINIT_MULTITHREADED))) { // Bug 87857: if we get E_INVALIDARG, we need to do a CoUninitialize if (hr == E_INVALIDARG) CoUninitialize(); *static_cast<BOOL *>(pvInit) = TRUE; return; } if (FAILED(CoCreateInstance( CLSID_ProcessDebugManager, NULL, CLSCTX_INPROC_SERVER, IID_IProcessDebugManager, reinterpret_cast<void **>(&g_pPDM)))) { *static_cast<BOOL *>(pvInit) = TRUE; CoUninitialize(); return; } *static_cast<BOOL *>(pvInit) = TRUE; while (TRUE) { DWORD dwRet = MsgWaitForMultipleObjects(1, &g_hPDMTermEvent, FALSE, INFINITE, QS_ALLINPUT); if (dwRet == WAIT_OBJECT_0) break; MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) DispatchMessage(&msg); } g_pPDM->Release(); CoUninitialize(); g_pPDM = NULL; // indication that the thread is gone } /*=================================================================== HRESULT StartPDM() kick off the PDM thread ===================================================================*/ HRESULT StartPDM() { BOOL fStarted = FALSE; g_hPDMTermEvent = IIS_CREATE_EVENT( "g_hPDMTermEvent", &g_hPDMTermEvent, TRUE, FALSE ); if( g_hPDMTermEvent == NULL ) return E_FAIL; _beginthread(Debugger, 0, &fStarted); while (!fStarted) Sleep(100); if (g_pPDM == NULL) // could not create the PDM for some reason { CloseHandle(g_hPDMTermEvent); g_hPDMTermEvent = NULL; return E_FAIL; } return S_OK; } /*=================================================================== HRESULT InitDebugging Initialize everything we need for debugging ===================================================================*/ HRESULT InitDebugging ( CIsapiReqInfo *pIReq ) { HRESULT hr; // this stack size should cover the static string directly // below and the process pid. If the app name is found, the // buffer is resized. STACK_BUFFER(tempWszDebugAppName, 128); // Start the PDM if (FAILED(hr = StartPDM())) return hr; Assert (g_pPDM); // StartPDM succeeds ==> g_pPDM <> NULL ErrInitCriticalSection(&g_csDebugLock, hr); if (FAILED(hr)) return hr; // Create the debug application & give it a name if (FAILED(hr = g_pPDM->CreateApplication(&g_pDebugApp))) goto LErrorCleanup; wchar_t *wszDebugAppName = (wchar_t *)tempWszDebugAppName.QueryPtr(); wcscpy(wszDebugAppName, L"Microsoft Active Server Pages"); // DO NOT LOCALIZE THIS STRING if (g_fOOP) { // Bug 154300: If a friendly app. name exists, use it along with the PID for // WAM identification. // // Declare some temporaries // DWORD dwApplMDPathLen; DWORD dwRequiredBuffer = 0; STACK_BUFFER( tempMDData, 2048 ); BYTE *prgbData = (BYTE *)tempMDData.QueryPtr(); TCHAR *szApplMDPath = pIReq->QueryPszApplnMDPath(); // // if the webserver returned NULL for ApplnMDPath which is not expected we return an error. // if (!szApplMDPath) { hr = E_FAIL; goto LErrorCleanup; } // get friendly name from metabase hr = pIReq->GetAspMDData( szApplMDPath, MD_APP_FRIENDLY_NAME, METADATA_INHERIT, ASP_MD_UT_APP, STRING_METADATA, tempMDData.QuerySize(), 0, prgbData, &dwRequiredBuffer); if (hr == RETURNCODETOHRESULT(ERROR_INSUFFICIENT_BUFFER)) { if (tempMDData.Resize(dwRequiredBuffer) == FALSE) { hr = E_OUTOFMEMORY; } else { prgbData = (BYTE *)tempMDData.QueryPtr(); hr = pIReq->GetAspMDData( szApplMDPath, MD_APP_FRIENDLY_NAME, METADATA_INHERIT, ASP_MD_UT_APP, STRING_METADATA, dwRequiredBuffer, 0, prgbData, &dwRequiredBuffer); } } // For OOP append process id if (SUCCEEDED(hr) && *reinterpret_cast<wchar_t *>(prgbData) != 0) { wchar_t *pwszAppName = reinterpret_cast<wchar_t *>(prgbData); // first thing we need to do is resize the buffer... if (tempWszDebugAppName.Resize((wcslen(wszDebugAppName) * 2) // string already in buffer + (wcslen(pwszAppName) * 2) // length of app name + 20 // max size of a process ID + 10 // various format chars from below + 2) == FALSE) { // NULL termination hr = E_OUTOFMEMORY; } else { wszDebugAppName = (wchar_t *)tempWszDebugAppName.QueryPtr(); _snwprintf(&wszDebugAppName[wcslen(wszDebugAppName)], (tempWszDebugAppName.QuerySize()/2) - wcslen(wszDebugAppName), L" (%s, %d)", reinterpret_cast<wchar_t *>(prgbData), GetCurrentProcessId()); } } else { _snwprintf(&wszDebugAppName[wcslen(wszDebugAppName)], (tempWszDebugAppName.QuerySize()/2) - wcslen(wszDebugAppName), L" (%d)", GetCurrentProcessId()); } hr = S_OK; } if (FAILED(hr = g_pDebugApp->SetName(wszDebugAppName))) goto LErrorCleanup; if (FAILED(hr = g_pPDM->AddApplication(g_pDebugApp, &g_dwDenaliAppCookie))) goto LErrorCleanup; if (FAILED(hr = g_pDebugApp->GetRootNode(&g_pDebugAppRoot))) goto LErrorCleanup; // Init the hash table used for Keeping track of virtual server roots if (FAILED(hr = g_HashMDPath2DebugRoot.Init())) goto LErrorCleanup; // Create the array for passing data to debug thread if ((g_prgThreadCallArgs = new vector<DebugThreadCallArgs>) == NULL) { hr = E_OUTOFMEMORY; goto LErrorCleanup; } return S_OK; LErrorCleanup: // Clean up some globals (some thing may be NULL and some not) if (g_pDebugAppRoot) { g_pDebugAppRoot->Release(); g_pDebugAppRoot = NULL; } if (g_pDebugApp) { g_pDebugApp->Release(); g_pDebugApp = NULL; } // Kill PDM thread if we started it up. if (g_pPDM) { SetEvent(g_hPDMTermEvent); while (g_pPDM) Sleep(100); CloseHandle(g_hPDMTermEvent); g_pPDM = NULL; DeleteCriticalSection(&g_csDebugLock); } return hr; } /*=================================================================== UnInitDebugging Uninitialize debugging NOTE: WE DO NOT RELEASE THE VIPER DEBUG ACTIVITY. (EVEN THOUGH INIT CREATES IT) THIS IS BECAUSE UNINIT MUST BE INVOKED WHILE SCRIPTS ON THE ACTIVITY ARE STILL RUNNING! ===================================================================*/ HRESULT UnInitDebugging() { // Clear and UnInit the hash tables (containing the application nodes) CDebugNodeElem *pNukeDebugNode = static_cast<CDebugNodeElem *>(g_HashMDPath2DebugRoot.Head()); while (pNukeDebugNode != NULL) { CDebugNodeElem *pNext = static_cast<CDebugNodeElem *>(pNukeDebugNode->m_pNext); pNukeDebugNode->m_pServerRoot->Detach(); pNukeDebugNode->m_pServerRoot->Close(); pNukeDebugNode->m_pServerRoot->Release(); delete pNukeDebugNode; pNukeDebugNode = pNext; } g_HashMDPath2DebugRoot.UnInit(); DeleteCriticalSection(&g_csDebugLock); // Unlink the top node if (g_pDebugAppRoot) { g_pDebugAppRoot->Detach(); g_pDebugAppRoot->Close(); g_pDebugAppRoot->Release(); } // Delete the application if (g_pDebugApp) { Assert (g_pPDM != NULL); // EXPLICITLY ignore failure result here: // if Init() failed earlier, then RemoveApplication will fail here. g_pPDM->RemoveApplication(g_dwDenaliAppCookie); g_pDebugApp->Close(); g_pDebugApp->Release(); g_pDebugApp = NULL; } // Tell the PDM to suicide if (g_pPDM) { SetEvent(g_hPDMTermEvent); while (g_pPDM) Sleep(100); CloseHandle(g_hPDMTermEvent); } // delete the argument buffer delete g_prgThreadCallArgs; return S_OK; } /*=================================================================== GetServerDebugRoot Each virtual server has its own root in the application tree. (i.e. the tree looks like Microsoft ASP <Virtual Server 1 Name> <Denali Application Name> <Files> <Virtual Server 2 Name> <Denali Application> ... Since there may be multiple applications per each server, the server nodes are managed at one central location (here) so that new applications get added to the correct nodes. ===================================================================*/ HRESULT GetServerDebugRoot ( CIsapiReqInfo *pIReq, IDebugApplicationNode **ppDebugRoot ) { HRESULT hr = E_FAIL; STACK_BUFFER( tempMDData, 2048 ); *ppDebugRoot = NULL; // Get the metabase path for this virtual server from the CIsapiReqInfo DWORD dwInstanceMDPathLen; char *szInstanceMDPath; STACK_BUFFER( instPathBuf, 128 ); if (!SERVER_GET(pIReq, "INSTANCE_META_PATH", &instPathBuf, &dwInstanceMDPathLen)) return HRESULT_FROM_WIN32(GetLastError()); szInstanceMDPath = (char *)instPathBuf.QueryPtr(); // See if we already have a node for this path - If not then create it and add to hash table EnterCriticalSection(&g_csDebugLock); CDebugNodeElem *pDebugNode = static_cast<CDebugNodeElem *>(g_HashMDPath2DebugRoot.FindElem(szInstanceMDPath, dwInstanceMDPathLen - 1)); BOOL fDeleteDebugNode = FALSE; if (!pDebugNode) { // Node does not exist, so create a new application node. pDebugNode = new CDebugNodeElem; if (pDebugNode == NULL) { hr = E_OUTOFMEMORY; goto LExit; } fDeleteDebugNode = TRUE; if (FAILED(hr = pDebugNode->Init(szInstanceMDPath, dwInstanceMDPathLen - 1))) { goto LExit; } // Look up server name in metabase. BYTE *prgbData = (BYTE *)tempMDData.QueryPtr(); DWORD dwRequiredBuffer = 0; hr = pIReq->GetAspMDDataA( szInstanceMDPath, MD_SERVER_COMMENT, METADATA_INHERIT, IIS_MD_UT_SERVER, STRING_METADATA, tempMDData.QuerySize(), 0, prgbData, &dwRequiredBuffer); if (hr == RETURNCODETOHRESULT(ERROR_INSUFFICIENT_BUFFER)) { if (tempMDData.Resize(dwRequiredBuffer) == FALSE) { hr = E_OUTOFMEMORY; } else { prgbData = reinterpret_cast<BYTE *>(tempMDData.QueryPtr()); hr = pIReq->GetAspMDDataA( szInstanceMDPath, MD_SERVER_COMMENT, METADATA_INHERIT, IIS_MD_UT_SERVER, STRING_METADATA, dwRequiredBuffer, 0, prgbData, &dwRequiredBuffer); } } if (FAILED(hr)) { // ServerComment does not exist, so construct using server name and port STACK_BUFFER( serverNameBuff, 16 ); DWORD cbServerName; STACK_BUFFER( serverPortBuff, 10 ); DWORD cbServerPort; STACK_BUFFER( debugNodeBuff, 30 ); if (!SERVER_GET(pIReq, "LOCAL_ADDR", &serverNameBuff, &cbServerName) || !SERVER_GET(pIReq, "SERVER_PORT", &serverPortBuff, &cbServerPort)) { hr = E_FAIL; goto LExit; } char *szServerName = (char *)serverNameBuff.QueryPtr(); char *szServerPort = (char*)serverPortBuff.QueryPtr(); // resize the debugNodeBuff to hold <serverIP>:<port>'\0'. if (!debugNodeBuff.Resize(cbServerName + cbServerPort + 2)) { hr = E_OUTOFMEMORY; goto LExit; } // Syntax is <serverIP:port> char *szDebugNode = (char *)debugNodeBuff.QueryPtr(); strcpyExA(strcpyExA(strcpyExA(szDebugNode, szServerName), ":"), szServerPort); // Convert to Wide Char hr = MultiByteToWideChar(CP_ACP, 0, szDebugNode, -1, reinterpret_cast<wchar_t *>(prgbData), tempMDData.QuerySize() / 2); if (FAILED(hr)) goto LExit; } // We've got the metadata (ServerComment), create a debug node with this name IDebugApplicationNode *pServerRoot; if (FAILED(hr = g_pDebugApp->CreateApplicationNode(&pServerRoot))) goto LExit; // Create a doc provider for the node CFileNode *pFileNode = new CFileNode; if (pFileNode == NULL) { hr = E_OUTOFMEMORY; goto LExit; } if (FAILED(hr = pFileNode->Init(reinterpret_cast<wchar_t *>(prgbData)))) goto LExit; if (FAILED(hr = pServerRoot->SetDocumentProvider(pFileNode))) goto LExit; // pFileNode has been AddRef'ed and we don't need it now. pFileNode->Release(); // Attach to the UI if (FAILED(pServerRoot->Attach(g_pDebugAppRoot))) goto LExit; // OK, Now add this item to the hashtable (this eats the reference from creation) pDebugNode->m_pServerRoot = pServerRoot; g_HashMDPath2DebugRoot.AddElem(pDebugNode); fDeleteDebugNode = FALSE; } *ppDebugRoot = pDebugNode->m_pServerRoot; (*ppDebugRoot)->AddRef(); hr = S_OK; LExit: if (fDeleteDebugNode) { delete pDebugNode; } LeaveCriticalSection(&g_csDebugLock); return hr; } /*=================================================================== C F i l e N o d e Implementation of CFileNode - trivial class ===================================================================*/ const GUID IID_IFileNode = { 0x41047bd2, 0xfe1e, 0x11d0, { 0x8f, 0x3f, 0x0, 0xc0, 0x4f, 0xc3, 0x4d, 0xcc } }; CFileNode::CFileNode() : m_cRefs(1), m_cDocuments(0), m_wszName(NULL) {} CFileNode::~CFileNode() { delete[] m_wszName; } HRESULT CFileNode::Init(wchar_t *wszName) { if ((m_wszName = new wchar_t [wcslen(wszName) + 1]) == NULL) return E_OUTOFMEMORY; wcscpy(m_wszName, wszName); return S_OK; } HRESULT CFileNode::QueryInterface(const GUID &uidInterface, void **ppvObj) { if (uidInterface == IID_IUnknown || uidInterface == IID_IDebugDocumentProvider || uidInterface == IID_IFileNode) { *ppvObj = this; AddRef(); return S_OK; } else return E_NOINTERFACE; } ULONG CFileNode::AddRef() { InterlockedIncrement(reinterpret_cast<long *>(&m_cRefs)); return m_cRefs; } ULONG CFileNode::Release() { LONG cRefs = InterlockedDecrement(reinterpret_cast<long *>(&m_cRefs)); if (cRefs) return cRefs; delete this; return 0; } HRESULT CFileNode::GetDocument(IDebugDocument **ppDebugDoc) { return QueryInterface(IID_IDebugDocument, reinterpret_cast<void **>(ppDebugDoc)); } HRESULT CFileNode::GetName(DOCUMENTNAMETYPE, BSTR *pbstrName) { return ((*pbstrName = SysAllocString(m_wszName)) == NULL)? E_OUTOFMEMORY : S_OK; }
31.571921
140
0.517801
npocmaka
d9399880189f27bd5e1d4eb31ece04c6f4fd198e
1,820
cc
C++
src/q_1301_1350/q1309.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
null
null
null
src/q_1301_1350/q1309.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
2
2021-12-15T10:51:15.000Z
2022-01-26T17:03:16.000Z
src/q_1301_1350/q1309.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <iostream> #include <string> using namespace std; /** * This file is generated by leetcode_add.py * * 1309. * Decrypt String from Alphabet to Integer Mapping * * ––––––––––––––––––––––––––––– Description ––––––––––––––––––––––––––––– * * You are given a string ‘s’ formed by digits and ‘'#'’ . We want to map * ‘s’ to English lowercase characters as * - Characters ( ‘'a'’ to ‘'i')’ are represented by ( ‘'1'’ to ‘'9'’ * ) * - Characters ( ‘'j'’ to ‘'z')’ are represented by ( ‘'10#'’ to * ‘'26#'’ ) * Return “the string formed after mapping” * The test cases are generated so that a unique mapping will always * exist. * * ––––––––––––––––––––––––––––– Constraints ––––––––––––––––––––––––––––– * * • ‘1 ≤ s.length ≤ 1000’ * • ‘s’ consists of digits and the ‘'#'’ letter. * • ‘s’ will be a valid string such that mapping is always possible. * */ struct q1309 : public ::testing::Test { // Leetcode answer here class Solution { public: string freqAlphabets(string s) { string res; for (int i = s.size() - 1; i >= 0; --i) { if (s[i] == '#') { res.push_back(stoi(s.substr(i - 2, 2)) - 10 + 'j'); -- --i; } else { res.push_back(s[i] - '1' + 'a'); } } reverse(res.begin(), res.end()); return res; } }; class Solution *solution; }; TEST_F(q1309, sample_input01) { solution = new Solution(); string s = "10#11#12"; string exp = "jkab"; string act = solution->freqAlphabets(s); EXPECT_EQ(act, exp); delete solution; } TEST_F(q1309, sample_input02) { solution = new Solution(); string s = "1326#"; string exp = "acz"; string act = solution->freqAlphabets(s); EXPECT_EQ(act, exp); delete solution; }
25.277778
75
0.535165
vNaonLu
d93f27f778a565a45c114b985a25a601b82867f6
3,865
hpp
C++
SDK/ARKSurvivalEvolved_DinoTamedInventoryComponent_Beetle_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_DinoTamedInventoryComponent_Beetle_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_DinoTamedInventoryComponent_Beetle_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DinoTamedInventoryComponent_Beetle_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.CraftItem struct UDinoTamedInventoryComponent_Beetle_C_CraftItem_Params { int ItemToCraftIndex; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.BPInventoryRefresh struct UDinoTamedInventoryComponent_Beetle_C_BPInventoryRefresh_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.BPInitializeInventory struct UDinoTamedInventoryComponent_Beetle_C_BPInitializeInventory_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.CheckIfAnythingNewCanBeCrafted struct UDinoTamedInventoryComponent_Beetle_C_CheckIfAnythingNewCanBeCrafted_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.Initial Set Crafting Times struct UDinoTamedInventoryComponent_Beetle_C_Initial_Set_Crafting_Times_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.TryToCraft struct UDinoTamedInventoryComponent_Beetle_C_TryToCraft_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.UnsetAll struct UDinoTamedInventoryComponent_Beetle_C_UnsetAll_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.HasEnoughResources struct UDinoTamedInventoryComponent_Beetle_C_HasEnoughResources_Params { int IndexClassToCheck; // (Parm, ZeroConstructor, IsPlainOldData) bool hasEnough; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int NumberOfTimesCanCraft; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.RemoveUncraftable struct UDinoTamedInventoryComponent_Beetle_C_RemoveUncraftable_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.BPNotifyItemAdded struct UDinoTamedInventoryComponent_Beetle_C_BPNotifyItemAdded_Params { class UPrimalItem** anItem; // (Parm, ZeroConstructor, IsPlainOldData) bool* bEquipItem; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.BPNotifyItemRemoved struct UDinoTamedInventoryComponent_Beetle_C_BPNotifyItemRemoved_Params { class UPrimalItem** anItem; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.ExecuteUbergraph_DinoTamedInventoryComponent_Beetle struct UDinoTamedInventoryComponent_Beetle_C_ExecuteUbergraph_DinoTamedInventoryComponent_Beetle_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
42.944444
161
0.686158
2bite
d93fdb9f6e0fdeebf1f4d05913e9536ebe9b383c
1,055
hpp
C++
src/boost/atomic/detail/wait_caps_dragonfly_umtx.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
null
null
null
src/boost/atomic/detail/wait_caps_dragonfly_umtx.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
1
2021-08-30T18:02:49.000Z
2021-08-30T18:02:49.000Z
src/boost/atomic/detail/wait_caps_dragonfly_umtx.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
null
null
null
/* * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * Copyright (c) 2020 Andrey Semashev */ /*! * \file atomic/detail/wait_caps_dragonfly_umtx.hpp * * This header defines waiting/notifying operations capabilities macros. */ #ifndef BOOST_ATOMIC_DETAIL_WAIT_CAPS_DRAGONFLY_UMTX_HPP_INCLUDED_ #define BOOST_ATOMIC_DETAIL_WAIT_CAPS_DRAGONFLY_UMTX_HPP_INCLUDED_ #include "boost/atomic/detail/config.hpp" #include "boost/atomic/detail/capabilities.hpp" #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif // DragonFly BSD umtx_sleep/umtx_wakeup use physical address to the atomic object as a key, which means it should support address-free operations. // https://man.dragonflybsd.org/?command=umtx&section=2 #define BOOST_ATOMIC_HAS_NATIVE_INT32_WAIT_NOTIFY BOOST_ATOMIC_INT32_LOCK_FREE #define BOOST_ATOMIC_HAS_NATIVE_INT32_IPC_WAIT_NOTIFY BOOST_ATOMIC_INT32_LOCK_FREE #endif // BOOST_ATOMIC_DETAIL_WAIT_CAPS_DRAGONFLY_UMTX_HPP_INCLUDED_
34.032258
146
0.824645
107-systems
d9409cbbe2b6fa384db0888d8d6ee9a87ab578d0
42,365
cpp
C++
framework/hpp_api_vulkan_sample.cpp
jwinarske/Vulkan-Samples
11a0eeffa223e3c049780fd783900da0bfe50431
[ "Apache-2.0" ]
20
2020-03-25T17:57:32.000Z
2022-03-12T08:16:10.000Z
framework/hpp_api_vulkan_sample.cpp
JasonWinston/Vulkan-Samples
fe3fd6435e5f209b00d72a85004f189d01debee4
[ "Apache-2.0" ]
1
2020-02-18T07:08:52.000Z
2020-02-18T07:08:52.000Z
framework/hpp_api_vulkan_sample.cpp
JasonWinston/Vulkan-Samples
fe3fd6435e5f209b00d72a85004f189d01debee4
[ "Apache-2.0" ]
1
2020-04-12T16:23:18.000Z
2020-04-12T16:23:18.000Z
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * 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 <hpp_api_vulkan_sample.h> #include <common/hpp_vk_common.h> #include <core/hpp_buffer.h> #include <hpp_gltf_loader.h> // Instantiate the default dispatcher VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE bool HPPApiVulkanSample::prepare(vkb::platform::HPPPlatform &platform) { if (!HPPVulkanSample::prepare(platform)) { return false; } // initialize function pointers for C++-bindings static vk::DynamicLoader dl; VULKAN_HPP_DEFAULT_DISPATCHER.init(dl.getProcAddress<PFN_vkGetInstanceProcAddr>("vkGetInstanceProcAddr")); VULKAN_HPP_DEFAULT_DISPATCHER.init(get_instance().get_handle()); VULKAN_HPP_DEFAULT_DISPATCHER.init(get_device().get_handle()); depth_format = vkb::common::get_suitable_depth_format(get_device().get_gpu().get_handle()); // Create synchronization objects // Create a semaphore used to synchronize image presentation // Ensures that the current swapchain render target has completed presentation and has been released by the presentation engine, ready for rendering semaphores.acquired_image_ready = get_device().get_handle().createSemaphore({}); // Create a semaphore used to synchronize command submission // Ensures that the image is not presented until all commands have been sumbitted and executed semaphores.render_complete = get_device().get_handle().createSemaphore({}); // Set up submit info structure // Semaphores will stay the same during application lifetime // Command buffer submission info is set by each example submit_info = vk::SubmitInfo(); submit_info.pWaitDstStageMask = &submit_pipeline_stages; if (platform.get_window().get_window_mode() != vkb::Window::Mode::Headless) { submit_info.setWaitSemaphores(semaphores.acquired_image_ready); submit_info.setSignalSemaphores(semaphores.render_complete); } queue = get_device().get_suitable_graphics_queue().get_handle(); create_swapchain_buffers(); create_command_pool(); create_command_buffers(); create_synchronization_primitives(); setup_depth_stencil(); setup_render_pass(); create_pipeline_cache(); setup_framebuffer(); extent = get_render_context().get_surface_extent(); gui = std::make_unique<vkb::Gui>(*this, platform.get_window(), /*stats=*/nullptr, 15.0f, true); gui->prepare(pipeline_cache, render_pass, {load_shader("uioverlay/uioverlay.vert", vk::ShaderStageFlagBits::eVertex), load_shader("uioverlay/uioverlay.frag", vk::ShaderStageFlagBits::eFragment)}); return true; } void HPPApiVulkanSample::update(float delta_time) { if (view_updated) { view_updated = false; view_changed(); } update_overlay(delta_time); render(delta_time); camera.update(delta_time); if (camera.moving()) { view_updated = true; } get_platform().on_post_draw(get_render_context()); } bool HPPApiVulkanSample::resize(const uint32_t, const uint32_t) { if (!prepared) { return false; } get_render_context().handle_surface_changes(); // Don't recreate the swapchain if the dimensions haven't changed if (extent == get_render_context().get_surface_extent()) { return false; } extent = get_render_context().get_surface_extent(); prepared = false; // Ensure all operations on the device have been finished before destroying resources get_device().wait_idle(); create_swapchain_buffers(); // Recreate the frame buffers get_device().get_handle().destroyImageView(depth_stencil.view); get_device().get_handle().destroyImage(depth_stencil.image); get_device().get_handle().freeMemory(depth_stencil.mem); setup_depth_stencil(); for (uint32_t i = 0; i < framebuffers.size(); i++) { get_device().get_handle().destroyFramebuffer(framebuffers[i]); framebuffers[i] = nullptr; } setup_framebuffer(); if (extent.width && extent.height && gui) { gui->resize(extent.width, extent.height); } // Command buffers need to be recreated as they may store // references to the recreated frame buffer destroy_command_buffers(); create_command_buffers(); build_command_buffers(); get_device().wait_idle(); if (extent.width && extent.height) { camera.update_aspect_ratio((float) extent.width / (float) extent.height); } // Notify derived class view_changed(); prepared = true; return true; } void HPPApiVulkanSample::create_render_context(vkb::Platform &platform) { HPPVulkanSample::create_render_context(platform, {{vk::Format::eB8G8R8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear}, {vk::Format::eR8G8B8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear}, {vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}, {vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}}); } void HPPApiVulkanSample::prepare_render_context() { HPPVulkanSample::prepare_render_context(); } void HPPApiVulkanSample::input_event(const vkb::InputEvent &input_event) { HPPVulkanSample::input_event(input_event); bool gui_captures_event = false; if (gui) { gui_captures_event = gui->input_event(input_event); } if (!gui_captures_event) { if (input_event.get_source() == vkb::EventSource::Mouse) { const auto &mouse_button = static_cast<const vkb::MouseButtonInputEvent &>(input_event); handle_mouse_move(static_cast<int32_t>(mouse_button.get_pos_x()), static_cast<int32_t>(mouse_button.get_pos_y())); if (mouse_button.get_action() == vkb::MouseAction::Down) { switch (mouse_button.get_button()) { case vkb::MouseButton::Left: mouse_buttons.left = true; break; case vkb::MouseButton::Right: mouse_buttons.right = true; break; case vkb::MouseButton::Middle: mouse_buttons.middle = true; break; default: break; } } else if (mouse_button.get_action() == vkb::MouseAction::Up) { switch (mouse_button.get_button()) { case vkb::MouseButton::Left: mouse_buttons.left = false; break; case vkb::MouseButton::Right: mouse_buttons.right = false; break; case vkb::MouseButton::Middle: mouse_buttons.middle = false; break; default: break; } } } else if (input_event.get_source() == vkb::EventSource::Touchscreen) { const auto &touch_event = static_cast<const vkb::TouchInputEvent &>(input_event); if (touch_event.get_action() == vkb::TouchAction::Down) { touch_down = true; touch_pos.x = static_cast<int32_t>(touch_event.get_pos_x()); touch_pos.y = static_cast<int32_t>(touch_event.get_pos_y()); mouse_pos.x = touch_event.get_pos_x(); mouse_pos.y = touch_event.get_pos_y(); mouse_buttons.left = true; } else if (touch_event.get_action() == vkb::TouchAction::Up) { touch_pos.x = static_cast<int32_t>(touch_event.get_pos_x()); touch_pos.y = static_cast<int32_t>(touch_event.get_pos_y()); touch_timer = 0.0; touch_down = false; camera.keys.up = false; mouse_buttons.left = false; } else if (touch_event.get_action() == vkb::TouchAction::Move) { bool handled = false; if (gui) { ImGuiIO &io = ImGui::GetIO(); handled = io.WantCaptureMouse; } if (!handled) { int32_t eventX = static_cast<int32_t>(touch_event.get_pos_x()); int32_t eventY = static_cast<int32_t>(touch_event.get_pos_y()); float deltaX = (float) (touch_pos.y - eventY) * rotation_speed * 0.5f; float deltaY = (float) (touch_pos.x - eventX) * rotation_speed * 0.5f; camera.rotate(glm::vec3(deltaX, 0.0f, 0.0f)); camera.rotate(glm::vec3(0.0f, -deltaY, 0.0f)); rotation.x += deltaX; rotation.y -= deltaY; view_changed(); touch_pos.x = eventX; touch_pos.y = eventY; } } } else if (input_event.get_source() == vkb::EventSource::Keyboard) { const auto &key_button = static_cast<const vkb::KeyInputEvent &>(input_event); if (key_button.get_action() == vkb::KeyAction::Down) { switch (key_button.get_code()) { case vkb::KeyCode::W: camera.keys.up = true; break; case vkb::KeyCode::S: camera.keys.down = true; break; case vkb::KeyCode::A: camera.keys.left = true; break; case vkb::KeyCode::D: camera.keys.right = true; break; case vkb::KeyCode::P: paused = !paused; break; default: break; } } else if (key_button.get_action() == vkb::KeyAction::Up) { switch (key_button.get_code()) { case vkb::KeyCode::W: camera.keys.up = false; break; case vkb::KeyCode::S: camera.keys.down = false; break; case vkb::KeyCode::A: camera.keys.left = false; break; case vkb::KeyCode::D: camera.keys.right = false; break; default: break; } } } } } void HPPApiVulkanSample::handle_mouse_move(int32_t x, int32_t y) { int32_t dx = (int32_t) mouse_pos.x - x; int32_t dy = (int32_t) mouse_pos.y - y; bool handled = false; if (gui) { ImGuiIO &io = ImGui::GetIO(); handled = io.WantCaptureMouse; } mouse_moved((float) x, (float) y, handled); if (handled) { mouse_pos = glm::vec2((float) x, (float) y); return; } if (mouse_buttons.left) { rotation.x += dy * 1.25f * rotation_speed; rotation.y -= dx * 1.25f * rotation_speed; camera.rotate(glm::vec3(dy * camera.rotation_speed, -dx * camera.rotation_speed, 0.0f)); view_updated = true; } if (mouse_buttons.right) { zoom += dy * .005f * zoom_speed; camera.translate(glm::vec3(-0.0f, 0.0f, dy * .005f * zoom_speed)); view_updated = true; } if (mouse_buttons.middle) { camera_pos.x -= dx * 0.01f; camera_pos.y -= dy * 0.01f; camera.translate(glm::vec3(-dx * 0.01f, -dy * 0.01f, 0.0f)); view_updated = true; } mouse_pos = glm::vec2((float) x, (float) y); } void HPPApiVulkanSample::mouse_moved(double x, double y, bool &handled) {} bool HPPApiVulkanSample::check_command_buffers() { for (auto &command_buffer : draw_cmd_buffers) { if (command_buffer) { return false; } } return true; } void HPPApiVulkanSample::create_command_buffers() { // Create one command buffer for each swap chain image and reuse for rendering vk::CommandBufferAllocateInfo allocate_info( cmd_pool, vk::CommandBufferLevel::ePrimary, static_cast<uint32_t>(get_render_context().get_render_frames().size())); draw_cmd_buffers = get_device().get_handle().allocateCommandBuffers(allocate_info); } void HPPApiVulkanSample::destroy_command_buffers() { get_device().get_handle().freeCommandBuffers(cmd_pool, draw_cmd_buffers); } void HPPApiVulkanSample::create_pipeline_cache() { pipeline_cache = get_device().get_handle().createPipelineCache({}); } vk::PipelineShaderStageCreateInfo HPPApiVulkanSample::load_shader(const std::string &file, vk::ShaderStageFlagBits stage) { shader_modules.push_back(vkb::common::load_shader(file.c_str(), get_device().get_handle(), stage)); assert(shader_modules.back()); return vk::PipelineShaderStageCreateInfo({}, stage, shader_modules.back(), "main"); } void HPPApiVulkanSample::update_overlay(float delta_time) { if (gui) { gui->show_simple_window(get_name(), vkb::to_u32(1.0f / delta_time), [this]() { on_update_ui_overlay(gui->get_drawer()); }); gui->update(delta_time); if (gui->update_buffers() || gui->get_drawer().is_dirty()) { build_command_buffers(); gui->get_drawer().clear(); } } } void HPPApiVulkanSample::draw_ui(const vk::CommandBuffer command_buffer) { if (gui) { command_buffer.setViewport(0, vk::Viewport(0.0f, 0.0f, static_cast<float>(extent.width), static_cast<float>(extent.height), 0.0f, 1.0f)); command_buffer.setScissor(0, vk::Rect2D({0, 0}, extent)); gui->draw(command_buffer); } } void HPPApiVulkanSample::prepare_frame() { if (get_render_context().has_swapchain()) { handle_surface_changes(); // Acquire the next image from the swap chain // Shows how to filter an error code from a vulkan function, which is mapped to an exception but should be handled here! vk::Result result; try { result = get_render_context().get_swapchain().acquire_next_image(current_buffer, semaphores.acquired_image_ready); } catch (const vk::SystemError &e) { if (e.code() == vk::Result::eErrorOutOfDateKHR) { result = vk::Result::eErrorOutOfDateKHR; } else { throw; } } // Recreate the swapchain if it's no longer compatible with the surface (eErrorOutOfDateKHR) or no longer optimal for // presentation (eSuboptimalKHR) if ((result == vk::Result::eErrorOutOfDateKHR) || (result == vk::Result::eSuboptimalKHR)) { resize(extent.width, extent.height); } } } void HPPApiVulkanSample::submit_frame() { if (get_render_context().has_swapchain()) { const auto &queue = get_device().get_queue_by_present(0); vk::SwapchainKHR swapchain = get_render_context().get_swapchain().get_handle(); vk::PresentInfoKHR present_info({}, swapchain, current_buffer); // Check if a wait semaphore has been specified to wait for before presenting the image if (semaphores.render_complete) { present_info.setWaitSemaphores(semaphores.render_complete); } // Shows how to filter an error code from a vulkan function, which is mapped to an exception but should be handled here! vk::Result present_result; try { present_result = queue.present(present_info); } catch (const vk::SystemError &e) { if (e.code() == vk::Result::eErrorOutOfDateKHR) { // Swap chain is no longer compatible with the surface and needs to be recreated resize(extent.width, extent.height); return; } else { // rethrow this error throw; } } } // DO NOT USE // vkDeviceWaitIdle and vkQueueWaitIdle are extremely expensive functions, and are used here purely for demonstrating the vulkan API // without having to concern ourselves with proper syncronization. These functions should NEVER be used inside the render loop like this (every frame). get_device().get_queue_by_present(0).wait_idle(); } HPPApiVulkanSample::~HPPApiVulkanSample() { if (get_device().get_handle()) { get_device().wait_idle(); // Clean up Vulkan resources get_device().get_handle().destroyDescriptorPool(descriptor_pool); destroy_command_buffers(); get_device().get_handle().destroyRenderPass(render_pass); for (auto &framebuffer : framebuffers) { get_device().get_handle().destroyFramebuffer(framebuffer); } for (auto &swapchain_buffer : swapchain_buffers) { get_device().get_handle().destroyImageView(swapchain_buffer.view); } for (auto &shader_module : shader_modules) { get_device().get_handle().destroyShaderModule(shader_module); } get_device().get_handle().destroyImageView(depth_stencil.view); get_device().get_handle().destroyImage(depth_stencil.image); get_device().get_handle().freeMemory(depth_stencil.mem); get_device().get_handle().destroyPipelineCache(pipeline_cache); get_device().get_handle().destroyCommandPool(cmd_pool); get_device().get_handle().destroySemaphore(semaphores.acquired_image_ready); get_device().get_handle().destroySemaphore(semaphores.render_complete); for (auto &fence : wait_fences) { get_device().get_handle().destroyFence(fence); } } gui.reset(); } void HPPApiVulkanSample::view_changed() {} void HPPApiVulkanSample::build_command_buffers() {} void HPPApiVulkanSample::create_synchronization_primitives() { // Wait fences to sync command buffer access vk::FenceCreateInfo fence_create_info(vk::FenceCreateFlagBits::eSignaled); wait_fences.resize(draw_cmd_buffers.size()); for (auto &fence : wait_fences) { fence = get_device().get_handle().createFence(fence_create_info); } } void HPPApiVulkanSample::create_command_pool() { uint32_t queue_family_index = get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics | vk::QueueFlagBits::eCompute, 0).get_family_index(); vk::CommandPoolCreateInfo command_pool_info(vk::CommandPoolCreateFlagBits::eResetCommandBuffer, queue_family_index); cmd_pool = get_device().get_handle().createCommandPool(command_pool_info); } void HPPApiVulkanSample::setup_depth_stencil() { vk::ImageCreateInfo image_create_info; image_create_info.imageType = vk::ImageType::e2D; image_create_info.format = depth_format; image_create_info.extent = vk::Extent3D(get_render_context().get_surface_extent().width, get_render_context().get_surface_extent().height, 1); image_create_info.mipLevels = 1; image_create_info.arrayLayers = 1; image_create_info.samples = vk::SampleCountFlagBits::e1; image_create_info.tiling = vk::ImageTiling::eOptimal; image_create_info.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransferSrc; depth_stencil.image = get_device().get_handle().createImage(image_create_info); vk::MemoryRequirements memReqs = get_device().get_handle().getImageMemoryRequirements(depth_stencil.image); vk::MemoryAllocateInfo memory_allocation(memReqs.size, get_device().get_memory_type(memReqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal)); depth_stencil.mem = get_device().get_handle().allocateMemory(memory_allocation); get_device().get_handle().bindImageMemory(depth_stencil.image, depth_stencil.mem, 0); vk::ImageViewCreateInfo image_view_create_info; image_view_create_info.viewType = vk::ImageViewType::e2D; image_view_create_info.image = depth_stencil.image; image_view_create_info.format = depth_format; image_view_create_info.subresourceRange.baseMipLevel = 0; image_view_create_info.subresourceRange.levelCount = 1; image_view_create_info.subresourceRange.baseArrayLayer = 0; image_view_create_info.subresourceRange.layerCount = 1; image_view_create_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eDepth; // Stencil aspect should only be set on depth + stencil formats (vk::Format::eD16UnormS8Uint..vk::Format::eD32SfloatS8Uint if (vk::Format::eD16UnormS8Uint <= depth_format) { image_view_create_info.subresourceRange.aspectMask |= vk::ImageAspectFlagBits::eStencil; } depth_stencil.view = get_device().get_handle().createImageView(image_view_create_info); } void HPPApiVulkanSample::setup_framebuffer() { std::array<vk::ImageView, 2> attachments; // Depth/Stencil attachment is the same for all frame buffers attachments[1] = depth_stencil.view; vk::FramebufferCreateInfo framebuffer_create_info( {}, render_pass, attachments, get_render_context().get_surface_extent().width, get_render_context().get_surface_extent().height, 1); // Delete existing frame buffers for (auto &framebuffer : framebuffers) { get_device().get_handle().destroyFramebuffer(framebuffer); } framebuffers.clear(); // Create frame buffers for every swap chain image framebuffers.reserve(swapchain_buffers.size()); for (auto &buffer : swapchain_buffers) { attachments[0] = buffer.view; framebuffers.push_back(get_device().get_handle().createFramebuffer(framebuffer_create_info)); } } void HPPApiVulkanSample::setup_render_pass() { std::array<vk::AttachmentDescription, 2> attachments; // Color attachment attachments[0].format = get_render_context().get_format(); attachments[0].samples = vk::SampleCountFlagBits::e1; attachments[0].loadOp = vk::AttachmentLoadOp::eClear; attachments[0].storeOp = vk::AttachmentStoreOp::eStore; attachments[0].stencilLoadOp = vk::AttachmentLoadOp::eDontCare; attachments[0].stencilStoreOp = vk::AttachmentStoreOp::eDontCare; attachments[0].initialLayout = vk::ImageLayout::eUndefined; attachments[0].finalLayout = vk::ImageLayout::ePresentSrcKHR; // Depth attachment attachments[1].format = depth_format; attachments[1].samples = vk::SampleCountFlagBits::e1; attachments[1].loadOp = vk::AttachmentLoadOp::eClear; attachments[1].storeOp = vk::AttachmentStoreOp::eDontCare; attachments[1].stencilLoadOp = vk::AttachmentLoadOp::eClear; attachments[1].stencilStoreOp = vk::AttachmentStoreOp::eDontCare; attachments[1].initialLayout = vk::ImageLayout::eUndefined; attachments[1].finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal; vk::AttachmentReference color_reference(0, vk::ImageLayout::eColorAttachmentOptimal); vk::AttachmentReference depth_reference(1, vk::ImageLayout::eDepthStencilAttachmentOptimal); vk::SubpassDescription subpass_description({}, vk::PipelineBindPoint::eGraphics, {}, color_reference, {}, &depth_reference); // Subpass dependencies for layout transitions std::array<vk::SubpassDependency, 2> dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = vk::PipelineStageFlagBits::eBottomOfPipe; dependencies[0].dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; dependencies[0].srcAccessMask = vk::AccessFlagBits::eMemoryRead; dependencies[0].dstAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite; dependencies[0].dependencyFlags = vk::DependencyFlagBits::eByRegion; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; dependencies[1].dstStageMask = vk::PipelineStageFlagBits::eBottomOfPipe; dependencies[1].srcAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite; dependencies[1].dstAccessMask = vk::AccessFlagBits::eMemoryRead; dependencies[1].dependencyFlags = vk::DependencyFlagBits::eByRegion; vk::RenderPassCreateInfo render_pass_create_info({}, attachments, subpass_description, dependencies); render_pass = get_device().get_handle().createRenderPass(render_pass_create_info); } void HPPApiVulkanSample::update_render_pass_flags(RenderPassCreateFlags flags) { get_device().get_handle().destroyRenderPass(render_pass); vk::AttachmentLoadOp color_attachment_load_op = vk::AttachmentLoadOp::eClear; vk::ImageLayout color_attachment_image_layout = vk::ImageLayout::eUndefined; // Samples can keep the color attachment contents, e.g. if they have previously written to the swap chain images if (flags & RenderPassCreateFlags::ColorAttachmentLoad) { color_attachment_load_op = vk::AttachmentLoadOp::eLoad; color_attachment_image_layout = vk::ImageLayout::ePresentSrcKHR; } std::array<vk::AttachmentDescription, 2> attachments = {}; // Color attachment attachments[0].format = get_render_context().get_format(); attachments[0].samples = vk::SampleCountFlagBits::e1; attachments[0].loadOp = color_attachment_load_op; attachments[0].storeOp = vk::AttachmentStoreOp::eStore; attachments[0].stencilLoadOp = vk::AttachmentLoadOp::eDontCare; attachments[0].stencilStoreOp = vk::AttachmentStoreOp::eDontCare; attachments[0].initialLayout = color_attachment_image_layout; attachments[0].finalLayout = vk::ImageLayout::ePresentSrcKHR; // Depth attachment attachments[1].format = depth_format; attachments[1].samples = vk::SampleCountFlagBits::e1; attachments[1].loadOp = vk::AttachmentLoadOp::eClear; attachments[1].storeOp = vk::AttachmentStoreOp::eDontCare; attachments[1].stencilLoadOp = vk::AttachmentLoadOp::eClear; attachments[1].stencilStoreOp = vk::AttachmentStoreOp::eDontCare; attachments[1].initialLayout = vk::ImageLayout::eUndefined; attachments[1].finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal; vk::AttachmentReference color_reference(0, vk::ImageLayout::eColorAttachmentOptimal); vk::AttachmentReference depth_reference(1, vk::ImageLayout::eDepthStencilAttachmentOptimal); vk::SubpassDescription subpass_description({}, vk::PipelineBindPoint::eGraphics, {}, color_reference, {}, &depth_reference); // Subpass dependencies for layout transitions std::array<vk::SubpassDependency, 2> dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = vk::PipelineStageFlagBits::eBottomOfPipe; dependencies[0].dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; dependencies[0].srcAccessMask = vk::AccessFlagBits::eMemoryWrite; dependencies[0].dstAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite; dependencies[0].dependencyFlags = vk::DependencyFlagBits::eByRegion; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; dependencies[1].dstStageMask = vk::PipelineStageFlagBits::eBottomOfPipe; dependencies[1].srcAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite; dependencies[1].dstAccessMask = vk::AccessFlagBits::eMemoryRead; dependencies[1].dependencyFlags = vk::DependencyFlagBits::eByRegion; vk::RenderPassCreateInfo render_pass_create_info({}, attachments, subpass_description, dependencies); render_pass = get_device().get_handle().createRenderPass(render_pass_create_info); } void HPPApiVulkanSample::on_update_ui_overlay(vkb::Drawer &drawer) {} void HPPApiVulkanSample::create_swapchain_buffers() { if (get_render_context().has_swapchain()) { auto &images = get_render_context().get_swapchain().get_images(); // Get the swap chain buffers containing the image and imageview for (auto &swapchain_buffer : swapchain_buffers) { get_device().get_handle().destroyImageView(swapchain_buffer.view); } swapchain_buffers.clear(); swapchain_buffers.reserve(images.size()); for (auto &image : images) { vk::ImageViewCreateInfo color_attachment_view; color_attachment_view.image = image; color_attachment_view.viewType = vk::ImageViewType::e2D; color_attachment_view.format = get_render_context().get_swapchain().get_format(); color_attachment_view.components = {vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA}; color_attachment_view.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; color_attachment_view.subresourceRange.baseMipLevel = 0; color_attachment_view.subresourceRange.levelCount = 1; color_attachment_view.subresourceRange.baseArrayLayer = 0; color_attachment_view.subresourceRange.layerCount = 1; swapchain_buffers.push_back({image, get_device().get_handle().createImageView(color_attachment_view)}); } } else { auto &frames = get_render_context().get_render_frames(); // Get the swap chain buffers containing the image and imageview swapchain_buffers.clear(); swapchain_buffers.reserve(frames.size()); for (auto &frame : frames) { auto &image_view = *frame->get_render_target().get_views().begin(); swapchain_buffers.push_back({image_view.get_image().get_handle(), image_view.get_handle()}); } } } void HPPApiVulkanSample::update_swapchain_image_usage_flags(std::set<vk::ImageUsageFlagBits> const &image_usage_flags) { get_render_context().update_swapchain(image_usage_flags); create_swapchain_buffers(); setup_framebuffer(); } void HPPApiVulkanSample::handle_surface_changes() { vk::SurfaceCapabilitiesKHR surface_properties = get_device().get_gpu().get_handle().getSurfaceCapabilitiesKHR(get_render_context().get_swapchain().get_surface()); if (surface_properties.currentExtent != get_render_context().get_surface_extent()) { resize(surface_properties.currentExtent.width, surface_properties.currentExtent.height); } } HPPTexture HPPApiVulkanSample::load_texture(const std::string &file) { HPPTexture texture; texture.image = vkb::scene_graph::components::HPPImage::load(file, file); texture.image->create_vk_image(get_device()); const auto &queue = get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics, 0); vk::CommandBuffer command_buffer = get_device().create_command_buffer(vk::CommandBufferLevel::ePrimary, true); vkb::core::HPPBuffer stage_buffer{get_device(), texture.image->get_data().size(), vk::BufferUsageFlagBits::eTransferSrc, VMA_MEMORY_USAGE_CPU_ONLY}; stage_buffer.update(texture.image->get_data()); // Setup buffer copy regions for each mip level std::vector<vk::BufferImageCopy> bufferCopyRegions; auto &mipmaps = texture.image->get_mipmaps(); for (size_t i = 0; i < mipmaps.size(); i++) { vk::BufferImageCopy buffer_copy_region; buffer_copy_region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; buffer_copy_region.imageSubresource.mipLevel = vkb::to_u32(i); buffer_copy_region.imageSubresource.baseArrayLayer = 0; buffer_copy_region.imageSubresource.layerCount = 1; buffer_copy_region.imageExtent.width = texture.image->get_extent().width >> i; buffer_copy_region.imageExtent.height = texture.image->get_extent().height >> i; buffer_copy_region.imageExtent.depth = 1; buffer_copy_region.bufferOffset = mipmaps[i].offset; bufferCopyRegions.push_back(buffer_copy_region); } vk::ImageSubresourceRange subresource_range(vk::ImageAspectFlagBits::eColor, 0, vkb::to_u32(mipmaps.size()), 0, 1); // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy vkb::common::set_image_layout( command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, subresource_range); // Copy mip levels from staging buffer command_buffer.copyBufferToImage( stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, bufferCopyRegions); // Change texture image layout to shader read after all mip levels have been copied vkb::common::set_image_layout(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); // Create a defaultsampler vk::SamplerCreateInfo sampler_create_info; sampler_create_info.magFilter = vk::Filter::eLinear; sampler_create_info.minFilter = vk::Filter::eLinear; sampler_create_info.mipmapMode = vk::SamplerMipmapMode::eLinear; sampler_create_info.addressModeU = vk::SamplerAddressMode::eRepeat; sampler_create_info.addressModeV = vk::SamplerAddressMode::eRepeat; sampler_create_info.addressModeW = vk::SamplerAddressMode::eRepeat; sampler_create_info.mipLodBias = 0.0f; sampler_create_info.compareOp = vk::CompareOp::eNever; sampler_create_info.minLod = 0.0f; // Max level-of-detail should match mip level count sampler_create_info.maxLod = static_cast<float>(mipmaps.size()); // Only enable anisotropic filtering if enabled on the device // Note that for simplicity, we will always be using max. available anisotropy level for the current device // This may have an impact on performance, esp. on lower-specced devices // In a real-world scenario the level of anisotropy should be a user setting or e.g. lowered for mobile devices by default sampler_create_info.maxAnisotropy = get_device().get_gpu().get_features().samplerAnisotropy ? (get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy) : 1.0f; sampler_create_info.anisotropyEnable = get_device().get_gpu().get_features().samplerAnisotropy; sampler_create_info.borderColor = vk::BorderColor::eFloatOpaqueWhite; texture.sampler = get_device().get_handle().createSampler(sampler_create_info); return texture; } HPPTexture HPPApiVulkanSample::load_texture_array(const std::string &file) { HPPTexture texture{}; texture.image = vkb::scene_graph::components::HPPImage::load(file, file); texture.image->create_vk_image(get_device(), vk::ImageViewType::e2DArray); const auto &queue = get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics, 0); vk::CommandBuffer command_buffer = get_device().create_command_buffer(vk::CommandBufferLevel::ePrimary, true); vkb::core::HPPBuffer stage_buffer{get_device(), texture.image->get_data().size(), vk::BufferUsageFlagBits::eTransferSrc, VMA_MEMORY_USAGE_CPU_ONLY}; stage_buffer.update(texture.image->get_data()); // Setup buffer copy regions for each mip level std::vector<vk::BufferImageCopy> buffer_copy_regions; auto & mipmaps = texture.image->get_mipmaps(); const auto &layers = texture.image->get_layers(); auto &offsets = texture.image->get_offsets(); for (uint32_t layer = 0; layer < layers; layer++) { for (size_t i = 0; i < mipmaps.size(); i++) { vk::BufferImageCopy buffer_copy_region; buffer_copy_region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; buffer_copy_region.imageSubresource.mipLevel = vkb::to_u32(i); buffer_copy_region.imageSubresource.baseArrayLayer = layer; buffer_copy_region.imageSubresource.layerCount = 1; buffer_copy_region.imageExtent.width = texture.image->get_extent().width >> i; buffer_copy_region.imageExtent.height = texture.image->get_extent().height >> i; buffer_copy_region.imageExtent.depth = 1; buffer_copy_region.bufferOffset = offsets[layer][i]; buffer_copy_regions.push_back(buffer_copy_region); } } vk::ImageSubresourceRange subresource_range(vk::ImageAspectFlagBits::eColor, 0, vkb::to_u32(mipmaps.size()), 0, layers); // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy vkb::common::set_image_layout( command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, subresource_range); // Copy mip levels from staging buffer command_buffer.copyBufferToImage( stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, buffer_copy_regions); // Change texture image layout to shader read after all mip levels have been copied vkb::common::set_image_layout(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); // Create a defaultsampler vk::SamplerCreateInfo sampler_create_info; sampler_create_info.magFilter = vk::Filter::eLinear; sampler_create_info.minFilter = vk::Filter::eLinear; sampler_create_info.mipmapMode = vk::SamplerMipmapMode::eLinear; sampler_create_info.addressModeU = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.addressModeV = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.addressModeW = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.mipLodBias = 0.0f; sampler_create_info.compareOp = vk::CompareOp::eNever; sampler_create_info.minLod = 0.0f; // Max level-of-detail should match mip level count sampler_create_info.maxLod = static_cast<float>(mipmaps.size()); // Only enable anisotropic filtering if enabled on the devicec sampler_create_info.maxAnisotropy = get_device().get_gpu().get_features().samplerAnisotropy ? get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy : 1.0f; sampler_create_info.anisotropyEnable = get_device().get_gpu().get_features().samplerAnisotropy; sampler_create_info.borderColor = vk::BorderColor::eFloatOpaqueWhite; texture.sampler = get_device().get_handle().createSampler(sampler_create_info); return texture; } HPPTexture HPPApiVulkanSample::load_texture_cubemap(const std::string &file) { HPPTexture texture{}; texture.image = vkb::scene_graph::components::HPPImage::load(file, file); texture.image->create_vk_image(get_device(), vk::ImageViewType::eCube, vk::ImageCreateFlagBits::eCubeCompatible); const auto &queue = get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics, 0); vk::CommandBuffer command_buffer = get_device().create_command_buffer(vk::CommandBufferLevel::ePrimary, true); vkb::core::HPPBuffer stage_buffer{get_device(), texture.image->get_data().size(), vk::BufferUsageFlagBits::eTransferSrc, VMA_MEMORY_USAGE_CPU_ONLY}; stage_buffer.update(texture.image->get_data()); // Setup buffer copy regions for each mip level std::vector<vk::BufferImageCopy> buffer_copy_regions; auto & mipmaps = texture.image->get_mipmaps(); const auto &layers = texture.image->get_layers(); auto &offsets = texture.image->get_offsets(); for (uint32_t layer = 0; layer < layers; layer++) { for (size_t i = 0; i < mipmaps.size(); i++) { vk::BufferImageCopy buffer_copy_region; buffer_copy_region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; buffer_copy_region.imageSubresource.mipLevel = vkb::to_u32(i); buffer_copy_region.imageSubresource.baseArrayLayer = layer; buffer_copy_region.imageSubresource.layerCount = 1; buffer_copy_region.imageExtent.width = texture.image->get_extent().width >> i; buffer_copy_region.imageExtent.height = texture.image->get_extent().height >> i; buffer_copy_region.imageExtent.depth = 1; buffer_copy_region.bufferOffset = offsets[layer][i]; buffer_copy_regions.push_back(buffer_copy_region); } } vk::ImageSubresourceRange subresource_range(vk::ImageAspectFlagBits::eColor, 0, vkb::to_u32(mipmaps.size()), 0, layers); // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy vkb::common::set_image_layout( command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, subresource_range); // Copy mip levels from staging buffer command_buffer.copyBufferToImage( stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, buffer_copy_regions); // Change texture image layout to shader read after all mip levels have been copied vkb::common::set_image_layout(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); // Create a defaultsampler vk::SamplerCreateInfo sampler_create_info; sampler_create_info.magFilter = vk::Filter::eLinear; sampler_create_info.minFilter = vk::Filter::eLinear; sampler_create_info.mipmapMode = vk::SamplerMipmapMode::eLinear; sampler_create_info.addressModeU = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.addressModeV = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.addressModeW = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.mipLodBias = 0.0f; sampler_create_info.compareOp = vk::CompareOp::eNever; sampler_create_info.minLod = 0.0f; // Max level-of-detail should match mip level count sampler_create_info.maxLod = static_cast<float>(mipmaps.size()); // Only enable anisotropic filtering if enabled on the devicec sampler_create_info.maxAnisotropy = get_device().get_gpu().get_features().samplerAnisotropy ? get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy : 1.0f; sampler_create_info.anisotropyEnable = get_device().get_gpu().get_features().samplerAnisotropy; sampler_create_info.borderColor = vk::BorderColor::eFloatOpaqueWhite; texture.sampler = get_device().get_handle().createSampler(sampler_create_info); return texture; } std::unique_ptr<vkb::scene_graph::components::HPPSubMesh> HPPApiVulkanSample::load_model(const std::string &file, uint32_t index) { vkb::HPPGLTFLoader loader{get_device()}; std::unique_ptr<vkb::scene_graph::components::HPPSubMesh> model = loader.read_model_from_file(file, index); if (!model) { LOGE("Cannot load model from file: {}", file.c_str()); throw std::runtime_error("Cannot load model from: " + file); } return model; } void HPPApiVulkanSample::draw_model(std::unique_ptr<vkb::scene_graph::components::HPPSubMesh> &model, vk::CommandBuffer command_buffer) { vk::DeviceSize offset = 0; const auto &vertex_buffer = model->get_vertex_buffer("vertex_buffer"); auto & index_buffer = model->get_index_buffer(); command_buffer.bindVertexBuffers(0, vertex_buffer.get_handle(), offset); command_buffer.bindIndexBuffer(index_buffer.get_handle(), 0, model->get_index_type()); command_buffer.drawIndexed(model->vertex_indices, 1, 0, 0, 0); } void HPPApiVulkanSample::with_command_buffer(const std::function<void(vk::CommandBuffer command_buffer)> &f, vk::Semaphore signalSemaphore) { vk::CommandBuffer command_buffer = get_device().create_command_buffer(vk::CommandBufferLevel::ePrimary, true); f(command_buffer); get_device().flush_command_buffer(command_buffer, queue, true, signalSemaphore); }
38.063792
164
0.734167
jwinarske
d9457793291e785a08605435946b202f9931092b
3,219
hh
C++
silo/masstree/hashcode.hh
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
579
2019-02-24T20:58:06.000Z
2022-03-31T08:56:48.000Z
silo/masstree/hashcode.hh
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
64
2019-02-25T02:48:31.000Z
2022-03-30T03:38:40.000Z
silo/masstree/hashcode.hh
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
86
2019-02-28T01:40:50.000Z
2022-02-23T08:02:26.000Z
/* Masstree * Eddie Kohler, Yandong Mao, Robert Morris * Copyright (c) 2012-2013 President and Fellows of Harvard College * Copyright (c) 2012-2013 Massachusetts Institute of Technology * * 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, subject to the conditions * listed in the Masstree LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Masstree LICENSE file; the license in that file * is legally binding. */ #ifndef CLICK_HASHCODE_HH #define CLICK_HASHCODE_HH #include <stddef.h> #include <inttypes.h> #if HAVE_STD_HASH #include <functional> #endif // Notes about the hashcode template: On GCC 4.3.0, "template <>" is required // on the specializations or they aren't used. Just plain overloaded // functions aren't used. The specializations must be e.g. "const char &", // not "char", or GCC complains about a specialization not matching the // general template. The main template takes a const reference for two // reasons. First, providing both "hashcode_t hashcode(T)" and "hashcode_t // hashcode(const T&)" leads to ambiguity errors. Second, providing only // "hashcode_t hashcode(T)" is slower by looks like 8% when T is a String, // because of copy constructors; for types with more expensive non-default // copy constructors this would probably be worse. typedef size_t hashcode_t; ///< Typical type for a hashcode() value. template <typename T> inline hashcode_t hashcode(T const &x) { return x.hashcode(); } template <> inline hashcode_t hashcode(char const &x) { return x; } template <> inline hashcode_t hashcode(signed char const &x) { return x; } template <> inline hashcode_t hashcode(unsigned char const &x) { return x; } template <> inline hashcode_t hashcode(short const &x) { return x; } template <> inline hashcode_t hashcode(unsigned short const &x) { return x; } template <> inline hashcode_t hashcode(int const &x) { return x; } template <> inline hashcode_t hashcode(unsigned const &x) { return x; } template <> inline hashcode_t hashcode(long const &x) { return x; } template <> inline hashcode_t hashcode(unsigned long const &x) { return x; } template <> inline hashcode_t hashcode(long long const &x) { return (x >> 32) ^ x; } template <> inline hashcode_t hashcode(unsigned long long const &x) { return (x >> 32) ^ x; } #if HAVE_INT64_TYPES && !HAVE_INT64_IS_LONG && !HAVE_INT64_IS_LONG_LONG template <> inline hashcode_t hashcode(int64_t const &x) { return (x >> 32) ^ x; } template <> inline hashcode_t hashcode(uint64_t const &x) { return (x >> 32) ^ x; } #endif template <typename T> inline hashcode_t hashcode(T * const &x) { return reinterpret_cast<uintptr_t>(x) >> 3; } template <typename T> inline typename T::key_const_reference hashkey(const T &x) { return x.hashkey(); } #endif
26.825
77
0.726313
anshsarkar
d947e3baf055e1e080d2544c76a3526f6d37bcff
5,232
cpp
C++
service/resource-container/android/resource-container/src/main/jni/JniRcsResourceAttributes.cpp
jongsunglee/test_iotivity
809ccf01cc31e663e177e0292e17099dc06502bd
[ "Apache-2.0" ]
301
2015-01-20T16:11:32.000Z
2021-11-25T04:29:36.000Z
service/resource-container/android/resource-container/src/main/jni/JniRcsResourceAttributes.cpp
jongsunglee/test_iotivity
809ccf01cc31e663e177e0292e17099dc06502bd
[ "Apache-2.0" ]
21
2019-10-02T08:31:36.000Z
2021-12-09T21:46:49.000Z
service/resource-container/android/resource-container/src/main/jni/JniRcsResourceAttributes.cpp
jongsunglee/test_iotivity
809ccf01cc31e663e177e0292e17099dc06502bd
[ "Apache-2.0" ]
233
2015-01-26T03:41:59.000Z
2022-03-18T23:54:04.000Z
/****************************************************************** * * Copyright 2015 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ #include "JniRcsResourceAttributes.h" #include "JNIEnvWrapper.h" #include "JavaClasses.h" #include "JavaLocalRef.h" #include "JniRcsValue.h" #include "Log.h" #include "Verify.h" using namespace OIC::Service; #define LOG_TAG "JNI-RCSResourceAttributes" namespace { jclass g_cls_RCSResourceAttributes; jmethodID g_ctor_RCSResourceAttributes; jfieldID g_field_mCache; } void initRCSResourceAttributes(JNIEnvWrapper* env) { g_cls_RCSResourceAttributes = env->FindClassAsGlobalRef(CLS_NAME_RESOURCEATTRIBUTES); g_ctor_RCSResourceAttributes = env->GetConstructorID(g_cls_RCSResourceAttributes, "()V"); g_field_mCache = env->GetFieldID(g_cls_RCSResourceAttributes, "mCache", AS_SIG(CLS_NAME_MAP)); } void clearRCSResourceAttributes(JNIEnvWrapper* env) { env->DeleteGlobalRef(g_cls_RCSResourceAttributes); } jobject newAttributesObject(JNIEnv* env, const RCSResourceAttributes& attrs) { jobject obj = env->NewObject(g_cls_RCSResourceAttributes, g_ctor_RCSResourceAttributes); VERIFY_NO_EXC_RET_DEF(env); jobject mapObj = env->GetObjectField(obj, g_field_mCache); //EXPECT(mapObj, "Map is null."); for (const auto& p : attrs) { JavaLocalObject keyObj{ env, newStringObject(env, p.key()) }; //VERIFY_NO_EXC(env); JavaLocalObject valueObj{ env, newRCSValueObject(env, p.value()) }; //VERIFY_NO_EXC(env); invoke_Map_put(env, mapObj, keyObj, valueObj); //VERIFY_NO_EXC(env); } // setSafeNativeHandle< RCSResourceAttributes >(env, obj, attrs); return obj; } jobject newAttributesObject(JNIEnvWrapper* env, const RCSResourceAttributes& attrs) { jobject obj = env->NewObject(g_cls_RCSResourceAttributes, g_ctor_RCSResourceAttributes); jobject mapObj = env->GetObjectField(obj, g_field_mCache); //EXPECT(mapObj, "Map is null."); for (const auto& p : attrs) { JavaLocalObject keyObj{ env, newStringObject(env, p.key()) }; //VERIFY_NO_EXC(env); JavaLocalObject valueObj{ env, newRCSValueObject(env, p.value()) }; //VERIFY_NO_EXC(env); invoke_Map_put(env, mapObj, keyObj, valueObj); //VERIFY_NO_EXC(env); } // setSafeNativeHandle< RCSResourceAttributes >(env, obj, attrs); return obj; } RCSResourceAttributes toNativeAttributes(JNIEnv* env, jobject attrsObj) { EXPECT_RET(attrsObj, "attrsObj is null!", { }); JNIEnvWrapper envWrapper{ env }; try { return toNativeAttributes(&envWrapper, attrsObj); } catch (const JavaException&) { return {}; } } RCSResourceAttributes toNativeAttributes(JNIEnvWrapper* env, jobject attrsObj) { EXPECT_RET(attrsObj, "attrsObj is null!", { }); RCSResourceAttributes attrs; /*if (hasNativeHandle(env, attrsObj)) { attrs = getNativeHandleAs< RCSResourceAttributes >(env, attrsObj); }*/ LOGD("writeNativeAttributesFromMap"); writeNativeAttributesFromMap(env, JavaLocalObject{ env, env->GetObjectField(attrsObj, g_field_mCache) }, attrs); return attrs; } void writeNativeAttributesFromMap(JNIEnv* env, jobject mapObj, RCSResourceAttributes& targetAttrs) { JNIEnvWrapper envWrapper{ env }; try { return writeNativeAttributesFromMap(&envWrapper, mapObj, targetAttrs); } catch (const JavaException&) { } } void writeNativeAttributesFromMap(JNIEnvWrapper* env, jobject mapObj, RCSResourceAttributes& targetAttrs) { LOGD("in write native attributes from map"); LOGD("invoke map entry set"); JavaLocalObject setObj{ env, invoke_Map_entrySet(env, mapObj) }; LOGD("invoke set iterator"); JavaLocalObject iterObj{ env, invoke_Set_iterator(env, setObj) }; LOGD("invoke has next"); while (invoke_Iterator_hasNext(env, iterObj)) { LOGD("invoke entry obj next"); JavaLocalObject entryObj{ env, invoke_Iterator_next(env, iterObj) }; LOGD("invoke key obj next"); JavaLocalObject keyObj{ env, invoke_MapEntry_getKey(env, entryObj) }; LOGD("invoke value obj next"); JavaLocalObject valueObj{ env, invoke_MapEntry_getValue(env, entryObj) }; LOGD("invoke toStdString"); auto key = toStdString(env, static_cast< jstring >(keyObj.get())); LOGD("invoke toNativeAttrsvalue"); targetAttrs[std::move(key)] = toNativeAttrsValue(env, valueObj); } LOGD("in write native attributes from map finished"); }
29.897143
98
0.687882
jongsunglee