blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
58cdee96c85f35cac02cc2dd5b984ebe067c0fd3
4dc9caed5cb3f4639587d3d596a82cd748254045
/lib/jsrt/jsrtRuntime.cpp
4c6f8d7501d0a7046c1b54cd2558c73d7e0ff751
[ "MIT" ]
permissive
jkrems/ChakraCore
2e68c27a8a278c36bfa144f77dbd79398279c52b
59b31e5821b7b8df3ed1f5021ed971da82cde9e1
refs/heads/master
2021-01-18T04:42:10.298111
2016-01-22T23:45:30
2016-01-22T23:45:30
50,215,307
2
0
null
2016-01-23T00:06:01
2016-01-23T00:06:00
null
UTF-8
C++
false
false
3,753
cpp
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include <JsrtPch.h> #include "JsrtRuntime.h" #include "Base\ThreadContextTLSEntry.h" #include "Base\ThreadBoundThreadContextManager.h" JsrtRuntime::JsrtRuntime(ThreadContext * threadContext, bool useIdle, bool dispatchExceptions) { Assert(threadContext != NULL); this->threadContext = threadContext; this->contextList = NULL; this->collectCallback = NULL; this->beforeCollectCallback = NULL; this->callbackContext = NULL; this->allocationPolicyManager = threadContext->GetAllocationPolicyManager(); this->useIdle = useIdle; this->dispatchExceptions = dispatchExceptions; if (useIdle) { this->threadService.Initialize(threadContext); } threadContext->SetJSRTRuntime(this); #ifdef ENABLE_DEBUG_CONFIG_OPTIONS serializeByteCodeForLibrary = false; #endif } JsrtRuntime::~JsrtRuntime() { HeapDelete(allocationPolicyManager); } // This is called at process detach. // threadcontext created from runtime should not be destroyed in ThreadBoundThreadContext // we should clean them up at process detach only as runtime can be used in other threads // even after the current physical thread was destroyed. // This is called after ThreadBoundThreadContext are cleaned up, so the remaining items // in the globalthreadContext linklist should be for jsrt only. void JsrtRuntime::Uninitialize() { ThreadContext* currentThreadContext = ThreadContext::GetThreadContextList(); ThreadContext* tmpThreadContext; while (currentThreadContext) { Assert(!currentThreadContext->IsScriptActive()); JsrtRuntime* currentRuntime = static_cast<JsrtRuntime*>(currentThreadContext->GetJSRTRuntime()); tmpThreadContext = currentThreadContext; currentThreadContext = currentThreadContext->Next(); currentRuntime->CloseContexts(); RentalThreadContextManager::DestroyThreadContext(tmpThreadContext); HeapDelete(currentRuntime); } } void JsrtRuntime::CloseContexts() { while (this->contextList != NULL) { this->contextList->Dispose(false); // This will remove it from the list } } void JsrtRuntime::SetBeforeCollectCallback(JsBeforeCollectCallback beforeCollectCallback, void * callbackContext) { if (beforeCollectCallback != NULL) { if (this->collectCallback == NULL) { this->collectCallback = this->threadContext->AddRecyclerCollectCallBack(RecyclerCollectCallbackStatic, this); } this->beforeCollectCallback = beforeCollectCallback; this->callbackContext = callbackContext; } else { if (this->collectCallback != NULL) { this->threadContext->RemoveRecyclerCollectCallBack(this->collectCallback); this->collectCallback = NULL; } this->beforeCollectCallback = NULL; this->callbackContext = NULL; } } void JsrtRuntime::RecyclerCollectCallbackStatic(void * context, RecyclerCollectCallBackFlags flags) { if (flags & Collect_Begin) { JsrtRuntime * _this = reinterpret_cast<JsrtRuntime *>(context); try { _this->beforeCollectCallback(_this->callbackContext); } catch (...) { AssertMsg(false, "Unexpected non-engine exception."); } } } unsigned int JsrtRuntime::Idle() { return this->threadService.Idle(); }
[ "chakrabot@users.noreply.github.com" ]
chakrabot@users.noreply.github.com
4db9c70c61db7971c9070cabc53957b38d661d83
4c83c841c32f0f3db42ee6edb9d622a60ef4982d
/CODEFORECES/Educational Codeforces Round 82 (Rated for Div. 2) /A.cpp
007419a77c6bf58f5e396aab4c03ba28b4267af8
[]
no_license
marco-park/problemSolving
544762cd64cc730fdc1607114d2b40d56e22da8d
b68966b00227a7a8177b46b2898418d468964e6f
refs/heads/master
2023-09-04T11:11:42.963727
2021-09-22T14:08:35
2021-09-22T14:08:35
231,756,065
0
0
null
null
null
null
UTF-8
C++
false
false
695
cpp
#include <iostream> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; while(n--){ int ret = 0; string s; cin >> s; bool flag = false; int first=-1,last=-1; for(int i=0;s[i];i++){ if(s[i]=='1'){ first = i; break; } } if(first==-1){ cout << 0 << '\n'; continue; } for(int i=0;s[i];i++){ if(s[i]=='1')last = i; } for(int i=first+1;i<last;i++){ if(s[i]=='0')ret++; } cout << ret << '\n'; } }
[ "sungbinpark@bagseongbin-ui-MacBookPro.local" ]
sungbinpark@bagseongbin-ui-MacBookPro.local
ea4810bfe623fcf38cb20225163266e27341cf25
bc1d68d7a7c837b8a99e516050364a7254030727
/src/ZOJ/ZOJ3359 Penalties Kick.cpp
340c597dac915040f00d996d016edb8caa89265e
[]
no_license
kester-lin/acm_backup
1e86b0b4699f8fa50a526ce091f242ee75282f59
a4850379c6c67a42da6b5aea499306e67edfc9fd
refs/heads/master
2021-05-28T20:01:31.044690
2013-05-16T03:27:21
2013-05-16T03:27:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,952
cpp
// ZOJ3359 Penalties Kick.cpp : Defines the entry point for the console application. // // #include "stdafx.h" #include <fstream> #include <stdio.h> #include <iostream> #include <string.h> #include <string> #include <vector> #include <stack> #include <queue> #include <deque> #include <map> #include <math.h> #include <algorithm> #include <numeric> #include <functional> #include <memory.h> using namespace std; int main(void) { // ifstream cin("data.txt"); int ncases; int casenum; char str1[4],str2[4],str3[4]; cin>>ncases; int kick[3][22]; for(casenum=1;casenum<=ncases;++casenum) { for(int i=0;i<22;++i) { scanf("%s %s %s",&str1,&str2,&str3); if (str1[0]=='y') { kick[0][i]=1; } else { kick[0][i]=0; } if (str2[0]=='y') { kick[1][i]=1; } else { kick[1][i]=0; } if (str3[0]=='y') { kick[2][i]=1; } else { kick[2][i]=0; } } int away(0),home(0),count(0); int flag(1); printf("Match %d:\n",casenum); for(int i=0;i<3 && flag;++i) { for(int j=0;j<11;++j) { ++count; home += kick[i][j]; if(count<6 && home-away>5-count+1) { printf("Winner: home\nScore: %d:%d\n",home,away); flag=0; break; } if(count<6 && away-home>5-count) { printf("Winner: away\nScore: %d:%d\n",home,away); flag=0; break; } away += kick[i][j+11]; if(count<6 && home-away>5-count) { printf("Winner: home\nScore: %d:%d\n",home,away); flag=0; break; } if(count<6 && away-home>5-count) { printf("Winner: away\nScore: %d:%d\n",home,away); flag=0; break; } if (count>5 && home>away) { printf("Winner: home\nScore: %d:%d\n",home,away); flag=0; break; } else if(count>5 && away>home) { printf("Winner: away\nScore: %d:%d\n",home,away); flag=0; break; } } } } return 0; }
[ "neosfung@gmail.com" ]
neosfung@gmail.com
4591199bf730a592d1a198c301f4ae151c9d1a7a
8bbeb7b5721a9dbf40caa47a96e6961ceabb0128
/cpp/40.Combination Sum II(组合总和 II).cpp
9a6e2a7978bbecde17012f916cb1588b963804f5
[ "MIT" ]
permissive
lishulongVI/leetcode
bb5b75642f69dfaec0c2ee3e06369c715125b1ba
6731e128be0fd3c0bdfe885c1a409ac54b929597
refs/heads/master
2020-03-23T22:17:40.335970
2018-07-23T14:46:06
2018-07-23T14:46:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,921
cpp
/* <p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sums to <code>target</code>.</p> <p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p> <p><strong>Note:</strong></p> <ul> <li>All numbers (including <code>target</code>) will be positive integers.</li> <li>The solution set must not contain duplicate combinations.</li> </ul> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> candidates =&nbsp;<code>[10,1,2,7,6,1,5]</code>, target =&nbsp;<code>8</code>, <strong>A solution set is:</strong> [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> candidates =&nbsp;[2,5,2,1,2], target =&nbsp;5, <strong>A solution set is:</strong> [ &nbsp; [1,2,2], &nbsp; [5] ] </pre> <p>给定一个数组&nbsp;<code>candidates</code>&nbsp;和一个目标数&nbsp;<code>target</code>&nbsp;,找出&nbsp;<code>candidates</code>&nbsp;中所有可以使数字和为&nbsp;<code>target</code>&nbsp;的组合。</p> <p><code>candidates</code>&nbsp;中的每个数字在每个组合中只能使用一次。</p> <p><strong>说明:</strong></p> <ul> <li>所有数字(包括目标数)都是正整数。</li> <li>解集不能包含重复的组合。&nbsp;</li> </ul> <p><strong>示例&nbsp;1:</strong></p> <pre><strong>输入:</strong> candidates =&nbsp;<code>[10,1,2,7,6,1,5]</code>, target =&nbsp;<code>8</code>, <strong>所求解集为:</strong> [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] </pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入:</strong> candidates =&nbsp;[2,5,2,1,2], target =&nbsp;5, <strong>所求解集为:</strong> [ &nbsp; [1,2,2], &nbsp; [5] ]</pre> <p>给定一个数组&nbsp;<code>candidates</code>&nbsp;和一个目标数&nbsp;<code>target</code>&nbsp;,找出&nbsp;<code>candidates</code>&nbsp;中所有可以使数字和为&nbsp;<code>target</code>&nbsp;的组合。</p> <p><code>candidates</code>&nbsp;中的每个数字在每个组合中只能使用一次。</p> <p><strong>说明:</strong></p> <ul> <li>所有数字(包括目标数)都是正整数。</li> <li>解集不能包含重复的组合。&nbsp;</li> </ul> <p><strong>示例&nbsp;1:</strong></p> <pre><strong>输入:</strong> candidates =&nbsp;<code>[10,1,2,7,6,1,5]</code>, target =&nbsp;<code>8</code>, <strong>所求解集为:</strong> [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] </pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入:</strong> candidates =&nbsp;[2,5,2,1,2], target =&nbsp;5, <strong>所求解集为:</strong> [ &nbsp; [1,2,2], &nbsp; [5] ]</pre> */ class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { } };
[ "lishulong@wecash.net" ]
lishulong@wecash.net
91d09979d57b684671cd59d331137dc2a5028cc6
af96101dcbe0618a30616027580bca5a556369e5
/include/AnnErrorCode.hpp
32404211686997505c097e9789a8bc23433ab4b2
[ "MIT" ]
permissive
zerubeus/Annwvyn
a9c7cd27c34b2fd89621511c0912a9bdcc779758
e5485e817ae45d611bd46e9410c160d1e109050d
refs/heads/master
2020-12-30T19:11:11.009976
2016-01-22T00:57:00
2016-01-22T00:57:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,384
hpp
/** * \file AnnErrorCode.hpp * \brief Define a serise of hex code as constant keywords to define error codes. * \author A. Brainville (Ybalrid) */ #ifndef ANN_ERROR_CODE #define ANN_ERROR_CODE #define ANN_ERR_CRITIC 0xDEAD60D // Dead God /* Indicate that the execution environement of the engine hasn't been about to be initialized - Check log file */ #define ANN_ERR_MEMORY 0xFAA760D // Fa_t God /* Indicate that a memory error has been caused inside the engine - Check if you haven't done something stupid pointers - Please don't try to delete anything created by the engine, it's not you're problem - Check log file for more information */ #define ANN_ERR_RENDER 0x5ADE60D // Sa_d God /* Indicate an irecuperable error with the renderer. Either during initialization or during rendering - Check OVR runtime version - Check hardware (HMD plugged, Graphics card compatible) - Check other software (Graphics drivers) - Check log file for more information */ #define ANN_ERR_INFILE 0x12F1D31 // Infi-del /* Indicate that the engine is unable to understand an Annwvyn file you tried to load - Check file path in your code - Check file path referenced in the file - Check syntax of the file - Check log file at the moment of crash for more information */ #define ANN_ERR_UNKOWN 0x200760D // No_t God /* See log. Something gone wrong and don't have a specific error code. */ #endif
[ "ybalrid@cecmu.org" ]
ybalrid@cecmu.org
3d434a406ad97c8aa6bf08b405417239564ddcef
8c8ea056e5c38abe04c70c1a89fcd610613777de
/module02/ex01/Fixed.class.hpp
189214b42b403244fe548af5aabed5819e228d19
[]
no_license
1337hunter/cpp_modules
96992f7a000323ffee98fa7ee95bd5ce0686c381
b8cce9989c3092d878654799b390c0ab23d44e6e
refs/heads/master
2023-03-22T09:26:28.061684
2021-03-12T07:11:21
2021-03-12T07:11:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,393
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Fixed.class.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gbright <gbright@student.21-school.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/13 09:23:01 by gbright #+# #+# */ /* Updated: 2020/09/14 12:44:21 by gbright ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FIXED_CLASS_HPP # define FIXED_CLASS_HPP #include <iostream> class Fixed { int value; static const int pos = 8; public: Fixed(void); ~Fixed(void); Fixed(Fixed const &what); Fixed(const int n); Fixed(const float n); float toFloat(void) const; int toInt(void) const; void operator=(const Fixed &what); int getRawBits(void) const; void setRawBits(int const raw); }; std::ostream &operator<<(std::ostream &os, const Fixed &what); #endif
[ "ant.sergy@gmail.com" ]
ant.sergy@gmail.com
c579a1d27b315496f028f79d1f8555c3818da229
c91629e7617b264bfdf3a21294b03c13ae6b34ba
/inside_New1.5/inside_New1.5.ino
3635c64910cd53de0e6105f6ded62a759b380f3b
[]
no_license
mmywong/ezLCD_RoomStatusManager
1ec8ebe9f69782dcbceb70748c2e7376ff34b029
57b6b0d0597650288862093aa5711222a9b303ed
refs/heads/master
2021-01-01T19:15:27.838332
2015-07-20T19:57:26
2015-07-20T19:57:26
38,768,445
0
0
null
null
null
null
UTF-8
C++
false
false
6,846
ino
#include <SPI.h> #include <Ethernet.h> #include <EthernetUdp.h> #include <ezLCDLib.h> #include <string.h> ezLCD3 lcd; // Each Inside LCD needs a unique mac and ip // have 2 sets of mac and ip below to test 2 LCDs // upload sketch with 1 or the other for each LCD /* byte mac[] = { 0xAA, 0xAA, 0xAA, 0xBB, 0xBB, 0xCC }; byte ip[] = { 172, 21, 42, 58 }; char *ipaddress = "172.21.42.58"; byte localPort = 99; char room[10] = "4012"; */ byte mac[] = { 0xAA, 0xAA, 0xAA, 0xBB, 0xBB, 0xCB }; // unique mac address byte ip[] = { 172, 21, 42, 57 }; // unique ip address char *ipaddress = "172.21.42.57"; // ip address in string form. might be used to pass into Qt byte localPort = 99; // hardcoded localPort char room[10] = "4011"; // room number. might be used to pass into Qt char roombuf[10]; // buffer to hold the room number EthernetUDP Udp; static char buffer[UDP_TX_PACKET_MAX_SIZE]; // states enum States{Initial, HomeScreen, Select, DND, HK} state; int stateIDLE = 10; int stateDND = 30; int stateHK = 40; //Changing states based on reading from QT int st = 0; int r = 0; // r is read value from Qt for any state changes void Tick_State(){ switch(state){ case Initial: //the first state. set to choice. Choice(); state = Select; break; case Select: // while choice, check inputs, switch input to home, DND, or HK. become state. if((lcd.currentWidget==3) && (lcd.currentInfo==PRESSED) || r == stateDND) { //widget 3 put over do not disturb is a touchzone. DoNotDisturb(); //being pressed take you to the do not disturb screen state = DND; //state changed to DND } else if((lcd.currentWidget==4) && (lcd.currentInfo==PRESSED) || r == stateHK) { // widget 4 put over house keeping is a touchzone HouseKeeping(); // being pressed takes you to the house keeping screen state = HK; // state changed to HK } break; case DND: // same as homescreen. if((lcd.currentWidget==1) && (lcd.currentInfo==PRESSED) || r == stateIDLE) { // widget 1 is on DND and HK screen Choice(); // being pressed takes you to the Choice screen state = Select; // state changed to Select } else if(r == stateHK) { HouseKeeping(); // being pressed takes you to the house keeping screen state = HK; } break; case HK: // same as homescreen if((lcd.currentWidget==1) && (lcd.currentInfo==PRESSED) || r == stateIDLE) { // widget 1 is on DND and HK screen Choice(); // being pressed takes you to the Choice screen state = Select; // state changed to Select } else if(r == stateDND) { DoNotDisturb(); //being pressed take you to the do not disturb screen state = DND; } break; default: // default state state = Initial; break; } switch(state) { case Select: //Choice(); st = stateIDLE; break; case DND: //DoNotDisturb(); st = stateDND; break; case HK: //HouseKeeping(); st = stateHK; break; default: break; } } void setup() { lcd.begin( EZM_BAUD_RATE ); Ethernet.begin(mac,ip); Udp.begin(localPort); strcpy(roombuf, room); state = Initial; // first state becomes choice(); } void loop() { lcd.wstack(0); Tick_State(); // state machine activation writeStatus(st); } // send status update from LCD to Qt void writeStatus(int x){ int packetSize = Udp.parsePacket(); if(packetSize) { static char buffer[UDP_TX_PACKET_MAX_SIZE]; // clear buffer for(int i = 0; i < UDP_TX_PACKET_MAX_SIZE; ++i) { buffer[i] = 0; } Udp.read(buffer,UDP_TX_PACKET_MAX_SIZE); // read new data from Qt and store into buffer r = atoi(buffer); // if read data from Qt is dummy data 100 and is not the curren status on LCD, new state is read data from Qt if(r != 100 && r != x) { x = r; } itoa(x, buffer, 10); strcat(buffer, roombuf); strcat(buffer, ipaddress); Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write(buffer); Udp.endPacket(); /* Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write(buffer); Udp.endPacket(); strcpy(buffer, room); Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write(buffer); Udp.endPacket(); strcpy(buffer, ipaddress); Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write(buffer); Udp.endPacket(); */ } } void Choice() //choice function. multiple end points using touchzones. { lcd.cls(BLACK); lcd.light(0); //light off. pring image. light on. lcd.picture("Metro0.bmp"); lcd.light(100); lcd.font("Serif24"); // create font, color, position, angle. print out House Keeping lcd.color(WHITE); lcd.xy(165,155); lcd.fontO(1); lcd.print("House"); lcd.color(WHITE); lcd.xy(185,155); lcd.fontO(1); lcd.print("Keeping"); lcd.color(WHITE); // create color, position, angle. print out Do Not Disturb lcd.xy(110,155); lcd.fontO(1); lcd.print("Do Not"); lcd.color(WHITE); lcd.xy(130,155); lcd.fontO(1); lcd.print("Disturb"); lcd.font("0"); lcd.fontO(1); lcd.color(WHITE); lcd.xy(235,155); lcd.println("Touch To"); lcd.xy(250,200); lcd.println("Change Room Status"); lcd.touchZone(3,110,35,50,170,1); // touchzone 3 takes you to state DND lcd.touchZone(4,165,35,50,170,1); // touchzone 4 takes you to state HK } void HouseKeeping() //housekeeping. loop to choice on touchznoe. { lcd.light(0); // light off, ptint picture position, light on lcd.picture(100,60,"clean.bmp"); lcd.light(100); lcd.touchZone(1,0,0,320,240,1); //create touchzone for looping to choice } void DoNotDisturb() // do not disturb. loop to choice on touchzone. { lcd.light(0); // light off, ptint picture position, light on lcd.picture(100,60,"dont.bmp"); lcd.light(100); lcd.touchZone(1,0,0,320,240,1); //create touchzone for looping to choice }
[ "dcheung24@yahoo.com" ]
dcheung24@yahoo.com
e4855cbb9264dd4019ad5eb79f16cec71afe08a4
33d9fb53e5e5ec22dd8f7336399a4d60c6987f7b
/zImprovedArmor/ZenGin/Gothic_I_Addon/API/oNews.h
98afb5b7d8ffed36c29b75c29383545b806ee74a
[]
no_license
Gratt-5r2/zImprovedArmor
bae5dde5c0c1ae1b3614141d7592b8a73eee2a41
061915791032acfed45703284d2ccd5d394e4a88
refs/heads/master
2023-04-30T23:20:52.486636
2023-03-12T12:42:08
2023-03-12T12:42:08
332,370,109
1
2
null
2023-04-18T23:44:42
2021-01-24T04:54:39
C++
UTF-8
C++
false
false
4,872
h
// Supported with union (c) 2018-2021 Union team #ifndef __ONEWS_H__VER1__ #define __ONEWS_H__VER1__ namespace Gothic_I_Addon { const int MAX_ENTRY = 20; typedef enum oENewsSpreadType { NEWS_DONT_SPREAD, NEWS_SPREAD_NPC_FRIENDLY_TOWARDS_VICTIM, NEWS_SPREAD_NPC_FRIENDLY_TOWARDS_WITNESS, NEWS_SPREAD_NPC_FRIENDLY_TOWARDS_OFFENDER, NEWS_SPREAD_NPC_SAME_GUILD_VICTIM } oTNewsSpreadType; // sizeof 64h class oCNews { public: int told; // sizeof 04h offset 04h float spread_time; // sizeof 04h offset 08h oTNewsSpreadType spreadType; // sizeof 04h offset 0Ch int news_id; // sizeof 04h offset 10h int gossip; // sizeof 04h offset 14h oCNpc* mNpcWitness; // sizeof 04h offset 18h oCNpc* mNpcOffender; // sizeof 04h offset 1Ch oCNpc* mNpcVictim; // sizeof 04h offset 20h zSTRING witnessName; // sizeof 14h offset 24h zSTRING offenderName; // sizeof 14h offset 38h zSTRING victimName; // sizeof 14h offset 4Ch int guildvictim; // sizeof 04h offset 60h void oCNews_OnInit() zCall( 0x006B8850 ); void oCNews_OnInit( int, int, oCNpc*, oCNpc*, oCNpc*, int ) zCall( 0x006B8A10 ); oCNews() zInit( oCNews_OnInit() ); oCNews( int a0, int a1, oCNpc* a2, oCNpc* a3, oCNpc* a4, int a5 ) zInit( oCNews_OnInit( a0, a1, a2, a3, a4, a5 )); ~oCNews() zCall( 0x006B8C30 ); int GetID() zCall( 0x006B8DE0 ); int IsIdentical( int, oCNpc*, oCNpc* ) zCall( 0x006B8DF0 ); void SetSpreadTime( float ) zCall( 0x006B8E20 ); float GetSpreadTime() zCall( 0x006B8E50 ); void SetGossip( int ) zCall( 0x006B8E60 ); int IsGossip() zCall( 0x006B8E80 ); int IsGuildVictim() zCall( 0x006B8E90 ); void GetNewsData( int&, int&, oCNpc*&, oCNpc*&, oCNpc*& ) zCall( 0x006B8EA0 ); static int GetRemainingNews() zCall( 0x006B8360 ); static void CheckRemainingNews() zCall( 0x006B8370 ); virtual void Archive( zCArchiver& ) zCall( 0x006B8FB0 ); virtual void Unarchive( zCArchiver& ) zCall( 0x006B9260 ); // static properties static int& news_counter; // user API #include "oCNews.inl" }; // sizeof 0Ch class oCNewsMemory { public: zCList<oCNews> iknow; // sizeof 08h offset 04h void oCNewsMemory_OnInit() zCall( 0x006B7560 ); oCNewsMemory() zInit( oCNewsMemory_OnInit() ); ~oCNewsMemory() zCall( 0x006B7580 ); void Insert( oCNews* ) zCall( 0x006B7690 ); void Remove( oCNews* ) zCall( 0x006B7770 ); oCNews* GetNews( int, oCNpc*, oCNpc* ) zCall( 0x006B77F0 ); void CheckSpreadNews() zCall( 0x006B7830 ); int SearchNews( int, oCNpc*, oCNpc* ) zCall( 0x006B78C0 ); void ShowDebugInfos() zCall( 0x006B7940 ); oCNews* GetNewsByNumber( int ) zCall( 0x006B7F40 ); void ClearNews() zCall( 0x006B7F70 ); int DeleteNewsByNumber( int ) zCall( 0x006B8070 ); virtual void Archive( zCArchiver& ) zCall( 0x006B8110 ); virtual void Unarchive( zCArchiver& ) zCall( 0x006B8190 ); // user API #include "oCNewsMemory.inl" }; // sizeof 58h class oCNewsManager { public: int called_BAssessAndMem; // sizeof 04h offset 00h int sentry; // sizeof 04h offset 04h int spreadList[MAX_ENTRY]; // sizeof 50h offset 08h void oCNewsManager_OnInit() zCall( 0x006B6BC0 ); oCNewsManager() zInit( oCNewsManager_OnInit() ); ~oCNewsManager() zCall( 0x006B6BE0 ); void CreateNews( int, int, oCNpc*, oCNpc*, oCNpc*, int ) zCall( 0x006B6BF0 ); void SpreadToGuild( int ) zCall( 0x006B6F40 ); int IsInSpreadList( int ) zCall( 0x006B6F60 ); void SpreadNews( oCNews* ) zCall( 0x006B6F90 ); // user API #include "oCNewsManager.inl" }; } // namespace Gothic_I_Addon #endif // __ONEWS_H__VER1__
[ "amax96@yandex.ru" ]
amax96@yandex.ru
603eb5b01d302a8b7a77ed71ff246b89404c730f
128dbe5cb2898497ec87d75ef1bb9cad14abd427
/test/doctest-rapidcheck.hpp
a2b9d9c4e53bd68b87b8853ada3cadb96ae5e4a1
[ "MIT" ]
permissive
objectx/cpp-clockwork-base32
569f65c68889e31cf4823dd030d82ca9db56ea8d
441d21ec1ae4beb32372f4bfa9290f006671e76d
refs/heads/master
2022-12-04T23:52:34.370369
2020-08-10T16:45:57
2020-08-10T16:45:57
282,008,617
4
0
null
null
null
null
UTF-8
C++
false
false
1,100
hpp
/// @brief Helper function for using the `rapidcheck` under the `doctest`. #pragma once #include <doctest/doctest.h> #include <rapidcheck.h> #include <utility> namespace rc { template <typename Testable_> void prop (const std::string &description, Testable_ &&testable) { using namespace detail; DOCTEST_SUBCASE(description.c_str()) { const auto result = checkTestable(std::forward<Testable_>(testable)); if (result.template is<SuccessResult> ()) { const auto success = result.template get<SuccessResult> (); if (! success.distribution.empty ()) { std::cout << "- " << description << '\n'; printResultMessage (result, std::cout); std::cout << std::endl; } } else { std::ostringstream ss; printResultMessage (result, ss); DOCTEST_FAIL_CHECK (ss.str() << "\n"); } } } }
[ "objectxtreme@gmail.com" ]
objectxtreme@gmail.com
a73c3d8e564683fb47a857f7d097443396bae4b9
4beae9d121cced388d2295d1cbc436b80b4a25f2
/src/qt/addressbookpage.cpp
fe7659f13c34212cad71dd5bc762a566f81eb551
[ "MIT" ]
permissive
volbil/newmocha
8e5e5e3cbb51d05a330e7ad05d3bed4a3632ded6
809c90fbb6bc72364af2ed0ba6f97abac9d23e22
refs/heads/master
2022-06-11T09:37:03.595755
2020-04-27T02:35:06
2020-04-27T02:35:06
260,594,664
0
0
null
2020-05-02T01:50:46
2020-05-02T01:50:45
null
UTF-8
C++
false
false
11,047
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2019 The Mocha Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/mocha-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "mochagui.h" #include "csvmodelwriter.h" #include "editaddressdialog.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "qrdialog.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(const PlatformStyle *platformStyle, Mode _mode, Tabs _tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(_mode), tab(_tab) { ui->setupUi(this); if (!platformStyle->getImagesOnButtons()) { ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); } else { ui->newAddress->setIcon(QIcon(":/icons/add")); ui->copyAddress->setIcon(QIcon(":/icons/editcopy")); ui->deleteAddress->setIcon(QIcon(":/icons/remove")); ui->exportButton->setIcon(QIcon(":/icons/export")); } ui->showAddressQRCode->setIcon(QIcon()); switch(mode) { case ForSelection: switch(tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch(tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch(tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your Mocha addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your Mocha addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction *copyAddressAction = new QAction(tr("&Copy Address"), this); QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *editAction = new QAction(tr("&Edit"), this); QAction *showAddressQRCodeAction = new QAction(tr("&Show address QR code"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(this); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); contextMenu->addAction(showAddressQRCodeAction); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(showAddressQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showAddressQRCode_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *_model) { this->model = _model; if(!_model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(_model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!model) return; if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::on_showAddressQRCode_clicked() { QList<QModelIndex> entries = GUIUtil::getEntryData(ui->tableView, AddressTableModel::Address); if (entries.empty()) { return; } QString strAddress = entries.at(0).data(Qt::EditRole).toString(); QRDialog* dialog = new QRDialog(this); OptionsModel *model = new OptionsModel(nullptr, false); dialog->setModel(model); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setInfo(tr("QR code"), "mocha:"+strAddress, "", strAddress); dialog->show(); } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); ui->showAddressQRCode->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); ui->showAddressQRCode->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); for (const QModelIndex& index : indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), nullptr); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
[ "whoffman1031@gmail.com" ]
whoffman1031@gmail.com
b5b542ddb006aab5006730f387b512e5117a679c
6fc57553a02b485ad20c6e9a65679cd71fa0a35d
/garnet/bin/system_monitor/harvester/gather_cpu.cc
d9a33e45929e23a58a0e6347f94c9dd361172152
[ "BSD-3-Clause" ]
permissive
OpenTrustGroup/fuchsia
2c782ac264054de1a121005b4417d782591fb4d8
647e593ea661b8bf98dcad2096e20e8950b24a97
refs/heads/master
2023-01-23T08:12:32.214842
2019-08-03T20:27:06
2019-08-03T20:27:06
178,452,475
1
1
BSD-3-Clause
2023-01-05T00:43:10
2019-03-29T17:53:42
C++
UTF-8
C++
false
false
2,720
cc
// Copyright 2019 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 "gather_cpu.h" #include <zircon/status.h> #include "harvester.h" #include "src/lib/fxl/logging.h" namespace harvester { namespace { // Utility function to label and append a cpu sample to the |list|. |cpu| is the // index returned from the kernel. |path| is the kind of sample, e.g. // "interrupt_count". void AddCpuValue(SampleList* list, size_t cpu, const std::string path, dockyard::SampleValue value) { std::ostringstream label; label << "cpu:" << cpu << ":" << path; list->emplace_back(label.str(), value); } } // namespace void GatherCpu::Gather() { // TODO(smbug.com/34): Determine the array size at runtime (32 is arbitrary). zx_info_cpu_stats_t stats[32]; size_t actual, avail; zx_status_t err = zx_object_get_info(RootResource(), ZX_INFO_CPU_STATS, &stats, sizeof(stats), &actual, &avail); if (err != ZX_OK) { FXL_LOG(ERROR) << "ZX_INFO_CPU_STATS returned " << err << "(" << zx_status_get_string(err) << ")"; return; } auto now = std::chrono::high_resolution_clock::now(); auto cpu_time = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count(); SampleList list; for (size_t i = 0; i < actual; ++i) { // Note: stats[i].flags are not currently recorded. // Kernel scheduler counters. AddCpuValue(&list, i, "reschedules", stats[i].reschedules); AddCpuValue(&list, i, "context_switches", stats[i].context_switches); AddCpuValue(&list, i, "meaningful_irq_preempts", stats[i].irq_preempts); AddCpuValue(&list, i, "preempts", stats[i].preempts); AddCpuValue(&list, i, "yields", stats[i].yields); // CPU level interrupts and exceptions. uint64_t busy_time = cpu_time > stats[i].idle_time ? cpu_time - stats[i].idle_time : 0ull; AddCpuValue(&list, i, "busy_time", busy_time); AddCpuValue(&list, i, "idle_time", stats[i].idle_time); AddCpuValue(&list, i, "external_hardware_interrupts", stats[i].ints); AddCpuValue(&list, i, "timer_interrupts", stats[i].timer_ints); AddCpuValue(&list, i, "timer_callbacks", stats[i].timers); AddCpuValue(&list, i, "syscalls", stats[i].syscalls); // Inter-processor interrupts. AddCpuValue(&list, i, "reschedule_ipis", stats[i].reschedule_ipis); AddCpuValue(&list, i, "generic_ipis", stats[i].generic_ipis); } DockyardProxyStatus status = Dockyard().SendSampleList(list); if (status != DockyardProxyStatus::OK) { FXL_LOG(ERROR) << "SendSampleList failed (" << status << ")"; } } } // namespace harvester
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
6d630bb6f2e03b627272c32721bb296a1ba73ec7
b3310d8daefc2bb52c0dc844c7f7399466c60cfc
/cUI_Icon_Speaker.cpp
8e3709fa48e8ee1f51cae18bad42e4d23633ab6e
[]
no_license
LalDi/SmileGate_Project
b89783c296924bedb33a7aa622f023bdbb8f383c
03d6a115f2143d5dd2dec060fea1c901ea694d1b
refs/heads/master
2022-11-24T13:01:15.986313
2020-07-30T14:34:42
2020-07-30T14:34:42
276,552,771
0
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
#include "Framework.h" cUI_Icon_Speaker::cUI_Icon_Speaker(POINT Pos, int tag) :cGameObject(Pos, tag) { m_Sprite = IMAGEMANAGER->AddImage("Option_Icon_Speaker", "./Images/Option/Option_Icon_Speaker.png"); } cUI_Icon_Speaker::~cUI_Icon_Speaker() { } void cUI_Icon_Speaker::Update() { } void cUI_Icon_Speaker::Render() { m_Sprite->CenterRender(m_Pos); }
[ "jungjh0513@naver.com" ]
jungjh0513@naver.com
345e6dd334e0d0c98b53540f454e172f3c358594
91c38d6739ef7eb47455396371cb75f0a668c9ff
/lib/Executors/Evers/Executor/Specializations/ResolveTErrorUndefined.hpp
4251ecf0a8bc19968c28306b8f6d9656714c694e
[ "MIT" ]
permissive
rocky01/promise
8256ab0d2e599f690f31e6b035e1ae67293e60a1
638415a117207a4cae9181e04114e1d7575a9689
refs/heads/master
2020-04-01T09:14:14.878034
2018-10-15T07:31:16
2018-10-15T07:31:16
153,066,476
2
0
null
null
null
null
UTF-8
C++
false
false
1,875
hpp
#ifndef _EVEREXECUTOR_RESOLVETERRORUNDEFINED_HPP_ #define _EVEREXECUTOR_RESOLVETERRORUNDEFINED_HPP_ #include "Executors/Evers/Executor/ResolveTErrorT.hpp" namespace prm { template < typename PerformerT, typename ResolveArgT, bool IsEmplace, typename... PerformerArgsT > class EverExecutor<PerformerT, ResolveArgT, ErrorTypeUndefined, IsEmplace, PerformerArgsT...> : public IExecutor<ResolveArgT>, public IFinisher, public PromiseExecutor<ResolveArgT, ErrorTypeUndefined> { using pe = PromiseExecutor<ResolveArgT, ErrorTypeUndefined>; using PerformerType = PerformerT; // only for enable if public: ENABLE_IF_IS_NOT_EMPLACE(PerformerType, IsEmplace) EverExecutor(PerformerT&& performer) : performer_(std::forward<PerformerT>(performer)) {} ENABLE_IF_IS_EMPLACE(PerformerType, IsEmplace) EverExecutor(PerformerArgsT&&... performerArgs) : performer_(std::forward<PerformerArgsT>(performerArgs)...) {} void execute(ResolveArgT executeArg) override { pe::state_ = State::InProgress; reporter_ = std::make_unique<Reporter<ResolveArgT, ErrorTypeUndefined>>(executeArg); impl(getOperatorTypeCounterpartForEver(&PerformerT::operator())); } void finish() override { pe::state_ = State::Resolved; if (pe::nextPromiseExecutor_) { pe::nextPromiseExecutor_->execute(reporter_->getResolveArg()); } } private: void impl(FinisherReporter) { Finisher finisher(this); performer_(finisher, *reporter_); } void impl(FinisherOnly) { Finisher finisher(this); performer_(finisher); } std::unique_ptr<Reporter<ResolveArgT, ErrorTypeUndefined>> reporter_; PerformerT performer_; }; } // namespace prm #endif // _EVEREXECUTOR_RESOLVETERRORUNDEFINED_HPP_
[ "pawel.mazurek@nokia.com" ]
pawel.mazurek@nokia.com
1c5a69448b59f2bd17db49de4e6b83ce34070fca
9058a5332c0a23b9b0c09c4bd1fd28adeda1f535
/DediwareSourceCode/Dlg_ATmega/stdafx.cpp
9e07dd3c9c7130ea0bf5f3b0281ced9fe1ac1af1
[]
no_license
AllenJunior/Allen
4fe92340cb3bd7b03c2a72492d16821fe994acc7
e21d4e247736c5847b113f9ef103d57930643ee4
refs/heads/My-Design
2020-05-19T19:49:20.275658
2017-02-05T07:12:07
2017-02-05T07:12:07
40,643,800
0
0
null
2017-02-05T07:38:07
2015-08-13T06:59:32
C++
UTF-8
C++
false
false
203
cpp
// stdafx.cpp : source file that includes just the standard includes // Dlg_ATmega.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "allenliu521@gmail.com" ]
allenliu521@gmail.com
1b8bed92855c6ef9ca7cce361a4e48503ac6544e
43b61e6af99f8fde8a6d3a2748ed66ada0f0f3b9
/Sources/OpenGL0/OpenGL0/Model.h
cfedb79caee7356b8b0d9cb046abfd6d986d057f
[]
no_license
biopox/Fowler_Robinson_Tuton_389
b6976d18bb87457d8677a2ab63efceb8fe9a2446
b50c9bffb6adc2afbd4db918d0d1108c1c6cd5c7
refs/heads/master
2021-09-13T22:16:59.859310
2018-05-05T00:49:29
2018-05-05T00:49:29
117,934,588
0
0
null
2018-04-02T11:58:12
2018-01-18T04:58:44
C
UTF-8
C++
false
false
1,491
h
#pragma once #include<Windows.h> #include<stdlib.h> #include<stdio.h> #include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include <iterator> #include <string.h> #include <map> #include <vector> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <gl\GLU.h> #include <gl\GL.h> #include <assimp\Importer.hpp> #include <assimp\scene.h> #include <assimp\postprocess.h> using namespace std; class OBJ { public: vector<float> vertices; vector<float> textures; vector<float> normals; vector<int> faces; // vertices of each face vector<int> facesNormal; // normals of each face vector<int> facesTexture; // texture coordinates of each face bool verticesIncludeW; // If .obj has v x y z [w] bool texturesIncludeW; // If .obj has vt u v [w] int facesSize; // Size of face e.g. triangles are 3 int faceMode; // v: 0 // v, t: 1 // v, t, n: 2 // v, n: 3 string name; // Name of object }; vector<OBJ> loadOBJ(string path, float scale); void printOBJ(vector<OBJ> objects); float *verticesToFloat(OBJ obj); float *getVerticesArray(OBJ obj); int *getFacesArray(OBJ obj); GLint TextureFromFile(const char *path, string directory);
[ "benjamin.fowler@student.nmt.edu" ]
benjamin.fowler@student.nmt.edu
7a1ff6ad21194cc87f5ca4b1815479ced047cd0a
2e0b981eff3c786b642493745e5331ece929e76f
/Precomputed.cpp
08b134f02cb5e8d6ab61b794797db3fc126bd72f
[]
no_license
den385/primes-app
4877cf14811eedf314b76f1e77a27360caafeaa7
eb9bf9388b741e12293b145f19ace97bb120a0a3
refs/heads/master
2021-05-27T16:23:01.904497
2014-10-22T18:38:54
2014-10-22T18:38:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,213
cpp
#include "stdafx.h" #include "Hashtable.h" using namespace std; using namespace stdext; typedef long long int64; typedef unsigned long long uint64; const string path = "precomputed_bin/"; const int NUMBERS_IN_CHUNK = 10 * 1000 * 1000; const int NCHUNKS32 = 20; const int NCHUNKS64 = 5; const int BYTES_IN_NUMBER32 = 4; const int BYTES_IN_NUMBER64 = 8; const int TOTAL_NUMBERS32 = NUMBERS_IN_CHUNK * NCHUNKS32; const int TOTAL_NUMBERS64 = NUMBERS_IN_CHUNK * NCHUNKS64; const unsigned long MIN32 = 0x00000000; const unsigned long MAX32 = 0xFFFFFFFF; const unsigned long long MAX64 = 5336500537; static char * buffer32; static char * buffer64; /* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both * windows and linux. */ int64 GetTimeHns64() { /* Windows */ FILETIME ft; LARGE_INTEGER li; /* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it * to a LARGE_INTEGER structure. */ GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; uint64 ret = li.QuadPart; ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */ return ret; } pair<unsigned long long, unsigned long long> Init( bool silent, Callback ReportProgress ) { if ( sizeof ( unsigned long ) != 4 ) throw( "Bit size of unsigned long unexpected." ); if ( sizeof ( unsigned long long ) != 8 ) throw( "Bit size of unsigned long long unexpected." ); //auto mytime = GetTimeHns64(); buffer32 = new char[ NCHUNKS32 * BYTES_IN_NUMBER32 * NUMBERS_IN_CHUNK ]; buffer64 = new char[ NCHUNKS64 * BYTES_IN_NUMBER64 * NUMBERS_IN_CHUNK ]; // process 32bit chunks of primes for ( int n=1; n <= NCHUNKS32; ++n ) { ifstream* file = new ifstream( path + "precomputed" + to_string( (long long)n ), ios::in | ios::binary ); if ( !file->is_open() ) throw runtime_error("couldn't open"); int shift32 = (n-1) * BYTES_IN_NUMBER32 * NUMBERS_IN_CHUNK; file->read( buffer32 + shift32, BYTES_IN_NUMBER32 * NUMBERS_IN_CHUNK ); file->close(); file->clear(); delete file; if ( !silent ) ReportProgress( n * 4 ); } // process 64bit chunks of primes for ( int n=NCHUNKS32 + 1; n <= NCHUNKS32 + NCHUNKS64; ++n ) { ifstream* file = new ifstream( path + "precomputed" + to_string( (long long) n ), ios::in | ios::binary ); if ( !file->is_open() ) throw runtime_error("couldn't open"); int shift64 = (n-NCHUNKS32-1) * BYTES_IN_NUMBER64 * NUMBERS_IN_CHUNK; file->read( buffer64 + shift64, BYTES_IN_NUMBER64 * NUMBERS_IN_CHUNK ); file->close(); file->clear(); delete file; if ( !silent ) ReportProgress( n * 4 ); } return pair<unsigned long long, unsigned long long>( MIN32, MAX64 ); } bool Request( unsigned long long a ) { unsigned long * decoded32 = reinterpret_cast<unsigned long *>( buffer32 ); unsigned long long * decoded64 = reinterpret_cast<unsigned long long *>( buffer64 ); bool result; if ( a <= MAX32 ) result = binary_search( decoded32, decoded32 + TOTAL_NUMBERS32, (unsigned long)a ); else result = binary_search( decoded64, decoded64 + TOTAL_NUMBERS64, a ); return result; } void Destroy() { delete[] buffer32; delete[] buffer64; }
[ "d-shr@yandex.ru" ]
d-shr@yandex.ru
0b859466de34107317ec74cd98708822732c87ff
6d7a3bb26053cb180f35c88daf108f5a773ff293
/wasm_llvm/utils/TableGen/CodeGenDAGPatterns.cpp
610513b38b062675836673dcbbc2126b2e29fa67
[ "NCSA", "MIT" ]
permissive
WaykiChain/wicc-wasm-cdt
e4088f0313fbeb1aae7f4631b2735fbd2fc3c0c6
fcf9edcc9d8abf689c6a2452399735c887185bfa
refs/heads/master
2021-07-06T15:20:58.417585
2020-10-12T01:25:17
2020-10-12T01:25:17
237,560,833
1
2
MIT
2020-10-12T01:25:19
2020-02-01T04:19:53
C++
UTF-8
C++
false
false
163,439
cpp
//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the CodeGenDAGPatterns class, which is used to read and // represent the patterns present in a .td file for instructions. // //===----------------------------------------------------------------------===// #include "CodeGenDAGPatterns.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include <algorithm> #include <cstdio> #include <set> using namespace llvm; #define DEBUG_TYPE "dag-patterns" static inline bool isIntegerOrPtr(MVT VT) { return VT.isInteger() || VT == MVT::iPTR; } static inline bool isFloatingPoint(MVT VT) { return VT.isFloatingPoint(); } static inline bool isVector(MVT VT) { return VT.isVector(); } static inline bool isScalar(MVT VT) { return !VT.isVector(); } template <typename Predicate> static bool berase_if(MachineValueTypeSet &S, Predicate P) { bool Erased = false; // It is ok to iterate over MachineValueTypeSet and remove elements from it // at the same time. for (MVT T : S) { if (!P(T)) continue; Erased = true; S.erase(T); } return Erased; } // --- TypeSetByHwMode // This is a parameterized type-set class. For each mode there is a list // of types that are currently possible for a given tree node. Type // inference will apply to each mode separately. TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) { for (const ValueTypeByHwMode &VVT : VTList) insert(VVT); } bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const { for (const auto &I : *this) { if (I.second.size() > 1) return false; if (!AllowEmpty && I.second.empty()) return false; } return true; } ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const { assert(isValueTypeByHwMode(true) && "The type set has multiple types for at least one HW mode"); ValueTypeByHwMode VVT; for (const auto &I : *this) { MVT T = I.second.empty() ? MVT::Other : *I.second.begin(); VVT.getOrCreateTypeForMode(I.first, T); } return VVT; } bool TypeSetByHwMode::isPossible() const { for (const auto &I : *this) if (!I.second.empty()) return true; return false; } bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) { bool Changed = false; SmallDenseSet<unsigned, 4> Modes; for (const auto &P : VVT) { unsigned M = P.first; Modes.insert(M); // Make sure there exists a set for each specific mode from VVT. Changed |= getOrCreate(M).insert(P.second).second; } // If VVT has a default mode, add the corresponding type to all // modes in "this" that do not exist in VVT. if (Modes.count(DefaultMode)) { MVT DT = VVT.getType(DefaultMode); for (auto &I : *this) if (!Modes.count(I.first)) Changed |= I.second.insert(DT).second; } return Changed; } // Constrain the type set to be the intersection with VTS. bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) { bool Changed = false; if (hasDefault()) { for (const auto &I : VTS) { unsigned M = I.first; if (M == DefaultMode || hasMode(M)) continue; Map.insert({M, Map.at(DefaultMode)}); Changed = true; } } for (auto &I : *this) { unsigned M = I.first; SetType &S = I.second; if (VTS.hasMode(M) || VTS.hasDefault()) { Changed |= intersect(I.second, VTS.get(M)); } else if (!S.empty()) { S.clear(); Changed = true; } } return Changed; } template <typename Predicate> bool TypeSetByHwMode::constrain(Predicate P) { bool Changed = false; for (auto &I : *this) Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); }); return Changed; } template <typename Predicate> bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) { assert(empty()); for (const auto &I : VTS) { SetType &S = getOrCreate(I.first); for (auto J : I.second) if (P(J)) S.insert(J); } return !empty(); } void TypeSetByHwMode::writeToStream(raw_ostream &OS) const { SmallVector<unsigned, 4> Modes; Modes.reserve(Map.size()); for (const auto &I : *this) Modes.push_back(I.first); if (Modes.empty()) { OS << "{}"; return; } array_pod_sort(Modes.begin(), Modes.end()); OS << '{'; for (unsigned M : Modes) { OS << ' ' << getModeName(M) << ':'; writeToStream(get(M), OS); } OS << " }"; } void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) { SmallVector<MVT, 4> Types(S.begin(), S.end()); array_pod_sort(Types.begin(), Types.end()); OS << '['; for (unsigned i = 0, e = Types.size(); i != e; ++i) { OS << ValueTypeByHwMode::getMVTName(Types[i]); if (i != e-1) OS << ' '; } OS << ']'; } bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const { bool HaveDefault = hasDefault(); if (HaveDefault != VTS.hasDefault()) return false; if (isSimple()) { if (VTS.isSimple()) return *begin() == *VTS.begin(); return false; } SmallDenseSet<unsigned, 4> Modes; for (auto &I : *this) Modes.insert(I.first); for (const auto &I : VTS) Modes.insert(I.first); if (HaveDefault) { // Both sets have default mode. for (unsigned M : Modes) { if (get(M) != VTS.get(M)) return false; } } else { // Neither set has default mode. for (unsigned M : Modes) { // If there is no default mode, an empty set is equivalent to not having // the corresponding mode. bool NoModeThis = !hasMode(M) || get(M).empty(); bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty(); if (NoModeThis != NoModeVTS) return false; if (!NoModeThis) if (get(M) != VTS.get(M)) return false; } } return true; } namespace llvm { raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) { T.writeToStream(OS); return OS; } } LLVM_DUMP_METHOD void TypeSetByHwMode::dump() const { dbgs() << *this << '\n'; } bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) { bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR); auto Int = [&In](MVT T) -> bool { return !In.count(T); }; if (OutP == InP) return berase_if(Out, Int); // Compute the intersection of scalars separately to account for only // one set containing iPTR. // The itersection of iPTR with a set of integer scalar types that does not // include iPTR will result in the most specific scalar type: // - iPTR is more specific than any set with two elements or more // - iPTR is less specific than any single integer scalar type. // For example // { iPTR } * { i32 } -> { i32 } // { iPTR } * { i32 i64 } -> { iPTR } // and // { iPTR i32 } * { i32 } -> { i32 } // { iPTR i32 } * { i32 i64 } -> { i32 i64 } // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 } // Compute the difference between the two sets in such a way that the // iPTR is in the set that is being subtracted. This is to see if there // are any extra scalars in the set without iPTR that are not in the // set containing iPTR. Then the iPTR could be considered a "wildcard" // matching these scalars. If there is only one such scalar, it would // replace the iPTR, if there are more, the iPTR would be retained. SetType Diff; if (InP) { Diff = Out; berase_if(Diff, [&In](MVT T) { return In.count(T); }); // Pre-remove these elements and rely only on InP/OutP to determine // whether a change has been made. berase_if(Out, [&Diff](MVT T) { return Diff.count(T); }); } else { Diff = In; berase_if(Diff, [&Out](MVT T) { return Out.count(T); }); Out.erase(MVT::iPTR); } // The actual intersection. bool Changed = berase_if(Out, Int); unsigned NumD = Diff.size(); if (NumD == 0) return Changed; if (NumD == 1) { Out.insert(*Diff.begin()); // This is a change only if Out was the one with iPTR (which is now // being replaced). Changed |= OutP; } else { // Multiple elements from Out are now replaced with iPTR. Out.insert(MVT::iPTR); Changed |= !OutP; } return Changed; } bool TypeSetByHwMode::validate() const { #ifndef NDEBUG if (empty()) return true; bool AllEmpty = true; for (const auto &I : *this) AllEmpty &= I.second.empty(); return !AllEmpty; #endif return true; } // --- TypeInfer bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out, const TypeSetByHwMode &In) { ValidateOnExit _1(Out, *this); In.validate(); if (In.empty() || Out == In || TP.hasError()) return false; if (Out.empty()) { Out = In; return true; } bool Changed = Out.constrain(In); if (Changed && Out.empty()) TP.error("Type contradiction"); return Changed; } bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) { ValidateOnExit _1(Out, *this); if (TP.hasError()) return false; assert(!Out.empty() && "cannot pick from an empty set"); bool Changed = false; for (auto &I : Out) { TypeSetByHwMode::SetType &S = I.second; if (S.size() <= 1) continue; MVT T = *S.begin(); // Pick the first element. S.clear(); S.insert(T); Changed = true; } return Changed; } bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) { ValidateOnExit _1(Out, *this); if (TP.hasError()) return false; if (!Out.empty()) return Out.constrain(isIntegerOrPtr); return Out.assign_if(getLegalTypes(), isIntegerOrPtr); } bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) { ValidateOnExit _1(Out, *this); if (TP.hasError()) return false; if (!Out.empty()) return Out.constrain(isFloatingPoint); return Out.assign_if(getLegalTypes(), isFloatingPoint); } bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) { ValidateOnExit _1(Out, *this); if (TP.hasError()) return false; if (!Out.empty()) return Out.constrain(isScalar); return Out.assign_if(getLegalTypes(), isScalar); } bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) { ValidateOnExit _1(Out, *this); if (TP.hasError()) return false; if (!Out.empty()) return Out.constrain(isVector); return Out.assign_if(getLegalTypes(), isVector); } bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) { ValidateOnExit _1(Out, *this); if (TP.hasError() || !Out.empty()) return false; Out = getLegalTypes(); return true; } template <typename Iter, typename Pred, typename Less> static Iter min_if(Iter B, Iter E, Pred P, Less L) { if (B == E) return E; Iter Min = E; for (Iter I = B; I != E; ++I) { if (!P(*I)) continue; if (Min == E || L(*I, *Min)) Min = I; } return Min; } template <typename Iter, typename Pred, typename Less> static Iter max_if(Iter B, Iter E, Pred P, Less L) { if (B == E) return E; Iter Max = E; for (Iter I = B; I != E; ++I) { if (!P(*I)) continue; if (Max == E || L(*Max, *I)) Max = I; } return Max; } /// Make sure that for each type in Small, there exists a larger type in Big. bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big) { ValidateOnExit _1(Small, *this), _2(Big, *this); if (TP.hasError()) return false; bool Changed = false; if (Small.empty()) Changed |= EnforceAny(Small); if (Big.empty()) Changed |= EnforceAny(Big); assert(Small.hasDefault() && Big.hasDefault()); std::vector<unsigned> Modes = union_modes(Small, Big); // 1. Only allow integer or floating point types and make sure that // both sides are both integer or both floating point. // 2. Make sure that either both sides have vector types, or neither // of them does. for (unsigned M : Modes) { TypeSetByHwMode::SetType &S = Small.get(M); TypeSetByHwMode::SetType &B = Big.get(M); if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) { auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); }; Changed |= berase_if(S, NotInt) | berase_if(B, NotInt); } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) { auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); }; Changed |= berase_if(S, NotFP) | berase_if(B, NotFP); } else if (S.empty() || B.empty()) { Changed = !S.empty() || !B.empty(); S.clear(); B.clear(); } else { TP.error("Incompatible types"); return Changed; } if (none_of(S, isVector) || none_of(B, isVector)) { Changed |= berase_if(S, isVector) | berase_if(B, isVector); } } auto LT = [](MVT A, MVT B) -> bool { return A.getScalarSizeInBits() < B.getScalarSizeInBits() || (A.getScalarSizeInBits() == B.getScalarSizeInBits() && A.getSizeInBits() < B.getSizeInBits()); }; auto LE = [](MVT A, MVT B) -> bool { // This function is used when removing elements: when a vector is compared // to a non-vector, it should return false (to avoid removal). if (A.isVector() != B.isVector()) return false; // Note on the < comparison below: // X86 has patterns like // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))), // where the truncated vector is given a type v16i8, while the source // vector has type v4i32. They both have the same size in bits. // The minimal type in the result is obviously v16i8, and when we remove // all types from the source that are smaller-or-equal than v8i16, the // only source type would also be removed (since it's equal in size). return A.getScalarSizeInBits() <= B.getScalarSizeInBits() || A.getSizeInBits() < B.getSizeInBits(); }; for (unsigned M : Modes) { TypeSetByHwMode::SetType &S = Small.get(M); TypeSetByHwMode::SetType &B = Big.get(M); // MinS = min scalar in Small, remove all scalars from Big that are // smaller-or-equal than MinS. auto MinS = min_if(S.begin(), S.end(), isScalar, LT); if (MinS != S.end()) Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS)); // MaxS = max scalar in Big, remove all scalars from Small that are // larger than MaxS. auto MaxS = max_if(B.begin(), B.end(), isScalar, LT); if (MaxS != B.end()) Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1)); // MinV = min vector in Small, remove all vectors from Big that are // smaller-or-equal than MinV. auto MinV = min_if(S.begin(), S.end(), isVector, LT); if (MinV != S.end()) Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV)); // MaxV = max vector in Big, remove all vectors from Small that are // larger than MaxV. auto MaxV = max_if(B.begin(), B.end(), isVector, LT); if (MaxV != B.end()) Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1)); } return Changed; } /// 1. Ensure that for each type T in Vec, T is a vector type, and that /// for each type U in Elem, U is a scalar type. /// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector) /// type T in Vec, such that U is the element type of T. bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, TypeSetByHwMode &Elem) { ValidateOnExit _1(Vec, *this), _2(Elem, *this); if (TP.hasError()) return false; bool Changed = false; if (Vec.empty()) Changed |= EnforceVector(Vec); if (Elem.empty()) Changed |= EnforceScalar(Elem); for (unsigned M : union_modes(Vec, Elem)) { TypeSetByHwMode::SetType &V = Vec.get(M); TypeSetByHwMode::SetType &E = Elem.get(M); Changed |= berase_if(V, isScalar); // Scalar = !vector Changed |= berase_if(E, isVector); // Vector = !scalar assert(!V.empty() && !E.empty()); SmallSet<MVT,4> VT, ST; // Collect element types from the "vector" set. for (MVT T : V) VT.insert(T.getVectorElementType()); // Collect scalar types from the "element" set. for (MVT T : E) ST.insert(T); // Remove from V all (vector) types whose element type is not in S. Changed |= berase_if(V, [&ST](MVT T) -> bool { return !ST.count(T.getVectorElementType()); }); // Remove from E all (scalar) types, for which there is no corresponding // type in V. Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); }); } return Changed; } bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, const ValueTypeByHwMode &VVT) { TypeSetByHwMode Tmp(VVT); ValidateOnExit _1(Vec, *this), _2(Tmp, *this); return EnforceVectorEltTypeIs(Vec, Tmp); } /// Ensure that for each type T in Sub, T is a vector type, and there /// exists a type U in Vec such that U is a vector type with the same /// element type as T and at least as many elements as T. bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec, TypeSetByHwMode &Sub) { ValidateOnExit _1(Vec, *this), _2(Sub, *this); if (TP.hasError()) return false; /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B. auto IsSubVec = [](MVT B, MVT P) -> bool { if (!B.isVector() || !P.isVector()) return false; // Logically a <4 x i32> is a valid subvector of <n x 4 x i32> // but until there are obvious use-cases for this, keep the // types separate. if (B.isScalableVector() != P.isScalableVector()) return false; if (B.getVectorElementType() != P.getVectorElementType()) return false; return B.getVectorNumElements() < P.getVectorNumElements(); }; /// Return true if S has no element (vector type) that T is a sub-vector of, /// i.e. has the same element type as T and more elements. auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool { for (const auto &I : S) if (IsSubVec(T, I)) return false; return true; }; /// Return true if S has no element (vector type) that T is a super-vector /// of, i.e. has the same element type as T and fewer elements. auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool { for (const auto &I : S) if (IsSubVec(I, T)) return false; return true; }; bool Changed = false; if (Vec.empty()) Changed |= EnforceVector(Vec); if (Sub.empty()) Changed |= EnforceVector(Sub); for (unsigned M : union_modes(Vec, Sub)) { TypeSetByHwMode::SetType &S = Sub.get(M); TypeSetByHwMode::SetType &V = Vec.get(M); Changed |= berase_if(S, isScalar); // Erase all types from S that are not sub-vectors of a type in V. Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1)); // Erase all types from V that are not super-vectors of a type in S. Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1)); } return Changed; } /// 1. Ensure that V has a scalar type iff W has a scalar type. /// 2. Ensure that for each vector type T in V, there exists a vector /// type U in W, such that T and U have the same number of elements. /// 3. Ensure that for each vector type U in W, there exists a vector /// type T in V, such that T and U have the same number of elements /// (reverse of 2). bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) { ValidateOnExit _1(V, *this), _2(W, *this); if (TP.hasError()) return false; bool Changed = false; if (V.empty()) Changed |= EnforceAny(V); if (W.empty()) Changed |= EnforceAny(W); // An actual vector type cannot have 0 elements, so we can treat scalars // as zero-length vectors. This way both vectors and scalars can be // processed identically. auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool { return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0); }; for (unsigned M : union_modes(V, W)) { TypeSetByHwMode::SetType &VS = V.get(M); TypeSetByHwMode::SetType &WS = W.get(M); SmallSet<unsigned,2> VN, WN; for (MVT T : VS) VN.insert(T.isVector() ? T.getVectorNumElements() : 0); for (MVT T : WS) WN.insert(T.isVector() ? T.getVectorNumElements() : 0); Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1)); Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1)); } return Changed; } /// 1. Ensure that for each type T in A, there exists a type U in B, /// such that T and U have equal size in bits. /// 2. Ensure that for each type U in B, there exists a type T in A /// such that T and U have equal size in bits (reverse of 1). bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) { ValidateOnExit _1(A, *this), _2(B, *this); if (TP.hasError()) return false; bool Changed = false; if (A.empty()) Changed |= EnforceAny(A); if (B.empty()) Changed |= EnforceAny(B); auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool { return !Sizes.count(T.getSizeInBits()); }; for (unsigned M : union_modes(A, B)) { TypeSetByHwMode::SetType &AS = A.get(M); TypeSetByHwMode::SetType &BS = B.get(M); SmallSet<unsigned,2> AN, BN; for (MVT T : AS) AN.insert(T.getSizeInBits()); for (MVT T : BS) BN.insert(T.getSizeInBits()); Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1)); Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1)); } return Changed; } void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) { ValidateOnExit _1(VTS, *this); TypeSetByHwMode Legal = getLegalTypes(); bool HaveLegalDef = Legal.hasDefault(); for (auto &I : VTS) { unsigned M = I.first; if (!Legal.hasMode(M) && !HaveLegalDef) { TP.error("Invalid mode " + Twine(M)); return; } expandOverloads(I.second, Legal.get(M)); } } void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out, const TypeSetByHwMode::SetType &Legal) { std::set<MVT> Ovs; for (MVT T : Out) { if (!T.isOverloaded()) continue; Ovs.insert(T); // MachineValueTypeSet allows iteration and erasing. Out.erase(T); } for (MVT Ov : Ovs) { switch (Ov.SimpleTy) { case MVT::iPTRAny: Out.insert(MVT::iPTR); return; case MVT::iAny: for (MVT T : MVT::integer_valuetypes()) if (Legal.count(T)) Out.insert(T); for (MVT T : MVT::integer_vector_valuetypes()) if (Legal.count(T)) Out.insert(T); return; case MVT::fAny: for (MVT T : MVT::fp_valuetypes()) if (Legal.count(T)) Out.insert(T); for (MVT T : MVT::fp_vector_valuetypes()) if (Legal.count(T)) Out.insert(T); return; case MVT::vAny: for (MVT T : MVT::vector_valuetypes()) if (Legal.count(T)) Out.insert(T); return; case MVT::Any: for (MVT T : MVT::all_valuetypes()) if (Legal.count(T)) Out.insert(T); return; default: break; } } } TypeSetByHwMode TypeInfer::getLegalTypes() { if (!LegalTypesCached) { // Stuff all types from all modes into the default mode. const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes(); for (const auto &I : LTS) LegalCache.insert(I.second); LegalTypesCached = true; } TypeSetByHwMode VTS; VTS.getOrCreate(DefaultMode) = LegalCache; return VTS; } #ifndef NDEBUG TypeInfer::ValidateOnExit::~ValidateOnExit() { if (!VTS.validate()) { dbgs() << "Type set is empty for each HW mode:\n" "possible type contradiction in the pattern below " "(use -print-records with llvm-tblgen to see all " "expanded records).\n"; Infer.TP.dump(); llvm_unreachable(nullptr); } } #endif //===----------------------------------------------------------------------===// // TreePredicateFn Implementation //===----------------------------------------------------------------------===// /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag. TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) { assert( (!hasPredCode() || !hasImmCode()) && ".td file corrupt: can't have a node predicate *and* an imm predicate"); } bool TreePredicateFn::hasPredCode() const { return isLoad() || isStore() || isAtomic() || !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty(); } std::string TreePredicateFn::getPredCode() const { std::string Code = ""; if (!isLoad() && !isStore() && !isAtomic()) { Record *MemoryVT = getMemoryVT(); if (MemoryVT) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "MemoryVT requires IsLoad or IsStore"); } if (!isLoad() && !isStore()) { if (isUnindexed()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsUnindexed requires IsLoad or IsStore"); Record *ScalarMemoryVT = getScalarMemoryVT(); if (ScalarMemoryVT) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "ScalarMemoryVT requires IsLoad or IsStore"); } if (isLoad() + isStore() + isAtomic() > 1) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsLoad, IsStore, and IsAtomic are mutually exclusive"); if (isLoad()) { if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() && !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsLoad cannot be used by itself"); } else { if (isNonExtLoad()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsNonExtLoad requires IsLoad"); if (isAnyExtLoad()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsAnyExtLoad requires IsLoad"); if (isSignExtLoad()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsSignExtLoad requires IsLoad"); if (isZeroExtLoad()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsZeroExtLoad requires IsLoad"); } if (isStore()) { if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() && getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsStore cannot be used by itself"); } else { if (isNonTruncStore()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsNonTruncStore requires IsStore"); if (isTruncStore()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsTruncStore requires IsStore"); } if (isAtomic()) { if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() && !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() && !isAtomicOrderingAcquireRelease() && !isAtomicOrderingSequentiallyConsistent() && !isAtomicOrderingAcquireOrStronger() && !isAtomicOrderingReleaseOrStronger() && !isAtomicOrderingWeakerThanAcquire() && !isAtomicOrderingWeakerThanRelease()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsAtomic cannot be used by itself"); } else { if (isAtomicOrderingMonotonic()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsAtomicOrderingMonotonic requires IsAtomic"); if (isAtomicOrderingAcquire()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsAtomicOrderingAcquire requires IsAtomic"); if (isAtomicOrderingRelease()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsAtomicOrderingRelease requires IsAtomic"); if (isAtomicOrderingAcquireRelease()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsAtomicOrderingAcquireRelease requires IsAtomic"); if (isAtomicOrderingSequentiallyConsistent()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsAtomicOrderingSequentiallyConsistent requires IsAtomic"); if (isAtomicOrderingAcquireOrStronger()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsAtomicOrderingAcquireOrStronger requires IsAtomic"); if (isAtomicOrderingReleaseOrStronger()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsAtomicOrderingReleaseOrStronger requires IsAtomic"); if (isAtomicOrderingWeakerThanAcquire()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsAtomicOrderingWeakerThanAcquire requires IsAtomic"); } if (isLoad() || isStore() || isAtomic()) { StringRef SDNodeName = isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode"; Record *MemoryVT = getMemoryVT(); if (MemoryVT) Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" + MemoryVT->getName() + ") return false;\n") .str(); } if (isAtomic() && isAtomicOrderingMonotonic()) Code += "if (cast<AtomicSDNode>(N)->getOrdering() != " "AtomicOrdering::Monotonic) return false;\n"; if (isAtomic() && isAtomicOrderingAcquire()) Code += "if (cast<AtomicSDNode>(N)->getOrdering() != " "AtomicOrdering::Acquire) return false;\n"; if (isAtomic() && isAtomicOrderingRelease()) Code += "if (cast<AtomicSDNode>(N)->getOrdering() != " "AtomicOrdering::Release) return false;\n"; if (isAtomic() && isAtomicOrderingAcquireRelease()) Code += "if (cast<AtomicSDNode>(N)->getOrdering() != " "AtomicOrdering::AcquireRelease) return false;\n"; if (isAtomic() && isAtomicOrderingSequentiallyConsistent()) Code += "if (cast<AtomicSDNode>(N)->getOrdering() != " "AtomicOrdering::SequentiallyConsistent) return false;\n"; if (isAtomic() && isAtomicOrderingAcquireOrStronger()) Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) " "return false;\n"; if (isAtomic() && isAtomicOrderingWeakerThanAcquire()) Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) " "return false;\n"; if (isAtomic() && isAtomicOrderingReleaseOrStronger()) Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) " "return false;\n"; if (isAtomic() && isAtomicOrderingWeakerThanRelease()) Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) " "return false;\n"; if (isLoad() || isStore()) { StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode"; if (isUnindexed()) Code += ("if (cast<" + SDNodeName + ">(N)->getAddressingMode() != ISD::UNINDEXED) " "return false;\n") .str(); if (isLoad()) { if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() + isZeroExtLoad()) > 1) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and " "IsZeroExtLoad are mutually exclusive"); if (isNonExtLoad()) Code += "if (cast<LoadSDNode>(N)->getExtensionType() != " "ISD::NON_EXTLOAD) return false;\n"; if (isAnyExtLoad()) Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) " "return false;\n"; if (isSignExtLoad()) Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) " "return false;\n"; if (isZeroExtLoad()) Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) " "return false;\n"; } else { if ((isNonTruncStore() + isTruncStore()) > 1) PrintFatalError( getOrigPatFragRecord()->getRecord()->getLoc(), "IsNonTruncStore, and IsTruncStore are mutually exclusive"); if (isNonTruncStore()) Code += " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n"; if (isTruncStore()) Code += " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n"; } Record *ScalarMemoryVT = getScalarMemoryVT(); if (ScalarMemoryVT) Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT().getScalarType() != MVT::" + ScalarMemoryVT->getName() + ") return false;\n") .str(); } std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode"); Code += PredicateCode; if (PredicateCode.empty() && !Code.empty()) Code += "return true;\n"; return Code; } bool TreePredicateFn::hasImmCode() const { return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty(); } std::string TreePredicateFn::getImmCode() const { return PatFragRec->getRecord()->getValueAsString("ImmediateCode"); } bool TreePredicateFn::immCodeUsesAPInt() const { return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt"); } bool TreePredicateFn::immCodeUsesAPFloat() const { bool Unset; // The return value will be false when IsAPFloat is unset. return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat", Unset); } bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field, bool Value) const { bool Unset; bool Result = getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset); if (Unset) return false; return Result == Value; } bool TreePredicateFn::isLoad() const { return isPredefinedPredicateEqualTo("IsLoad", true); } bool TreePredicateFn::isStore() const { return isPredefinedPredicateEqualTo("IsStore", true); } bool TreePredicateFn::isAtomic() const { return isPredefinedPredicateEqualTo("IsAtomic", true); } bool TreePredicateFn::isUnindexed() const { return isPredefinedPredicateEqualTo("IsUnindexed", true); } bool TreePredicateFn::isNonExtLoad() const { return isPredefinedPredicateEqualTo("IsNonExtLoad", true); } bool TreePredicateFn::isAnyExtLoad() const { return isPredefinedPredicateEqualTo("IsAnyExtLoad", true); } bool TreePredicateFn::isSignExtLoad() const { return isPredefinedPredicateEqualTo("IsSignExtLoad", true); } bool TreePredicateFn::isZeroExtLoad() const { return isPredefinedPredicateEqualTo("IsZeroExtLoad", true); } bool TreePredicateFn::isNonTruncStore() const { return isPredefinedPredicateEqualTo("IsTruncStore", false); } bool TreePredicateFn::isTruncStore() const { return isPredefinedPredicateEqualTo("IsTruncStore", true); } bool TreePredicateFn::isAtomicOrderingMonotonic() const { return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true); } bool TreePredicateFn::isAtomicOrderingAcquire() const { return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true); } bool TreePredicateFn::isAtomicOrderingRelease() const { return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true); } bool TreePredicateFn::isAtomicOrderingAcquireRelease() const { return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true); } bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const { return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent", true); } bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const { return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true); } bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const { return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false); } bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const { return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true); } bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const { return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false); } Record *TreePredicateFn::getMemoryVT() const { Record *R = getOrigPatFragRecord()->getRecord(); if (R->isValueUnset("MemoryVT")) return nullptr; return R->getValueAsDef("MemoryVT"); } Record *TreePredicateFn::getScalarMemoryVT() const { Record *R = getOrigPatFragRecord()->getRecord(); if (R->isValueUnset("ScalarMemoryVT")) return nullptr; return R->getValueAsDef("ScalarMemoryVT"); } StringRef TreePredicateFn::getImmType() const { if (immCodeUsesAPInt()) return "const APInt &"; if (immCodeUsesAPFloat()) return "const APFloat &"; return "int64_t"; } StringRef TreePredicateFn::getImmTypeIdentifier() const { if (immCodeUsesAPInt()) return "APInt"; else if (immCodeUsesAPFloat()) return "APFloat"; return "I64"; } /// isAlwaysTrue - Return true if this is a noop predicate. bool TreePredicateFn::isAlwaysTrue() const { return !hasPredCode() && !hasImmCode(); } /// Return the name to use in the generated code to reference this, this is /// "Predicate_foo" if from a pattern fragment "foo". std::string TreePredicateFn::getFnName() const { return "Predicate_" + PatFragRec->getRecord()->getName().str(); } /// getCodeToRunOnSDNode - Return the code for the function body that /// evaluates this predicate. The argument is expected to be in "Node", /// not N. This handles casting and conversion to a concrete node type as /// appropriate. std::string TreePredicateFn::getCodeToRunOnSDNode() const { // Handle immediate predicates first. std::string ImmCode = getImmCode(); if (!ImmCode.empty()) { if (isLoad()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsLoad cannot be used with ImmLeaf or its subclasses"); if (isStore()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "IsStore cannot be used with ImmLeaf or its subclasses"); if (isUnindexed()) PrintFatalError( getOrigPatFragRecord()->getRecord()->getLoc(), "IsUnindexed cannot be used with ImmLeaf or its subclasses"); if (isNonExtLoad()) PrintFatalError( getOrigPatFragRecord()->getRecord()->getLoc(), "IsNonExtLoad cannot be used with ImmLeaf or its subclasses"); if (isAnyExtLoad()) PrintFatalError( getOrigPatFragRecord()->getRecord()->getLoc(), "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses"); if (isSignExtLoad()) PrintFatalError( getOrigPatFragRecord()->getRecord()->getLoc(), "IsSignExtLoad cannot be used with ImmLeaf or its subclasses"); if (isZeroExtLoad()) PrintFatalError( getOrigPatFragRecord()->getRecord()->getLoc(), "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses"); if (isNonTruncStore()) PrintFatalError( getOrigPatFragRecord()->getRecord()->getLoc(), "IsNonTruncStore cannot be used with ImmLeaf or its subclasses"); if (isTruncStore()) PrintFatalError( getOrigPatFragRecord()->getRecord()->getLoc(), "IsTruncStore cannot be used with ImmLeaf or its subclasses"); if (getMemoryVT()) PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(), "MemoryVT cannot be used with ImmLeaf or its subclasses"); if (getScalarMemoryVT()) PrintFatalError( getOrigPatFragRecord()->getRecord()->getLoc(), "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses"); std::string Result = (" " + getImmType() + " Imm = ").str(); if (immCodeUsesAPFloat()) Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n"; else if (immCodeUsesAPInt()) Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n"; else Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n"; return Result + ImmCode; } // Handle arbitrary node predicates. assert(hasPredCode() && "Don't have any predicate code!"); StringRef ClassName; if (PatFragRec->getOnlyTree()->isLeaf()) ClassName = "SDNode"; else { Record *Op = PatFragRec->getOnlyTree()->getOperator(); ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName(); } std::string Result; if (ClassName == "SDNode") Result = " SDNode *N = Node;\n"; else Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n"; return Result + getPredCode(); } //===----------------------------------------------------------------------===// // PatternToMatch implementation // /// getPatternSize - Return the 'size' of this pattern. We want to match large /// patterns before small ones. This is used to determine the size of a /// pattern. static unsigned getPatternSize(const TreePatternNode *P, const CodeGenDAGPatterns &CGP) { unsigned Size = 3; // The node itself. // If the root node is a ConstantSDNode, increases its size. // e.g. (set R32:$dst, 0). if (P->isLeaf() && isa<IntInit>(P->getLeafValue())) Size += 2; if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) { Size += AM->getComplexity(); // We don't want to count any children twice, so return early. return Size; } // If this node has some predicate function that must match, it adds to the // complexity of this node. if (!P->getPredicateFns().empty()) ++Size; // Count children in the count if they are also nodes. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) { const TreePatternNode *Child = P->getChild(i); if (!Child->isLeaf() && Child->getNumTypes()) { const TypeSetByHwMode &T0 = Child->getType(0); // At this point, all variable type sets should be simple, i.e. only // have a default mode. if (T0.getMachineValueType() != MVT::Other) { Size += getPatternSize(Child, CGP); continue; } } if (Child->isLeaf()) { if (isa<IntInit>(Child->getLeafValue())) Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2). else if (Child->getComplexPatternInfo(CGP)) Size += getPatternSize(Child, CGP); else if (!Child->getPredicateFns().empty()) ++Size; } } return Size; } /// Compute the complexity metric for the input pattern. This roughly /// corresponds to the number of nodes that are covered. int PatternToMatch:: getPatternComplexity(const CodeGenDAGPatterns &CGP) const { return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity(); } /// getPredicateCheck - Return a single string containing all of this /// pattern's predicates concatenated with "&&" operators. /// std::string PatternToMatch::getPredicateCheck() const { SmallVector<const Predicate*,4> PredList; for (const Predicate &P : Predicates) PredList.push_back(&P); llvm::sort(PredList.begin(), PredList.end(), deref<llvm::less>()); std::string Check; for (unsigned i = 0, e = PredList.size(); i != e; ++i) { if (i != 0) Check += " && "; Check += '(' + PredList[i]->getCondString() + ')'; } return Check; } //===----------------------------------------------------------------------===// // SDTypeConstraint implementation // SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) { OperandNo = R->getValueAsInt("OperandNum"); if (R->isSubClassOf("SDTCisVT")) { ConstraintType = SDTCisVT; VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH); for (const auto &P : VVT) if (P.second == MVT::isVoid) PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT"); } else if (R->isSubClassOf("SDTCisPtrTy")) { ConstraintType = SDTCisPtrTy; } else if (R->isSubClassOf("SDTCisInt")) { ConstraintType = SDTCisInt; } else if (R->isSubClassOf("SDTCisFP")) { ConstraintType = SDTCisFP; } else if (R->isSubClassOf("SDTCisVec")) { ConstraintType = SDTCisVec; } else if (R->isSubClassOf("SDTCisSameAs")) { ConstraintType = SDTCisSameAs; x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum"); } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) { ConstraintType = SDTCisVTSmallerThanOp; x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum"); } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) { ConstraintType = SDTCisOpSmallerThanOp; x.SDTCisOpSmallerThanOp_Info.BigOperandNum = R->getValueAsInt("BigOperandNum"); } else if (R->isSubClassOf("SDTCisEltOfVec")) { ConstraintType = SDTCisEltOfVec; x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum"); } else if (R->isSubClassOf("SDTCisSubVecOfVec")) { ConstraintType = SDTCisSubVecOfVec; x.SDTCisSubVecOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum"); } else if (R->isSubClassOf("SDTCVecEltisVT")) { ConstraintType = SDTCVecEltisVT; VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH); for (const auto &P : VVT) { MVT T = P.second; if (T.isVector()) PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT"); if (!T.isInteger() && !T.isFloatingPoint()) PrintFatalError(R->getLoc(), "Must use integer or floating point type " "as SDTCVecEltisVT"); } } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) { ConstraintType = SDTCisSameNumEltsAs; x.SDTCisSameNumEltsAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum"); } else if (R->isSubClassOf("SDTCisSameSizeAs")) { ConstraintType = SDTCisSameSizeAs; x.SDTCisSameSizeAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum"); } else { PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n"); } } /// getOperandNum - Return the node corresponding to operand #OpNo in tree /// N, and the result number in ResNo. static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N, const SDNodeInfo &NodeInfo, unsigned &ResNo) { unsigned NumResults = NodeInfo.getNumResults(); if (OpNo < NumResults) { ResNo = OpNo; return N; } OpNo -= NumResults; if (OpNo >= N->getNumChildren()) { std::string S; raw_string_ostream OS(S); OS << "Invalid operand number in type constraint " << (OpNo+NumResults) << " "; N->print(OS); PrintFatalError(OS.str()); } return N->getChild(OpNo); } /// ApplyTypeConstraint - Given a node in a pattern, apply this type /// constraint to the nodes operands. This returns true if it makes a /// change, false otherwise. If a type contradiction is found, flag an error. bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo, TreePattern &TP) const { if (TP.hasError()) return false; unsigned ResNo = 0; // The result number being referenced. TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo); TypeInfer &TI = TP.getInfer(); switch (ConstraintType) { case SDTCisVT: // Operand must be a particular type. return NodeToApply->UpdateNodeType(ResNo, VVT, TP); case SDTCisPtrTy: // Operand must be same as target pointer type. return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP); case SDTCisInt: // Require it to be one of the legal integer VTs. return TI.EnforceInteger(NodeToApply->getExtType(ResNo)); case SDTCisFP: // Require it to be one of the legal fp VTs. return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo)); case SDTCisVec: // Require it to be one of the legal vector VTs. return TI.EnforceVector(NodeToApply->getExtType(ResNo)); case SDTCisSameAs: { unsigned OResNo = 0; TreePatternNode *OtherNode = getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo); return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)| OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP); } case SDTCisVTSmallerThanOp: { // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must // have an integer type that is smaller than the VT. if (!NodeToApply->isLeaf() || !isa<DefInit>(NodeToApply->getLeafValue()) || !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef() ->isSubClassOf("ValueType")) { TP.error(N->getOperator()->getName() + " expects a VT operand!"); return false; } DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue()); const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo(); auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes()); TypeSetByHwMode TypeListTmp(VVT); unsigned OResNo = 0; TreePatternNode *OtherNode = getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo, OResNo); return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo)); } case SDTCisOpSmallerThanOp: { unsigned BResNo = 0; TreePatternNode *BigOperand = getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo, BResNo); return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo), BigOperand->getExtType(BResNo)); } case SDTCisEltOfVec: { unsigned VResNo = 0; TreePatternNode *VecOperand = getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo, VResNo); // Filter vector types out of VecOperand that don't have the right element // type. return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo), NodeToApply->getExtType(ResNo)); } case SDTCisSubVecOfVec: { unsigned VResNo = 0; TreePatternNode *BigVecOperand = getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo, VResNo); // Filter vector types out of BigVecOperand that don't have the // right subvector type. return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo), NodeToApply->getExtType(ResNo)); } case SDTCVecEltisVT: { return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT); } case SDTCisSameNumEltsAs: { unsigned OResNo = 0; TreePatternNode *OtherNode = getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum, N, NodeInfo, OResNo); return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo), NodeToApply->getExtType(ResNo)); } case SDTCisSameSizeAs: { unsigned OResNo = 0; TreePatternNode *OtherNode = getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum, N, NodeInfo, OResNo); return TI.EnforceSameSize(OtherNode->getExtType(OResNo), NodeToApply->getExtType(ResNo)); } } llvm_unreachable("Invalid ConstraintType!"); } // Update the node type to match an instruction operand or result as specified // in the ins or outs lists on the instruction definition. Return true if the // type was actually changed. bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo, Record *Operand, TreePattern &TP) { // The 'unknown' operand indicates that types should be inferred from the // context. if (Operand->isSubClassOf("unknown_class")) return false; // The Operand class specifies a type directly. if (Operand->isSubClassOf("Operand")) { Record *R = Operand->getValueAsDef("Type"); const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo(); return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP); } // PointerLikeRegClass has a type that is determined at runtime. if (Operand->isSubClassOf("PointerLikeRegClass")) return UpdateNodeType(ResNo, MVT::iPTR, TP); // Both RegisterClass and RegisterOperand operands derive their types from a // register class def. Record *RC = nullptr; if (Operand->isSubClassOf("RegisterClass")) RC = Operand; else if (Operand->isSubClassOf("RegisterOperand")) RC = Operand->getValueAsDef("RegClass"); assert(RC && "Unknown operand type"); CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo(); return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP); } bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const { for (unsigned i = 0, e = Types.size(); i != e; ++i) if (!TP.getInfer().isConcrete(Types[i], true)) return true; for (unsigned i = 0, e = getNumChildren(); i != e; ++i) if (getChild(i)->ContainsUnresolvedType(TP)) return true; return false; } bool TreePatternNode::hasProperTypeByHwMode() const { for (const TypeSetByHwMode &S : Types) if (!S.isDefaultOnly()) return true; for (const TreePatternNodePtr &C : Children) if (C->hasProperTypeByHwMode()) return true; return false; } bool TreePatternNode::hasPossibleType() const { for (const TypeSetByHwMode &S : Types) if (!S.isPossible()) return false; for (const TreePatternNodePtr &C : Children) if (!C->hasPossibleType()) return false; return true; } bool TreePatternNode::setDefaultMode(unsigned Mode) { for (TypeSetByHwMode &S : Types) { S.makeSimple(Mode); // Check if the selected mode had a type conflict. if (S.get(DefaultMode).empty()) return false; } for (const TreePatternNodePtr &C : Children) if (!C->setDefaultMode(Mode)) return false; return true; } //===----------------------------------------------------------------------===// // SDNodeInfo implementation // SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) { EnumName = R->getValueAsString("Opcode"); SDClassName = R->getValueAsString("SDClass"); Record *TypeProfile = R->getValueAsDef("TypeProfile"); NumResults = TypeProfile->getValueAsInt("NumResults"); NumOperands = TypeProfile->getValueAsInt("NumOperands"); // Parse the properties. Properties = parseSDPatternOperatorProperties(R); // Parse the type constraints. std::vector<Record*> ConstraintList = TypeProfile->getValueAsListOfDefs("Constraints"); for (Record *R : ConstraintList) TypeConstraints.emplace_back(R, CGH); } /// getKnownType - If the type constraints on this node imply a fixed type /// (e.g. all stores return void, etc), then return it as an /// MVT::SimpleValueType. Otherwise, return EEVT::Other. MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const { unsigned NumResults = getNumResults(); assert(NumResults <= 1 && "We only work with nodes with zero or one result so far!"); assert(ResNo == 0 && "Only handles single result nodes so far"); for (const SDTypeConstraint &Constraint : TypeConstraints) { // Make sure that this applies to the correct node result. if (Constraint.OperandNo >= NumResults) // FIXME: need value # continue; switch (Constraint.ConstraintType) { default: break; case SDTypeConstraint::SDTCisVT: if (Constraint.VVT.isSimple()) return Constraint.VVT.getSimple().SimpleTy; break; case SDTypeConstraint::SDTCisPtrTy: return MVT::iPTR; } } return MVT::Other; } //===----------------------------------------------------------------------===// // TreePatternNode implementation // static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) { if (Operator->getName() == "set" || Operator->getName() == "implicit") return 0; // All return nothing. if (Operator->isSubClassOf("Intrinsic")) return CDP.getIntrinsic(Operator).IS.RetVTs.size(); if (Operator->isSubClassOf("SDNode")) return CDP.getSDNodeInfo(Operator).getNumResults(); if (Operator->isSubClassOf("PatFrag")) { // If we've already parsed this pattern fragment, get it. Otherwise, handle // the forward reference case where one pattern fragment references another // before it is processed. if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) return PFRec->getOnlyTree()->getNumTypes(); // Get the result tree. DagInit *Tree = Operator->getValueAsDag("Fragment"); Record *Op = nullptr; if (Tree) if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator())) Op = DI->getDef(); assert(Op && "Invalid Fragment"); return GetNumNodeResults(Op, CDP); } if (Operator->isSubClassOf("Instruction")) { CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator); unsigned NumDefsToAdd = InstInfo.Operands.NumDefs; // Subtract any defaulted outputs. for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) { Record *OperandNode = InstInfo.Operands[i].Rec; if (OperandNode->isSubClassOf("OperandWithDefaultOps") && !CDP.getDefaultOperand(OperandNode).DefaultOps.empty()) --NumDefsToAdd; } // Add on one implicit def if it has a resolvable type. if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other) ++NumDefsToAdd; return NumDefsToAdd; } if (Operator->isSubClassOf("SDNodeXForm")) return 1; // FIXME: Generalize SDNodeXForm if (Operator->isSubClassOf("ValueType")) return 1; // A type-cast of one result. if (Operator->isSubClassOf("ComplexPattern")) return 1; errs() << *Operator; PrintFatalError("Unhandled node in GetNumNodeResults"); } void TreePatternNode::print(raw_ostream &OS) const { if (isLeaf()) OS << *getLeafValue(); else OS << '(' << getOperator()->getName(); for (unsigned i = 0, e = Types.size(); i != e; ++i) { OS << ':'; getExtType(i).writeToStream(OS); } if (!isLeaf()) { if (getNumChildren() != 0) { OS << " "; getChild(0)->print(OS); for (unsigned i = 1, e = getNumChildren(); i != e; ++i) { OS << ", "; getChild(i)->print(OS); } } OS << ")"; } for (const TreePredicateFn &Pred : PredicateFns) OS << "<<P:" << Pred.getFnName() << ">>"; if (TransformFn) OS << "<<X:" << TransformFn->getName() << ">>"; if (!getName().empty()) OS << ":$" << getName(); } void TreePatternNode::dump() const { print(errs()); } /// isIsomorphicTo - Return true if this node is recursively /// isomorphic to the specified node. For this comparison, the node's /// entire state is considered. The assigned name is ignored, since /// nodes with differing names are considered isomorphic. However, if /// the assigned name is present in the dependent variable set, then /// the assigned name is considered significant and the node is /// isomorphic if the names match. bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N, const MultipleUseVarSet &DepVars) const { if (N == this) return true; if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() || getPredicateFns() != N->getPredicateFns() || getTransformFn() != N->getTransformFn()) return false; if (isLeaf()) { if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) { if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) { return ((DI->getDef() == NDI->getDef()) && (DepVars.find(getName()) == DepVars.end() || getName() == N->getName())); } } return getLeafValue() == N->getLeafValue(); } if (N->getOperator() != getOperator() || N->getNumChildren() != getNumChildren()) return false; for (unsigned i = 0, e = getNumChildren(); i != e; ++i) if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars)) return false; return true; } /// clone - Make a copy of this tree and all of its children. /// TreePatternNodePtr TreePatternNode::clone() const { TreePatternNodePtr New; if (isLeaf()) { New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes()); } else { std::vector<TreePatternNodePtr> CChildren; CChildren.reserve(Children.size()); for (unsigned i = 0, e = getNumChildren(); i != e; ++i) CChildren.push_back(getChild(i)->clone()); New = std::make_shared<TreePatternNode>(getOperator(), CChildren, getNumTypes()); } New->setName(getName()); New->Types = Types; New->setPredicateFns(getPredicateFns()); New->setTransformFn(getTransformFn()); return New; } /// RemoveAllTypes - Recursively strip all the types of this tree. void TreePatternNode::RemoveAllTypes() { // Reset to unknown type. std::fill(Types.begin(), Types.end(), TypeSetByHwMode()); if (isLeaf()) return; for (unsigned i = 0, e = getNumChildren(); i != e; ++i) getChild(i)->RemoveAllTypes(); } /// SubstituteFormalArguments - Replace the formal arguments in this tree /// with actual values specified by ArgMap. void TreePatternNode::SubstituteFormalArguments( std::map<std::string, TreePatternNodePtr> &ArgMap) { if (isLeaf()) return; for (unsigned i = 0, e = getNumChildren(); i != e; ++i) { TreePatternNode *Child = getChild(i); if (Child->isLeaf()) { Init *Val = Child->getLeafValue(); // Note that, when substituting into an output pattern, Val might be an // UnsetInit. if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) && cast<DefInit>(Val)->getDef()->getName() == "node")) { // We found a use of a formal argument, replace it with its value. TreePatternNodePtr NewChild = ArgMap[Child->getName()]; assert(NewChild && "Couldn't find formal argument!"); assert((Child->getPredicateFns().empty() || NewChild->getPredicateFns() == Child->getPredicateFns()) && "Non-empty child predicate clobbered!"); setChild(i, std::move(NewChild)); } } else { getChild(i)->SubstituteFormalArguments(ArgMap); } } } /// InlinePatternFragments - If this pattern refers to any pattern /// fragments, inline them into place, giving us a pattern without any /// PatFrag references. TreePatternNodePtr TreePatternNode::InlinePatternFragments(TreePatternNodePtr T, TreePattern &TP) { if (TP.hasError()) return nullptr; if (isLeaf()) return T; // nothing to do. Record *Op = getOperator(); if (!Op->isSubClassOf("PatFrag")) { // Just recursively inline children nodes. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) { TreePatternNodePtr Child = getChildShared(i); TreePatternNodePtr NewChild = Child->InlinePatternFragments(Child, TP); assert((Child->getPredicateFns().empty() || NewChild->getPredicateFns() == Child->getPredicateFns()) && "Non-empty child predicate clobbered!"); setChild(i, std::move(NewChild)); } return T; } // Otherwise, we found a reference to a fragment. First, look up its // TreePattern record. TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op); // Verify that we are passing the right number of operands. if (Frag->getNumArgs() != Children.size()) { TP.error("'" + Op->getName() + "' fragment requires " + Twine(Frag->getNumArgs()) + " operands!"); return {nullptr}; } TreePatternNodePtr FragTree = Frag->getOnlyTree()->clone(); TreePredicateFn PredFn(Frag); if (!PredFn.isAlwaysTrue()) FragTree->addPredicateFn(PredFn); // Resolve formal arguments to their actual value. if (Frag->getNumArgs()) { // Compute the map of formal to actual arguments. std::map<std::string, TreePatternNodePtr> ArgMap; for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) { const TreePatternNodePtr &Child = getChildShared(i); ArgMap[Frag->getArgName(i)] = Child->InlinePatternFragments(Child, TP); } FragTree->SubstituteFormalArguments(ArgMap); } FragTree->setName(getName()); for (unsigned i = 0, e = Types.size(); i != e; ++i) FragTree->UpdateNodeType(i, getExtType(i), TP); // Transfer in the old predicates. for (const TreePredicateFn &Pred : getPredicateFns()) FragTree->addPredicateFn(Pred); // The fragment we inlined could have recursive inlining that is needed. See // if there are any pattern fragments in it and inline them as needed. return FragTree->InlinePatternFragments(FragTree, TP); } /// getImplicitType - Check to see if the specified record has an implicit /// type which should be applied to it. This will infer the type of register /// references from the register file information, for example. /// /// When Unnamed is set, return the type of a DAG operand with no name, such as /// the F8RC register class argument in: /// /// (COPY_TO_REGCLASS GPR:$src, F8RC) /// /// When Unnamed is false, return the type of a named DAG operand such as the /// GPR:$src operand above. /// static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo, bool NotRegisters, bool Unnamed, TreePattern &TP) { CodeGenDAGPatterns &CDP = TP.getDAGPatterns(); // Check to see if this is a register operand. if (R->isSubClassOf("RegisterOperand")) { assert(ResNo == 0 && "Regoperand ref only has one result!"); if (NotRegisters) return TypeSetByHwMode(); // Unknown. Record *RegClass = R->getValueAsDef("RegClass"); const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo(); return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes()); } // Check to see if this is a register or a register class. if (R->isSubClassOf("RegisterClass")) { assert(ResNo == 0 && "Regclass ref only has one result!"); // An unnamed register class represents itself as an i32 immediate, for // example on a COPY_TO_REGCLASS instruction. if (Unnamed) return TypeSetByHwMode(MVT::i32); // In a named operand, the register class provides the possible set of // types. if (NotRegisters) return TypeSetByHwMode(); // Unknown. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo(); return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes()); } if (R->isSubClassOf("PatFrag")) { assert(ResNo == 0 && "FIXME: PatFrag with multiple results?"); // Pattern fragment types will be resolved when they are inlined. return TypeSetByHwMode(); // Unknown. } if (R->isSubClassOf("Register")) { assert(ResNo == 0 && "Registers only produce one result!"); if (NotRegisters) return TypeSetByHwMode(); // Unknown. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo(); return TypeSetByHwMode(T.getRegisterVTs(R)); } if (R->isSubClassOf("SubRegIndex")) { assert(ResNo == 0 && "SubRegisterIndices only produce one result!"); return TypeSetByHwMode(MVT::i32); } if (R->isSubClassOf("ValueType")) { assert(ResNo == 0 && "This node only has one result!"); // An unnamed VTSDNode represents itself as an MVT::Other immediate. // // (sext_inreg GPR:$src, i16) // ~~~ if (Unnamed) return TypeSetByHwMode(MVT::Other); // With a name, the ValueType simply provides the type of the named // variable. // // (sext_inreg i32:$src, i16) // ~~~~~~~~ if (NotRegisters) return TypeSetByHwMode(); // Unknown. const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes(); return TypeSetByHwMode(getValueTypeByHwMode(R, CGH)); } if (R->isSubClassOf("CondCode")) { assert(ResNo == 0 && "This node only has one result!"); // Using a CondCodeSDNode. return TypeSetByHwMode(MVT::Other); } if (R->isSubClassOf("ComplexPattern")) { assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?"); if (NotRegisters) return TypeSetByHwMode(); // Unknown. return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType()); } if (R->isSubClassOf("PointerLikeRegClass")) { assert(ResNo == 0 && "Regclass can only have one result!"); TypeSetByHwMode VTS(MVT::iPTR); TP.getInfer().expandOverloads(VTS); return VTS; } if (R->getName() == "node" || R->getName() == "srcvalue" || R->getName() == "zero_reg") { // Placeholder. return TypeSetByHwMode(); // Unknown. } if (R->isSubClassOf("Operand")) { const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes(); Record *T = R->getValueAsDef("Type"); return TypeSetByHwMode(getValueTypeByHwMode(T, CGH)); } TP.error("Unknown node flavor used in pattern: " + R->getName()); return TypeSetByHwMode(MVT::Other); } /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the /// CodeGenIntrinsic information for it, otherwise return a null pointer. const CodeGenIntrinsic *TreePatternNode:: getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const { if (getOperator() != CDP.get_intrinsic_void_sdnode() && getOperator() != CDP.get_intrinsic_w_chain_sdnode() && getOperator() != CDP.get_intrinsic_wo_chain_sdnode()) return nullptr; unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue(); return &CDP.getIntrinsicInfo(IID); } /// getComplexPatternInfo - If this node corresponds to a ComplexPattern, /// return the ComplexPattern information, otherwise return null. const ComplexPattern * TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const { Record *Rec; if (isLeaf()) { DefInit *DI = dyn_cast<DefInit>(getLeafValue()); if (!DI) return nullptr; Rec = DI->getDef(); } else Rec = getOperator(); if (!Rec->isSubClassOf("ComplexPattern")) return nullptr; return &CGP.getComplexPattern(Rec); } unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const { // A ComplexPattern specifically declares how many results it fills in. if (const ComplexPattern *CP = getComplexPatternInfo(CGP)) return CP->getNumOperands(); // If MIOperandInfo is specified, that gives the count. if (isLeaf()) { DefInit *DI = dyn_cast<DefInit>(getLeafValue()); if (DI && DI->getDef()->isSubClassOf("Operand")) { DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo"); if (MIOps->getNumArgs()) return MIOps->getNumArgs(); } } // Otherwise there is just one result. return 1; } /// NodeHasProperty - Return true if this node has the specified property. bool TreePatternNode::NodeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const { if (isLeaf()) { if (const ComplexPattern *CP = getComplexPatternInfo(CGP)) return CP->hasProperty(Property); return false; } if (Property != SDNPHasChain) { // The chain proprety is already present on the different intrinsic node // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed // on the intrinsic. Anything else is specific to the individual intrinsic. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP)) return Int->hasProperty(Property); } if (!Operator->isSubClassOf("SDPatternOperator")) return false; return CGP.getSDNodeInfo(Operator).hasProperty(Property); } /// TreeHasProperty - Return true if any node in this tree has the specified /// property. bool TreePatternNode::TreeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const { if (NodeHasProperty(Property, CGP)) return true; for (unsigned i = 0, e = getNumChildren(); i != e; ++i) if (getChild(i)->TreeHasProperty(Property, CGP)) return true; return false; } /// isCommutativeIntrinsic - Return true if the node corresponds to a /// commutative intrinsic. bool TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const { if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) return Int->isCommutative; return false; } static bool isOperandClass(const TreePatternNode *N, StringRef Class) { if (!N->isLeaf()) return N->getOperator()->isSubClassOf(Class); DefInit *DI = dyn_cast<DefInit>(N->getLeafValue()); if (DI && DI->getDef()->isSubClassOf(Class)) return true; return false; } static void emitTooManyOperandsError(TreePattern &TP, StringRef InstName, unsigned Expected, unsigned Actual) { TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) + " operands but expected only " + Twine(Expected) + "!"); } static void emitTooFewOperandsError(TreePattern &TP, StringRef InstName, unsigned Actual) { TP.error("Instruction '" + InstName + "' expects more than the provided " + Twine(Actual) + " operands!"); } /// ApplyTypeConstraints - Apply all of the type constraints relevant to /// this node and its children in the tree. This returns true if it makes a /// change, false otherwise. If a type contradiction is found, flag an error. bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) { if (TP.hasError()) return false; CodeGenDAGPatterns &CDP = TP.getDAGPatterns(); if (isLeaf()) { if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) { // If it's a regclass or something else known, include the type. bool MadeChange = false; for (unsigned i = 0, e = Types.size(); i != e; ++i) MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i, NotRegisters, !hasName(), TP), TP); return MadeChange; } if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) { assert(Types.size() == 1 && "Invalid IntInit"); // Int inits are always integers. :) bool MadeChange = TP.getInfer().EnforceInteger(Types[0]); if (!TP.getInfer().isConcrete(Types[0], false)) return MadeChange; ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false); for (auto &P : VVT) { MVT::SimpleValueType VT = P.second.SimpleTy; if (VT == MVT::iPTR || VT == MVT::iPTRAny) continue; unsigned Size = MVT(VT).getSizeInBits(); // Make sure that the value is representable for this type. if (Size >= 32) continue; // Check that the value doesn't use more bits than we have. It must // either be a sign- or zero-extended equivalent of the original. int64_t SignBitAndAbove = II->getValue() >> (Size - 1); if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1) continue; TP.error("Integer value '" + Twine(II->getValue()) + "' is out of range for type '" + getEnumName(VT) + "'!"); break; } return MadeChange; } return false; } // special handling for set, which isn't really an SDNode. if (getOperator()->getName() == "set") { assert(getNumTypes() == 0 && "Set doesn't produce a value"); assert(getNumChildren() >= 2 && "Missing RHS of a set?"); unsigned NC = getNumChildren(); TreePatternNode *SetVal = getChild(NC-1); bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters); for (unsigned i = 0; i < NC-1; ++i) { TreePatternNode *Child = getChild(i); MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters); // Types of operands must match. MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP); MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP); } return MadeChange; } if (getOperator()->getName() == "implicit") { assert(getNumTypes() == 0 && "Node doesn't produce a value"); bool MadeChange = false; for (unsigned i = 0; i < getNumChildren(); ++i) MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters); return MadeChange; } if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) { bool MadeChange = false; // Apply the result type to the node. unsigned NumRetVTs = Int->IS.RetVTs.size(); unsigned NumParamVTs = Int->IS.ParamVTs.size(); for (unsigned i = 0, e = NumRetVTs; i != e; ++i) MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP); if (getNumChildren() != NumParamVTs + 1) { TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) + " operands, not " + Twine(getNumChildren() - 1) + " operands!"); return false; } // Apply type info to the intrinsic ID. MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP); for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) { MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters); MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i]; assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case"); MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP); } return MadeChange; } if (getOperator()->isSubClassOf("SDNode")) { const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator()); // Check that the number of operands is sane. Negative operands -> varargs. if (NI.getNumOperands() >= 0 && getNumChildren() != (unsigned)NI.getNumOperands()) { TP.error(getOperator()->getName() + " node requires exactly " + Twine(NI.getNumOperands()) + " operands!"); return false; } bool MadeChange = false; for (unsigned i = 0, e = getNumChildren(); i != e; ++i) MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters); MadeChange |= NI.ApplyTypeConstraints(this, TP); return MadeChange; } if (getOperator()->isSubClassOf("Instruction")) { const DAGInstruction &Inst = CDP.getInstruction(getOperator()); CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(getOperator()); bool MadeChange = false; // Apply the result types to the node, these come from the things in the // (outs) list of the instruction. unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs, Inst.getNumResults()); for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP); // If the instruction has implicit defs, we apply the first one as a result. // FIXME: This sucks, it should apply all implicit defs. if (!InstInfo.ImplicitDefs.empty()) { unsigned ResNo = NumResultsToAdd; // FIXME: Generalize to multiple possible types and multiple possible // ImplicitDefs. MVT::SimpleValueType VT = InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()); if (VT != MVT::Other) MadeChange |= UpdateNodeType(ResNo, VT, TP); } // If this is an INSERT_SUBREG, constrain the source and destination VTs to // be the same. if (getOperator()->getName() == "INSERT_SUBREG") { assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled"); MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP); MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP); } else if (getOperator()->getName() == "REG_SEQUENCE") { // We need to do extra, custom typechecking for REG_SEQUENCE since it is // variadic. unsigned NChild = getNumChildren(); if (NChild < 3) { TP.error("REG_SEQUENCE requires at least 3 operands!"); return false; } if (NChild % 2 == 0) { TP.error("REG_SEQUENCE requires an odd number of operands!"); return false; } if (!isOperandClass(getChild(0), "RegisterClass")) { TP.error("REG_SEQUENCE requires a RegisterClass for first operand!"); return false; } for (unsigned I = 1; I < NChild; I += 2) { TreePatternNode *SubIdxChild = getChild(I + 1); if (!isOperandClass(SubIdxChild, "SubRegIndex")) { TP.error("REG_SEQUENCE requires a SubRegIndex for operand " + Twine(I + 1) + "!"); return false; } } } unsigned ChildNo = 0; for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) { Record *OperandNode = Inst.getOperand(i); // If the instruction expects a predicate or optional def operand, we // codegen this by setting the operand to it's default value if it has a // non-empty DefaultOps field. if (OperandNode->isSubClassOf("OperandWithDefaultOps") && !CDP.getDefaultOperand(OperandNode).DefaultOps.empty()) continue; // Verify that we didn't run out of provided operands. if (ChildNo >= getNumChildren()) { emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren()); return false; } TreePatternNode *Child = getChild(ChildNo++); unsigned ChildResNo = 0; // Instructions always use res #0 of their op. // If the operand has sub-operands, they may be provided by distinct // child patterns, so attempt to match each sub-operand separately. if (OperandNode->isSubClassOf("Operand")) { DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo"); if (unsigned NumArgs = MIOpInfo->getNumArgs()) { // But don't do that if the whole operand is being provided by // a single ComplexPattern-related Operand. if (Child->getNumMIResults(CDP) < NumArgs) { // Match first sub-operand against the child we already have. Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef(); MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP); // And the remaining sub-operands against subsequent children. for (unsigned Arg = 1; Arg < NumArgs; ++Arg) { if (ChildNo >= getNumChildren()) { emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren()); return false; } Child = getChild(ChildNo++); SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef(); MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP); } continue; } } } // If we didn't match by pieces above, attempt to match the whole // operand now. MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP); } if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) { emitTooManyOperandsError(TP, getOperator()->getName(), ChildNo, getNumChildren()); return false; } for (unsigned i = 0, e = getNumChildren(); i != e; ++i) MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters); return MadeChange; } if (getOperator()->isSubClassOf("ComplexPattern")) { bool MadeChange = false; for (unsigned i = 0; i < getNumChildren(); ++i) MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters); return MadeChange; } assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!"); // Node transforms always take one operand. if (getNumChildren() != 1) { TP.error("Node transform '" + getOperator()->getName() + "' requires one operand!"); return false; } bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters); return MadeChange; } /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the /// RHS of a commutative operation, not the on LHS. static bool OnlyOnRHSOfCommutative(TreePatternNode *N) { if (!N->isLeaf() && N->getOperator()->getName() == "imm") return true; if (N->isLeaf() && isa<IntInit>(N->getLeafValue())) return true; return false; } /// canPatternMatch - If it is impossible for this pattern to match on this /// target, fill in Reason and return false. Otherwise, return true. This is /// used as a sanity check for .td files (to prevent people from writing stuff /// that can never possibly work), and to prevent the pattern permuter from /// generating stuff that is useless. bool TreePatternNode::canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP) { if (isLeaf()) return true; for (unsigned i = 0, e = getNumChildren(); i != e; ++i) if (!getChild(i)->canPatternMatch(Reason, CDP)) return false; // If this is an intrinsic, handle cases that would make it not match. For // example, if an operand is required to be an immediate. if (getOperator()->isSubClassOf("Intrinsic")) { // TODO: return true; } if (getOperator()->isSubClassOf("ComplexPattern")) return true; // If this node is a commutative operator, check that the LHS isn't an // immediate. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator()); bool isCommIntrinsic = isCommutativeIntrinsic(CDP); if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) { // Scan all of the operands of the node and make sure that only the last one // is a constant node, unless the RHS also is. if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) { unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id. for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i) if (OnlyOnRHSOfCommutative(getChild(i))) { Reason="Immediate value must be on the RHS of commutative operators!"; return false; } } } return true; } //===----------------------------------------------------------------------===// // TreePattern implementation // TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput, CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false), Infer(*this) { for (Init *I : RawPat->getValues()) Trees.push_back(ParseTreePattern(I, "")); } TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput, CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false), Infer(*this) { Trees.push_back(ParseTreePattern(Pat, "")); } TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput, CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false), Infer(*this) { Trees.push_back(Pat); } void TreePattern::error(const Twine &Msg) { if (HasError) return; dump(); PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg); HasError = true; } void TreePattern::ComputeNamedNodes() { for (TreePatternNodePtr &Tree : Trees) ComputeNamedNodes(Tree.get()); } void TreePattern::ComputeNamedNodes(TreePatternNode *N) { if (!N->getName().empty()) NamedNodes[N->getName()].push_back(N); for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) ComputeNamedNodes(N->getChild(i)); } TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName) { if (DefInit *DI = dyn_cast<DefInit>(TheInit)) { Record *R = DI->getDef(); // Direct reference to a leaf DagNode or PatFrag? Turn it into a // TreePatternNode of its own. For example: /// (foo GPR, imm) -> (foo GPR, (imm)) if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) return ParseTreePattern( DagInit::get(DI, nullptr, std::vector<std::pair<Init*, StringInit*> >()), OpName); // Input argument? TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1); if (R->getName() == "node" && !OpName.empty()) { if (OpName.empty()) error("'node' argument requires a name to match with operand list"); Args.push_back(OpName); } Res->setName(OpName); return Res; } // ?:$name or just $name. if (isa<UnsetInit>(TheInit)) { if (OpName.empty()) error("'?' argument requires a name to match with operand list"); TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1); Args.push_back(OpName); Res->setName(OpName); return Res; } if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) { if (!OpName.empty()) error("Constant int or bit argument should not have a name!"); if (isa<BitInit>(TheInit)) TheInit = TheInit->convertInitializerTo(IntRecTy::get()); return std::make_shared<TreePatternNode>(TheInit, 1); } if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) { // Turn this into an IntInit. Init *II = BI->convertInitializerTo(IntRecTy::get()); if (!II || !isa<IntInit>(II)) error("Bits value must be constants!"); return ParseTreePattern(II, OpName); } DagInit *Dag = dyn_cast<DagInit>(TheInit); if (!Dag) { TheInit->print(errs()); error("Pattern has unexpected init kind!"); } DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator()); if (!OpDef) error("Pattern has unexpected operator type!"); Record *Operator = OpDef->getDef(); if (Operator->isSubClassOf("ValueType")) { // If the operator is a ValueType, then this must be "type cast" of a leaf // node. if (Dag->getNumArgs() != 1) error("Type cast only takes one operand!"); TreePatternNodePtr New = ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0)); // Apply the type cast. assert(New->getNumTypes() == 1 && "FIXME: Unhandled"); const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes(); New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this); if (!OpName.empty()) error("ValueType cast should not have a name!"); return New; } // Verify that this is something that makes sense for an operator. if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") && !Operator->isSubClassOf("Instruction") && !Operator->isSubClassOf("SDNodeXForm") && !Operator->isSubClassOf("Intrinsic") && !Operator->isSubClassOf("ComplexPattern") && Operator->getName() != "set" && Operator->getName() != "implicit") error("Unrecognized node '" + Operator->getName() + "'!"); // Check to see if this is something that is illegal in an input pattern. if (isInputPattern) { if (Operator->isSubClassOf("Instruction") || Operator->isSubClassOf("SDNodeXForm")) error("Cannot use '" + Operator->getName() + "' in an input pattern!"); } else { if (Operator->isSubClassOf("Intrinsic")) error("Cannot use '" + Operator->getName() + "' in an output pattern!"); if (Operator->isSubClassOf("SDNode") && Operator->getName() != "imm" && Operator->getName() != "fpimm" && Operator->getName() != "tglobaltlsaddr" && Operator->getName() != "tconstpool" && Operator->getName() != "tjumptable" && Operator->getName() != "tframeindex" && Operator->getName() != "texternalsym" && Operator->getName() != "tblockaddress" && Operator->getName() != "tglobaladdr" && Operator->getName() != "bb" && Operator->getName() != "vt" && Operator->getName() != "mcsym") error("Cannot use '" + Operator->getName() + "' in an output pattern!"); } std::vector<TreePatternNodePtr> Children; // Parse all the operands. for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i))); // Get the actual number of results before Operator is converted to an intrinsic // node (which is hard-coded to have either zero or one result). unsigned NumResults = GetNumNodeResults(Operator, CDP); // If the operator is an intrinsic, then this is just syntactic sugar for // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and // convert the intrinsic name to a number. if (Operator->isSubClassOf("Intrinsic")) { const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator); unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1; // If this intrinsic returns void, it must have side-effects and thus a // chain. if (Int.IS.RetVTs.empty()) Operator = getDAGPatterns().get_intrinsic_void_sdnode(); else if (Int.ModRef != CodeGenIntrinsic::NoMem) // Has side-effects, requires chain. Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode(); else // Otherwise, no chain. Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode(); Children.insert(Children.begin(), std::make_shared<TreePatternNode>(IntInit::get(IID), 1)); } if (Operator->isSubClassOf("ComplexPattern")) { for (unsigned i = 0; i < Children.size(); ++i) { TreePatternNodePtr Child = Children[i]; if (Child->getName().empty()) error("All arguments to a ComplexPattern must be named"); // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)" // and "(MY_PAT $b, $a)" should not be allowed in the same pattern; // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)". auto OperandId = std::make_pair(Operator, i); auto PrevOp = ComplexPatternOperands.find(Child->getName()); if (PrevOp != ComplexPatternOperands.end()) { if (PrevOp->getValue() != OperandId) error("All ComplexPattern operands must appear consistently: " "in the same order in just one ComplexPattern instance."); } else ComplexPatternOperands[Child->getName()] = OperandId; } } TreePatternNodePtr Result = std::make_shared<TreePatternNode>(Operator, Children, NumResults); Result->setName(OpName); if (Dag->getName()) { assert(Result->getName().empty()); Result->setName(Dag->getNameStr()); } return Result; } /// SimplifyTree - See if we can simplify this tree to eliminate something that /// will never match in favor of something obvious that will. This is here /// strictly as a convenience to target authors because it allows them to write /// more type generic things and have useless type casts fold away. /// /// This returns true if any change is made. static bool SimplifyTree(TreePatternNodePtr &N) { if (N->isLeaf()) return false; // If we have a bitconvert with a resolved type and if the source and // destination types are the same, then the bitconvert is useless, remove it. if (N->getOperator()->getName() == "bitconvert" && N->getExtType(0).isValueTypeByHwMode(false) && N->getExtType(0) == N->getChild(0)->getExtType(0) && N->getName().empty()) { N = N->getChildShared(0); SimplifyTree(N); return true; } // Walk all children. bool MadeChange = false; for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) { TreePatternNodePtr Child = N->getChildShared(i); MadeChange |= SimplifyTree(Child); N->setChild(i, std::move(Child)); } return MadeChange; } /// InferAllTypes - Infer/propagate as many types throughout the expression /// patterns as possible. Return true if all types are inferred, false /// otherwise. Flags an error if a type contradiction is found. bool TreePattern:: InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) { if (NamedNodes.empty()) ComputeNamedNodes(); bool MadeChange = true; while (MadeChange) { MadeChange = false; for (TreePatternNodePtr &Tree : Trees) { MadeChange |= Tree->ApplyTypeConstraints(*this, false); MadeChange |= SimplifyTree(Tree); } // If there are constraints on our named nodes, apply them. for (auto &Entry : NamedNodes) { SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second; // If we have input named node types, propagate their types to the named // values here. if (InNamedTypes) { if (!InNamedTypes->count(Entry.getKey())) { error("Node '" + std::string(Entry.getKey()) + "' in output pattern but not input pattern"); return true; } const SmallVectorImpl<TreePatternNode*> &InNodes = InNamedTypes->find(Entry.getKey())->second; // The input types should be fully resolved by now. for (TreePatternNode *Node : Nodes) { // If this node is a register class, and it is the root of the pattern // then we're mapping something onto an input register. We allow // changing the type of the input register in this case. This allows // us to match things like: // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>; if (Node == Trees[0].get() && Node->isLeaf()) { DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue()); if (DI && (DI->getDef()->isSubClassOf("RegisterClass") || DI->getDef()->isSubClassOf("RegisterOperand"))) continue; } assert(Node->getNumTypes() == 1 && InNodes[0]->getNumTypes() == 1 && "FIXME: cannot name multiple result nodes yet"); MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0), *this); } } // If there are multiple nodes with the same name, they must all have the // same type. if (Entry.second.size() > 1) { for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) { TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1]; assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 && "FIXME: cannot name multiple result nodes yet"); MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this); MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this); } } } } bool HasUnresolvedTypes = false; for (const TreePatternNodePtr &Tree : Trees) HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this); return !HasUnresolvedTypes; } void TreePattern::print(raw_ostream &OS) const { OS << getRecord()->getName(); if (!Args.empty()) { OS << "(" << Args[0]; for (unsigned i = 1, e = Args.size(); i != e; ++i) OS << ", " << Args[i]; OS << ")"; } OS << ": "; if (Trees.size() > 1) OS << "[\n"; for (const TreePatternNodePtr &Tree : Trees) { OS << "\t"; Tree->print(OS); OS << "\n"; } if (Trees.size() > 1) OS << "]\n"; } void TreePattern::dump() const { print(errs()); } //===----------------------------------------------------------------------===// // CodeGenDAGPatterns implementation // CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R, PatternRewriterFn PatternRewriter) : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()), PatternRewriter(PatternRewriter) { Intrinsics = CodeGenIntrinsicTable(Records, false); TgtIntrinsics = CodeGenIntrinsicTable(Records, true); ParseNodeInfo(); ParseNodeTransforms(); ParseComplexPatterns(); ParsePatternFragments(); ParseDefaultOperands(); ParseInstructions(); ParsePatternFragments(/*OutFrags*/true); ParsePatterns(); // Break patterns with parameterized types into a series of patterns, // where each one has a fixed type and is predicated on the conditions // of the associated HW mode. ExpandHwModeBasedTypes(); // Generate variants. For example, commutative patterns can match // multiple ways. Add them to PatternsToMatch as well. GenerateVariants(); // Infer instruction flags. For example, we can detect loads, // stores, and side effects in many cases by examining an // instruction's pattern. InferInstructionFlags(); // Verify that instruction flags match the patterns. VerifyInstructionFlags(); } Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const { Record *N = Records.getDef(Name); if (!N || !N->isSubClassOf("SDNode")) PrintFatalError("Error getting SDNode '" + Name + "'!"); return N; } // Parse all of the SDNode definitions for the target, populating SDNodes. void CodeGenDAGPatterns::ParseNodeInfo() { std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode"); const CodeGenHwModes &CGH = getTargetInfo().getHwModes(); while (!Nodes.empty()) { Record *R = Nodes.back(); SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH))); Nodes.pop_back(); } // Get the builtin intrinsic nodes. intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void"); intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain"); intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain"); } /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms /// map, and emit them to the file as functions. void CodeGenDAGPatterns::ParseNodeTransforms() { std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm"); while (!Xforms.empty()) { Record *XFormNode = Xforms.back(); Record *SDNode = XFormNode->getValueAsDef("Opcode"); StringRef Code = XFormNode->getValueAsString("XFormFunction"); SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code))); Xforms.pop_back(); } } void CodeGenDAGPatterns::ParseComplexPatterns() { std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern"); while (!AMs.empty()) { ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back())); AMs.pop_back(); } } /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td /// file, building up the PatternFragments map. After we've collected them all, /// inline fragments together as necessary, so that there are no references left /// inside a pattern fragment to a pattern fragment. /// void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) { std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag"); // First step, parse all of the fragments. for (Record *Frag : Fragments) { if (OutFrags != Frag->isSubClassOf("OutPatFrag")) continue; DagInit *Tree = Frag->getValueAsDag("Fragment"); TreePattern *P = (PatternFragments[Frag] = llvm::make_unique<TreePattern>( Frag, Tree, !Frag->isSubClassOf("OutPatFrag"), *this)).get(); // Validate the argument list, converting it to set, to discard duplicates. std::vector<std::string> &Args = P->getArgList(); // Copy the args so we can take StringRefs to them. auto ArgsCopy = Args; SmallDenseSet<StringRef, 4> OperandsSet; OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end()); if (OperandsSet.count("")) P->error("Cannot have unnamed 'node' values in pattern fragment!"); // Parse the operands list. DagInit *OpsList = Frag->getValueAsDag("Operands"); DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator()); // Special cases: ops == outs == ins. Different names are used to // improve readability. if (!OpsOp || (OpsOp->getDef()->getName() != "ops" && OpsOp->getDef()->getName() != "outs" && OpsOp->getDef()->getName() != "ins")) P->error("Operands list should start with '(ops ... '!"); // Copy over the arguments. Args.clear(); for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) { if (!isa<DefInit>(OpsList->getArg(j)) || cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node") P->error("Operands list should all be 'node' values."); if (!OpsList->getArgName(j)) P->error("Operands list should have names for each operand!"); StringRef ArgNameStr = OpsList->getArgNameStr(j); if (!OperandsSet.count(ArgNameStr)) P->error("'" + ArgNameStr + "' does not occur in pattern or was multiply specified!"); OperandsSet.erase(ArgNameStr); Args.push_back(ArgNameStr); } if (!OperandsSet.empty()) P->error("Operands list does not contain an entry for operand '" + *OperandsSet.begin() + "'!"); // If there is a code init for this fragment, keep track of the fact that // this fragment uses it. TreePredicateFn PredFn(P); if (!PredFn.isAlwaysTrue()) P->getOnlyTree()->addPredicateFn(PredFn); // If there is a node transformation corresponding to this, keep track of // it. Record *Transform = Frag->getValueAsDef("OperandTransform"); if (!getSDNodeTransform(Transform).second.empty()) // not noop xform? P->getOnlyTree()->setTransformFn(Transform); } // Now that we've parsed all of the tree fragments, do a closure on them so // that there are not references to PatFrags left inside of them. for (Record *Frag : Fragments) { if (OutFrags != Frag->isSubClassOf("OutPatFrag")) continue; TreePattern &ThePat = *PatternFragments[Frag]; ThePat.InlinePatternFragments(); // Infer as many types as possible. Don't worry about it if we don't infer // all of them, some may depend on the inputs of the pattern. ThePat.InferAllTypes(); ThePat.resetError(); // If debugging, print out the pattern fragment result. LLVM_DEBUG(ThePat.dump()); } } void CodeGenDAGPatterns::ParseDefaultOperands() { std::vector<Record*> DefaultOps; DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps"); // Find some SDNode. assert(!SDNodes.empty() && "No SDNodes parsed?"); Init *SomeSDNode = DefInit::get(SDNodes.begin()->first); for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) { DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps"); // Clone the DefaultInfo dag node, changing the operator from 'ops' to // SomeSDnode so that we can parse this. std::vector<std::pair<Init*, StringInit*> > Ops; for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op) Ops.push_back(std::make_pair(DefaultInfo->getArg(op), DefaultInfo->getArgName(op))); DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops); // Create a TreePattern to parse this. TreePattern P(DefaultOps[i], DI, false, *this); assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!"); // Copy the operands over into a DAGDefaultOperand. DAGDefaultOperand DefaultOpInfo; const TreePatternNodePtr &T = P.getTree(0); for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) { TreePatternNodePtr TPN = T->getChildShared(op); while (TPN->ApplyTypeConstraints(P, false)) /* Resolve all types */; if (TPN->ContainsUnresolvedType(P)) { PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" + DefaultOps[i]->getName() + "' doesn't have a concrete type!"); } DefaultOpInfo.DefaultOps.push_back(std::move(TPN)); } // Insert it into the DefaultOperands map so we can find it later. DefaultOperands[DefaultOps[i]] = DefaultOpInfo; } } /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an /// instruction input. Return true if this is a real use. static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat, std::map<std::string, TreePatternNodePtr> &InstInputs) { // No name -> not interesting. if (Pat->getName().empty()) { if (Pat->isLeaf()) { DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue()); if (DI && (DI->getDef()->isSubClassOf("RegisterClass") || DI->getDef()->isSubClassOf("RegisterOperand"))) I.error("Input " + DI->getDef()->getName() + " must be named!"); } return false; } Record *Rec; if (Pat->isLeaf()) { DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue()); if (!DI) I.error("Input $" + Pat->getName() + " must be an identifier!"); Rec = DI->getDef(); } else { Rec = Pat->getOperator(); } // SRCVALUE nodes are ignored. if (Rec->getName() == "srcvalue") return false; TreePatternNodePtr &Slot = InstInputs[Pat->getName()]; if (!Slot) { Slot = Pat; return true; } Record *SlotRec; if (Slot->isLeaf()) { SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef(); } else { assert(Slot->getNumChildren() == 0 && "can't be a use with children!"); SlotRec = Slot->getOperator(); } // Ensure that the inputs agree if we've already seen this input. if (Rec != SlotRec) I.error("All $" + Pat->getName() + " inputs must agree with each other"); if (Slot->getExtTypes() != Pat->getExtTypes()) I.error("All $" + Pat->getName() + " inputs must agree with each other"); return true; } /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is /// part of "I", the instruction), computing the set of inputs and outputs of /// the pattern. Report errors if we see anything naughty. void CodeGenDAGPatterns::FindPatternInputsAndOutputs( TreePattern &I, TreePatternNodePtr Pat, std::map<std::string, TreePatternNodePtr> &InstInputs, std::map<std::string, TreePatternNodePtr> &InstResults, std::vector<Record *> &InstImpResults) { if (Pat->isLeaf()) { bool isUse = HandleUse(I, Pat, InstInputs); if (!isUse && Pat->getTransformFn()) I.error("Cannot specify a transform function for a non-input value!"); return; } if (Pat->getOperator()->getName() == "implicit") { for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) { TreePatternNode *Dest = Pat->getChild(i); if (!Dest->isLeaf()) I.error("implicitly defined value should be a register!"); DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue()); if (!Val || !Val->getDef()->isSubClassOf("Register")) I.error("implicitly defined value should be a register!"); InstImpResults.push_back(Val->getDef()); } return; } if (Pat->getOperator()->getName() != "set") { // If this is not a set, verify that the children nodes are not void typed, // and recurse. for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) { if (Pat->getChild(i)->getNumTypes() == 0) I.error("Cannot have void nodes inside of patterns!"); FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs, InstResults, InstImpResults); } // If this is a non-leaf node with no children, treat it basically as if // it were a leaf. This handles nodes like (imm). bool isUse = HandleUse(I, Pat, InstInputs); if (!isUse && Pat->getTransformFn()) I.error("Cannot specify a transform function for a non-input value!"); return; } // Otherwise, this is a set, validate and collect instruction results. if (Pat->getNumChildren() == 0) I.error("set requires operands!"); if (Pat->getTransformFn()) I.error("Cannot specify a transform function on a set node!"); // Check the set destinations. unsigned NumDests = Pat->getNumChildren()-1; for (unsigned i = 0; i != NumDests; ++i) { TreePatternNodePtr Dest = Pat->getChildShared(i); if (!Dest->isLeaf()) I.error("set destination should be a register!"); DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue()); if (!Val) { I.error("set destination should be a register!"); continue; } if (Val->getDef()->isSubClassOf("RegisterClass") || Val->getDef()->isSubClassOf("ValueType") || Val->getDef()->isSubClassOf("RegisterOperand") || Val->getDef()->isSubClassOf("PointerLikeRegClass")) { if (Dest->getName().empty()) I.error("set destination must have a name!"); if (InstResults.count(Dest->getName())) I.error("cannot set '" + Dest->getName() + "' multiple times"); InstResults[Dest->getName()] = Dest; } else if (Val->getDef()->isSubClassOf("Register")) { InstImpResults.push_back(Val->getDef()); } else { I.error("set destination should be a register!"); } } // Verify and collect info from the computation. FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs, InstResults, InstImpResults); } //===----------------------------------------------------------------------===// // Instruction Analysis //===----------------------------------------------------------------------===// class InstAnalyzer { const CodeGenDAGPatterns &CDP; public: bool hasSideEffects; bool mayStore; bool mayLoad; bool isBitcast; bool isVariadic; InstAnalyzer(const CodeGenDAGPatterns &cdp) : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false), isBitcast(false), isVariadic(false) {} void Analyze(const TreePattern *Pat) { // Assume only the first tree is the pattern. The others are clobber nodes. AnalyzeNode(Pat->getTree(0).get()); } void Analyze(const PatternToMatch &Pat) { AnalyzeNode(Pat.getSrcPattern()); } private: bool IsNodeBitcast(const TreePatternNode *N) const { if (hasSideEffects || mayLoad || mayStore || isVariadic) return false; if (N->getNumChildren() != 2) return false; const TreePatternNode *N0 = N->getChild(0); if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue())) return false; const TreePatternNode *N1 = N->getChild(1); if (N1->isLeaf()) return false; if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf()) return false; const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator()); if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1) return false; return OpInfo.getEnumName() == "ISD::BITCAST"; } public: void AnalyzeNode(const TreePatternNode *N) { if (N->isLeaf()) { if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) { Record *LeafRec = DI->getDef(); // Handle ComplexPattern leaves. if (LeafRec->isSubClassOf("ComplexPattern")) { const ComplexPattern &CP = CDP.getComplexPattern(LeafRec); if (CP.hasProperty(SDNPMayStore)) mayStore = true; if (CP.hasProperty(SDNPMayLoad)) mayLoad = true; if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true; } } return; } // Analyze children. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) AnalyzeNode(N->getChild(i)); // Ignore set nodes, which are not SDNodes. if (N->getOperator()->getName() == "set") { isBitcast = IsNodeBitcast(N); return; } // Notice properties of the node. if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true; if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true; if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true; if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true; if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) { // If this is an intrinsic, analyze it. if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref) mayLoad = true;// These may load memory. if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod) mayStore = true;// Intrinsics that can write to memory are 'mayStore'. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem || IntInfo->hasSideEffects) // ReadWriteMem intrinsics can have other strange effects. hasSideEffects = true; } } }; static bool InferFromPattern(CodeGenInstruction &InstInfo, const InstAnalyzer &PatInfo, Record *PatDef) { bool Error = false; // Remember where InstInfo got its flags. if (InstInfo.hasUndefFlags()) InstInfo.InferredFrom = PatDef; // Check explicitly set flags for consistency. if (InstInfo.hasSideEffects != PatInfo.hasSideEffects && !InstInfo.hasSideEffects_Unset) { // Allow explicitly setting hasSideEffects = 1 on instructions, even when // the pattern has no side effects. That could be useful for div/rem // instructions that may trap. if (!InstInfo.hasSideEffects) { Error = true; PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " + Twine(InstInfo.hasSideEffects)); } } if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) { Error = true; PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " + Twine(InstInfo.mayStore)); } if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) { // Allow explicitly setting mayLoad = 1, even when the pattern has no loads. // Some targets translate immediates to loads. if (!InstInfo.mayLoad) { Error = true; PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " + Twine(InstInfo.mayLoad)); } } // Transfer inferred flags. InstInfo.hasSideEffects |= PatInfo.hasSideEffects; InstInfo.mayStore |= PatInfo.mayStore; InstInfo.mayLoad |= PatInfo.mayLoad; // These flags are silently added without any verification. InstInfo.isBitcast |= PatInfo.isBitcast; // Don't infer isVariadic. This flag means something different on SDNodes and // instructions. For example, a CALL SDNode is variadic because it has the // call arguments as operands, but a CALL instruction is not variadic - it // has argument registers as implicit, not explicit uses. return Error; } /// hasNullFragReference - Return true if the DAG has any reference to the /// null_frag operator. static bool hasNullFragReference(DagInit *DI) { DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator()); if (!OpDef) return false; Record *Operator = OpDef->getDef(); // If this is the null fragment, return true. if (Operator->getName() == "null_frag") return true; // If any of the arguments reference the null fragment, return true. for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) { DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i)); if (Arg && hasNullFragReference(Arg)) return true; } return false; } /// hasNullFragReference - Return true if any DAG in the list references /// the null_frag operator. static bool hasNullFragReference(ListInit *LI) { for (Init *I : LI->getValues()) { DagInit *DI = dyn_cast<DagInit>(I); assert(DI && "non-dag in an instruction Pattern list?!"); if (hasNullFragReference(DI)) return true; } return false; } /// Get all the instructions in a tree. static void getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) { if (Tree->isLeaf()) return; if (Tree->getOperator()->isSubClassOf("Instruction")) Instrs.push_back(Tree->getOperator()); for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i) getInstructionsInTree(Tree->getChild(i), Instrs); } /// Check the class of a pattern leaf node against the instruction operand it /// represents. static bool checkOperandClass(CGIOperandList::OperandInfo &OI, Record *Leaf) { if (OI.Rec == Leaf) return true; // Allow direct value types to be used in instruction set patterns. // The type will be checked later. if (Leaf->isSubClassOf("ValueType")) return true; // Patterns can also be ComplexPattern instances. if (Leaf->isSubClassOf("ComplexPattern")) return true; return false; } const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern( CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) { assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!"); // Parse the instruction. auto I = llvm::make_unique<TreePattern>(CGI.TheDef, Pat, true, *this); // Inline pattern fragments into it. I->InlinePatternFragments(); // Infer as many types as possible. If we cannot infer all of them, we can // never do anything with this instruction pattern: report it to the user. if (!I->InferAllTypes()) I->error("Could not infer all types in pattern!"); // InstInputs - Keep track of all of the inputs of the instruction, along // with the record they are declared as. std::map<std::string, TreePatternNodePtr> InstInputs; // InstResults - Keep track of all the virtual registers that are 'set' // in the instruction, including what reg class they are. std::map<std::string, TreePatternNodePtr> InstResults; std::vector<Record*> InstImpResults; // Verify that the top-level forms in the instruction are of void type, and // fill in the InstResults map. SmallString<32> TypesString; for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) { TypesString.clear(); TreePatternNodePtr Pat = I->getTree(j); if (Pat->getNumTypes() != 0) { raw_svector_ostream OS(TypesString); for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) { if (k > 0) OS << ", "; Pat->getExtType(k).writeToStream(OS); } I->error("Top-level forms in instruction pattern should have" " void types, has types " + OS.str()); } // Find inputs and outputs, and verify the structure of the uses/defs. FindPatternInputsAndOutputs(*I, Pat, InstInputs, InstResults, InstImpResults); } // Now that we have inputs and outputs of the pattern, inspect the operands // list for the instruction. This determines the order that operands are // added to the machine instruction the node corresponds to. unsigned NumResults = InstResults.size(); // Parse the operands list from the (ops) list, validating it. assert(I->getArgList().empty() && "Args list should still be empty here!"); // Check that all of the results occur first in the list. std::vector<Record*> Results; SmallVector<TreePatternNodePtr, 2> ResNodes; for (unsigned i = 0; i != NumResults; ++i) { if (i == CGI.Operands.size()) I->error("'" + InstResults.begin()->first + "' set but does not appear in operand list!"); const std::string &OpName = CGI.Operands[i].Name; // Check that it exists in InstResults. TreePatternNodePtr RNode = InstResults[OpName]; if (!RNode) I->error("Operand $" + OpName + " does not exist in operand list!"); Record *R = cast<DefInit>(RNode->getLeafValue())->getDef(); ResNodes.push_back(std::move(RNode)); if (!R) I->error("Operand $" + OpName + " should be a set destination: all " "outputs must occur before inputs in operand list!"); if (!checkOperandClass(CGI.Operands[i], R)) I->error("Operand $" + OpName + " class mismatch!"); // Remember the return type. Results.push_back(CGI.Operands[i].Rec); // Okay, this one checks out. InstResults.erase(OpName); } // Loop over the inputs next. Make a copy of InstInputs so we can destroy // the copy while we're checking the inputs. std::map<std::string, TreePatternNodePtr> InstInputsCheck(InstInputs); std::vector<TreePatternNodePtr> ResultNodeOperands; std::vector<Record*> Operands; for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) { CGIOperandList::OperandInfo &Op = CGI.Operands[i]; const std::string &OpName = Op.Name; if (OpName.empty()) I->error("Operand #" + Twine(i) + " in operands list has no name!"); if (!InstInputsCheck.count(OpName)) { // If this is an operand with a DefaultOps set filled in, we can ignore // this. When we codegen it, we will do so as always executed. if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) { // Does it have a non-empty DefaultOps field? If so, ignore this // operand. if (!getDefaultOperand(Op.Rec).DefaultOps.empty()) continue; } I->error("Operand $" + OpName + " does not appear in the instruction pattern"); } TreePatternNodePtr InVal = InstInputsCheck[OpName]; InstInputsCheck.erase(OpName); // It occurred, remove from map. if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) { Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef(); if (!checkOperandClass(Op, InRec)) I->error("Operand $" + OpName + "'s register class disagrees" " between the operand and pattern"); } Operands.push_back(Op.Rec); // Construct the result for the dest-pattern operand list. TreePatternNodePtr OpNode = InVal->clone(); // No predicate is useful on the result. OpNode->clearPredicateFns(); // Promote the xform function to be an explicit node if set. if (Record *Xform = OpNode->getTransformFn()) { OpNode->setTransformFn(nullptr); std::vector<TreePatternNodePtr> Children; Children.push_back(OpNode); OpNode = std::make_shared<TreePatternNode>(Xform, Children, OpNode->getNumTypes()); } ResultNodeOperands.push_back(std::move(OpNode)); } if (!InstInputsCheck.empty()) I->error("Input operand $" + InstInputsCheck.begin()->first + " occurs in pattern but not in operands list!"); TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>( I->getRecord(), ResultNodeOperands, GetNumNodeResults(I->getRecord(), *this)); // Copy fully inferred output node types to instruction result pattern. for (unsigned i = 0; i != NumResults; ++i) { assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled"); ResultPattern->setType(i, ResNodes[i]->getExtType(0)); } // Create and insert the instruction. // FIXME: InstImpResults should not be part of DAGInstruction. Record *R = I->getRecord(); DAGInstruction &TheInst = DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R), std::forward_as_tuple(std::move(I), Results, Operands, InstImpResults)).first->second; // Use a temporary tree pattern to infer all types and make sure that the // constructed result is correct. This depends on the instruction already // being inserted into the DAGInsts map. TreePattern Temp(TheInst.getPattern()->getRecord(), ResultPattern, false, *this); Temp.InferAllTypes(&TheInst.getPattern()->getNamedNodesMap()); TheInst.setResultPattern(Temp.getOnlyTree()); return TheInst; } /// ParseInstructions - Parse all of the instructions, inlining and resolving /// any fragments involved. This populates the Instructions list with fully /// resolved instructions. void CodeGenDAGPatterns::ParseInstructions() { std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction"); for (Record *Instr : Instrs) { ListInit *LI = nullptr; if (isa<ListInit>(Instr->getValueInit("Pattern"))) LI = Instr->getValueAsListInit("Pattern"); // If there is no pattern, only collect minimal information about the // instruction for its operand list. We have to assume that there is one // result, as we have no detailed info. A pattern which references the // null_frag operator is as-if no pattern were specified. Normally this // is from a multiclass expansion w/ a SDPatternOperator passed in as // null_frag. if (!LI || LI->empty() || hasNullFragReference(LI)) { std::vector<Record*> Results; std::vector<Record*> Operands; CodeGenInstruction &InstInfo = Target.getInstruction(Instr); if (InstInfo.Operands.size() != 0) { for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j) Results.push_back(InstInfo.Operands[j].Rec); // The rest are inputs. for (unsigned j = InstInfo.Operands.NumDefs, e = InstInfo.Operands.size(); j < e; ++j) Operands.push_back(InstInfo.Operands[j].Rec); } // Create and insert the instruction. std::vector<Record*> ImpResults; Instructions.insert(std::make_pair(Instr, DAGInstruction(nullptr, Results, Operands, ImpResults))); continue; // no pattern. } CodeGenInstruction &CGI = Target.getInstruction(Instr); const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions); (void)DI; LLVM_DEBUG(DI.getPattern()->dump()); } // If we can, convert the instructions to be patterns that are matched! for (auto &Entry : Instructions) { DAGInstruction &TheInst = Entry.second; TreePattern *I = TheInst.getPattern(); if (!I) continue; // No pattern. if (PatternRewriter) PatternRewriter(I); // FIXME: Assume only the first tree is the pattern. The others are clobber // nodes. TreePatternNodePtr Pattern = I->getTree(0); TreePatternNodePtr SrcPattern; if (Pattern->getOperator()->getName() == "set") { SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone(); } else{ // Not a set (store or something?) SrcPattern = Pattern; } Record *Instr = Entry.first; ListInit *Preds = Instr->getValueAsListInit("Predicates"); int Complexity = Instr->getValueAsInt("AddedComplexity"); AddPatternToMatch( I, PatternToMatch(Instr, makePredList(Preds), SrcPattern, TheInst.getResultPattern(), TheInst.getImpResults(), Complexity, Instr->getID())); } } typedef std::pair<TreePatternNode *, unsigned> NameRecord; static void FindNames(TreePatternNode *P, std::map<std::string, NameRecord> &Names, TreePattern *PatternTop) { if (!P->getName().empty()) { NameRecord &Rec = Names[P->getName()]; // If this is the first instance of the name, remember the node. if (Rec.second++ == 0) Rec.first = P; else if (Rec.first->getExtTypes() != P->getExtTypes()) PatternTop->error("repetition of value: $" + P->getName() + " where different uses have different types!"); } if (!P->isLeaf()) { for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) FindNames(P->getChild(i), Names, PatternTop); } } std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) { std::vector<Predicate> Preds; for (Init *I : L->getValues()) { if (DefInit *Pred = dyn_cast<DefInit>(I)) Preds.push_back(Pred->getDef()); else llvm_unreachable("Non-def on the list"); } // Sort so that different orders get canonicalized to the same string. llvm::sort(Preds.begin(), Preds.end()); return Preds; } void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern, PatternToMatch &&PTM) { // Do some sanity checking on the pattern we're about to match. std::string Reason; if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) { PrintWarning(Pattern->getRecord()->getLoc(), Twine("Pattern can never match: ") + Reason); return; } // If the source pattern's root is a complex pattern, that complex pattern // must specify the nodes it can potentially match. if (const ComplexPattern *CP = PTM.getSrcPattern()->getComplexPatternInfo(*this)) if (CP->getRootNodes().empty()) Pattern->error("ComplexPattern at root must specify list of opcodes it" " could match"); // Find all of the named values in the input and output, ensure they have the // same type. std::map<std::string, NameRecord> SrcNames, DstNames; FindNames(PTM.getSrcPattern(), SrcNames, Pattern); FindNames(PTM.getDstPattern(), DstNames, Pattern); // Scan all of the named values in the destination pattern, rejecting them if // they don't exist in the input pattern. for (const auto &Entry : DstNames) { if (SrcNames[Entry.first].first == nullptr) Pattern->error("Pattern has input without matching name in output: $" + Entry.first); } // Scan all of the named values in the source pattern, rejecting them if the // name isn't used in the dest, and isn't used to tie two values together. for (const auto &Entry : SrcNames) if (DstNames[Entry.first].first == nullptr && SrcNames[Entry.first].second == 1) Pattern->error("Pattern has dead named input: $" + Entry.first); PatternsToMatch.push_back(PTM); } void CodeGenDAGPatterns::InferInstructionFlags() { ArrayRef<const CodeGenInstruction*> Instructions = Target.getInstructionsByEnumValue(); // First try to infer flags from the primary instruction pattern, if any. SmallVector<CodeGenInstruction*, 8> Revisit; unsigned Errors = 0; for (unsigned i = 0, e = Instructions.size(); i != e; ++i) { CodeGenInstruction &InstInfo = const_cast<CodeGenInstruction &>(*Instructions[i]); // Get the primary instruction pattern. const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern(); if (!Pattern) { if (InstInfo.hasUndefFlags()) Revisit.push_back(&InstInfo); continue; } InstAnalyzer PatInfo(*this); PatInfo.Analyze(Pattern); Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef); } // Second, look for single-instruction patterns defined outside the // instruction. for (const PatternToMatch &PTM : ptms()) { // We can only infer from single-instruction patterns, otherwise we won't // know which instruction should get the flags. SmallVector<Record*, 8> PatInstrs; getInstructionsInTree(PTM.getDstPattern(), PatInstrs); if (PatInstrs.size() != 1) continue; // Get the single instruction. CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front()); // Only infer properties from the first pattern. We'll verify the others. if (InstInfo.InferredFrom) continue; InstAnalyzer PatInfo(*this); PatInfo.Analyze(PTM); Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord()); } if (Errors) PrintFatalError("pattern conflicts"); // Revisit instructions with undefined flags and no pattern. if (Target.guessInstructionProperties()) { for (CodeGenInstruction *InstInfo : Revisit) { if (InstInfo->InferredFrom) continue; // The mayLoad and mayStore flags default to false. // Conservatively assume hasSideEffects if it wasn't explicit. if (InstInfo->hasSideEffects_Unset) InstInfo->hasSideEffects = true; } return; } // Complain about any flags that are still undefined. for (CodeGenInstruction *InstInfo : Revisit) { if (InstInfo->InferredFrom) continue; if (InstInfo->hasSideEffects_Unset) PrintError(InstInfo->TheDef->getLoc(), "Can't infer hasSideEffects from patterns"); if (InstInfo->mayStore_Unset) PrintError(InstInfo->TheDef->getLoc(), "Can't infer mayStore from patterns"); if (InstInfo->mayLoad_Unset) PrintError(InstInfo->TheDef->getLoc(), "Can't infer mayLoad from patterns"); } } /// Verify instruction flags against pattern node properties. void CodeGenDAGPatterns::VerifyInstructionFlags() { unsigned Errors = 0; for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) { const PatternToMatch &PTM = *I; SmallVector<Record*, 8> Instrs; getInstructionsInTree(PTM.getDstPattern(), Instrs); if (Instrs.empty()) continue; // Count the number of instructions with each flag set. unsigned NumSideEffects = 0; unsigned NumStores = 0; unsigned NumLoads = 0; for (const Record *Instr : Instrs) { const CodeGenInstruction &InstInfo = Target.getInstruction(Instr); NumSideEffects += InstInfo.hasSideEffects; NumStores += InstInfo.mayStore; NumLoads += InstInfo.mayLoad; } // Analyze the source pattern. InstAnalyzer PatInfo(*this); PatInfo.Analyze(PTM); // Collect error messages. SmallVector<std::string, 4> Msgs; // Check for missing flags in the output. // Permit extra flags for now at least. if (PatInfo.hasSideEffects && !NumSideEffects) Msgs.push_back("pattern has side effects, but hasSideEffects isn't set"); // Don't verify store flags on instructions with side effects. At least for // intrinsics, side effects implies mayStore. if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores) Msgs.push_back("pattern may store, but mayStore isn't set"); // Similarly, mayStore implies mayLoad on intrinsics. if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads) Msgs.push_back("pattern may load, but mayLoad isn't set"); // Print error messages. if (Msgs.empty()) continue; ++Errors; for (const std::string &Msg : Msgs) PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " + (Instrs.size() == 1 ? "instruction" : "output instructions")); // Provide the location of the relevant instruction definitions. for (const Record *Instr : Instrs) { if (Instr != PTM.getSrcRecord()) PrintError(Instr->getLoc(), "defined here"); const CodeGenInstruction &InstInfo = Target.getInstruction(Instr); if (InstInfo.InferredFrom && InstInfo.InferredFrom != InstInfo.TheDef && InstInfo.InferredFrom != PTM.getSrcRecord()) PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern"); } } if (Errors) PrintFatalError("Errors in DAG patterns"); } /// Given a pattern result with an unresolved type, see if we can find one /// instruction with an unresolved result type. Force this result type to an /// arbitrary element if it's possible types to converge results. static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) { if (N->isLeaf()) return false; // Analyze children. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) if (ForceArbitraryInstResultType(N->getChild(i), TP)) return true; if (!N->getOperator()->isSubClassOf("Instruction")) return false; // If this type is already concrete or completely unknown we can't do // anything. TypeInfer &TI = TP.getInfer(); for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) { if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false)) continue; // Otherwise, force its type to an arbitrary choice. if (TI.forceArbitrary(N->getExtType(i))) return true; } return false; } void CodeGenDAGPatterns::ParsePatterns() { std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern"); for (Record *CurPattern : Patterns) { DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch"); // If the pattern references the null_frag, there's nothing to do. if (hasNullFragReference(Tree)) continue; TreePattern Pattern(CurPattern, Tree, true, *this); // Inline pattern fragments into it. Pattern.InlinePatternFragments(); ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs"); if (LI->empty()) continue; // no pattern. // Parse the instruction. TreePattern Result(CurPattern, LI, false, *this); // Inline pattern fragments into it. Result.InlinePatternFragments(); if (Result.getNumTrees() != 1) Result.error("Cannot handle instructions producing instructions " "with temporaries yet!"); bool IterateInference; bool InferredAllPatternTypes, InferredAllResultTypes; do { // Infer as many types as possible. If we cannot infer all of them, we // can never do anything with this pattern: report it to the user. InferredAllPatternTypes = Pattern.InferAllTypes(&Pattern.getNamedNodesMap()); // Infer as many types as possible. If we cannot infer all of them, we // can never do anything with this pattern: report it to the user. InferredAllResultTypes = Result.InferAllTypes(&Pattern.getNamedNodesMap()); IterateInference = false; // Apply the type of the result to the source pattern. This helps us // resolve cases where the input type is known to be a pointer type (which // is considered resolved), but the result knows it needs to be 32- or // 64-bits. Infer the other way for good measure. for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(), Pattern.getTree(0)->getNumTypes()); i != e; ++i) { IterateInference = Pattern.getTree(0)->UpdateNodeType( i, Result.getTree(0)->getExtType(i), Result); IterateInference |= Result.getTree(0)->UpdateNodeType( i, Pattern.getTree(0)->getExtType(i), Result); } // If our iteration has converged and the input pattern's types are fully // resolved but the result pattern is not fully resolved, we may have a // situation where we have two instructions in the result pattern and // the instructions require a common register class, but don't care about // what actual MVT is used. This is actually a bug in our modelling: // output patterns should have register classes, not MVTs. // // In any case, to handle this, we just go through and disambiguate some // arbitrary types to the result pattern's nodes. if (!IterateInference && InferredAllPatternTypes && !InferredAllResultTypes) IterateInference = ForceArbitraryInstResultType(Result.getTree(0).get(), Result); } while (IterateInference); // Verify that we inferred enough types that we can do something with the // pattern and result. If these fire the user has to add type casts. if (!InferredAllPatternTypes) Pattern.error("Could not infer all types in pattern!"); if (!InferredAllResultTypes) { Pattern.dump(); Result.error("Could not infer all types in pattern result!"); } // Validate that the input pattern is correct. std::map<std::string, TreePatternNodePtr> InstInputs; std::map<std::string, TreePatternNodePtr> InstResults; std::vector<Record*> InstImpResults; for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j) FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs, InstResults, InstImpResults); // Promote the xform function to be an explicit node if set. const TreePatternNodePtr &DstPattern = Result.getOnlyTree(); std::vector<TreePatternNodePtr> ResultNodeOperands; for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) { TreePatternNodePtr OpNode = DstPattern->getChildShared(ii); if (Record *Xform = OpNode->getTransformFn()) { OpNode->setTransformFn(nullptr); std::vector<TreePatternNodePtr> Children; Children.push_back(OpNode); OpNode = std::make_shared<TreePatternNode>(Xform, Children, OpNode->getNumTypes()); } ResultNodeOperands.push_back(OpNode); } TreePatternNodePtr DstShared = DstPattern->isLeaf() ? DstPattern : std::make_shared<TreePatternNode>(DstPattern->getOperator(), ResultNodeOperands, DstPattern->getNumTypes()); for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i) DstShared->setType(i, Result.getOnlyTree()->getExtType(i)); TreePattern Temp(Result.getRecord(), DstShared, false, *this); Temp.InferAllTypes(); // A pattern may end up with an "impossible" type, i.e. a situation // where all types have been eliminated for some node in this pattern. // This could occur for intrinsics that only make sense for a specific // value type, and use a specific register class. If, for some mode, // that register class does not accept that type, the type inference // will lead to a contradiction, which is not an error however, but // a sign that this pattern will simply never match. if (Pattern.getTree(0)->hasPossibleType() && Temp.getOnlyTree()->hasPossibleType()) { ListInit *Preds = CurPattern->getValueAsListInit("Predicates"); int Complexity = CurPattern->getValueAsInt("AddedComplexity"); if (PatternRewriter) PatternRewriter(&Pattern); AddPatternToMatch(&Pattern, PatternToMatch(CurPattern, makePredList(Preds), Pattern.getTree(0), Temp.getOnlyTree(), std::move(InstImpResults), Complexity, CurPattern->getID())); } } } static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) { for (const TypeSetByHwMode &VTS : N->getExtTypes()) for (const auto &I : VTS) Modes.insert(I.first); for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) collectModes(Modes, N->getChild(i)); } void CodeGenDAGPatterns::ExpandHwModeBasedTypes() { const CodeGenHwModes &CGH = getTargetInfo().getHwModes(); std::map<unsigned,std::vector<Predicate>> ModeChecks; std::vector<PatternToMatch> Copy = PatternsToMatch; PatternsToMatch.clear(); auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) { TreePatternNodePtr NewSrc = P.SrcPattern->clone(); TreePatternNodePtr NewDst = P.DstPattern->clone(); if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) { return; } std::vector<Predicate> Preds = P.Predicates; const std::vector<Predicate> &MC = ModeChecks[Mode]; Preds.insert(Preds.end(), MC.begin(), MC.end()); PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc), std::move(NewDst), P.getDstRegs(), P.getAddedComplexity(), Record::getNewUID(), Mode); }; for (PatternToMatch &P : Copy) { TreePatternNodePtr SrcP = nullptr, DstP = nullptr; if (P.SrcPattern->hasProperTypeByHwMode()) SrcP = P.SrcPattern; if (P.DstPattern->hasProperTypeByHwMode()) DstP = P.DstPattern; if (!SrcP && !DstP) { PatternsToMatch.push_back(P); continue; } std::set<unsigned> Modes; if (SrcP) collectModes(Modes, SrcP.get()); if (DstP) collectModes(Modes, DstP.get()); // The predicate for the default mode needs to be constructed for each // pattern separately. // Since not all modes must be present in each pattern, if a mode m is // absent, then there is no point in constructing a check for m. If such // a check was created, it would be equivalent to checking the default // mode, except not all modes' predicates would be a part of the checking // code. The subsequently generated check for the default mode would then // have the exact same patterns, but a different predicate code. To avoid // duplicated patterns with different predicate checks, construct the // default check as a negation of all predicates that are actually present // in the source/destination patterns. std::vector<Predicate> DefaultPred; for (unsigned M : Modes) { if (M == DefaultMode) continue; if (ModeChecks.find(M) != ModeChecks.end()) continue; // Fill the map entry for this mode. const HwMode &HM = CGH.getMode(M); ModeChecks[M].emplace_back(Predicate(HM.Features, true)); // Add negations of the HM's predicates to the default predicate. DefaultPred.emplace_back(Predicate(HM.Features, false)); } for (unsigned M : Modes) { if (M == DefaultMode) continue; AppendPattern(P, M); } bool HasDefault = Modes.count(DefaultMode); if (HasDefault) AppendPattern(P, DefaultMode); } } /// Dependent variable map for CodeGenDAGPattern variant generation typedef StringMap<int> DepVarMap; static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) { if (N->isLeaf()) { if (N->hasName() && isa<DefInit>(N->getLeafValue())) DepMap[N->getName()]++; } else { for (size_t i = 0, e = N->getNumChildren(); i != e; ++i) FindDepVarsOf(N->getChild(i), DepMap); } } /// Find dependent variables within child patterns static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) { DepVarMap depcounts; FindDepVarsOf(N, depcounts); for (const auto &Pair : depcounts) { if (Pair.getValue() > 1) DepVars.insert(Pair.getKey()); } } #ifndef NDEBUG /// Dump the dependent variable set: static void DumpDepVars(MultipleUseVarSet &DepVars) { if (DepVars.empty()) { LLVM_DEBUG(errs() << "<empty set>"); } else { LLVM_DEBUG(errs() << "[ "); for (const auto &DepVar : DepVars) { LLVM_DEBUG(errs() << DepVar.getKey() << " "); } LLVM_DEBUG(errs() << "]"); } } #endif /// CombineChildVariants - Given a bunch of permutations of each child of the /// 'operator' node, put them together in all possible ways. static void CombineChildVariants( TreePatternNodePtr Orig, const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants, std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP, const MultipleUseVarSet &DepVars) { // Make sure that each operand has at least one variant to choose from. for (const auto &Variants : ChildVariants) if (Variants.empty()) return; // The end result is an all-pairs construction of the resultant pattern. std::vector<unsigned> Idxs; Idxs.resize(ChildVariants.size()); bool NotDone; do { #ifndef NDEBUG LLVM_DEBUG(if (!Idxs.empty()) { errs() << Orig->getOperator()->getName() << ": Idxs = [ "; for (unsigned Idx : Idxs) { errs() << Idx << " "; } errs() << "]\n"; }); #endif // Create the variant and add it to the output list. std::vector<TreePatternNodePtr> NewChildren; for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i) NewChildren.push_back(ChildVariants[i][Idxs[i]]); TreePatternNodePtr R = std::make_shared<TreePatternNode>( Orig->getOperator(), NewChildren, Orig->getNumTypes()); // Copy over properties. R->setName(Orig->getName()); R->setPredicateFns(Orig->getPredicateFns()); R->setTransformFn(Orig->getTransformFn()); for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i) R->setType(i, Orig->getExtType(i)); // If this pattern cannot match, do not include it as a variant. std::string ErrString; // Scan to see if this pattern has already been emitted. We can get // duplication due to things like commuting: // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a) // which are the same pattern. Ignore the dups. if (R->canPatternMatch(ErrString, CDP) && none_of(OutVariants, [&](TreePatternNodePtr Variant) { return R->isIsomorphicTo(Variant.get(), DepVars); })) OutVariants.push_back(R); // Increment indices to the next permutation by incrementing the // indices from last index backward, e.g., generate the sequence // [0, 0], [0, 1], [1, 0], [1, 1]. int IdxsIdx; for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) { if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size()) Idxs[IdxsIdx] = 0; else break; } NotDone = (IdxsIdx >= 0); } while (NotDone); } /// CombineChildVariants - A helper function for binary operators. /// static void CombineChildVariants(TreePatternNodePtr Orig, const std::vector<TreePatternNodePtr> &LHS, const std::vector<TreePatternNodePtr> &RHS, std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP, const MultipleUseVarSet &DepVars) { std::vector<std::vector<TreePatternNodePtr>> ChildVariants; ChildVariants.push_back(LHS); ChildVariants.push_back(RHS); CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars); } static void GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N, std::vector<TreePatternNodePtr> &Children) { assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!"); Record *Operator = N->getOperator(); // Only permit raw nodes. if (!N->getName().empty() || !N->getPredicateFns().empty() || N->getTransformFn()) { Children.push_back(N); return; } if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator) Children.push_back(N->getChildShared(0)); else GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children); if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator) Children.push_back(N->getChildShared(1)); else GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children); } /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of /// the (potentially recursive) pattern by using algebraic laws. /// static void GenerateVariantsOf(TreePatternNodePtr N, std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP, const MultipleUseVarSet &DepVars) { // We cannot permute leaves or ComplexPattern uses. if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) { OutVariants.push_back(N); return; } // Look up interesting info about the node. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator()); // If this node is associative, re-associate. if (NodeInfo.hasProperty(SDNPAssociative)) { // Re-associate by pulling together all of the linked operators std::vector<TreePatternNodePtr> MaximalChildren; GatherChildrenOfAssociativeOpcode(N, MaximalChildren); // Only handle child sizes of 3. Otherwise we'll end up trying too many // permutations. if (MaximalChildren.size() == 3) { // Find the variants of all of our maximal children. std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants; GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars); GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars); GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars); // There are only two ways we can permute the tree: // (A op B) op C and A op (B op C) // Within these forms, we can also permute A/B/C. // Generate legal pair permutations of A/B/C. std::vector<TreePatternNodePtr> ABVariants; std::vector<TreePatternNodePtr> BAVariants; std::vector<TreePatternNodePtr> ACVariants; std::vector<TreePatternNodePtr> CAVariants; std::vector<TreePatternNodePtr> BCVariants; std::vector<TreePatternNodePtr> CBVariants; CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars); CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars); CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars); CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars); CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars); CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars); // Combine those into the result: (x op x) op x CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars); CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars); CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars); CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars); CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars); CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars); // Combine those into the result: x op (x op x) CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars); CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars); CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars); CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars); CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars); CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars); return; } } // Compute permutations of all children. std::vector<std::vector<TreePatternNodePtr>> ChildVariants; ChildVariants.resize(N->getNumChildren()); for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars); // Build all permutations based on how the children were formed. CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars); // If this node is commutative, consider the commuted order. bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP); if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) { assert((N->getNumChildren()>=2 || isCommIntrinsic) && "Commutative but doesn't have 2 children!"); // Don't count children which are actually register references. unsigned NC = 0; for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) { TreePatternNode *Child = N->getChild(i); if (Child->isLeaf()) if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) { Record *RR = DI->getDef(); if (RR->isSubClassOf("Register")) continue; } NC++; } // Consider the commuted order. if (isCommIntrinsic) { // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd // operands are the commutative operands, and there might be more operands // after those. assert(NC >= 3 && "Commutative intrinsic should have at least 3 children!"); std::vector<std::vector<TreePatternNodePtr>> Variants; Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id. Variants.push_back(std::move(ChildVariants[2])); Variants.push_back(std::move(ChildVariants[1])); for (unsigned i = 3; i != NC; ++i) Variants.push_back(std::move(ChildVariants[i])); CombineChildVariants(N, Variants, OutVariants, CDP, DepVars); } else if (NC == N->getNumChildren()) { std::vector<std::vector<TreePatternNodePtr>> Variants; Variants.push_back(std::move(ChildVariants[1])); Variants.push_back(std::move(ChildVariants[0])); for (unsigned i = 2; i != NC; ++i) Variants.push_back(std::move(ChildVariants[i])); CombineChildVariants(N, Variants, OutVariants, CDP, DepVars); } } } // GenerateVariants - Generate variants. For example, commutative patterns can // match multiple ways. Add them to PatternsToMatch as well. void CodeGenDAGPatterns::GenerateVariants() { LLVM_DEBUG(errs() << "Generating instruction variants.\n"); // Loop over all of the patterns we've collected, checking to see if we can // generate variants of the instruction, through the exploitation of // identities. This permits the target to provide aggressive matching without // the .td file having to contain tons of variants of instructions. // // Note that this loop adds new patterns to the PatternsToMatch list, but we // intentionally do not reconsider these. Any variants of added patterns have // already been added. // for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) { MultipleUseVarSet DepVars; std::vector<TreePatternNodePtr> Variants; FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars); LLVM_DEBUG(errs() << "Dependent/multiply used variables: "); LLVM_DEBUG(DumpDepVars(DepVars)); LLVM_DEBUG(errs() << "\n"); GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants, *this, DepVars); assert(!Variants.empty() && "Must create at least original variant!"); if (Variants.size() == 1) // No additional variants for this pattern. continue; LLVM_DEBUG(errs() << "FOUND VARIANTS OF: "; PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n"); for (unsigned v = 0, e = Variants.size(); v != e; ++v) { TreePatternNodePtr Variant = Variants[v]; LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump(); errs() << "\n"); // Scan to see if an instruction or explicit pattern already matches this. bool AlreadyExists = false; for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) { // Skip if the top level predicates do not match. if (PatternsToMatch[i].getPredicates() != PatternsToMatch[p].getPredicates()) continue; // Check to see if this variant already exists. if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) { LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n"); AlreadyExists = true; break; } } // If we already have it, ignore the variant. if (AlreadyExists) continue; // Otherwise, add it to the list of patterns we have. PatternsToMatch.push_back(PatternToMatch( PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(), Variant, PatternsToMatch[i].getDstPatternShared(), PatternsToMatch[i].getDstRegs(), PatternsToMatch[i].getAddedComplexity(), Record::getNewUID())); } LLVM_DEBUG(errs() << "\n"); } }
[ "1634054493@qq.com" ]
1634054493@qq.com
a109d05542d25c7e810c6f26333fba66c1cf24ac
3c39e829d2f4376e0d86dc911c3876d1b3181e74
/Prim 2nd MST.cpp
3fc653ada5c6264965185bc83bcdf6629ecc43f9
[]
no_license
Asif-EWU/algorithms
6c0f0c1bbc2cd725d4a381b6b2fae02a86c7484b
92c2e30c1b5b1d30ff49b6ab0015d8248d6f4558
refs/heads/master
2022-11-15T12:55:06.944814
2020-07-16T13:38:19
2020-07-16T13:38:19
280,163,502
0
0
null
null
null
null
UTF-8
C++
false
false
2,197
cpp
#include<bits/stdc++.h> #define MX 100 using namespace std; struct Edge { int to, cost; Edge(int _to, int _cost) { to=_to; cost=_cost; } }; bool operator<(Edge a, Edge b) { return a.cost>b.cost; } vector<Edge>arr[MX]; int prim(int from, int node) { priority_queue<Edge>pq; bool taken[MX]; int cost[MX]; int x, y, sum=0; int temp1=INT_MAX, temp2; for(int i=1; i<=node; i++) { taken[i]=false; cost[i]=INT_MAX; } cost[from]=0; pq.push(Edge(from,cost[from])); while(!pq.empty()) { Edge top=pq.top(); pq.pop(); if(taken[top.to]) continue; taken[top.to]=true; sum+=top.cost; for(int i=0; i<arr[top.to].size(); i++) { x=arr[top.to][i].to; y=arr[top.to][i].cost; if(taken[x]) continue; if(cost[x]>y) { if(temp1>cost[x]) // for 2nd MST { // for 2nd MST temp1=cost[x]; // for 2nd MST temp2=y; // for 2nd MST } // for 2nd MST cost[x]=y; pq.push(Edge(x,cost[x])); } else if(cost[x]<y) // for 2nd MST { // for 2nd MST if(temp1>y) // for 2nd MST { // for 2nd MST temp1=y; // for 2nd MST temp2=cost[x]; // for 2nd MST } // for 2nd MST } // for 2nd MST } } cout << "1st MST: " << sum << endl; cout << "2nd MST: " << sum-temp2+temp1 << endl; } int main() { freopen("_prim.txt", "r", stdin); int node, edge, a, b, c; cin >> node >> edge; for(int i=0; i<edge; i++) { cin >> a >> b >> c; arr[a].push_back(Edge(b,c)); arr[b].push_back(Edge(a,c)); } prim(1,node); return 0; }
[ "asifratul45@gmail.com" ]
asifratul45@gmail.com
ca3e0290705144e94485968dadd5cabf137358b4
0ddaa06fb8a84a00e9e91371004f1e2c60a116ba
/app_main.cpp
f370689c632282342e026c5489c990a71e15abe5
[]
no_license
jpgallegos3/Camera-Fly-Through
ea7a8bf130057b40b0e5fce1a867361bf9a2332b
16b2aaf61dfaedb51da04227e0ca19e1783596b1
refs/heads/master
2021-01-25T04:37:45.595873
2017-06-06T00:41:24
2017-06-06T00:41:24
93,458,916
0
0
null
null
null
null
UTF-8
C++
false
false
1,898
cpp
# include <iostream> //# include <gsim/gs.h> # include "ogl_tools.h" # include "app_window.h" //========================================================================== // Main routine //========================================================================== int main ( int argc, char** argv ) { // Init freeglut library: glutInit ( &argc, argv ); glutInitDisplayMode ( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH ); glutInitContextProfile ( GLUT_CORE_PROFILE ); // Display some info: //std::cout<<"Camera keys: Arrows + PgUp and PgDn\n"; //std::cout<<"Load models: keys 1,2,3\n"; std::cout <<"Project 2 Fly through camera: \n"; std::cout <<"Axis on/off: space bar\n"; std::cout << "Curves on/off: v\n"; std::cout << " 3 Curves to choose from:\n"; std::cout << " 1 - BSpline Curve 1:\n"; std::cout << " 2 - Overhead Plane curve\n"; std::cout << " 3 - BSpline Curve 2:\n\n"; std::cout << "Press 1, 2, 3 to pick a camera curve\n"; std::cout<<"Press c to initiate camera \n\n"; //std::cout<<"Notes:\n"; //std::cout<<"- the smooth normal generation runs much faster in Release mode;\n"; //std::cout<<"- this application crashed in one of my computers but I could not reproduce the problem, "<< //"let me know if you find a bug somewhere in the code.\n\n"; // Now create the window of your application: AppWindow* w = new AppWindow ( "CSE_170 Jered Gallegos|Aaron Chiang Project 2", 300, 300, 640, 480 ); // Use a white canvas etc: glClearColor(0.5, 0.5, 0.85, 0.5); glEnable(GL_BLEND); // for transparency and antialiasing smoothing glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glEnable(GL_POINT_SMOOTH); glPointSize(5.0); // Finally start the main loop: w->run (); }
[ "noreply@github.com" ]
jpgallegos3.noreply@github.com
ef634fb628cad6ee68c96eae4e72744abcb85b3d
949c330078c043d0b24c061d8aaeb60422ad4fa0
/HumpaLampa_Capsense/HumpaLampa_Capsense.ino
893b08ecf61c52083ffdbe42e5a4e765e687d566
[]
no_license
famibelle/HumpaLampa
64990e1756504ef8b00896b99e11eb46aff5c161
c59b5e8aa1a991298ef39e492b71aa6d298be793
refs/heads/main
2023-01-02T09:26:25.938231
2020-10-12T14:29:25
2020-10-12T14:29:25
303,401,856
0
0
null
null
null
null
UTF-8
C++
false
false
2,585
ino
#include <avr/interrupt.h> #include <avr/sleep.h> /* Ce programme est une adaptation de l'Arduino Starter Kit example Project 13 - Touch Sensor Lamp Les composants - 1 megohm resistance - du papier d'aluminium - un système d'éclaireage à LED Library utilisée: - CapacitiveSensor library par Paul Badger http://www.arduino.cc/playground/Main/CapacitiveSensor */ #include <CapacitiveSensor.h> #include <SandTimer.h> #define HEURE 1 #define MINUTE 1 #define SECONDE 1 #define VEILLE 1 SandTimer TouchInterval; SandTimer PowerOff; // create an instance of the library // pinoche 4 envoie le signal électrique // pinoche 2 détecte une variation CapacitiveSensor capSensor = CapacitiveSensor(4, 2); // Seuil qui déclenche l'allumage de la lampe, mon conseil est de faire des test pour déterminer le bon niveau. // avec un seuil très faible, on peut allumer la lampe en passant la main au dessus du capteur dans un mouvement très Jedi :-) int threshold = 30; bool contact = false; // La variable contact change d'état à chaque franchissement du seuil. // pinoche à laquelle la LED is connected const int ledPin = 12; void setup() { // Ouverture d'une connextion série Serial.begin(9600); // Configuration de la pinoche LED en mode sortie d'information pinMode(ledPin, OUTPUT); pinMode(13, OUTPUT); } void loop() { // On introduit un delai de quelques secondes pour eviter que le bagotement entre deeux contacts TouchInterval.start(1000); PowerOff.start(1000*SECONDE*MINUTE*HEURE * VEILLE); // Au bout de 3h on éteint tout // détection de la valeur de la pinoche connectée à la feuille d'aluminium long sensorValue = capSensor.capacitiveSensor(30); // print out the sensor value Serial.println(sensorValue); digitalWrite(13,LOW); // if the value is greater than the threshold if (sensorValue > threshold) { // turn the LED on // digitalWrite(ledPin, HIGH); if (TouchInterval.finished()) { contact = !contact; } PowerOff.startOver(); Serial.println("Contact"); } // if it's lower than the threshold else { // turn the LED off // digitalWrite(ledPin, LOW); } if (contact == true) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } delay(10); if (PowerOff.finished()) { set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here sleep_enable(); // enables the sleep bit in the mcucr register } }
[ "noreply@github.com" ]
famibelle.noreply@github.com
e5637de3ec6d02822275d9ceee8034c587693827
071ab7375e4342433c2edfb2f5f3d6d1bd4b4aed
/Blending/transparency/main.cpp
fa9343e2b69665c99af283ed01b0f648479aff68
[]
no_license
Nicolas99-9/OPengGLTeaching
70bbbd8112ae5cea9f14d1b8ce5071bca84fbd68
2881dbcf21f5618ee78b7fe6ce953c9748308659
refs/heads/master
2021-01-10T15:51:29.608972
2016-02-27T16:49:51
2016-02-27T16:49:51
51,576,901
0
0
null
null
null
null
UTF-8
C++
false
false
13,084
cpp
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <cstdio> #include "Shader.h" #include <SOIL.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Camera.h" #include "Model.h" // Function prototypes void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void Do_movement(); // Properties GLuint screenWidth = 800, screenHeight = 600; // Camera Camera camera(glm::vec3(0.0f, 0.0f, 3.0f)); GLfloat lastX = screenWidth / 2.0; GLfloat lastY = screenHeight / 2.0; bool keys[1024]; // Light attributes glm::vec3 lightPos(1.2f, 1.0f, 2.0f); // Deltatime GLfloat deltaTime = 0.0f; // Time between current frame and last frame GLfloat lastFrame = 0.0f; // Time of last frame void error_callback(int error, const char* description) { fputs(description, stderr); } // This function loads a texture from file. Note: texture loading functions like these are usually // managed by a 'Resource Manager' that manages all resources (like textures, models, audio). // For learning purposes we'll just define it as a utility function. // This function loads a texture from file. Note: texture loading functions like these are usually // managed by a 'Resource Manager' that manages all resources (like textures, models, audio). // For learning purposes we'll just define it as a utility function. GLuint loadTexture(GLchar* path, GLboolean alpha) { //Generate texture ID and load texture data GLuint textureID; glGenTextures(1, &textureID); int width, height; unsigned char* image = SOIL_load_image(path, &width, &height, 0, alpha ? SOIL_LOAD_RGBA : SOIL_LOAD_RGB); // Assign texture to ID glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, alpha ? GL_RGBA : GL_RGB, width, height, 0, alpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); // Parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, alpha ? GL_CLAMP_TO_EDGE : GL_REPEAT); // Use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes value from next repeat glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, alpha ? GL_CLAMP_TO_EDGE : GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); SOIL_free_image_data(image); return textureID; } int main(void) { // initialise the windows GLFWwindow *window; glfwSetErrorCallback(error_callback); if (!glfwInit()) { return -1; } window = glfwCreateWindow(640, 480, "Test", NULL, NULL); if (window == nullptr) { std::cout << "Erreur lors du chargement de la fenetree "; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); printf("OpenGL Version:%s\n", glGetString(GL_VERSION)); printf("GLSL Version :%s\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); // create a windows if (!window) { fprintf(stderr, "Failed to initialize GLFW\n"); glfwTerminate(); return -1; } // make the window's current context // loop until the window close glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // GLFW Options //glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // triangle // must be normalized to be inside the screen // GLEW INITIALISATION glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout << "Failed to initialize GLEW" << std::endl; } glViewport(0, 0, screenWidth, screenHeight); // Setup some OpenGL options glEnable(GL_DEPTH_TEST); //glDepthFunc(GL_ALWAYS); // Set to always pass the depth test (same effect as glDisable(GL_DEPTH_TEST)) //glDepthFunc(GL_LESS); //enable stencil testing //------------------------------------------------------------------ //glEnable(GL_STENCIL_TEST); //glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); Shader shader("shader.vs", "shader.frag"); Shader lampShader("shaderLight.vs", "shaderLight.frag"); #pragma region "object_initialization" // Set the object data (buffers, vertex attributes) GLfloat cubeVertices[] = { // Positions // Texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; GLfloat planeVertices[] = { // Positions // Texture Coords (note we set these higher than 1 that together with GL_REPEAT as texture wrapping mode will cause the floor texture to repeat) 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, 5.0f, 0.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, -5.0f, 2.0f, 2.0f }; GLfloat transparentVertices[] = { // Positions // Texture Coords (swapped y coordinates because texture is flipped upside down) 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.0f, 1.0f, 0.0f }; // Setup cube VAO GLuint cubeVAO, cubeVBO; glGenVertexArrays(1, &cubeVAO); glGenBuffers(1, &cubeVBO); glBindVertexArray(cubeVAO); glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); // Setup plane VAO GLuint planeVAO, planeVBO; glGenVertexArrays(1, &planeVAO); glGenBuffers(1, &planeVBO); glBindVertexArray(planeVAO); glBindBuffer(GL_ARRAY_BUFFER, planeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); // Setup transparent plane VAO GLuint transparentVAO, transparentVBO; glGenVertexArrays(1, &transparentVAO); glGenBuffers(1, &transparentVBO); glBindVertexArray(transparentVAO); glBindBuffer(GL_ARRAY_BUFFER, transparentVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(transparentVertices), transparentVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); // Load textures GLuint cubeTexture = loadTexture("images/container.jpg",false); GLuint floorTexture = loadTexture("images/sol.jpg",false); GLuint transparentTexture = loadTexture("images/blending_transparent_window.png", true); //enable different levels of transparency glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); #pragma endregion std::vector<glm::vec3> windows; windows.push_back(glm::vec3(-1.5f, 0.0f, -0.48f)); windows.push_back(glm::vec3(1.5f, 0.0f, 0.51f)); windows.push_back(glm::vec3(0.0f, 0.0f, 0.7f)); windows.push_back(glm::vec3(-0.3f, 0.0f, -2.3f)); windows.push_back(glm::vec3(0.5f, 0.0f, -0.6f)); // Game loop while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents(); Do_movement(); // Clear the colorbuffer glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Sort windows std::map<GLfloat, glm::vec3> sorted; for (GLuint i = 0; i < windows.size(); i++) { GLfloat distance = glm::length(camera.Position - windows[i]); sorted[distance] = windows[i]; } // Draw objects shader.Use(); glm::mat4 model; glm::mat4 view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth / (float)screenHeight, 0.1f, 100.0f); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); // Cubes glBindVertexArray(cubeVAO); glBindTexture(GL_TEXTURE_2D, cubeTexture); // We omit the glActiveTexture part since TEXTURE0 is already the default active texture unit. (a single sampler used in fragment is set to 0 as well by default) model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); model = glm::mat4(); model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); // Floor glBindVertexArray(planeVAO); glBindTexture(GL_TEXTURE_2D, floorTexture); model = glm::mat4(); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 6); // Render windows (from furthest to nearest) glBindVertexArray(transparentVAO); glBindTexture(GL_TEXTURE_2D, transparentTexture); for (std::map<float, glm::vec3>::reverse_iterator it = sorted.rbegin(); it != sorted.rend(); ++it) { model = glm::mat4(); model = glm::translate(model, it->second); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 6); } glBindVertexArray(0); // Swap the buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; } // Is called whenever a key is pressed/released via GLFW void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); if (key >= 0 && key < 1024) { if (action == GLFW_PRESS) keys[key] = true; else if (action == GLFW_RELEASE) keys[key] = false; } } void Do_movement() { // Camera controls if (keys[GLFW_KEY_W]) camera.ProcessKeyboard(FORWARD, deltaTime); if (keys[GLFW_KEY_S]) camera.ProcessKeyboard(BACKWARD, deltaTime); if (keys[GLFW_KEY_A]) camera.ProcessKeyboard(LEFT, deltaTime); if (keys[GLFW_KEY_D]) camera.ProcessKeyboard(RIGHT, deltaTime); } bool firstMouse = true; void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } GLfloat xoffset = xpos - lastX; GLfloat yoffset = lastY - ypos; // Reversed since y-coordinates go from bottom to left lastX = xpos; lastY = ypos; camera.ProcessMouseMovement(xoffset, yoffset); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { camera.ProcessMouseScroll(yoffset); }
[ "bougie.nicolas@gmail.com" ]
bougie.nicolas@gmail.com
3410df3433ecff68da70002a280f6c2ed1d1c726
b8b36bfd9632a18aafc63e68763c89eb5e894e2d
/extractfile.cpp
fb72b09fbb7c6931ef923bc853db28a360a7a520
[]
no_license
LHFCOD/ExtractFile
8e7a07ddbdbdd5915e83dca787c5cdd7719b9d71
ec14b2c76aa4ccc5639f70edc73b81aadc23deaa
refs/heads/master
2021-05-02T08:05:07.539326
2018-02-09T02:31:01
2018-02-09T02:31:01
120,844,673
0
1
null
null
null
null
GB18030
C++
false
false
2,927
cpp
#include "extractfile.h" #include "qfile.h" #include "qfiledialog.h" #include "qmessagebox.h" ExtractFile::ExtractFile(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); ui.progressBar->setVisible(false); connect(ui.SelectBtn, SIGNAL(clicked()), this, SLOT(OnSelectBtn())); connect(ui.AppointBtn, SIGNAL(clicked()), this, SLOT(OnAppointBtn())); connect(ui.ExtractBtn , SIGNAL(clicked()), this, SLOT(OnExtractBtn())); } ExtractFile::~ExtractFile() { delete io;//清除io } void ExtractFile::OnAppointBtn() { QDir dir; RootDir = QFileDialog::getExistingDirectory(this, QString::fromLocal8Bit("选择文件夹"), dir.currentPath(),QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); ui.AppointText->setText(RootDir); } void ExtractFile::OnExtractBtn() { if (io == nullptr) { QMessageBox::information(NULL, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("未选择文件!")); return; } if (RootDir.length() == 0) { QMessageBox::information(NULL, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("未选择文件夹!")); return; } NowProcess = 0; ui.progressBar->setVisible(true); Extract(0,RootDir); ui.progressBar->setValue(io->FileCount); //ui.progressBar->setVisible(false); QMessageBox::information(NULL, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("抽取完成!")); } void ExtractFile::Extract(i32_t DID,QString path) { QVector<Directory> *vec=io->FilePool[DID]; for each(Directory direct in *vec) { QString str = QString::fromUtf16((ushort*)(direct.EntryName), direct.NameSize / 2-1);//文件名字 QString currentstr = path + QString::fromLocal8Bit("/"); currentstr.append(str); QByteArray arr = currentstr.toLocal8Bit();//这个地方不太明白,为啥要分开去写比较合适 char *tmp = arr.data(); if (direct.EntryType == 1) { QDir dir; dir.cd(path); dir.mkdir(str); Extract(direct.DID, path + "/" + str); } else { byte_t *p; if (direct.StreamSize <io-> m_Header.MiniSize) p =io-> ReadShortStreamFromSID(direct.SID, direct.StreamSize); else p = io->ReadStreamFromSID(direct.SID, direct.StreamSize);//一次性把所需要写的字符流读取,然后写入文件 FILE * pFile; pFile = fopen(tmp, "wb"); fwrite(p, sizeof(char), direct.StreamSize, pFile); fclose(pFile); NowProcess++; ui.progressBar->setValue(NowProcess); } } } void ExtractFile::OnSelectBtn() { QString path = QFileDialog::getOpenFileName(this, QString::fromLocal8Bit("打开文件"), ".", "MDS Files(*.mds)"); if (path.length() == 0) { QMessageBox::information(NULL, tr("Path"), QString::fromLocal8Bit("你未选择任何文件!")); } else { ui.SelectText->setText(path); if (io) delete io; io = new ComDocIO(path); ui.progressBar->setRange(0, io->FileCount); } }
[ "2278200244@qq.com" ]
2278200244@qq.com
33066600430f569226dd8018d7f018f421c5fe41
1aca27af5f40f53b5773ff35356c588836aef227
/Extensions/BabaPython/Sources/Games/Map.cpp
8b093fede989609ac46b9a6ad83c9614d7fd0e64
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
siva-msft/baba-is-auto
c9a5dfd2cb44629ee99f5ce5e733bf6e86fb8b8a
3237b5b70167130558827979bde7dcee14ef39f3
refs/heads/master
2022-06-26T12:05:50.536600
2020-05-12T21:55:39
2020-05-12T21:55:39
257,706,228
0
1
MIT
2020-05-12T21:55:40
2020-04-21T20:19:10
Python
UTF-8
C++
false
false
1,063
cpp
// Copyright (c) 2020 Chris Ohk // I am making my contributions/submissions to this project solely in our // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #include <Games/Map.hpp> #include <baba-is-auto/Games/Map.hpp> #include <pybind11/pybind11.h> #include <pybind11/stl.h> using namespace baba_is_auto; void AddMap(pybind11::module& m) { pybind11::class_<Map>(m, "Map") .def(pybind11::init<>()) .def(pybind11::init<std::size_t, std::size_t>()) .def("Reset", &Map::Reset) .def("GetWidth", &Map::GetWidth) .def("GetHeight", &Map::GetHeight) .def("Load", &Map::Load) .def("AddObject", &Map::AddObject) .def("RemoveObject", &Map::RemoveObject) .def("At", static_cast<Object& (Map::*)(std::size_t, std::size_t)>(&Map::At)) .def( "At", static_cast<const Object& (Map::*)(std::size_t, std::size_t) const>( &Map::At)) .def("GetPositions", &Map::GetPositions); }
[ "utilForever@gmail.com" ]
utilForever@gmail.com
8e9f5215fecaa9e009196ff081d857d8ff7771fb
5ef0619efc9193f5313439e94b87a777861649d2
/exp/basic/pic/Picture.h
8362175b5ba83244eafcca7754aaedf6f1319d7d
[]
no_license
SSPKUZX/cpp-comm
b73f0a6c6efc86afdd609c4c358d7637e0e1ddbd
ba64d086bd7f6eb5f29e6e97f3e5ae88a3d7ae4c
refs/heads/master
2021-01-19T16:40:35.938570
2017-11-16T12:57:19
2017-11-16T12:57:19
101,015,705
2
0
null
null
null
null
UTF-8
C++
false
false
1,106
h
#ifndef PICTURE_H_ #define PICTURE_H_ #include <iostream> class Picture { friend std::ostream& operator<< (std::ostream&, const Picture&); friend Picture frame(const Picture&); friend Picture operator| (const Picture&, const Picture&); friend Picture operator& (const Picture&, const Picture&); public: Picture(); Picture(const char* const*, unsigned int); Picture(const Picture&); ~Picture(); Picture& operator= (const Picture&); private: unsigned int width; unsigned int height; char* data; char& pixelAt(unsigned int row, unsigned int col); char pixelAt(unsigned int row, unsigned int col) const; static unsigned int max(unsigned int left, unsigned int right); void init(unsigned int w, unsigned int h); void copyBlock(unsigned int x, unsigned int y, const Picture& pic); void fillRect(unsigned int x, unsigned int y, unsigned int w, unsigned int h, const char ch); }; std::ostream& operator<< (std::ostream&, const Picture&); Picture operator| (const Picture&, const Picture&); Picture operator& (const Picture&, const Picture&); Picture frame(const Picture&); #endif
[ "948049305@qq.com" ]
948049305@qq.com
13f028b281e5fa4ff5bed94eef525ced586dc92a
0fd86e890bd1e1c915869286b6851b0ed1b1f57b
/2021-2022/summer-contest/01 Vowelless/vowelless.cpp
0b202acad10b27cf913275a7ec38c4ea594e666c
[]
no_license
flaming-snowman/pps
efc30e7aaf354753515c7e3076834948fdccbff2
ec7263d3520ae5fa12c85a2d5fa7f7d0445bc637
refs/heads/master
2023-07-01T23:14:50.929068
2021-08-09T03:55:43
2021-08-09T03:55:43
274,296,679
1
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
// My solution #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; string s; cin >> s; for(char c: s) { if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { n--; } } cout << n << '\n'; }
[ "a.flaming.snowman@gmail.com" ]
a.flaming.snowman@gmail.com
7f8d759a546c201f7b3316d8f21e461889d54a69
cc63466d8a66bb8925508791c007c0054149ce5a
/msj_archives/code/C++/Doc.cpp
0a1055907d33e741897eb779487a1e0f12de7134
[ "Unlicense" ]
permissive
liumorgan/misc-code
9675cc258162064083126a22d97902dae36739c9
d47a8d1cc41f19701ce628c9f15976bb5baa239d
refs/heads/master
2022-06-29T20:41:54.288305
2020-05-13T00:20:05
2020-05-13T00:20:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,161
cpp
//////////////////////////////////////////////////////////////// // 1997 Microsoft Systems Journal. // If this code works, it was written by Paul DiLascia. // If not, I don't know who wrote it. // // CSharedDoc implements an MFC doc class that does file sharing by // locking a file for the duration of an edit session. // Compiles with VC++ 5.0 or later // #include "stdafx.h" #include "doc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNCREATE(CSharedDoc, CDocument) BEGIN_MESSAGE_MAP(CSharedDoc, CDocument) END_MESSAGE_MAP() CSharedDoc::CSharedDoc() { m_pFile = NULL; } CSharedDoc::~CSharedDoc() { } ////////////////// // Load/Save doc as normal (use edit view) // void CSharedDoc::Serialize(CArchive& ar) { ((CEditView*)m_viewList.GetHead())->SerializeRaw(ar); } //////////////////////////////////////////////////////////////// // Below are overrides for shared stuff ///////////////// // Map "Save" to "Save As" if doc is read-only // BOOL CSharedDoc::DoFileSave() { return m_bReadOnly ? DoSave(NULL) : // do Save As CDocument::DoFileSave(); // save as normal } //////////////// // Create new doc. Close old one in case this is an SDI app // BOOL CSharedDoc::OnNewDocument() { CloseFile(); // Required for SDI app only, because MFC re-uses doc. BOOL bRet = CDocument::OnNewDocument(); if (bRet) // do normal stuff ((CEditView*)m_viewList.GetHead())->SetWindowText(NULL); return bRet; } ////////////////// // Open New doc. Close old one in case this is an SDI app // BOOL CSharedDoc::OnOpenDocument(LPCTSTR lpszPathName) { CloseFile(); // Required for SDI app only, because MFC re-uses doc // Open the file CFile* pFile = OpenFile(lpszPathName, m_bReadOnly); if (!pFile) { // Can't even open file read-only??? punt CString s; s.Format(_T("Unknown error opening file '%s'"), lpszPathName); AfxMessageBox(s); return FALSE; } if (m_bReadOnly) { // Doc was opened read-only: tell user CString s; s.Format(_T("File '%s' is in use.\nIt will be opened read-only"), lpszPathName); AfxMessageBox(s); } m_pFile = pFile; // Now do standard MFC Open, but close file if the open fails BOOL bRet = CDocument::OnOpenDocument(lpszPathName); if (!bRet) CloseFile(); return bRet; } ///////////////// // Save document. Use already-open file, unless saving to a new name. // Either way, lock the file and set length to zero before saving it. // Note: m_pFile could be NULL if this is a new document. // BOOL CSharedDoc::OnSaveDocument(LPCTSTR lpszPathName) { BOOL bReadOnly = m_bReadOnly; CFile* pFile = m_pFile; // Check for new doc BOOL bNewFile = (pFile==NULL) || (pFile->GetFilePath() != lpszPathName); if (bNewFile) { // new file, or saving w/different name: open new file pFile = OpenFile(lpszPathName, bReadOnly, TRUE); } // If can't get write access, can't save. // Display message and return FALSE. // if (bReadOnly || pFile == NULL) { CString s; s.Format(_T("File '%s' is in use.\nSave with a different name."), lpszPathName); AfxMessageBox(s); if (bNewFile && pFile) // if new file was opened: pFile->Close(); // close it return FALSE; } if (bNewFile) { // new file: close old one and install it CloseFile(); m_pFile = pFile; // and replace w/new one m_bReadOnly = bReadOnly;// read-only flag too } // Now do normal Serialize. Lock the file first and set length to zero // This is required because I opened with modeNoTruncate. You might // want to consider "robust" saving here: that is, save to a temp file // before destroying the original file; then if the save succeeds, replace // the original file with the new one. // pFile->LockRange(0,(DWORD)-1); // will throw exception if fails pFile->SetLength(0); // get rid of current contents BOOL bRet = CDocument::OnSaveDocument(lpszPathName); // normal MFC save pFile->UnlockRange(0,(DWORD)-1); // unlock return bRet; } ////////////////// // Close document: time to really close the file too. MFC only calls this // function in a MDI app, not SDI. // void CSharedDoc::OnCloseDocument() { CloseFile(); // close file CDocument::OnCloseDocument(); // Warning: must call this last // because MFC will "delete this" } ////////////////// // "Release" the file. This means either abort or close. // In the case of close, I don't really close it, but leave // file open for duration of user session. // void CSharedDoc::ReleaseFile(CFile* pFile, BOOL bAbort) { if (bAbort) CDocument::ReleaseFile(pFile, bAbort); else if (!m_bReadOnly) { pFile->Flush(); // write changes to disk, but don't close! } } ////////////////// // Override to use my always-open CFile object instead // of creating and opening a new one. // CFile* CSharedDoc::GetFile(LPCTSTR, UINT, CFileException*) { ASSERT_VALID(m_pFile); return m_pFile; } //////////////////////////////////////////////////////////////// // Helper functions // CFile::Open mode flags const OPENREAD = CFile::modeRead | CFile::shareDenyNone; const OPENWRITE = CFile::modeReadWrite | CFile::shareDenyWrite; const OPENCREATE = CFile::modeCreate | CFile::modeReadWrite | CFile::shareDenyWrite; ////////////////// // Open the document file. Try to open with write acess, else read-only. // bCreate says whether to create the file, used when saving to a new name. // Returns the CFile opened, and sets bReadOnly. // CFile* CSharedDoc::OpenFile(LPCTSTR lpszPathName, BOOL& bReadOnly, BOOL bCreate) { CFile* pFile = new CFile; ASSERT(pFile); bReadOnly = TRUE; // assume read only // try opening for write CFileException fe; if (pFile->Open(lpszPathName, bCreate ? OPENCREATE : OPENWRITE, &fe)) { bReadOnly = FALSE; // got write access } else if (bCreate || !pFile->Open(lpszPathName, OPENREAD, &fe)) { // can't open for read OR write--yikes! Time to punt delete pFile; pFile = NULL; } if (pFile) pFile->SeekToBegin(); return pFile; } ///////////////// // Close the file if it's open. Called from multiple places for SDI app // void CSharedDoc::CloseFile() { if (m_pFile) { m_pFile->Close(); m_pFile = NULL; } }
[ "1380950+sarangbaheti@users.noreply.github.com" ]
1380950+sarangbaheti@users.noreply.github.com
35854de2810e397892420629525613bfdbc917dc
9b7facbc51af989228f2452e2b8ed3d6b5fe8c66
/问题 E 特殊的语言/问题 E 特殊的语言/源.cpp
4ec0b812010bdbc409ed420f1acc87304aace455
[]
no_license
ZibeSun/OJ-Data-Structures-and-Algorithms
1028a08bf55b8685e6b1b3736bde42075c7ba789
e66c20a389e36085b277253a662f8d9763c7dd08
refs/heads/main
2023-06-06T07:08:19.608958
2021-07-02T04:14:35
2021-07-02T04:14:35
346,795,114
1
1
null
null
null
null
GB18030
C++
false
false
1,229
cpp
#include<iostream> #include<cstring> using namespace std; int SpecialLanguage(string str, string str1) { int num = 0; int len = str.length(); int len1 = str1.length(); for (int i = 0; i <= len-len1; i+=2) { if (str.substr(i, len1).compare(str1) == 0) num++; } return num; } int main() { string str; string str1; while (cin >> str >> str1) { cout << SpecialLanguage(str, str1) << endl; } } /* 题目描述 某城邦的语言,每个字是由两个字母构成的。考古学家发现把他们的文字数字化之后,当想搜索特定的句子时,总会匹配到错误的地方。 比如一段文字是 aabcdaabcdef,想要搜索 abcd,应当搜到的是 aabcda abcd ef ,却会得到额外的一个并不符合该语言语法的结果 a abcd aabcdef(因为每个字由两个字符组成,这样匹配就把正确的“字”拆开了)。 请你帮他实现正确的匹配算法。 输入 每组数据两行,第一行为该语言的主串,第二行为模式串,都由大写或小写英文字母组成,长度都不超过 10000,且一定为偶数个。 输出 每组数据输出正确匹配的次数 样例输入 abcdaabbab ab AbdcAbdcAbqAbdcAbdcAbp AbdcAb 样例输出 2 2 提示 */
[ "979271618@qq.com" ]
979271618@qq.com
b7b8b6278dbe90ad4de8b7e168eb919f83bcfcee
1e668279a619a3649c0f546970c469bb4fdd2b90
/include/precision.h
371b8c14bb77b43f9f6068af74a4337ce6360a57
[ "MIT" ]
permissive
doreiss/BAM
dbb8299fc382051d35c0e7c2fb1dc86915dae601
2f6abd5031c0a2ea1a74c2fa8d22764802e80323
refs/heads/master
2020-04-11T23:49:32.368774
2018-12-18T21:50:52
2018-12-18T21:50:52
162,180,773
0
0
null
null
null
null
UTF-8
C++
false
false
1,925
h
#ifndef BAM_PRECISION_H #define BAM_PRECISION_H #include <cmath> namespace BAM { #define FLOAT_PRECISION #ifdef DOUBLE_PRECISION typedef double real; typedef long long magic_int; #define REAL_MAX DBL_MAX #define REAL_SQRT_MAGIC 0x5fe6ec85e7de30daLL #define PI 3.14159265358979323846 #define realSqrt sqrt #define realAbs abs #define realSin sin #define realCos cos #define realTan tan #define realACos acos #define realASin asin #define realATan atan #define realATan2 atan2 #define realPow pow #define REAL_ZERO 0.0 #define REAL_ONE 1.0 #define REAL_TWO 2.0 #define REAL_THREE 3.0 #define REAL_FOUR 4.0 #define REAL_FIVE 5.0 #define REAL_HALF 0.5 #define REAL_THREEHALVES 1.5 #define REAL_FIVEHALVES 2.5 #define REAL_SEVENHALVES 3.5 #define REAL_NINEHALVES 4.5 #define REAL_MINUS_ONE -1.0 #define REAL_MINUS_TWO -2.0 #define REAL_HUNDRED_EIGHTY 180.0 #define REAL_THOUSAND 1000.0 #endif #ifdef FLOAT_PRECISION typedef float real; typedef long magic_int; #define REAL_MAX FLT_MAX #define REAL_SQRT_MAGIC 0x5f375a86 #define PI 3.14159265358979323846f #define realSqrt sqrtf #define realAbs fabsf #define realSin sinf #define realCos cosf #define realTan tanf #define realACos acosf #define realASin asinf #define realATan atanf #define realATan2 atan2f #define realPow powf #define realExp expf #define REAL_ZERO 0.0f #define REAL_ONE 1.0f #define REAL_TWO 2.0f #define REAL_THREE 3.0f #define REAL_FOUR 4.0f #define REAL_FIVE 5.0f #define REAL_HALF 0.5f #define REAL_THREEHALVES 1.5f #define REAL_FIVEHALVES 2.5f #define REAL_SEVENHALVES 3.5f #define REAL_NINEHALVES 4.5f #define REAL_MINUS_ONE -1.0f #define REAL_MINUS_TWO -2.0f #define REAL_HUNDRED_EIGHTY 180.0f #define REAL_THOUSAND 1000.f #endif } //BAM #endif //BAM_PRECISION_H
[ "dominic.reiss@gmail.com" ]
dominic.reiss@gmail.com
4044db600ff12d3ba670f2f1fda5c2c1d6986f68
f85cfed4ae3c54b5d31b43e10435bb4fc4875d7e
/sc-virt/src/utils/TableGen/DAGISelEmitter.cpp
0fe3bbd8d788d0c9b36e69a4bc994ddbc7ba8964
[ "MIT", "NCSA" ]
permissive
archercreat/dta-vs-osc
2f495f74e0a67d3672c1fc11ecb812d3bc116210
b39f4d4eb6ffea501025fc3e07622251c2118fe0
refs/heads/main
2023-08-01T01:54:05.925289
2021-09-05T21:00:35
2021-09-05T21:00:35
438,047,267
1
1
MIT
2021-12-13T22:45:20
2021-12-13T22:45:19
null
UTF-8
C++
false
false
6,244
cpp
//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits a DAG instruction selector. // //===----------------------------------------------------------------------===// #include "CodeGenDAGPatterns.h" #include "DAGISelMatcher.h" #include "llvm/Support/Debug.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" using namespace llvm; #define DEBUG_TYPE "dag-isel-emitter" namespace { /// DAGISelEmitter - The top-level class which coordinates construction /// and emission of the instruction selector. class DAGISelEmitter { CodeGenDAGPatterns CGP; public: explicit DAGISelEmitter(RecordKeeper &R) : CGP(R) {} void run(raw_ostream &OS); }; } // End anonymous namespace //===----------------------------------------------------------------------===// // DAGISelEmitter Helper methods // /// getResultPatternCost - Compute the number of instructions for this pattern. /// This is a temporary hack. We should really include the instruction /// latencies in this calculation. static unsigned getResultPatternCost(TreePatternNode *P, CodeGenDAGPatterns &CGP) { if (P->isLeaf()) return 0; unsigned Cost = 0; Record *Op = P->getOperator(); if (Op->isSubClassOf("Instruction")) { Cost++; CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op); if (II.usesCustomInserter) Cost += 10; } for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) Cost += getResultPatternCost(P->getChild(i), CGP); return Cost; } /// getResultPatternCodeSize - Compute the code size of instructions for this /// pattern. static unsigned getResultPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) { if (P->isLeaf()) return 0; unsigned Cost = 0; Record *Op = P->getOperator(); if (Op->isSubClassOf("Instruction")) { Cost += Op->getValueAsInt("CodeSize"); } for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) Cost += getResultPatternSize(P->getChild(i), CGP); return Cost; } namespace { // PatternSortingPredicate - return true if we prefer to match LHS before RHS. // In particular, we want to match maximal patterns first and lowest cost within // a particular complexity first. struct PatternSortingPredicate { PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {} CodeGenDAGPatterns &CGP; bool operator()(const PatternToMatch *LHS, const PatternToMatch *RHS) { const TreePatternNode *LHSSrc = LHS->getSrcPattern(); const TreePatternNode *RHSSrc = RHS->getSrcPattern(); MVT LHSVT = (LHSSrc->getNumTypes() != 0 ? LHSSrc->getType(0) : MVT::Other); MVT RHSVT = (RHSSrc->getNumTypes() != 0 ? RHSSrc->getType(0) : MVT::Other); if (LHSVT.isVector() != RHSVT.isVector()) return RHSVT.isVector(); if (LHSVT.isFloatingPoint() != RHSVT.isFloatingPoint()) return RHSVT.isFloatingPoint(); // Otherwise, if the patterns might both match, sort based on complexity, // which means that we prefer to match patterns that cover more nodes in the // input over nodes that cover fewer. int LHSSize = LHS->getPatternComplexity(CGP); int RHSSize = RHS->getPatternComplexity(CGP); if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost if (LHSSize < RHSSize) return false; // If the patterns have equal complexity, compare generated instruction cost unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP); unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP); if (LHSCost < RHSCost) return true; if (LHSCost > RHSCost) return false; unsigned LHSPatSize = getResultPatternSize(LHS->getDstPattern(), CGP); unsigned RHSPatSize = getResultPatternSize(RHS->getDstPattern(), CGP); if (LHSPatSize < RHSPatSize) return true; if (LHSPatSize > RHSPatSize) return false; // Sort based on the UID of the pattern, giving us a deterministic ordering // if all other sorting conditions fail. assert(LHS == RHS || LHS->ID != RHS->ID); return LHS->ID < RHS->ID; } }; } // End anonymous namespace void DAGISelEmitter::run(raw_ostream &OS) { emitSourceFileHeader("DAG Instruction Selector for the " + CGP.getTargetInfo().getName() + " target", OS); OS << "// *** NOTE: This file is #included into the middle of the target\n" << "// *** instruction selector class. These functions are really " << "methods.\n\n"; DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n"; for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end(); I != E; ++I) { errs() << "PATTERN: "; I->getSrcPattern()->dump(); errs() << "\nRESULT: "; I->getDstPattern()->dump(); errs() << "\n"; }); // Add all the patterns to a temporary list so we can sort them. std::vector<const PatternToMatch*> Patterns; for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end(); I != E; ++I) Patterns.push_back(&*I); // We want to process the matches in order of minimal cost. Sort the patterns // so the least cost one is at the start. std::sort(Patterns.begin(), Patterns.end(), PatternSortingPredicate(CGP)); // Convert each variant of each pattern into a Matcher. std::vector<Matcher*> PatternMatchers; for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { for (unsigned Variant = 0; ; ++Variant) { if (Matcher *M = ConvertPatternToMatcher(*Patterns[i], Variant, CGP)) PatternMatchers.push_back(M); else break; } } std::unique_ptr<Matcher> TheMatcher = llvm::make_unique<ScopeMatcher>(PatternMatchers); OptimizeMatcher(TheMatcher, CGP); //Matcher->dump(); EmitMatcherTable(TheMatcher.get(), CGP, OS); } namespace llvm { void EmitDAGISel(RecordKeeper &RK, raw_ostream &OS) { DAGISelEmitter(RK).run(OS); } } // End llvm namespace
[ "sebi@quantstamp.com" ]
sebi@quantstamp.com
3eb7b105599f70db9b8a0f717af2f0fe4ee39976
4c23be1a0ca76f68e7146f7d098e26c2bbfb2650
/ic8h18/0.0065/CH3COCH2O
4d6fffa817ac934b84ef726945d0ede2753d2a35
[]
no_license
labsandy/OpenFOAM_workspace
a74b473903ddbd34b31dc93917e3719bc051e379
6e0193ad9dabd613acf40d6b3ec4c0536c90aed4
refs/heads/master
2022-02-25T02:36:04.164324
2019-08-23T02:27:16
2019-08-23T02:27:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
842
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.0065"; object CH3COCH2O; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField uniform 2.81205e-29; boundaryField { boundary { type empty; } } // ************************************************************************* //
[ "jfeatherstone123@gmail.com" ]
jfeatherstone123@gmail.com
079bb2c625c315a8f617d84a85c1f9c6241b0f9b
9b59c3a2a6b248e0b8f4f2f51939844aced729ce
/Step1/neuron.cpp
e69ef8c90f343ebf79c2901d160cfa8b8f56dbd8
[]
no_license
TheEzo/AVS-1
7eb5aea6712826c00f7f83ae8fdf6d77a3cdfa22
64561b863115fce770a459c21bef12cd179d2fad
refs/heads/master
2022-03-13T15:58:42.567818
2019-11-10T10:45:06
2019-11-10T10:45:06
219,592,315
0
0
null
null
null
null
UTF-8
C++
false
false
453
cpp
/* * Architektury výpočetních systémů (AVS 2019) * Projekt c. 1 (ANN) * Login: xwilla00 */ #include <cstdlib> #include "neuron.h" float evalNeuron( size_t inputSize, size_t neuronCount, const float* input, const float* weights, float bias, size_t neuronId ) { float result = 0; for(int i = 0; i < inputSize; i++) result += input[i] * weights[i * neuronCount + neuronId]; result += bias; return result > 0 ? result : 0; }
[ "tomas.willaschek@nxp.com" ]
tomas.willaschek@nxp.com
8ee2d6b054341c27ddcf5d55f26e5940bfedd8cc
6e115adc9021ceed1b37e44abf3b89db7dc5fa21
/коды пп/final1/all.cpp
ce34a75070b421477f93262d6470fb1e84607833
[]
no_license
inirbayeva/pp1
baef1a8e6b638e62dcb2127e98c8634c2a59b8a3
e01afa0fe4bdb25a9c7a755c916b1e2bca0b0f81
refs/heads/master
2023-03-01T05:41:56.085163
2021-02-06T11:29:09
2021-02-06T11:29:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
835
cpp
#include <iostream> using namespace std; int main(){ int mary[7], mol[] = {1, 2, 5, 10, 20, 50, 100}; for (int i = 0; i < 7; i++) cin >> mary[i]; int n; cin>>n; int m[n]; for (int i = 0; i < n; i++) cin>>m[i]; for (int i = 0; i < n; i++) { int old[7]; for (int j = 0; j < 7; j++) old[j] = mary[j]; for (int j = 6; j >= 0; j--) { if (old[j] > 0) { while(m[i] >= mol[j] && old[j] > 0) { old[j]--; m[i] -= mol[j]; } } } if (m[i] == 0) { cout<< "Transaction accepted!\n"; for (int j = 0; j < 7; j++) mary[j] = old[j]; } else { cout<< "Transaction stopped!\n"; } } }
[ "you@example.com" ]
you@example.com
ef4da3ca9412ed3e71197c073ec6e75d8275b974
f69403a1fac323997daf0a44d8058f0e1b39709a
/csharp/src/corelib/WideChar.cpp
150372edc69f8187332de34b6f0852449e06bc10
[]
no_license
nfeltman/RenderGen
d4858e5559e1cfadc6748cd4e5cb4ad4cd4f900b
9e44b92da4da87d3ac35569f3449f8212d64f36b
refs/heads/master
2021-01-21T07:57:56.049014
2016-01-19T13:19:50
2016-01-19T13:19:50
6,394,209
0
0
null
null
null
null
UTF-8
C++
false
false
1,655
cpp
#include "WideChar.h" #ifdef WINDOWS_PLATFORM #include <Windows.h> #endif #include <stdio.h> #include <stdlib.h> #include <memory.h> char * WideCharToMByte(const wchar_t * buffer, int length) { #ifdef WINDOWS_PLATFORM size_t requiredBufferSize; requiredBufferSize = WideCharToMultiByte(CP_OEMCP, NULL, buffer, length, 0, 0, NULL, NULL)+1; if (requiredBufferSize) { char * multiByteBuffer = new char[requiredBufferSize]; WideCharToMultiByte(CP_OEMCP, NULL, buffer, length, multiByteBuffer, requiredBufferSize, NULL, NULL); multiByteBuffer[requiredBufferSize-1] = 0; return multiByteBuffer; } else return 0; #else size_t ret; char * dest = new char[length*2 + 1]; memset(dest, 0, sizeof(char)*(length*2+1)); wcstombs_s(&ret, dest, length*2+1, buffer, _TRUNCATE); return dest; #endif } wchar_t * MByteToWideChar(const char * buffer, int length) { #ifdef WINDOWS_PLATFORM // regard as ansi int rlength = MultiByteToWideChar(CP_ACP, 0, buffer, length, NULL, 0)-1; if (length < 0) length = 0; if (length != 0) { wchar_t * rbuffer = new wchar_t[length+1]; MultiByteToWideChar(CP_ACP, NULL, buffer, length, rbuffer, length+1); return rbuffer; } else return 0; #else size_t ret; wchar_t * dest = new wchar_t[length+1]; memset(dest, 0, sizeof(wchar_t)*(length+1)); mbstowcs_s(&ret, dest, length+1, buffer, _TRUNCATE); return dest; #endif } void MByteToWideChar(wchar_t * buffer, int bufferSize, const char * str, int length) { #ifdef WINDOWS_PLATFORM // regard as ansi MultiByteToWideChar(CP_ACP, NULL, str, length, buffer, bufferSize); #else size_t ret; mbstowcs_s(&ret, buffer, bufferSize, str, _TRUNCATE); #endif }
[ "yonghe@outlook.com" ]
yonghe@outlook.com
971b91ed8babddcd0cbf2b64caf12336f3c1c16e
1d35d3b77312ddd236a210254b82f92c88bc87b5
/src/qt/editaddressdialog.cpp
053b36ce7fdfadc2ec472ca8a43b5e2239ced438
[ "MIT" ]
permissive
blankcoin/blank
bee311cdfadf4f0bf449a20e6086736caa63c8f4
96be8b866e59cfaa8ee2884d9028c0293da92384
refs/heads/master
2020-03-20T23:12:54.777084
2018-06-22T05:35:12
2018-06-22T05:35:12
137,835,440
0
2
null
null
null
null
UTF-8
C++
false
false
3,729
cpp
#include "editaddressdialog.h" #include "ui_editaddressdialog.h" #include "addresstablemodel.h" #include "guiutil.h" #include <QDataWidgetMapper> #include <QMessageBox> EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *model) { this->model = model; if(!model) return; mapper->setModel(model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text()); break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; case AddressTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid Blank address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &address) { this->address = address; ui->addressEdit->setText(address); }
[ "ridwansky92@gmail.com" ]
ridwansky92@gmail.com
f10841b65b4b0a9c84454ab6bd4c6125f7453c3f
e72a75dcf0307af7ee53a29155bf61de13263020
/src/points_to_analysis/Common/Include/context.h
b2cb5adc8d08b5de1b027501245fa61c2001556d
[]
no_license
tapicer/resource-contracts-.net
f90e38a8c4e62c5408e70232f23edf5a1e641c30
f7b4977e6e004ec16dde4ad65266bb46417d2234
refs/heads/master
2020-03-28T00:43:48.508821
2016-12-05T17:03:56
2016-12-05T17:03:56
4,037,508
0
0
null
null
null
null
UTF-8
C++
false
false
78,683
h
#pragma warning( disable: 4049 ) /* more than 64k source lines */ /* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 6.00.0347 */ /* at Tue Sep 25 01:28:41 2001 */ /* Compiler settings for context.idl: Oicf, W0, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext error checks: allocation ref bounds_check enum stub_data , no_format_optimization VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 440 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __context_h__ #define __context_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IVsUserContext_FWD_DEFINED__ #define __IVsUserContext_FWD_DEFINED__ typedef interface IVsUserContext IVsUserContext; #endif /* __IVsUserContext_FWD_DEFINED__ */ #ifndef __IVsUserContextUpdate_FWD_DEFINED__ #define __IVsUserContextUpdate_FWD_DEFINED__ typedef interface IVsUserContextUpdate IVsUserContextUpdate; #endif /* __IVsUserContextUpdate_FWD_DEFINED__ */ #ifndef __IVsProvideUserContext_FWD_DEFINED__ #define __IVsProvideUserContext_FWD_DEFINED__ typedef interface IVsProvideUserContext IVsProvideUserContext; #endif /* __IVsProvideUserContext_FWD_DEFINED__ */ #ifndef __IVsProvideUserContextForObject_FWD_DEFINED__ #define __IVsProvideUserContextForObject_FWD_DEFINED__ typedef interface IVsProvideUserContextForObject IVsProvideUserContextForObject; #endif /* __IVsProvideUserContextForObject_FWD_DEFINED__ */ #ifndef __IVsUserContextItemCollection_FWD_DEFINED__ #define __IVsUserContextItemCollection_FWD_DEFINED__ typedef interface IVsUserContextItemCollection IVsUserContextItemCollection; #endif /* __IVsUserContextItemCollection_FWD_DEFINED__ */ #ifndef __IVsUserContextItem_FWD_DEFINED__ #define __IVsUserContextItem_FWD_DEFINED__ typedef interface IVsUserContextItem IVsUserContextItem; #endif /* __IVsUserContextItem_FWD_DEFINED__ */ #ifndef __IVsHelpAttributeList_FWD_DEFINED__ #define __IVsHelpAttributeList_FWD_DEFINED__ typedef interface IVsHelpAttributeList IVsHelpAttributeList; #endif /* __IVsHelpAttributeList_FWD_DEFINED__ */ #ifndef __IVsMonitorUserContext_FWD_DEFINED__ #define __IVsMonitorUserContext_FWD_DEFINED__ typedef interface IVsMonitorUserContext IVsMonitorUserContext; #endif /* __IVsMonitorUserContext_FWD_DEFINED__ */ #ifndef __IVsUserContextItemProvider_FWD_DEFINED__ #define __IVsUserContextItemProvider_FWD_DEFINED__ typedef interface IVsUserContextItemProvider IVsUserContextItemProvider; #endif /* __IVsUserContextItemProvider_FWD_DEFINED__ */ #ifndef __IVsUserContextCustomize_FWD_DEFINED__ #define __IVsUserContextCustomize_FWD_DEFINED__ typedef interface IVsUserContextCustomize IVsUserContextCustomize; #endif /* __IVsUserContextCustomize_FWD_DEFINED__ */ #ifndef __IVsUserContextItemEvents_FWD_DEFINED__ #define __IVsUserContextItemEvents_FWD_DEFINED__ typedef interface IVsUserContextItemEvents IVsUserContextItemEvents; #endif /* __IVsUserContextItemEvents_FWD_DEFINED__ */ #ifndef __VsContextClass_FWD_DEFINED__ #define __VsContextClass_FWD_DEFINED__ #ifdef __cplusplus typedef class VsContextClass VsContextClass; #else typedef struct VsContextClass VsContextClass; #endif /* __cplusplus */ #endif /* __VsContextClass_FWD_DEFINED__ */ /* header files for imported files */ #include "oleidl.h" #include "servprov.h" #include "oaidl.h" #include "ocidl.h" #ifdef __cplusplus extern "C"{ #endif void * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void * ); /* interface __MIDL_itf_context_0000 */ /* [local] */ #pragma once typedef DWORD_PTR VSCOOKIE; typedef DWORD_PTR VSCONTEXTUPDATECOOKIE; typedef DWORD_PTR VSSUBCONTEXTCOOKIE; typedef DWORD_PTR VSINFOPROVIDERCOOKIE; typedef enum tagVsUserContextPriority { VSUC_Priority_None = 0, VSUC_Priority_Ambient = 100, VSUC_Priority_State = 200, VSUC_Priority_Project = 300, VSUC_Priority_ProjectItem = 400, VSUC_Priority_Window = 500, VSUC_Priority_Selection = 600, VSUC_Priority_MarkerSel = 700, VSUC_Priority_Enterprise = 800, VSUC_Priority_WindowFrame = 900, VSUC_Priority_ToolWndSel = 1000, VSUC_Priority_Highest = 1100 } VSUSERCONTEXTPRIORITY; typedef enum tagVsUserContextAttributeUsage { VSUC_Usage_Filter = 0, VSUC_Usage_Lookup = 1, VSUC_Usage_LookupF1 = 2, VSUC_Usage_Lookup_CaseSensitive = 3, VSUC_Usage_LookupF1_CaseSensitive = 4 } VSUSERCONTEXTATTRIBUTEUSAGE; extern RPC_IF_HANDLE __MIDL_itf_context_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0000_v0_0_s_ifspec; #ifndef __IVsUserContext_INTERFACE_DEFINED__ #define __IVsUserContext_INTERFACE_DEFINED__ /* interface IVsUserContext */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContext; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("761081DF-D45F-4683-9B9E-1B7241E56F5C") IVsUserContext : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE AddAttribute( /* [in] */ VSUSERCONTEXTATTRIBUTEUSAGE usage, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveAttribute( /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue) = 0; virtual HRESULT STDMETHODCALLTYPE AddSubcontext( /* [in] */ IVsUserContext *pSubCtx, /* [in] */ int lPriority, /* [retval][out] */ VSCOOKIE *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveSubcontext( /* [in] */ VSCOOKIE dwcookie) = 0; virtual HRESULT STDMETHODCALLTYPE CountAttributes( /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ int *pc) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttribute( /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue) = 0; virtual HRESULT STDMETHODCALLTYPE CountSubcontexts( /* [retval][out] */ int *pc) = 0; virtual HRESULT STDMETHODCALLTYPE GetSubcontext( /* [in] */ int i, /* [retval][out] */ IVsUserContext **ppSubCtx) = 0; virtual HRESULT STDMETHODCALLTYPE IsDirty( /* [retval][out] */ BOOL *pfDirty) = 0; virtual HRESULT STDMETHODCALLTYPE SetDirty( /* [in] */ BOOL fDirty) = 0; virtual HRESULT STDMETHODCALLTYPE Update( void) = 0; virtual HRESULT STDMETHODCALLTYPE AdviseUpdate( /* [in] */ IVsUserContextUpdate *pUpdate, /* [retval][out] */ VSCOOKIE *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE UnadviseUpdate( /* [in] */ VSCOOKIE dwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttrUsage( /* [in] */ int index, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ VSUSERCONTEXTATTRIBUTEUSAGE *pUsage) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveAllSubcontext( void) = 0; virtual HRESULT STDMETHODCALLTYPE GetPriority( /* [retval][out] */ int *lPriority) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveAttributeIncludeChildren( /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttributePri( /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ int *piPriority, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue) = 0; }; #else /* C style interface */ typedef struct IVsUserContextVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContext * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContext * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContext * This); HRESULT ( STDMETHODCALLTYPE *AddAttribute )( IVsUserContext * This, /* [in] */ VSUSERCONTEXTATTRIBUTEUSAGE usage, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); HRESULT ( STDMETHODCALLTYPE *RemoveAttribute )( IVsUserContext * This, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); HRESULT ( STDMETHODCALLTYPE *AddSubcontext )( IVsUserContext * This, /* [in] */ IVsUserContext *pSubCtx, /* [in] */ int lPriority, /* [retval][out] */ VSCOOKIE *pdwCookie); HRESULT ( STDMETHODCALLTYPE *RemoveSubcontext )( IVsUserContext * This, /* [in] */ VSCOOKIE dwcookie); HRESULT ( STDMETHODCALLTYPE *CountAttributes )( IVsUserContext * This, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ int *pc); HRESULT ( STDMETHODCALLTYPE *GetAttribute )( IVsUserContext * This, /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); HRESULT ( STDMETHODCALLTYPE *CountSubcontexts )( IVsUserContext * This, /* [retval][out] */ int *pc); HRESULT ( STDMETHODCALLTYPE *GetSubcontext )( IVsUserContext * This, /* [in] */ int i, /* [retval][out] */ IVsUserContext **ppSubCtx); HRESULT ( STDMETHODCALLTYPE *IsDirty )( IVsUserContext * This, /* [retval][out] */ BOOL *pfDirty); HRESULT ( STDMETHODCALLTYPE *SetDirty )( IVsUserContext * This, /* [in] */ BOOL fDirty); HRESULT ( STDMETHODCALLTYPE *Update )( IVsUserContext * This); HRESULT ( STDMETHODCALLTYPE *AdviseUpdate )( IVsUserContext * This, /* [in] */ IVsUserContextUpdate *pUpdate, /* [retval][out] */ VSCOOKIE *pdwCookie); HRESULT ( STDMETHODCALLTYPE *UnadviseUpdate )( IVsUserContext * This, /* [in] */ VSCOOKIE dwCookie); HRESULT ( STDMETHODCALLTYPE *GetAttrUsage )( IVsUserContext * This, /* [in] */ int index, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ VSUSERCONTEXTATTRIBUTEUSAGE *pUsage); HRESULT ( STDMETHODCALLTYPE *RemoveAllSubcontext )( IVsUserContext * This); HRESULT ( STDMETHODCALLTYPE *GetPriority )( IVsUserContext * This, /* [retval][out] */ int *lPriority); HRESULT ( STDMETHODCALLTYPE *RemoveAttributeIncludeChildren )( IVsUserContext * This, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); HRESULT ( STDMETHODCALLTYPE *GetAttributePri )( IVsUserContext * This, /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ int *piPriority, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); END_INTERFACE } IVsUserContextVtbl; interface IVsUserContext { CONST_VTBL struct IVsUserContextVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContext_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContext_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContext_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContext_AddAttribute(This,usage,szName,szValue) \ (This)->lpVtbl -> AddAttribute(This,usage,szName,szValue) #define IVsUserContext_RemoveAttribute(This,szName,szValue) \ (This)->lpVtbl -> RemoveAttribute(This,szName,szValue) #define IVsUserContext_AddSubcontext(This,pSubCtx,lPriority,pdwCookie) \ (This)->lpVtbl -> AddSubcontext(This,pSubCtx,lPriority,pdwCookie) #define IVsUserContext_RemoveSubcontext(This,dwcookie) \ (This)->lpVtbl -> RemoveSubcontext(This,dwcookie) #define IVsUserContext_CountAttributes(This,pszName,fIncludeChildren,pc) \ (This)->lpVtbl -> CountAttributes(This,pszName,fIncludeChildren,pc) #define IVsUserContext_GetAttribute(This,iAttribute,pszName,fIncludeChildren,pbstrName,pbstrValue) \ (This)->lpVtbl -> GetAttribute(This,iAttribute,pszName,fIncludeChildren,pbstrName,pbstrValue) #define IVsUserContext_CountSubcontexts(This,pc) \ (This)->lpVtbl -> CountSubcontexts(This,pc) #define IVsUserContext_GetSubcontext(This,i,ppSubCtx) \ (This)->lpVtbl -> GetSubcontext(This,i,ppSubCtx) #define IVsUserContext_IsDirty(This,pfDirty) \ (This)->lpVtbl -> IsDirty(This,pfDirty) #define IVsUserContext_SetDirty(This,fDirty) \ (This)->lpVtbl -> SetDirty(This,fDirty) #define IVsUserContext_Update(This) \ (This)->lpVtbl -> Update(This) #define IVsUserContext_AdviseUpdate(This,pUpdate,pdwCookie) \ (This)->lpVtbl -> AdviseUpdate(This,pUpdate,pdwCookie) #define IVsUserContext_UnadviseUpdate(This,dwCookie) \ (This)->lpVtbl -> UnadviseUpdate(This,dwCookie) #define IVsUserContext_GetAttrUsage(This,index,fIncludeChildren,pUsage) \ (This)->lpVtbl -> GetAttrUsage(This,index,fIncludeChildren,pUsage) #define IVsUserContext_RemoveAllSubcontext(This) \ (This)->lpVtbl -> RemoveAllSubcontext(This) #define IVsUserContext_GetPriority(This,lPriority) \ (This)->lpVtbl -> GetPriority(This,lPriority) #define IVsUserContext_RemoveAttributeIncludeChildren(This,szName,szValue) \ (This)->lpVtbl -> RemoveAttributeIncludeChildren(This,szName,szValue) #define IVsUserContext_GetAttributePri(This,iAttribute,pszName,fIncludeChildren,piPriority,pbstrName,pbstrValue) \ (This)->lpVtbl -> GetAttributePri(This,iAttribute,pszName,fIncludeChildren,piPriority,pbstrName,pbstrValue) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsUserContext_AddAttribute_Proxy( IVsUserContext * This, /* [in] */ VSUSERCONTEXTATTRIBUTEUSAGE usage, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); void __RPC_STUB IVsUserContext_AddAttribute_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_RemoveAttribute_Proxy( IVsUserContext * This, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); void __RPC_STUB IVsUserContext_RemoveAttribute_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_AddSubcontext_Proxy( IVsUserContext * This, /* [in] */ IVsUserContext *pSubCtx, /* [in] */ int lPriority, /* [retval][out] */ VSCOOKIE *pdwCookie); void __RPC_STUB IVsUserContext_AddSubcontext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_RemoveSubcontext_Proxy( IVsUserContext * This, /* [in] */ VSCOOKIE dwcookie); void __RPC_STUB IVsUserContext_RemoveSubcontext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_CountAttributes_Proxy( IVsUserContext * This, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ int *pc); void __RPC_STUB IVsUserContext_CountAttributes_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_GetAttribute_Proxy( IVsUserContext * This, /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); void __RPC_STUB IVsUserContext_GetAttribute_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_CountSubcontexts_Proxy( IVsUserContext * This, /* [retval][out] */ int *pc); void __RPC_STUB IVsUserContext_CountSubcontexts_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_GetSubcontext_Proxy( IVsUserContext * This, /* [in] */ int i, /* [retval][out] */ IVsUserContext **ppSubCtx); void __RPC_STUB IVsUserContext_GetSubcontext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_IsDirty_Proxy( IVsUserContext * This, /* [retval][out] */ BOOL *pfDirty); void __RPC_STUB IVsUserContext_IsDirty_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_SetDirty_Proxy( IVsUserContext * This, /* [in] */ BOOL fDirty); void __RPC_STUB IVsUserContext_SetDirty_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_Update_Proxy( IVsUserContext * This); void __RPC_STUB IVsUserContext_Update_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_AdviseUpdate_Proxy( IVsUserContext * This, /* [in] */ IVsUserContextUpdate *pUpdate, /* [retval][out] */ VSCOOKIE *pdwCookie); void __RPC_STUB IVsUserContext_AdviseUpdate_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_UnadviseUpdate_Proxy( IVsUserContext * This, /* [in] */ VSCOOKIE dwCookie); void __RPC_STUB IVsUserContext_UnadviseUpdate_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_GetAttrUsage_Proxy( IVsUserContext * This, /* [in] */ int index, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ VSUSERCONTEXTATTRIBUTEUSAGE *pUsage); void __RPC_STUB IVsUserContext_GetAttrUsage_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_RemoveAllSubcontext_Proxy( IVsUserContext * This); void __RPC_STUB IVsUserContext_RemoveAllSubcontext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_GetPriority_Proxy( IVsUserContext * This, /* [retval][out] */ int *lPriority); void __RPC_STUB IVsUserContext_GetPriority_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_RemoveAttributeIncludeChildren_Proxy( IVsUserContext * This, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); void __RPC_STUB IVsUserContext_RemoveAttributeIncludeChildren_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_GetAttributePri_Proxy( IVsUserContext * This, /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ int *piPriority, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); void __RPC_STUB IVsUserContext_GetAttributePri_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContext_INTERFACE_DEFINED__ */ #ifndef __IVsUserContextUpdate_INTERFACE_DEFINED__ #define __IVsUserContextUpdate_INTERFACE_DEFINED__ /* interface IVsUserContextUpdate */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContextUpdate; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("F5ED7D1C-61B6-428A-8129-E13B36D9E9A7") IVsUserContextUpdate : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE UpdateUserContext( /* [in] */ IVsUserContext *pCtx, /* [in] */ VSCOOKIE dwCookie) = 0; }; #else /* C style interface */ typedef struct IVsUserContextUpdateVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextUpdate * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextUpdate * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextUpdate * This); HRESULT ( STDMETHODCALLTYPE *UpdateUserContext )( IVsUserContextUpdate * This, /* [in] */ IVsUserContext *pCtx, /* [in] */ VSCOOKIE dwCookie); END_INTERFACE } IVsUserContextUpdateVtbl; interface IVsUserContextUpdate { CONST_VTBL struct IVsUserContextUpdateVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextUpdate_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextUpdate_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextUpdate_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextUpdate_UpdateUserContext(This,pCtx,dwCookie) \ (This)->lpVtbl -> UpdateUserContext(This,pCtx,dwCookie) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsUserContextUpdate_UpdateUserContext_Proxy( IVsUserContextUpdate * This, /* [in] */ IVsUserContext *pCtx, /* [in] */ VSCOOKIE dwCookie); void __RPC_STUB IVsUserContextUpdate_UpdateUserContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextUpdate_INTERFACE_DEFINED__ */ #ifndef __IVsProvideUserContext_INTERFACE_DEFINED__ #define __IVsProvideUserContext_INTERFACE_DEFINED__ /* interface IVsProvideUserContext */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsProvideUserContext; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("997D7904-D948-4C8B-8BAB-0BDA1E212F6E") IVsProvideUserContext : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetUserContext( /* [retval][out] */ IVsUserContext **ppctx) = 0; }; #else /* C style interface */ typedef struct IVsProvideUserContextVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsProvideUserContext * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsProvideUserContext * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsProvideUserContext * This); HRESULT ( STDMETHODCALLTYPE *GetUserContext )( IVsProvideUserContext * This, /* [retval][out] */ IVsUserContext **ppctx); END_INTERFACE } IVsProvideUserContextVtbl; interface IVsProvideUserContext { CONST_VTBL struct IVsProvideUserContextVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsProvideUserContext_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsProvideUserContext_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsProvideUserContext_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsProvideUserContext_GetUserContext(This,ppctx) \ (This)->lpVtbl -> GetUserContext(This,ppctx) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsProvideUserContext_GetUserContext_Proxy( IVsProvideUserContext * This, /* [retval][out] */ IVsUserContext **ppctx); void __RPC_STUB IVsProvideUserContext_GetUserContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsProvideUserContext_INTERFACE_DEFINED__ */ #ifndef __IVsProvideUserContextForObject_INTERFACE_DEFINED__ #define __IVsProvideUserContextForObject_INTERFACE_DEFINED__ /* interface IVsProvideUserContextForObject */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsProvideUserContextForObject; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("F98CCC8A-9C5F-41EB-8421-711C0F1880E6") IVsProvideUserContextForObject : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetObjectContext( /* [in] */ IUnknown *punk, /* [retval][out] */ IVsUserContext **ppctx) = 0; }; #else /* C style interface */ typedef struct IVsProvideUserContextForObjectVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsProvideUserContextForObject * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsProvideUserContextForObject * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsProvideUserContextForObject * This); HRESULT ( STDMETHODCALLTYPE *GetObjectContext )( IVsProvideUserContextForObject * This, /* [in] */ IUnknown *punk, /* [retval][out] */ IVsUserContext **ppctx); END_INTERFACE } IVsProvideUserContextForObjectVtbl; interface IVsProvideUserContextForObject { CONST_VTBL struct IVsProvideUserContextForObjectVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsProvideUserContextForObject_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsProvideUserContextForObject_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsProvideUserContextForObject_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsProvideUserContextForObject_GetObjectContext(This,punk,ppctx) \ (This)->lpVtbl -> GetObjectContext(This,punk,ppctx) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsProvideUserContextForObject_GetObjectContext_Proxy( IVsProvideUserContextForObject * This, /* [in] */ IUnknown *punk, /* [retval][out] */ IVsUserContext **ppctx); void __RPC_STUB IVsProvideUserContextForObject_GetObjectContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsProvideUserContextForObject_INTERFACE_DEFINED__ */ #ifndef __IVsUserContextItemCollection_INTERFACE_DEFINED__ #define __IVsUserContextItemCollection_INTERFACE_DEFINED__ /* interface IVsUserContextItemCollection */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContextItemCollection; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("2A6DE4A2-5B3D-46EB-A65C-24C4EF4F396F") IVsUserContextItemCollection : public IUnknown { public: virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_Item( /* [in] */ VARIANT index, /* [retval][out] */ IVsUserContextItem **ppItem) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum( /* [retval][out] */ IUnknown **pEnum) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Count( /* [retval][out] */ long *pCount) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ItemAt( /* [in] */ long index, /* [retval][out] */ IVsUserContextItem **ppItem) = 0; }; #else /* C style interface */ typedef struct IVsUserContextItemCollectionVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextItemCollection * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextItemCollection * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextItemCollection * This); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Item )( IVsUserContextItemCollection * This, /* [in] */ VARIANT index, /* [retval][out] */ IVsUserContextItem **ppItem); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )( IVsUserContextItemCollection * This, /* [retval][out] */ IUnknown **pEnum); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )( IVsUserContextItemCollection * This, /* [retval][out] */ long *pCount); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemAt )( IVsUserContextItemCollection * This, /* [in] */ long index, /* [retval][out] */ IVsUserContextItem **ppItem); END_INTERFACE } IVsUserContextItemCollectionVtbl; interface IVsUserContextItemCollection { CONST_VTBL struct IVsUserContextItemCollectionVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextItemCollection_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextItemCollection_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextItemCollection_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextItemCollection_get_Item(This,index,ppItem) \ (This)->lpVtbl -> get_Item(This,index,ppItem) #define IVsUserContextItemCollection_get__NewEnum(This,pEnum) \ (This)->lpVtbl -> get__NewEnum(This,pEnum) #define IVsUserContextItemCollection_get_Count(This,pCount) \ (This)->lpVtbl -> get_Count(This,pCount) #define IVsUserContextItemCollection_get_ItemAt(This,index,ppItem) \ (This)->lpVtbl -> get_ItemAt(This,index,ppItem) #endif /* COBJMACROS */ #endif /* C style interface */ /* [id][propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItemCollection_get_Item_Proxy( IVsUserContextItemCollection * This, /* [in] */ VARIANT index, /* [retval][out] */ IVsUserContextItem **ppItem); void __RPC_STUB IVsUserContextItemCollection_get_Item_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItemCollection_get__NewEnum_Proxy( IVsUserContextItemCollection * This, /* [retval][out] */ IUnknown **pEnum); void __RPC_STUB IVsUserContextItemCollection_get__NewEnum_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItemCollection_get_Count_Proxy( IVsUserContextItemCollection * This, /* [retval][out] */ long *pCount); void __RPC_STUB IVsUserContextItemCollection_get_Count_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItemCollection_get_ItemAt_Proxy( IVsUserContextItemCollection * This, /* [in] */ long index, /* [retval][out] */ IVsUserContextItem **ppItem); void __RPC_STUB IVsUserContextItemCollection_get_ItemAt_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextItemCollection_INTERFACE_DEFINED__ */ #ifndef __IVsUserContextItem_INTERFACE_DEFINED__ #define __IVsUserContextItem_INTERFACE_DEFINED__ /* interface IVsUserContextItem */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContextItem; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("720B8500-17B3-4C89-AE84-2CFE7251B4B8") IVsUserContextItem : public IUnknown { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Name( /* [retval][out] */ BSTR *pbstrName) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Command( /* [retval][out] */ BSTR *pbstrCommand) = 0; virtual HRESULT STDMETHODCALLTYPE CountAttributes( /* [in] */ LPCOLESTR pszAttrName, /* [retval][out] */ int *pc) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttribute( /* [in] */ LPCOLESTR pszAttrName, /* [in] */ int index, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue) = 0; }; #else /* C style interface */ typedef struct IVsUserContextItemVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextItem * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextItem * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextItem * This); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( IVsUserContextItem * This, /* [retval][out] */ BSTR *pbstrName); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Command )( IVsUserContextItem * This, /* [retval][out] */ BSTR *pbstrCommand); HRESULT ( STDMETHODCALLTYPE *CountAttributes )( IVsUserContextItem * This, /* [in] */ LPCOLESTR pszAttrName, /* [retval][out] */ int *pc); HRESULT ( STDMETHODCALLTYPE *GetAttribute )( IVsUserContextItem * This, /* [in] */ LPCOLESTR pszAttrName, /* [in] */ int index, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); END_INTERFACE } IVsUserContextItemVtbl; interface IVsUserContextItem { CONST_VTBL struct IVsUserContextItemVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextItem_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextItem_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextItem_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextItem_get_Name(This,pbstrName) \ (This)->lpVtbl -> get_Name(This,pbstrName) #define IVsUserContextItem_get_Command(This,pbstrCommand) \ (This)->lpVtbl -> get_Command(This,pbstrCommand) #define IVsUserContextItem_CountAttributes(This,pszAttrName,pc) \ (This)->lpVtbl -> CountAttributes(This,pszAttrName,pc) #define IVsUserContextItem_GetAttribute(This,pszAttrName,index,pbstrName,pbstrValue) \ (This)->lpVtbl -> GetAttribute(This,pszAttrName,index,pbstrName,pbstrValue) #endif /* COBJMACROS */ #endif /* C style interface */ /* [propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItem_get_Name_Proxy( IVsUserContextItem * This, /* [retval][out] */ BSTR *pbstrName); void __RPC_STUB IVsUserContextItem_get_Name_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItem_get_Command_Proxy( IVsUserContextItem * This, /* [retval][out] */ BSTR *pbstrCommand); void __RPC_STUB IVsUserContextItem_get_Command_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItem_CountAttributes_Proxy( IVsUserContextItem * This, /* [in] */ LPCOLESTR pszAttrName, /* [retval][out] */ int *pc); void __RPC_STUB IVsUserContextItem_CountAttributes_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItem_GetAttribute_Proxy( IVsUserContextItem * This, /* [in] */ LPCOLESTR pszAttrName, /* [in] */ int index, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); void __RPC_STUB IVsUserContextItem_GetAttribute_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextItem_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_context_0259 */ /* [local] */ typedef enum tagAttrValueType { VSHAL_Real = 0, VSHAL_Display = 1 } ATTRVALUETYPE; extern RPC_IF_HANDLE __MIDL_itf_context_0259_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0259_v0_0_s_ifspec; #ifndef __IVsHelpAttributeList_INTERFACE_DEFINED__ #define __IVsHelpAttributeList_INTERFACE_DEFINED__ /* interface IVsHelpAttributeList */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsHelpAttributeList; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("0A56FB1E-1B2F-4699-8178-63B98E816F35") IVsHelpAttributeList : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetAttributeName( /* [out] */ BSTR *bstrName) = 0; virtual HRESULT STDMETHODCALLTYPE GetCount( /* [out] */ int *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE UpdateAttributeStatus( /* [in] */ BOOL *afActive) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttributeStatusVal( /* [in] */ BSTR bstrValue, /* [in] */ ATTRVALUETYPE type, /* [out] */ BOOL *pfActive) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttributeStatusIndex( /* [in] */ int index, /* [out] */ BOOL *pfActive) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttributeValue( /* [in] */ int index, /* [in] */ ATTRVALUETYPE type, /* [out] */ BSTR *pbstrValue) = 0; }; #else /* C style interface */ typedef struct IVsHelpAttributeListVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsHelpAttributeList * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsHelpAttributeList * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsHelpAttributeList * This); HRESULT ( STDMETHODCALLTYPE *GetAttributeName )( IVsHelpAttributeList * This, /* [out] */ BSTR *bstrName); HRESULT ( STDMETHODCALLTYPE *GetCount )( IVsHelpAttributeList * This, /* [out] */ int *pCount); HRESULT ( STDMETHODCALLTYPE *UpdateAttributeStatus )( IVsHelpAttributeList * This, /* [in] */ BOOL *afActive); HRESULT ( STDMETHODCALLTYPE *GetAttributeStatusVal )( IVsHelpAttributeList * This, /* [in] */ BSTR bstrValue, /* [in] */ ATTRVALUETYPE type, /* [out] */ BOOL *pfActive); HRESULT ( STDMETHODCALLTYPE *GetAttributeStatusIndex )( IVsHelpAttributeList * This, /* [in] */ int index, /* [out] */ BOOL *pfActive); HRESULT ( STDMETHODCALLTYPE *GetAttributeValue )( IVsHelpAttributeList * This, /* [in] */ int index, /* [in] */ ATTRVALUETYPE type, /* [out] */ BSTR *pbstrValue); END_INTERFACE } IVsHelpAttributeListVtbl; interface IVsHelpAttributeList { CONST_VTBL struct IVsHelpAttributeListVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsHelpAttributeList_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsHelpAttributeList_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsHelpAttributeList_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsHelpAttributeList_GetAttributeName(This,bstrName) \ (This)->lpVtbl -> GetAttributeName(This,bstrName) #define IVsHelpAttributeList_GetCount(This,pCount) \ (This)->lpVtbl -> GetCount(This,pCount) #define IVsHelpAttributeList_UpdateAttributeStatus(This,afActive) \ (This)->lpVtbl -> UpdateAttributeStatus(This,afActive) #define IVsHelpAttributeList_GetAttributeStatusVal(This,bstrValue,type,pfActive) \ (This)->lpVtbl -> GetAttributeStatusVal(This,bstrValue,type,pfActive) #define IVsHelpAttributeList_GetAttributeStatusIndex(This,index,pfActive) \ (This)->lpVtbl -> GetAttributeStatusIndex(This,index,pfActive) #define IVsHelpAttributeList_GetAttributeValue(This,index,type,pbstrValue) \ (This)->lpVtbl -> GetAttributeValue(This,index,type,pbstrValue) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_GetAttributeName_Proxy( IVsHelpAttributeList * This, /* [out] */ BSTR *bstrName); void __RPC_STUB IVsHelpAttributeList_GetAttributeName_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_GetCount_Proxy( IVsHelpAttributeList * This, /* [out] */ int *pCount); void __RPC_STUB IVsHelpAttributeList_GetCount_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_UpdateAttributeStatus_Proxy( IVsHelpAttributeList * This, /* [in] */ BOOL *afActive); void __RPC_STUB IVsHelpAttributeList_UpdateAttributeStatus_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_GetAttributeStatusVal_Proxy( IVsHelpAttributeList * This, /* [in] */ BSTR bstrValue, /* [in] */ ATTRVALUETYPE type, /* [out] */ BOOL *pfActive); void __RPC_STUB IVsHelpAttributeList_GetAttributeStatusVal_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_GetAttributeStatusIndex_Proxy( IVsHelpAttributeList * This, /* [in] */ int index, /* [out] */ BOOL *pfActive); void __RPC_STUB IVsHelpAttributeList_GetAttributeStatusIndex_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_GetAttributeValue_Proxy( IVsHelpAttributeList * This, /* [in] */ int index, /* [in] */ ATTRVALUETYPE type, /* [out] */ BSTR *pbstrValue); void __RPC_STUB IVsHelpAttributeList_GetAttributeValue_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsHelpAttributeList_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_context_0260 */ /* [local] */ #define VSUC_CURRENT_F1 ((LPCOLESTR)1) extern RPC_IF_HANDLE __MIDL_itf_context_0260_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0260_v0_0_s_ifspec; #ifndef __IVsMonitorUserContext_INTERFACE_DEFINED__ #define __IVsMonitorUserContext_INTERFACE_DEFINED__ /* interface IVsMonitorUserContext */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsMonitorUserContext; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("9C074FDB-3D7D-4512-9604-72B3B0A5F609") IVsMonitorUserContext : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetSite( /* [in] */ IServiceProvider *pSP) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ApplicationContext( /* [retval][out] */ IVsUserContext **ppContext) = 0; virtual /* [propput] */ HRESULT STDMETHODCALLTYPE put_ApplicationContext( /* [in] */ IVsUserContext *pContext) = 0; virtual HRESULT STDMETHODCALLTYPE CreateEmptyContext( /* [retval][out] */ IVsUserContext **ppContext) = 0; virtual HRESULT STDMETHODCALLTYPE GetContextItems( /* [out] */ IVsUserContextItemCollection **pplist) = 0; virtual HRESULT STDMETHODCALLTYPE FindTargetItems( /* [in] */ LPCOLESTR pszTargetAttr, /* [in] */ LPCOLESTR pszTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [out] */ BOOL *pfF1Kwd) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterItemProvider( /* [in] */ IVsUserContextItemProvider *pProvider, /* [retval][out] */ VSCOOKIE *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE UnregisterItemProvider( /* [in] */ VSCOOKIE dwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE AdviseContextItemEvents( /* [in] */ IVsUserContextItemEvents *pEvents, /* [retval][out] */ VSCOOKIE *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE UnadviseContextItemEvent( /* [in] */ VSCOOKIE dwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE GetNextCtxBagAttr( /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal) = 0; virtual HRESULT STDMETHODCALLTYPE ResetNextCtxBagAttr( void) = 0; virtual HRESULT STDMETHODCALLTYPE GetPrevAttrCache( /* [out] */ BSTR **pbstrCacheArray, /* [out] */ int **pnCurrNumStored, /* [out] */ int *pnMaxNumStored) = 0; virtual HRESULT STDMETHODCALLTYPE GetNextCtxBag( /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal) = 0; virtual HRESULT STDMETHODCALLTYPE IsIdleAvailable( /* [out] */ BOOL *pfIdleAvail) = 0; virtual HRESULT STDMETHODCALLTYPE SetTopicTypeFilter( /* [in] */ IVsHelpAttributeList *pTopicTypeList) = 0; virtual HRESULT STDMETHODCALLTYPE GetF1Kwd( /* [out] */ BSTR *pbstrKwd, /* [out] */ BOOL *fF1Kwd) = 0; virtual HRESULT STDMETHODCALLTYPE IsF1Lookup( /* [out] */ BOOL *fF1Lookup) = 0; }; #else /* C style interface */ typedef struct IVsMonitorUserContextVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsMonitorUserContext * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsMonitorUserContext * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsMonitorUserContext * This); HRESULT ( STDMETHODCALLTYPE *SetSite )( IVsMonitorUserContext * This, /* [in] */ IServiceProvider *pSP); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ApplicationContext )( IVsMonitorUserContext * This, /* [retval][out] */ IVsUserContext **ppContext); /* [propput] */ HRESULT ( STDMETHODCALLTYPE *put_ApplicationContext )( IVsMonitorUserContext * This, /* [in] */ IVsUserContext *pContext); HRESULT ( STDMETHODCALLTYPE *CreateEmptyContext )( IVsMonitorUserContext * This, /* [retval][out] */ IVsUserContext **ppContext); HRESULT ( STDMETHODCALLTYPE *GetContextItems )( IVsMonitorUserContext * This, /* [out] */ IVsUserContextItemCollection **pplist); HRESULT ( STDMETHODCALLTYPE *FindTargetItems )( IVsMonitorUserContext * This, /* [in] */ LPCOLESTR pszTargetAttr, /* [in] */ LPCOLESTR pszTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [out] */ BOOL *pfF1Kwd); HRESULT ( STDMETHODCALLTYPE *RegisterItemProvider )( IVsMonitorUserContext * This, /* [in] */ IVsUserContextItemProvider *pProvider, /* [retval][out] */ VSCOOKIE *pdwCookie); HRESULT ( STDMETHODCALLTYPE *UnregisterItemProvider )( IVsMonitorUserContext * This, /* [in] */ VSCOOKIE dwCookie); HRESULT ( STDMETHODCALLTYPE *AdviseContextItemEvents )( IVsMonitorUserContext * This, /* [in] */ IVsUserContextItemEvents *pEvents, /* [retval][out] */ VSCOOKIE *pdwCookie); HRESULT ( STDMETHODCALLTYPE *UnadviseContextItemEvent )( IVsMonitorUserContext * This, /* [in] */ VSCOOKIE dwCookie); HRESULT ( STDMETHODCALLTYPE *GetNextCtxBagAttr )( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal); HRESULT ( STDMETHODCALLTYPE *ResetNextCtxBagAttr )( IVsMonitorUserContext * This); HRESULT ( STDMETHODCALLTYPE *GetPrevAttrCache )( IVsMonitorUserContext * This, /* [out] */ BSTR **pbstrCacheArray, /* [out] */ int **pnCurrNumStored, /* [out] */ int *pnMaxNumStored); HRESULT ( STDMETHODCALLTYPE *GetNextCtxBag )( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal); HRESULT ( STDMETHODCALLTYPE *IsIdleAvailable )( IVsMonitorUserContext * This, /* [out] */ BOOL *pfIdleAvail); HRESULT ( STDMETHODCALLTYPE *SetTopicTypeFilter )( IVsMonitorUserContext * This, /* [in] */ IVsHelpAttributeList *pTopicTypeList); HRESULT ( STDMETHODCALLTYPE *GetF1Kwd )( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrKwd, /* [out] */ BOOL *fF1Kwd); HRESULT ( STDMETHODCALLTYPE *IsF1Lookup )( IVsMonitorUserContext * This, /* [out] */ BOOL *fF1Lookup); END_INTERFACE } IVsMonitorUserContextVtbl; interface IVsMonitorUserContext { CONST_VTBL struct IVsMonitorUserContextVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsMonitorUserContext_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsMonitorUserContext_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsMonitorUserContext_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsMonitorUserContext_SetSite(This,pSP) \ (This)->lpVtbl -> SetSite(This,pSP) #define IVsMonitorUserContext_get_ApplicationContext(This,ppContext) \ (This)->lpVtbl -> get_ApplicationContext(This,ppContext) #define IVsMonitorUserContext_put_ApplicationContext(This,pContext) \ (This)->lpVtbl -> put_ApplicationContext(This,pContext) #define IVsMonitorUserContext_CreateEmptyContext(This,ppContext) \ (This)->lpVtbl -> CreateEmptyContext(This,ppContext) #define IVsMonitorUserContext_GetContextItems(This,pplist) \ (This)->lpVtbl -> GetContextItems(This,pplist) #define IVsMonitorUserContext_FindTargetItems(This,pszTargetAttr,pszTargetAttrValue,ppList,pfF1Kwd) \ (This)->lpVtbl -> FindTargetItems(This,pszTargetAttr,pszTargetAttrValue,ppList,pfF1Kwd) #define IVsMonitorUserContext_RegisterItemProvider(This,pProvider,pdwCookie) \ (This)->lpVtbl -> RegisterItemProvider(This,pProvider,pdwCookie) #define IVsMonitorUserContext_UnregisterItemProvider(This,dwCookie) \ (This)->lpVtbl -> UnregisterItemProvider(This,dwCookie) #define IVsMonitorUserContext_AdviseContextItemEvents(This,pEvents,pdwCookie) \ (This)->lpVtbl -> AdviseContextItemEvents(This,pEvents,pdwCookie) #define IVsMonitorUserContext_UnadviseContextItemEvent(This,dwCookie) \ (This)->lpVtbl -> UnadviseContextItemEvent(This,dwCookie) #define IVsMonitorUserContext_GetNextCtxBagAttr(This,pbstrAttrName,pbstrAttrVal) \ (This)->lpVtbl -> GetNextCtxBagAttr(This,pbstrAttrName,pbstrAttrVal) #define IVsMonitorUserContext_ResetNextCtxBagAttr(This) \ (This)->lpVtbl -> ResetNextCtxBagAttr(This) #define IVsMonitorUserContext_GetPrevAttrCache(This,pbstrCacheArray,pnCurrNumStored,pnMaxNumStored) \ (This)->lpVtbl -> GetPrevAttrCache(This,pbstrCacheArray,pnCurrNumStored,pnMaxNumStored) #define IVsMonitorUserContext_GetNextCtxBag(This,pbstrAttrName,pbstrAttrVal) \ (This)->lpVtbl -> GetNextCtxBag(This,pbstrAttrName,pbstrAttrVal) #define IVsMonitorUserContext_IsIdleAvailable(This,pfIdleAvail) \ (This)->lpVtbl -> IsIdleAvailable(This,pfIdleAvail) #define IVsMonitorUserContext_SetTopicTypeFilter(This,pTopicTypeList) \ (This)->lpVtbl -> SetTopicTypeFilter(This,pTopicTypeList) #define IVsMonitorUserContext_GetF1Kwd(This,pbstrKwd,fF1Kwd) \ (This)->lpVtbl -> GetF1Kwd(This,pbstrKwd,fF1Kwd) #define IVsMonitorUserContext_IsF1Lookup(This,fF1Lookup) \ (This)->lpVtbl -> IsF1Lookup(This,fF1Lookup) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_SetSite_Proxy( IVsMonitorUserContext * This, /* [in] */ IServiceProvider *pSP); void __RPC_STUB IVsMonitorUserContext_SetSite_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [propget] */ HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_get_ApplicationContext_Proxy( IVsMonitorUserContext * This, /* [retval][out] */ IVsUserContext **ppContext); void __RPC_STUB IVsMonitorUserContext_get_ApplicationContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [propput] */ HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_put_ApplicationContext_Proxy( IVsMonitorUserContext * This, /* [in] */ IVsUserContext *pContext); void __RPC_STUB IVsMonitorUserContext_put_ApplicationContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_CreateEmptyContext_Proxy( IVsMonitorUserContext * This, /* [retval][out] */ IVsUserContext **ppContext); void __RPC_STUB IVsMonitorUserContext_CreateEmptyContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_GetContextItems_Proxy( IVsMonitorUserContext * This, /* [out] */ IVsUserContextItemCollection **pplist); void __RPC_STUB IVsMonitorUserContext_GetContextItems_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_FindTargetItems_Proxy( IVsMonitorUserContext * This, /* [in] */ LPCOLESTR pszTargetAttr, /* [in] */ LPCOLESTR pszTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [out] */ BOOL *pfF1Kwd); void __RPC_STUB IVsMonitorUserContext_FindTargetItems_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_RegisterItemProvider_Proxy( IVsMonitorUserContext * This, /* [in] */ IVsUserContextItemProvider *pProvider, /* [retval][out] */ VSCOOKIE *pdwCookie); void __RPC_STUB IVsMonitorUserContext_RegisterItemProvider_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_UnregisterItemProvider_Proxy( IVsMonitorUserContext * This, /* [in] */ VSCOOKIE dwCookie); void __RPC_STUB IVsMonitorUserContext_UnregisterItemProvider_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_AdviseContextItemEvents_Proxy( IVsMonitorUserContext * This, /* [in] */ IVsUserContextItemEvents *pEvents, /* [retval][out] */ VSCOOKIE *pdwCookie); void __RPC_STUB IVsMonitorUserContext_AdviseContextItemEvents_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_UnadviseContextItemEvent_Proxy( IVsMonitorUserContext * This, /* [in] */ VSCOOKIE dwCookie); void __RPC_STUB IVsMonitorUserContext_UnadviseContextItemEvent_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_GetNextCtxBagAttr_Proxy( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal); void __RPC_STUB IVsMonitorUserContext_GetNextCtxBagAttr_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_ResetNextCtxBagAttr_Proxy( IVsMonitorUserContext * This); void __RPC_STUB IVsMonitorUserContext_ResetNextCtxBagAttr_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_GetPrevAttrCache_Proxy( IVsMonitorUserContext * This, /* [out] */ BSTR **pbstrCacheArray, /* [out] */ int **pnCurrNumStored, /* [out] */ int *pnMaxNumStored); void __RPC_STUB IVsMonitorUserContext_GetPrevAttrCache_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_GetNextCtxBag_Proxy( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal); void __RPC_STUB IVsMonitorUserContext_GetNextCtxBag_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_IsIdleAvailable_Proxy( IVsMonitorUserContext * This, /* [out] */ BOOL *pfIdleAvail); void __RPC_STUB IVsMonitorUserContext_IsIdleAvailable_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_SetTopicTypeFilter_Proxy( IVsMonitorUserContext * This, /* [in] */ IVsHelpAttributeList *pTopicTypeList); void __RPC_STUB IVsMonitorUserContext_SetTopicTypeFilter_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_GetF1Kwd_Proxy( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrKwd, /* [out] */ BOOL *fF1Kwd); void __RPC_STUB IVsMonitorUserContext_GetF1Kwd_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_IsF1Lookup_Proxy( IVsMonitorUserContext * This, /* [out] */ BOOL *fF1Lookup); void __RPC_STUB IVsMonitorUserContext_IsF1Lookup_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsMonitorUserContext_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_context_0261 */ /* [local] */ enum _VSCIPPROPID { VSCIPPROPID_NIL = -1, VSCIPPROPID_LookupType = 100, VSCIPPROPID_Customize = 200 } ; typedef LONG VSCIPPROPID; extern RPC_IF_HANDLE __MIDL_itf_context_0261_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0261_v0_0_s_ifspec; #ifndef __IVsUserContextItemProvider_INTERFACE_DEFINED__ #define __IVsUserContextItemProvider_INTERFACE_DEFINED__ /* interface IVsUserContextItemProvider */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContextItemProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("715C98B7-05FB-4A1A-86C8-FF00CE2E5D64") IVsUserContextItemProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetProperty( /* [in] */ VSCIPPROPID property, /* [retval][out] */ VARIANT *pvar) = 0; virtual HRESULT STDMETHODCALLTYPE SetProperty( /* [in] */ VSCIPPROPID property, /* [in] */ VARIANT var) = 0; virtual HRESULT STDMETHODCALLTYPE KeywordLookup( /* [in] */ LPCOLESTR pwzTargetAttr, /* [in] */ LPCOLESTR pwzTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [in] */ IVsMonitorUserContext *pCMUC, /* [in] */ BOOL fCheckIdle, /* [in] */ BOOL fContinueInterrupt) = 0; virtual HRESULT STDMETHODCALLTYPE PackedAttributeLookup( /* [in] */ LPCOLESTR pwzRequired, /* [in] */ LPCOLESTR pwzScope, /* [out] */ IVsUserContextItemCollection **ppList) = 0; virtual HRESULT STDMETHODCALLTYPE LookupEnabled( /* [out] */ BOOL *pfLookupEnabled) = 0; }; #else /* C style interface */ typedef struct IVsUserContextItemProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextItemProvider * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextItemProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextItemProvider * This); HRESULT ( STDMETHODCALLTYPE *GetProperty )( IVsUserContextItemProvider * This, /* [in] */ VSCIPPROPID property, /* [retval][out] */ VARIANT *pvar); HRESULT ( STDMETHODCALLTYPE *SetProperty )( IVsUserContextItemProvider * This, /* [in] */ VSCIPPROPID property, /* [in] */ VARIANT var); HRESULT ( STDMETHODCALLTYPE *KeywordLookup )( IVsUserContextItemProvider * This, /* [in] */ LPCOLESTR pwzTargetAttr, /* [in] */ LPCOLESTR pwzTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [in] */ IVsMonitorUserContext *pCMUC, /* [in] */ BOOL fCheckIdle, /* [in] */ BOOL fContinueInterrupt); HRESULT ( STDMETHODCALLTYPE *PackedAttributeLookup )( IVsUserContextItemProvider * This, /* [in] */ LPCOLESTR pwzRequired, /* [in] */ LPCOLESTR pwzScope, /* [out] */ IVsUserContextItemCollection **ppList); HRESULT ( STDMETHODCALLTYPE *LookupEnabled )( IVsUserContextItemProvider * This, /* [out] */ BOOL *pfLookupEnabled); END_INTERFACE } IVsUserContextItemProviderVtbl; interface IVsUserContextItemProvider { CONST_VTBL struct IVsUserContextItemProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextItemProvider_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextItemProvider_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextItemProvider_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextItemProvider_GetProperty(This,property,pvar) \ (This)->lpVtbl -> GetProperty(This,property,pvar) #define IVsUserContextItemProvider_SetProperty(This,property,var) \ (This)->lpVtbl -> SetProperty(This,property,var) #define IVsUserContextItemProvider_KeywordLookup(This,pwzTargetAttr,pwzTargetAttrValue,ppList,pCMUC,fCheckIdle,fContinueInterrupt) \ (This)->lpVtbl -> KeywordLookup(This,pwzTargetAttr,pwzTargetAttrValue,ppList,pCMUC,fCheckIdle,fContinueInterrupt) #define IVsUserContextItemProvider_PackedAttributeLookup(This,pwzRequired,pwzScope,ppList) \ (This)->lpVtbl -> PackedAttributeLookup(This,pwzRequired,pwzScope,ppList) #define IVsUserContextItemProvider_LookupEnabled(This,pfLookupEnabled) \ (This)->lpVtbl -> LookupEnabled(This,pfLookupEnabled) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsUserContextItemProvider_GetProperty_Proxy( IVsUserContextItemProvider * This, /* [in] */ VSCIPPROPID property, /* [retval][out] */ VARIANT *pvar); void __RPC_STUB IVsUserContextItemProvider_GetProperty_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItemProvider_SetProperty_Proxy( IVsUserContextItemProvider * This, /* [in] */ VSCIPPROPID property, /* [in] */ VARIANT var); void __RPC_STUB IVsUserContextItemProvider_SetProperty_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItemProvider_KeywordLookup_Proxy( IVsUserContextItemProvider * This, /* [in] */ LPCOLESTR pwzTargetAttr, /* [in] */ LPCOLESTR pwzTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [in] */ IVsMonitorUserContext *pCMUC, /* [in] */ BOOL fCheckIdle, /* [in] */ BOOL fContinueInterrupt); void __RPC_STUB IVsUserContextItemProvider_KeywordLookup_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItemProvider_PackedAttributeLookup_Proxy( IVsUserContextItemProvider * This, /* [in] */ LPCOLESTR pwzRequired, /* [in] */ LPCOLESTR pwzScope, /* [out] */ IVsUserContextItemCollection **ppList); void __RPC_STUB IVsUserContextItemProvider_PackedAttributeLookup_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItemProvider_LookupEnabled_Proxy( IVsUserContextItemProvider * This, /* [out] */ BOOL *pfLookupEnabled); void __RPC_STUB IVsUserContextItemProvider_LookupEnabled_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextItemProvider_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_context_0262 */ /* [local] */ enum _LIMITTOPICSOURCE { CCW_LimKwd_SelOnly = 0, CCW_LimKwd_NoAmbient = 1, CCW_LimKwd_All = 2, CCW_LimKwd_Last = 3 } ; typedef LONG LIMITTOPICSOURCE; extern RPC_IF_HANDLE __MIDL_itf_context_0262_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0262_v0_0_s_ifspec; #ifndef __IVsUserContextCustomize_INTERFACE_DEFINED__ #define __IVsUserContextCustomize_INTERFACE_DEFINED__ /* interface IVsUserContextCustomize */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContextCustomize; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("0F817159-761D-447e-9600-4C3387F4C0FD") IVsUserContextCustomize : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetLimitKeywordSource( /* [retval][out] */ LONG *pLimKwdSrc) = 0; }; #else /* C style interface */ typedef struct IVsUserContextCustomizeVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextCustomize * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextCustomize * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextCustomize * This); HRESULT ( STDMETHODCALLTYPE *GetLimitKeywordSource )( IVsUserContextCustomize * This, /* [retval][out] */ LONG *pLimKwdSrc); END_INTERFACE } IVsUserContextCustomizeVtbl; interface IVsUserContextCustomize { CONST_VTBL struct IVsUserContextCustomizeVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextCustomize_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextCustomize_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextCustomize_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextCustomize_GetLimitKeywordSource(This,pLimKwdSrc) \ (This)->lpVtbl -> GetLimitKeywordSource(This,pLimKwdSrc) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsUserContextCustomize_GetLimitKeywordSource_Proxy( IVsUserContextCustomize * This, /* [retval][out] */ LONG *pLimKwdSrc); void __RPC_STUB IVsUserContextCustomize_GetLimitKeywordSource_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextCustomize_INTERFACE_DEFINED__ */ #ifndef __IVsUserContextItemEvents_INTERFACE_DEFINED__ #define __IVsUserContextItemEvents_INTERFACE_DEFINED__ /* interface IVsUserContextItemEvents */ /* [object][version][uuid] */ EXTERN_C const IID IID_IVsUserContextItemEvents; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("A2078F0E-A310-420A-BA27-16531905B88F") IVsUserContextItemEvents : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE OnUserContextItemsAvailable( /* [in] */ IVsUserContextItemCollection *pList) = 0; }; #else /* C style interface */ typedef struct IVsUserContextItemEventsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextItemEvents * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextItemEvents * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextItemEvents * This); HRESULT ( STDMETHODCALLTYPE *OnUserContextItemsAvailable )( IVsUserContextItemEvents * This, /* [in] */ IVsUserContextItemCollection *pList); END_INTERFACE } IVsUserContextItemEventsVtbl; interface IVsUserContextItemEvents { CONST_VTBL struct IVsUserContextItemEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextItemEvents_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextItemEvents_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextItemEvents_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextItemEvents_OnUserContextItemsAvailable(This,pList) \ (This)->lpVtbl -> OnUserContextItemsAvailable(This,pList) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsUserContextItemEvents_OnUserContextItemsAvailable_Proxy( IVsUserContextItemEvents * This, /* [in] */ IVsUserContextItemCollection *pList); void __RPC_STUB IVsUserContextItemEvents_OnUserContextItemsAvailable_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextItemEvents_INTERFACE_DEFINED__ */ #ifndef __VsContext_LIBRARY_DEFINED__ #define __VsContext_LIBRARY_DEFINED__ /* library VsContext */ /* [version][uuid] */ EXTERN_C const IID LIBID_VsContext; EXTERN_C const CLSID CLSID_VsContextClass; #ifdef __cplusplus class DECLSPEC_UUID("3c1f59c6-69cf-11d2-aa7c-00c04f990343") VsContextClass; #endif #endif /* __VsContext_LIBRARY_DEFINED__ */ /* interface __MIDL_itf_context_0264 */ /* [local] */ #define SID_SVsMonitorUserContext IID_IVsMonitorUserContext #define HH_1x_ATTR L"HtmlHelp_1.X_LookupInfo" #define KWD_GUID L"KWD_GUID" #define KEYWORD_CS L"KEYWORD_CS" extern RPC_IF_HANDLE __MIDL_itf_context_0264_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0264_v0_0_s_ifspec; /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( unsigned long *, unsigned long , BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal( unsigned long *, unsigned char *, BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * ); void __RPC_USER BSTR_UserFree( unsigned long *, BSTR * ); unsigned long __RPC_USER VARIANT_UserSize( unsigned long *, unsigned long , VARIANT * ); unsigned char * __RPC_USER VARIANT_UserMarshal( unsigned long *, unsigned char *, VARIANT * ); unsigned char * __RPC_USER VARIANT_UserUnmarshal(unsigned long *, unsigned char *, VARIANT * ); void __RPC_USER VARIANT_UserFree( unsigned long *, VARIANT * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ "tapicer@gmail.com" ]
tapicer@gmail.com
d35613ad073f6ef2e0b4f9e4dced1732fbd323e1
bbdd63f4403ad2e15dce8dfd5ef35263d2f2bd86
/common/x64/include/Paint.h
bfe3798f7131c1eb2eb94c673658fe13ee72a6f9
[]
no_license
MelodyD/pytest_API
a7d4dcb1bd8ba9b1981ca640080c27e2b5aaa0b7
77e11924e3fec6e3ddbf65f07d05cf77a4fe94ea
refs/heads/main
2023-07-18T10:02:15.382032
2021-09-11T12:57:08
2021-09-11T12:57:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,694
h
/******************************************************************************* * RoadDB Confidential * Copyright (c) RoadDB 2019-2020 * * This software is furnished under license and may be used or * copied only in accordance with the terms of such license. ******************************************************************************* * @file Paint.h * @brief The class definition of Paint. * * Change Log: * Date Author Changes * 2020-06-18 Wei Tian Init version. * ******************************************************************************* */ #pragma once #include <vector> #include <utility> #include <memory> #include "VehicleAPICommon.h" #include "Line.h" #include "LogicTypes.h" #include <memory> namespace RDBVehicleAPI { class Line; class Paint : public Visualization, public std::enable_shared_from_this<Paint> { public: ~Paint(); /** * @brief Get the line object expressed this paint. * @return line object. */ std::shared_ptr<const Line> &getExpressedLine() { return expressedLine_; } private: void setExpressedLine(const std::shared_ptr<const Line> &line) { expressedLine_ = line; } objectID_t getExpressedLineID() { return expressedLineId_; } Paint(const objectID_t &id, const objectID_t &expressedLineId); Paint() = delete; Paint(const Paint &obj) = delete; Paint &operator=(const Paint &obj) = delete; private: std::shared_ptr<const Line> expressedLine_; objectID_t expressedLineId_; FRIEND_2_ROADDATAINFO; }; } /* namespace RDBVehicleAPI */
[ "guangli.bao@roaddb.com" ]
guangli.bao@roaddb.com
0e5a02f2107f66b6536b8c58a55b17640f195c79
34252ecd8762d8c3ece6bac271c9c457202ff1a7
/nnopencl/NetT.h
c9d385330fea1f7dace24c0ad5af85d2aaba070c
[ "MIT" ]
permissive
freegraphics/cpputils
cdf16819e8d4ae10368e3ec84f232af9c5ef4e5c
3f990d4765a50c7428bd6a4929a83ff49d3567bd
refs/heads/master
2020-05-20T18:47:40.529569
2016-09-18T20:24:25
2016-09-18T20:24:25
68,520,367
0
0
null
null
null
null
UTF-8
C++
false
false
6,635
h
#pragma once #include "openclnet.h" namespace opencl { template<typename _InputState,typename _OutputState> struct NetT : public DLNet { public: typedef DLNet::LayersList Layers; protected: typedef DLNet base; public: NetT(DLNetKernels* _kernels) :base(_kernels) { } void load(const CString& _file_name) { base::load(_file_name); } void save(const CString& _file_name) { base::save(_file_name); } void init_net( size_t _batch_size ,size_t _hidden_layer_size,size_t _hidden_layers_count ,real _learning_rate,real _momentum,real _l2_decay ,bool _dropout_mode,real _dropout_prob ,bool _last_layer_half_tanh ,bool _last_layer_single_relu ,bool _last_layer_regression ,bool _run_only_mode ,real _weights_scale_coef ,size_t _dropout_layer_count = 0 ) { create_input(divisible_8(_InputState::size())-1,_batch_size); std::vector<LayerOptions> layers; { LayerOptions opts; opts.out_depth = _hidden_layer_size; opts.relu_mode = true; size_t i = 0; for(i=0;i<_hidden_layers_count;i++) { if(_dropout_layer_count && (i%_dropout_layer_count==_dropout_layer_count/2)) { opts.dropout_mode = _dropout_mode; opts.drop_probability = _dropout_prob; } else { opts.dropout_mode = false; opts.drop_probability = (real)0.0; } layers.push_back(opts); } } if(_last_layer_half_tanh) { LayerOptions opts1; opts1.out_depth = divisible_8(_OutputState::size())-1; layers.push_back(opts1); LayerOptions opts2; opts2.out_depth = opts1.out_depth; opts2.single_half_tanh_mode = true; layers.push_back(opts2); } else if(_last_layer_single_relu) { LayerOptions opts1; opts1.out_depth = divisible_8(_OutputState::size())-1; layers.push_back(opts1); LayerOptions opts2; opts2.out_depth = opts1.out_depth; opts2.single_relu_mode = true; layers.push_back(opts2); } else if(_last_layer_regression) { LayerOptions opts; opts.out_depth = divisible_8(_OutputState::size())-1; opts.regression_mode = true; layers.push_back(opts); } else { LayerOptions opts; opts.out_depth = divisible_8(_OutputState::size())-1; layers.push_back(opts); } NetOptions net_options; net_options.run_only_net_mode = _run_only_mode; net_options.learning_rate = _learning_rate; net_options.momentum = _momentum; net_options.l2_decay = _l2_decay; net_options.weights_scale_coef = _weights_scale_coef; create(layers,net_options); } void init_autoencoder( size_t _batch_size ,size_t _hidden_layer_size,size_t _hidden_layers_count ,size_t _encoded_size ,real _learning_rate,real _momentum,real _l2_decay ,bool _dropout_mode,real _dropout_prob ,bool _run_only_mode ,real _weights_scale_coef ,size_t _dropout_layer_count = 0 ) { VERIFY_EXIT(EQL(divisible_8(_encoded_size)-1,_encoded_size)); create_input(divisible_8(_InputState::size())-1,_batch_size); std::vector<LayerOptions> layers; // 1st part { LayerOptions opts; opts.out_depth = _hidden_layer_size; opts.relu_mode = true; size_t i = 0; for(i=0;i<_hidden_layers_count;i++) { if(_dropout_layer_count && i%_dropout_layer_count==_dropout_layer_count/2) { opts.dropout_mode = _dropout_mode; opts.drop_probability = _dropout_prob; } else { opts.dropout_mode = false; opts.drop_probability = (real)0.0; } layers.push_back(opts); } } // encoded { LayerOptions opts; opts.out_depth = divisible_8(_encoded_size)-1; layers.push_back(opts); } // 2nd part { LayerOptions opts; opts.out_depth = _hidden_layer_size; opts.relu_mode = true; size_t i = 0; for(i=0;i<_hidden_layers_count;i++) { if(_dropout_layer_count && i%_dropout_layer_count==_dropout_layer_count/2) { opts.dropout_mode = _dropout_mode; opts.drop_probability = _dropout_prob; } else { opts.dropout_mode = false; opts.drop_probability = (real)0.0; } layers.push_back(opts); } } // regression { LayerOptions opts; opts.out_depth = divisible_8(_OutputState::size())-1; opts.regression_mode = true; layers.push_back(opts); } NetOptions net_options; net_options.run_only_net_mode = _run_only_mode; net_options.learning_rate = _learning_rate; net_options.momentum = _momentum; net_options.l2_decay = _l2_decay; net_options.weights_scale_coef = _weights_scale_coef; create(layers,net_options); } Data& get_input_dw() { return input_dw; } Layers& get_layers() { return m_layers; } DLNetKernels* get_kernels() { return kernels; } };// template<> struct NetT template<typename _InputState,typename _OutputState> struct NetDataBaseT { public: typedef std::vector<real> WT; typedef _InputState InputState; typedef _OutputState OutputState; InputState input; OutputState output; protected: WT input_w; WT result_w; WT target_w; WT target_mask_w; public: NetDataBaseT() { input_w.resize(InputState::size()); result_w.resize(OutputState::size()); target_w.resize(OutputState::size()); target_mask_w.resize(OutputState::size()); } void to_vec(bool _train_mode) { input.to_vec(input_w); if(_train_mode) { output.to_vec(target_w); output.set_target_mask(target_mask_w); } } void from_vec() { output.from_vec(result_w); } const WT& get_input() const {return input_w;} const WT& get_target() const {return target_w;} const WT& get_target_mask() const {return target_mask_w;} WT& get_result() {return result_w;} void copy_to_net(NetT<InputState,OutputState>& _net,size_t _idx,bool _train_mode,bool _forward_mode) { } void copy_from_net(NetT<InputState,OutputState>& _net,size_t _idx,bool _train_mode,bool _forward_mode) { } };//template<> struct NetDataBaseT template<typename _NetData> struct NetDataHolder : protected std::list<_NetData> { protected: typedef std::list<_NetData> base; public: NetDataHolder() { } _NetData* create() { push_back(_NetData()); return &back(); } _NetData* create(const _NetData& _cd) { push_back(_NetData(_cd)); return &back(); } bool remove(_NetData* _cd) { base::iterator it = begin() ,ite = end() ; for(;it!=ite;++it) { if(EQL(&*it,_cd)) { erase(it); return true; } } return false; } };//template<> struct NetDataHolder }
[ "klizardin@gmail.com" ]
klizardin@gmail.com
c69767abf6c3217849e2e8f35dba59cafe618433
ccda07d0b27779e66b57c4d94441fe08d407e232
/tools/transform.h
3e002e801ed61512122c12dafbe9069415fb4349
[ "MIT" ]
permissive
arsenm/alive2
8677f8494b1dd6da514dbd1cbe00ae78eddbc7a6
a631decc679eca18ea6ab33b6083a8f9f1c7f95b
refs/heads/master
2022-11-17T10:36:26.547305
2020-07-07T15:41:11
2020-07-07T15:41:23
280,014,085
0
0
MIT
2020-07-16T00:35:46
2020-07-16T00:35:45
null
UTF-8
C++
false
false
1,332
h
#pragma once // Copyright (c) 2018-present The Alive2 Authors. // Distributed under the MIT license that can be found in the LICENSE file. #include "ir/function.h" #include "smt/solver.h" #include "util/errors.h" #include <string> #include <ostream> #include <unordered_map> namespace tools { struct TransformPrintOpts { bool print_fn_header = true; }; struct Transform { std::string name; IR::Function src, tgt; IR::Predicate *precondition = nullptr; void preprocess(); void print(std::ostream &os, const TransformPrintOpts &opt) const; friend std::ostream& operator<<(std::ostream &os, const Transform &t); }; class TypingAssignments { smt::Solver s, sneg; smt::Result r; bool has_only_one_solution = false; bool is_unsat = false; TypingAssignments(const smt::expr &e); public: bool operator!() const { return !(bool)*this; } operator bool() const; void operator++(void); bool hasSingleTyping() const { return has_only_one_solution; } friend class TransformVerify; }; class TransformVerify { Transform &t; std::unordered_map<std::string, const IR::Instr*> tgt_instrs; bool check_each_var; public: TransformVerify(Transform &t, bool check_each_var); util::Errors verify() const; TypingAssignments getTypings() const; void fixupTypes(const TypingAssignments &ty); }; }
[ "nuno.lopes@ist.utl.pt" ]
nuno.lopes@ist.utl.pt
f99101e27098783a1e4590e38fe08e41c3025d5c
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2458486_0/C++/NovGosh/main.cpp
a18a78dba99f1178310fb39f5547e29614f26a59
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,677
cpp
#include <cstdio> #include <fstream> #include <iostream> #include <set> #include <map> #include <queue> #include <deque> #include <cmath> #include <vector> #include <bitset> #include <string> #include <cstring> #include <algorithm> #include <ctime> #include <cstdlib> #include <cassert> #define pb push_back #define mp make_pair #define sz(A) (int) (A).size() #define eprintf(...) fprintf(stderr, __VA_ARGS__) #define eputs(A) fputs((A), stderr) #define sqr(A) ((A) * (A)) #define x first #define y second using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef long double LD; typedef pair <int, int> pii; const int T = 25; const int N = 20; const int SZ = 1 << N; struct node { bool flag; vector <int> res; node (bool flag = false) { node :: flag = flag; } node (bool flag, vector <int> res) { node :: flag = flag; node :: res = res; } }; int t, n, k, type[N], fcnt[T]; vector <int> tmp, v[N]; node dp[SZ]; void update (node & v, node a, int d) { tmp = a.res; tmp.push_back(d); if (!v.flag || v.res > tmp) v = node(true, tmp); } bool have (int mask, int num) { int cnt = fcnt[num]; for (int i = 0; i < n; i++) if (mask >> i & 1) { if (type[i] == num) cnt--; for (int j = 0; j < sz(v[i]); j++) if (v[i][j] == num) cnt++; } return cnt; } int main () { #ifdef DEBUG freopen(".in", "r", stdin); freopen(".out", "w", stdout); #endif cin >> t; for (int test = 0; test < t; test++) { cerr << test << endl; memset(fcnt, 0, sizeof(fcnt)); for (int i = 0; i < SZ; i++) dp[i] = node(); cin >> k >> n; cerr << k << ' ' << n << endl; for (int i = 0; i < k; i++) { int val; cin >> val; fcnt[val - 1]++; } for (int i = 0; i < n; i++) { cin >> type[i]; v[i].clear(); type[i]--; int cnt; cin >> cnt; for (int j = 0; j < cnt; j++) { int num; cin >> num; v[i].push_back(num - 1); } } dp[0] = node(true); for (int i = 0; i < (1 << n); i++) if (dp[i].flag) { for (int j = 0; j < n; j++) { if (!(i >> j & 1) && have(i, type[j])) { update(dp[i ^ (1 << j)], dp[i], j); } } } int last = (1 << n) - 1; printf("Case #%d: ", test + 1); if (dp[last].flag) { for (int i = 0; i < n; i++) printf("%d ", dp[last].res[i] + 1); puts(""); } else puts("IMPOSSIBLE"); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
1d2d13273e6152f04fb937537a50a0aae67b5b58
09c2c8d7f42dd5c678b064fd56bc65d49af16b3c
/dotenv.h
765692c695b17acec7b171908e3a2588d1966d75
[ "MIT" ]
permissive
sryze/dotenv
040e04e0cab99bba1d691ac657098fc327880a2c
b30ceb7b5de46a71c4bf682aa338d007b447964d
refs/heads/master
2023-04-01T09:15:31.697300
2021-04-09T18:40:39
2021-04-09T18:40:39
286,269,276
0
0
null
null
null
null
UTF-8
C++
false
false
351
h
#ifndef DOTENV_H #define DOTENV_H #include <string> namespace dotenv { std::string get(const std::string &name, const std::string &default_value = ""); void set(const std::string &name, const std::string &value); void unset(const std::string &name); void load(const std::string &filename = ".env"); } // namespace dotenv #endif
[ "sryze@protonmail.com" ]
sryze@protonmail.com
00fd0d74110b3ac1853aa0ca4673f2614ac7a033
2495c956bac63236aa071948b4c3c96ba0abfafb
/exercises.hpp
2f9698b5688b8fbd95cc0182cc189820ad2fd6b1
[]
no_license
mhrtmnn/GraphTheory_Exercises
3669713a2714b82bdb9854c2ae0d378330a3de48
0713caedd33e69a4d7374666b4deb2f749680f5b
refs/heads/master
2020-04-01T04:22:37.668901
2018-10-13T10:25:36
2018-10-13T10:26:21
152,860,774
0
0
null
null
null
null
UTF-8
C++
false
false
695
hpp
// // Created by marco on 5/8/16. // #ifndef GRAPHTHEORY_GIT_EXERCISES_HPP #define GRAPHTHEORY_GIT_EXERCISES_HPP #include "graphAlgorithms.hpp" #include "ComplexityAlgorithms.hpp" #include <thread> using namespace std; void printMetrics(Graph&, graphAlgorithms&); void startEx4(Graph&); void startEx5(); void startEx6(string, graphAlgorithms&); void startEx7(string, graphAlgorithms&); void Ex5Worker(vector<pair<int, int>>*, int, int); void createCSV(vector<pair<int, int>> &); void startEx10(graphAlgorithms&); void startEx11(ComplexityAlgorithms &); void printSAT(struct satFormula*); void printVal(struct satFormula*); void startEx13(string s); #endif //GRAPHTHEORY_GIT_EXERCISES_HPP
[ "marco.hartmann@tuhh.de" ]
marco.hartmann@tuhh.de
dc8b13faa19521e44997a38562ec1d411b944f6d
f19896ff3a1016d4ae63db6e9345cfcc4d0a2967
/Topics/Topic/Data Structures and Alogrithms (Topic)/Leetcode(Website)/205(Isomorphic Strings).cpp
de9bec1603db2408ffb11eae857cb0f48024e5d1
[]
no_license
Akshay199456/100DaysOfCode
079800b77a44abe560866cf4750dfc6c7fe01a59
b4ed8a6793c17bcb71c56686d98fcd683af64841
refs/heads/master
2023-08-08T07:59:02.723675
2023-08-01T03:44:15
2023-08-01T03:44:15
226,718,143
3
0
null
null
null
null
UTF-8
C++
false
false
3,370
cpp
// This problem was also solved using the UMPIRE approach /* -------------------------Question: Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. Example 1: Input: s = "egg", t = "add" Output: true Example 2: Input: s = "foo", t = "bar" Output: false Example 3: Input: s = "paper", t = "title" Output: true Note: You may assume both s and t have the same length. */ /* -------------------------My Approaches: 1. Using a map and set to store the occurrences This problem can be solved efficiently using a map and a set to store the occurrences of the characters in string s and t. To get more information about this approach, check out the corresponding images with respect to this problem in 'Helping Images'. Time and space complexity are both of O(n) since the both strings are assumed to be of the same length. Time complexity: O(n) Space complexity: O(n) */ /* -------------------------Other approaches 1. Using an array instead of a map. If we know the kind of characters we will be dealing with, we can use an array instead of a map. That way we can optimize on space complexity. In this problem, we know that all characters are possible and since there are 128 characters with ASCII characters that's the size I have chosen. We initialize initially the values to -1. After going through each character in both the strings, we make sure to correspond both the characters in the strings to the same value since they are mapped to each other. If they don't match in value, it means that they have been mapped to differnt characters and so we return false. If we get rhough the whole loop, we return true. Our space complexity here is O(1) since the array is of a constant fixed size and doesn't change with input. Time complexity: O(n) Space complexity: O(1) */ // My Approaches(1) class Solution { public: bool checkIsomorphic(string s, string t){ unordered_map<char, char> sMap; unordered_set<char> tSet; for(int i=0; i<s.size(); i++){ auto it = sMap.find(s[i]); if(it != sMap.end()){ if(sMap[s[i]] != t[i]) return false; } else{ auto it = tSet.find(t[i]); if(it != tSet.end()) return false; sMap[s[i]] = t[i]; tSet.emplace(t[i]); } } return true; } bool isIsomorphic(string s, string t) { if(!s.size()) return true; else return checkIsomorphic(s, t); } }; // Other approaches(1) class Solution { public: bool checkIsomorphic(string s, string t){ vector<int> sArray (128, -1), tArray(128, -1); for(int i=0; i<s.size(); i++){ if(sArray[s[i]] != tArray[t[i]]) return false; sArray[s[i]] = i; tArray[t[i]] = i; } return true; } bool isIsomorphic(string s, string t) { if(!s.size()) return true; else return checkIsomorphic(s, t); } };
[ "akshay.kum94@gmail.com" ]
akshay.kum94@gmail.com
f2d025c21ae40821d3c105e4e95e378398f3d77f
d5f9d7a79053303de0511565132bddf80dfee6f0
/QMultiWindowProject/mainwindow.h
45800811784d6aaaac2ae9cb8c2644e27838bd68
[]
no_license
metaliuyong/QtProjects
4f666fa2714a53fda61abf5f5a782804701721c2
49ca33edbbfbeb7d7e31a8db99450c10edf1dd4a
refs/heads/master
2022-12-29T05:39:13.213834
2020-10-15T22:49:55
2020-10-15T22:49:55
304,539,316
0
0
null
null
null
null
UTF-8
C++
false
false
359
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPaintEvent> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; protected: }; #endif // MAINWINDOW_H
[ "metaliuyong@gmail.com" ]
metaliuyong@gmail.com
cf7fe611769694de00c3f00c4beda7628dd9e336
88c1c2bf1327a15edf9614e24bb2100f7e57d2d2
/safeMain.cpp
133413ab6e0331d7ad0465b798a712496d18330d
[]
no_license
juanpinto232901/SUBtoCUDA
7805e52501e3068c375683a14589b8ff144669d3
7303ad43e9da1563e649ad55444503cdc6fba8d4
refs/heads/master
2020-05-27T21:40:23.274546
2019-06-04T13:43:20
2019-06-04T13:43:20
188,796,282
0
0
null
null
null
null
UTF-8
C++
false
false
162,133
cpp
#include <iostream> #include <fstream> #include <Windows.h> #include <cstdio> #include <string> #include <exception> #include <functional> #include <stdexcept> #include "signals_unity_bridge.h" #include "TimerHQ.h" #include <sdl\include\SDL.h> #include "cwipc_codec\include\api.h" #include "safeMain.h" #include <QDebug> #include <QMouseEvent> #include <qtimer.h> #include "CapturSUBThread.h" #include "CapturSUB.h" #undef main using namespace std; #define IMPORT(name) ((decltype(name)*)SDL_LoadFunction(lib, # name)) QVector<CapturSUBThread*> theSUBNodes; SafeMain::SafeMain(QWidget *parent) : useCUDA(false) , iSUBThreadsNumber(1) , iNumProcessorsQTH(1) , xRot(0.0) , yRot(0.0) , zRot(0.0) , m_fDistEye(0.0) , initialized(false) /// The devices was initialized , allocated(false) /// The memory was allocated , plyloaded(false) /// The file PLY was loaded , drawed(0) , m_fViewportZoomFactor(0.0) , ViewerVertexBuffer1(0) , iBufferID(0) #ifdef USE_CUDA , block_size(16) , positionCUDABuffer(0) , posColorCUDABuffer(0) , indicesCUDABuffer(0) #endif , iMaxMem(0) , filePos(0) , num_elems(0) , iNumBlocks(0) , iFileMaxSize(0) , m_iNumVertices(0) , m_iNumVerticesPerThread(0) , iThreadsNumber(0) /// Number of threads , moveUp(0.0) , incMov(0.0) , iAvatar(0xffffffff) , bSeeColor(true) , yElev(0) , bOnlyOne(false) , iPosPrev(0) #ifndef THREADSUB , mySUB01(0) , mySUB02(0) , mySUB03(0) #endif { qDebug() << QString("SafeMain constructor .......... "); setAutoFillBackground(false); setFocus(); for(int i=0; i<MAX_THREADS; i++) { ViewerVertexBufferTh[i] = 0; iBufferIDTh[i] = 0; num_elemsTh[i] = 0; } #ifndef THREADSUB m_fDistEye = -160; yElev = 100; #else // m_fDistEye = 150; m_fDistEye = 700.0; // m_fDistEye = 3150.0; yElev = -200; #endif iAvatar = 0xffffffff; bOnlyOne = false; iPosPrev = 0; iNumProcessorsQTH = QThread::idealThreadCount(); qDebug() << QString("iNumProcessorsQTH=%1").arg(iNumProcessorsQTH); // setThreadsNumber(4);// iNumProcessorsQTH - 2); setSUBThreadsNumber(NUMPCL); iThreadsNumber = NUMPCL; cudaInfo(); // safeMainV31(); #ifdef THREADSUB setUseSUBThreads(true); #else mySUB01 = new CapturSUB; mySUB02 = new CapturSUB; mySUB03 = new CapturSUB; #endif //#ifdef CONGL QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(animate())); timer->start(20); //#endif } SafeMain::~SafeMain() { #ifndef THREADSUB mySUB01->read_end(0); mySUB02->read_end(1); mySUB03->read_end(2); #endif } void* safeImport(void* lib, const char* name) { auto r = SDL_LoadFunction(lib, name); if (!r) throw runtime_error("Symbol not found: " + string(name)); return r; } //#define IMPORT(name) ((decltype(name)*)safeImport(lib, # name)) void SafeMain::safeMainV31()//int argc, char const* argv[]) { //if (argc != 3) // throw runtime_error("Usage: app.exe <signals-unity-bridge.dll> [media url]"); //const string libraryPath = argv[1]; //const string mediaUrl = argv[2]; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) throw runtime_error(string("Unable to initialize SDL: ") + SDL_GetError()); const string libraryPath = "signals-unity-bridge.dll"; const string mediaUrl = "http://vrt-pcl2dash.viaccess-orca.com/loot/vrtogether.mpd"; qDebug() << QString("libraryPath=%1 mediaUrl=%2").arg(libraryPath.c_str()).arg(mediaUrl.c_str()); auto lib = SDL_LoadObject(libraryPath.c_str()); if (!lib) throw runtime_error("Can't load '" + libraryPath + "': " + SDL_GetError()); auto func_sub_create = IMPORT(sub_create); auto func_sub_play = IMPORT(sub_play); auto func_sub_destroy = IMPORT(sub_destroy); auto func_sub_grab_frame = IMPORT(sub_grab_frame); auto func_sub_get_stream_count = IMPORT(sub_get_stream_count); auto handle = func_sub_create("MyMediaPipeline"); func_sub_play(handle, mediaUrl.c_str()); if (func_sub_get_stream_count(handle) == 0) throw runtime_error("No streams found"); vector<uint8_t> buffer; for (int i = 0; i < 100000; ++i) { FrameInfo info{}; buffer.resize(1024 * 1024 * 10); auto size = func_sub_grab_frame(handle, 0, buffer.data(), buffer.size(), &info); buffer.resize(size); if (size == 0) SDL_Delay(100); else { printf("Frame: % 5d bytes, t=%.3f [", (int)size, info.timestamp / 1000.0); for (int k = 0; k < (int)buffer.size(); ++k) { if (k == 8) { printf(" ..."); break; } printf(" %.2X", buffer[k]); } printf(" ]\n"); } } func_sub_destroy(handle); SDL_UnloadObject(lib); } int SafeMain::safeMain() { // if(argc != 2 && argc != 3) // throw runtime_error("Usage: app.exe <signals-unity-bridge.dll> [media url]"); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) throw runtime_error(string("Unable to initialize SDL: ") + SDL_GetError()); const string libraryPath = "signals-unity-bridge.dll"; const string mediaUrl = "http://vrt-pcl2dash.viaccess-orca.com/loot/vrtogether.mpd"; qDebug() << QString("libraryPath=%1 mediaUrl=%2").arg( libraryPath.c_str() ).arg(mediaUrl.c_str()); auto lib = SDL_LoadObject("D:/i2cat_vrtogether/v30_stable_qt5/getSUB/w64/signals-unity-bridge.dll");// libraryPath.c_str()); if (!lib)fprintf(stdout, "Error=%s", SDL_GetError()); auto func_sub_create = IMPORT(sub_create); auto func_sub_play = IMPORT(sub_play); auto func_sub_destroy = IMPORT(sub_destroy); auto func_sub_grab_frame = IMPORT(sub_grab_frame); Timer myTimer; FrameInfo* info = 0; info = (FrameInfo*)malloc(sizeof(FrameInfo)); int streamIndex = 0; uint8_t* dst = 0; auto handle = func_sub_create("MyMediaPipeline"); // struct sub_handle hhh = func_create("MyMediaPipeline"); func_sub_play(handle, mediaUrl.c_str()); size_t iSize = 0;//(size_t)func_sub_grab_frame; size_t iSizeB = 1048576 * 1; dst = (uint8_t*)malloc(iSizeB); cwipc_point* mypcl; mypcl = (cwipc_point*)malloc(iSizeB * 2 * sizeof(cwipc_point)); //qDebug() << QString("dst=%1 mypcl=%2 cwipc_point=%3 ").arg(_msize(dst)).arg(_msize(mypcl)).arg(sizeof(cwipc_point)); for (int n = 0; n < 200; n++) { myTimer.start(); //fprintf(stdout, "\n\nn= %d\n", (int)n); Sleep(30); iSize = 1048576; streamIndex = 0; iSize = (size_t)func_sub_grab_frame(handle, streamIndex, 0, 0, info); if (iSize > 0) { //fprintf(stdout, "iSize= %d\n", (int)iSize); //fprintf(stdout, "dst_size= %d handle=%d iSize=%d info=%d \n", (unsigned int)_msize(dst), (unsigned int)handle, (unsigned int)iSize, (unsigned int)_msize(info)); iSize = (size_t)func_sub_grab_frame(handle, streamIndex, dst, iSize, info); //for (int i = 0; i < 20; i++) { // qDebug() << QString( "i=%1 buff=%2 %3 ").arg( i).arg( dst[i]).arg( QString::number(dst[i], 16)); //} // // Uncompress // cwipc_decoder *decoder = cwipc_new_decoder(); if (decoder == NULL) { qDebug() << QString("%1: Could not create decoder \n").arg(libraryPath.c_str()); return 1; } decoder->feed((void*)dst, iSize); // free((uint8_t *)dst); // After feed() we can free the input buffer bool ok = decoder->available(true); if (!ok) { qDebug() << QString("%1: Decoder did not create pointcloud \n").arg(libraryPath.c_str()); return 1; } cwipc *pc = decoder->get(); if (pc == NULL) { qDebug() << QString("%1: Decoder did not return cwipc \n").arg(libraryPath.c_str()); return 1; } decoder->free(); // We don't need the encoder anymore //qDebug() << "Decoded successfully, " << pc->get_uncompressed_size(CWIPC_POINT_VERSION) << " bytes (uncompressed)"; int isizepcl = pc->get_uncompressed_size(CWIPC_POINT_VERSION); pc->copy_uncompressed(mypcl, isizepcl); // // Save pointcloud file // //if (cwipc_write(argv[2], pc, NULL) < 0) { // std::cerr << argv[0] << ": Error writing PLY file " << argv[2] << std::endl; // return 1; //} pc->free(); // We no longer need to pointcloud //for (int i = 0; i < 50; i++) { // qDebug() << QString("i=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg( i).arg( mypcl[i].x).arg( mypcl[i].y).arg( mypcl[i].z).arg( mypcl[i].r).arg( mypcl[i].g).arg( mypcl[i].b); //} } myTimer.stop(); double dTime = myTimer.getElapsedTimeInMilliSec(); fprintf(stdout, "............................................... time=%f ... ", dTime); } free(dst); dst = 0; free(mypcl); mypcl = 0; func_sub_destroy(handle); SDL_UnloadObject(lib); SDL_Quit(); //*/ return 1; } //**************************************************************************** void SafeMain::stopSUBThreads() { qDebug("stopSUBThreads Stopping threads ......................... "); if (theSUBNodes.size() < 1)return; QVector<CapturSUBThread*>::iterator itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { CapturSUBThread* thNode = (*itGeom); thNode->stop(); ++itGeom; } itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { CapturSUBThread* thNode = (*itGeom); thNode->wait(); ++itGeom; } } void SafeMain::unStopSUBThreads() { qDebug("unStopSUBThreads unStopping threads ......................... "); QVector<CapturSUBThread*>::iterator itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { CapturSUBThread* thNode = (*itGeom); thNode->unStop(); ++itGeom; } } void SafeMain::startSUBThreads() { qDebug() << QString("startSUBThreads ............... "); int iIndex = 0; QVector<CapturSUBThread*>::iterator itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { //uint sz3 = sz2; //if (szrest >= (uint)iIndex)sz3++; qDebug() << QString("VRtogetherWidget::startSUBThreads iIndex=%1 ").arg(iIndex); CapturSUBThread* thNode = (*itGeom); //thNode->setLimit(sz3); //thNode->setCount(0); //thNode->setMethod(0); thNode->setID(iIndex); ++itGeom; iIndex++; } iIndex = 0; itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { CapturSUBThread* thNode = (*itGeom); thNode->start((QThread::Priority)QThread::LowPriority); qDebug() << QString("startSUBThreads iIndex=%1 ").arg(iIndex); ++itGeom; iIndex++; } /* enum Priority { IdlePriority, LowestPriority, LowPriority, NormalPriority, HighPriority, HighestPriority, TimeCriticalPriority, InheritPriority }; */ } void SafeMain::setSUBThreads() { // makeCurrent(); qDebug() << QString("VRtogetherWidget::setSUBThreads ........................ num=%1 ").arg(getSUBThreadsNumber()); for (int i = 0; i < getSUBThreadsNumber(); i++) { CapturSUBThread* thNode = new CapturSUBThread(); QString tx1 = QString("TH%1").arg(i + 1); thNode->theGLMessageTh = &theGLMessage; thNode->setName(tx1); thNode->setID(i); mypcl[i] = thNode->getPCL(); theSUBNodes.append(thNode); } qDebug() << QString("setSUBThreads MAXQTHREADS= %1").arg(getSUBThreadsNumber()); int i = 0; QVector<CapturSUBThread*>::iterator itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { CapturSUBThread* thNode = (*itGeom); // qDebug() << QString("name=%1 worker=%2").arg(thNode->getName()).arg(thNode->getWorker()->getName()); qDebug() << QString("name=%1 ").arg(thNode->getName()); qDebug() << QString("SafeMain::setSUBThreads i=%1 mypcl_size=%2 mypcl_pointer=%3").arg(i).arg(_msize(mypcl[i])).arg((qlonglong)mypcl[i]); ++itGeom; i++; } } void SafeMain::destroySUBThreads() { QVector<CapturSUBThread*>::iterator it = theSUBNodes.begin(); while (it != theSUBNodes.end()) { it = theSUBNodes.erase(it); } qDebug() << QString("VRtogetherWidget::destroySUBThreads size=%1 ==== ").arg(theSUBNodes.size()); } void SafeMain::setUseSUBThreads(bool value) { //#define USE_CUDA_TREADS //#define USE_CUDA_NOTH //#define USE_CPU // doneCurrent(); if (!value) { stopSUBThreads(); } // makeCurrent(); if (value) { destroySUBThreads(); setSUBThreads(); startSUBThreads(); } } //***************************************************************************** void SafeMain::normalizeAngle(int *angle) { while (*angle < 0) *angle += 360 * 16; while (*angle > 360 * 16) *angle -= 360 * 16; } void SafeMain::setXRotation(int angle) { normalizeAngle(&angle); if (angle != xRot) { xRot = angle; emit xRotationChanged(angle); updateGL(); } } void SafeMain::setYRotation(int angle) { normalizeAngle(&angle); if (angle != yRot) { yRot = angle; emit yRotationChanged(angle); updateGL(); } } void SafeMain::setZRotation(int angle) { normalizeAngle(&angle); if (angle != zRot) { zRot = angle; emit zRotationChanged(angle); updateGL(); } } void SafeMain::setYElev(int elev) { yElev += elev; updateGL(); } void SafeMain::animate() { // qDebug() << QString("VRtogetherWidget::animate ------ initialized=%1 allocated=%2 plyloaded=%3 ").arg(initialized).arg(allocated).arg(plyloaded); if(!getInitialized() || !getAllocated())return; // qDebug() << QString("animate %1").arg(drawed); //theGLMessage.startAnimate(); paintGL(); addIncMov(); // gear1Rot += 2 * 16; drawed++; //frameRate.newFrame(); update(); } void SafeMain::initializeGL() { /* static const GLfloat lightPos[4] = { 5.0f, 5.0f, 10.0f, 1.0f }; static const GLfloat reflectance1[4] = { 0.8f, 0.1f, 0.0f, 1.0f }; static const GLfloat reflectance2[4] = { 0.0f, 0.8f, 0.2f, 1.0f }; static const GLfloat reflectance3[4] = { 0.2f, 0.2f, 1.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_POSITION, lightPos); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); gear1 = makeGear(reflectance1, 1.0, 4.0, 1.0, 0.7, 20); gear2 = makeGear(reflectance2, 0.5, 2.0, 2.0, 0.7, 10); gear3 = makeGear(reflectance3, 1.3, 2.0, 0.5, 0.7, 10); glEnable(GL_NORMALIZE); glClearColor(1.0f, 0.5f, 0.0f, 1.0f); //*/ // Declare RealSense pipeline, encapsulating the actual device and sensors //rs2::pipeline pipe; // Start streaming with default recommended configuration // pipe.start(); setFocus(); qDebug() << QString("SafeMain::initializeGL _____________________________________________________ "); glClearColor(1.0, 0.0, 0.5, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); #ifdef USE_CUDA_TREADS for(int i=0; i<iThreadsNumber; i++) { ViewerVertexBufferTh[i] = new GLVertexBuffers; ViewerVertexBufferTh[i]->setParams(i);// create vertexBuffer, colorBuffer and indexBuffer. } #else ViewerVertexBuffer1 = new GLVertexBuffers; ViewerVertexBuffer1->setParams(iBufferID);// create vertexBuffer, colorBuffer and indexBuffer. #endif setBuffers();// create the buffers posns, colors and indices. #ifdef USE_CUDA_TREADS int iPosBlock = 0;//iIndex * BUFFERMEM; int iMaxMem2 = (iMaxMem / iThreadsNumber) * 1; for(int i=0; i<iThreadsNumber; i++) { IndexType *indices = ViewerVertexBufferTh[i]->getIndices(iPosBlock); // qDebug() << QString("........................ pointer to indices=%1 ").arg((uint)indices); Q_ASSERT(indices); qDebug() << QString("Filling indices.........."); int iIndex = 0; for (int i1 = 0; i1 < MAX_Y / iThreadsNumber; i1++) { for (int j1 = 0; j1 < MAX_X; j1++) { indices[iIndex] = IndexType(iIndex); iIndex++; } } num_elemsTh[i] = iIndex; qDebug() << QString("................................ th=%1 num_elemsTh=%2 ").arg(i).arg(num_elemsTh[i]); ViewerVertexBufferTh[i]->allocVertexBuffer(iMaxMem2); ViewerVertexBufferTh[i]->allocColorBuffer(iMaxMem2); ViewerVertexBufferTh[i]->allocIndexBuffer(iMaxMem2); } // m_iNumVertices = iIndex; // m_iNumVerticesPerThread = m_iNumVertices / iThreadsNumber; //*/ #else IndexType *indices = ViewerVertexBuffer1->getIndices(); // qDebug() << QString("........................ pointer to indices=%1 ").arg((uint)indices); Q_ASSERT(indices); ViewerVertexBuffer1->allocVertexBuffer(iMaxMem); ViewerVertexBuffer1->allocColorBuffer(iMaxMem); //ViewerVertexBuffer1->allocAllBuffer(iMaxMem); ViewerVertexBuffer1->allocIndexBuffer(iMaxMem); qDebug() << QString("Filling indices.......... iMaxMem=%1 indices_size=%2 ").arg(iMaxMem).arg(_msize(indices)); int iIndex = 0; for (int i = 0; i < MAX_Y; i++) { for (int j = 0; j < MAX_X; j++) { indices[iIndex] = IndexType(iIndex); iIndex++; } } qDebug() << QString("Idices filled................................ "); num_elems = iIndex; m_iNumVertices = iIndex; m_iNumVerticesPerThread = m_iNumVertices / iThreadsNumber; qDebug() << QString("................................ num_elems=%1 ").arg(num_elems); #ifndef THREADSUB mySUB01->read_ini(0); mySUB02->read_ini(1); mySUB03->read_ini(2); #endif #endif //#define USE_CUDA_TREADS //#define USE_CUDA_NOTH //#define USE_CPU #ifdef USE_CUDA #ifdef USE_CUDA_NOTH setCudaParam(); allocVerticesCUDA(); #endif #ifdef USE_CUDA_TREADS setCudaParamThreads(); for(int i=0; i<iThreadsNumber; i++) { allocVerticesCUDAThreads(i); } #endif #ifdef USE_CUDA_TREADS_ONE setCudaParamMulti(); allocVerticesCUDA(); #endif #endif // qDebug() << QString("Filling indices.........."); // int iIndex = 0; // for (int i = 0; i < MAX_Y; i++) { // for (int j = 0; j < MAX_X; j++) { // indices[iIndex] = IndexType(iIndex); // iIndex++; // } // } // num_elems = iIndex; // m_iNumVertices = iIndex; // m_iNumVerticesPerThread = m_iNumVertices / iThreadsNumber; // qDebug() << QString("................................ num_elems=%1 ").arg(num_elems); ////*/ #ifdef USE_CUDA_TREADS setUseThreads(true); #endif // setUseSUBThreads(true); // oneAvatar(); initialized = true; /// The devices was initialized allocated = true; /// The memory was allocated plyloaded = true; /// The file PLY was loaded } void SafeMain::processGeomCUDA(float despX, float despY, float despZ) { QVector3D* vVertex = ViewerVertexBuffer1->getPosns(); QVector4Du* vColor = ViewerVertexBuffer1->getColors(); IndexType* vIndices = ViewerVertexBuffer1->getIndices(); bool bDraw = false; int iTest = 0; int iNumAvat = 6; FrameInfo* timestampInfo[NUMPCL]; for (int i = 0; i < getSUBThreadsNumber(); i++) { CapturSUBThread* thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 1; if (iTest && i == 0)bDraw = true; iTest = iAvatar & 2; if (iTest && i == 1)bDraw = true; iTest = iAvatar & 4; if (iTest && i == 2)bDraw = true; iTest = iAvatar & 8; if (iTest && i == 3)bDraw = true; iTest = iAvatar & 16; if (iTest && i == 4)bDraw = true; iTest = iAvatar & 32; if (iTest && i == 5)bDraw = true; iTest = iAvatar & 64; if (iTest && i == 6)bDraw = true; iTest = iAvatar & 128; if (iTest && i == 7)bDraw = true; iTest = iAvatar & 256; if (iTest && i == 8)bDraw = true; iTest = iAvatar & 512; if (iTest && i == 9)bDraw = true; iTest = iAvatar & 1024; if (iTest && i == 10)bDraw = true; iTest = iAvatar & 2048; if (iTest && i == 11)bDraw = true; // qDebug() << QString("SafeMain::processGeom th=%2 bDraw=%3 ").arg(i).arg(bDraw); // qDebug() << QString("iAvatar=%1 th=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { //ViewerVertexBuffer1->clearVertexBufferMem(64536, 1); //ViewerVertexBuffer1->clearColorBufferMem(64536, 1); int iposmat = 0; mypcl[i] = thNode->getPCL(); timestampInfo[i] = thNode->getInfo(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; iNumPointsPrev[i][iPosPrev] = iNumPoints[i]; // qDebug() << QString("th=%1 iNumPoints=%2 iAvatar=%3 ").arg(i).arg(iNumPoints[i]).arg(QString::number( iAvatar, 16)); if (iNumPoints[i] > 0 && mypcl[i]) { int iNumAvatar = 5; if (bOnlyOne)bDraw = false; if (iAvatar == 1 && bOnlyOne) { bDraw = true; iNumAvatar = 1; } if (iAvatar == 2 && bOnlyOne) { bDraw = true; iNumAvatar = 1; } if (iAvatar == 4 && bOnlyOne) { bDraw = true; iNumAvatar = 1; } //if (bOnlyOne) iNumAvatar = 1; //qDebug() << QString("SafeMain::processGeomTh th=%1 iNumPoints=%2 iNumAvatar=%3 ").arg(i).arg(iNumPoints[i]).arg(iNumAvatar); for (int j1 = 0; j1 < iNumAvatar; j1++) { if (bDraw) { iposmat = (i * 5) + j1; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (!bOnlyOne) { vx += despX; vy += despY; vz += despZ; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } } //*/ vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); #ifdef USE_CPU ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); #endif int uio = 0; } } if (i >= 2 && bDraw) { iposmat = (i * 5) + 5; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; vx += despX; vy += despY; vz += despZ; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } //*/ vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); #ifdef USE_CPU ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); #endif } } if (iPosPrev >= 10)iPosPrev = -1; iPosPrev++; } bDraw = false; } } void SafeMain::processGeomTh(float despX, float despY, float despZ) { QVector3D* vVertex = ViewerVertexBuffer1->getPosns(); QVector4Du* vColor = ViewerVertexBuffer1->getColors(); IndexType* vIndices = ViewerVertexBuffer1->getIndices(); bool bDraw = false; int iTest = 0; int iNumAvat = 6; FrameInfo* timestampInfo[NUMPCL]; for (int i = 0; i < getSUBThreadsNumber(); i++) { CapturSUBThread* thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 1; if (iTest && i == 0)bDraw = true; iTest = iAvatar & 2; if (iTest && i == 1)bDraw = true; iTest = iAvatar & 4; if (iTest && i == 2)bDraw = true; iTest = iAvatar & 8; if (iTest && i == 3)bDraw = true; iTest = iAvatar & 16; if (iTest && i == 4)bDraw = true; iTest = iAvatar & 32; if (iTest && i == 5)bDraw = true; iTest = iAvatar & 64; if (iTest && i == 6)bDraw = true; iTest = iAvatar & 128; if (iTest && i == 7)bDraw = true; iTest = iAvatar & 256; if (iTest && i == 8)bDraw = true; iTest = iAvatar & 512; if (iTest && i == 9)bDraw = true; iTest = iAvatar & 1024; if (iTest && i == 10)bDraw = true; iTest = iAvatar & 2048; if (iTest && i == 11)bDraw = true; // qDebug() << QString("SafeMain::processGeom th=%2 bDraw=%3 ").arg(i).arg(bDraw); // qDebug() << QString("iAvatar=%1 th=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { //ViewerVertexBuffer1->clearVertexBufferMem(64536, 1); //ViewerVertexBuffer1->clearColorBufferMem(64536, 1); int iposmat = 0; mypcl[i] = thNode->getPCL(); timestampInfo[i] = thNode->getInfo(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; iNumPointsPrev[i][iPosPrev] = iNumPoints[i]; // qDebug() << QString("th=%1 iNumPoints=%2 iAvatar=%3 ").arg(i).arg(iNumPoints[i]).arg(QString::number( iAvatar, 16)); if (iNumPoints[i] > 0 && mypcl[i]) { int iNumAvatar = 5; if (bOnlyOne)bDraw = false; if (iAvatar == 1 && bOnlyOne) { bDraw = true; iNumAvatar = 1; }; if (iAvatar == 2 && bOnlyOne) { bDraw = true; iNumAvatar = 1; } if (iAvatar == 4 && bOnlyOne) { bDraw = true; iNumAvatar = 1; } //if (bOnlyOne) iNumAvatar = 1; //qDebug() << QString("SafeMain::processGeomTh th=%1 iNumPoints=%2 iNumAvatar=%3 ").arg(i).arg(iNumPoints[i]).arg(iNumAvatar); for (int j1 = 0; j1 < iNumAvatar; j1++) { if (bDraw) { iposmat = (i * 5) + j1; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (!bOnlyOne) { vx += despX; vy += despY; vz += despZ; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } } //*/ vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); #ifdef USE_CPU ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); #endif int uio = 0; } } if (i >= 2 && bDraw) { iposmat = (i * 5) + 5; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; vx += despX; vy += despY; vz += despZ; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } //*/ vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); #ifdef USE_CPU ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); #endif } } if (iPosPrev >= 10)iPosPrev = -1; iPosPrev++; } bDraw = false; } } void SafeMain::processGeom(float despX, float despY, float despZ) { #ifndef THREADSUB QVector3D* vVertex = ViewerVertexBuffer1->getPosns(); QVector4Du* vColor = ViewerVertexBuffer1->getColors(); IndexType* vIndices = ViewerVertexBuffer1->getIndices(); bool bDraw = false; int iTest = 0; int iNumAvat = 6; FrameInfo* timestampInfo[NUMPCL]; int iposmat = 0; int i = 0; mypcl[i] = mySUB01->getPCL(); timestampInfo[i] = mySUB01->getInfo(); iNumPoints[i] = mySUB01->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (!bOnlyOne) { vx += despX; vy += despY; vz += despZ; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } } //*/ vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); } #endif } void SafeMain::paintGL() { if(!getInitialized() || !getAllocated())return; /* void (TVMReceiver::* ptfptr)(uint, DMesh) = &TVMReceiver::micasa; fnOnReceivedMesh(TVMReceiver::* tvmptr)(uint, DMesh) = &TVMReceiver::michoza; fnOnConnectionError(TVMReceiver::* errorptr)(uint) = &TVMReceiver::mierror; myTVMReceiver->myMesh.nVertices = 0; myTVMReceiver->myMesh.nTextures = 0; myTVMReceiver->myMesh.nTriangles = 0; //*/ // Wait for the next set of frames from the camera //auto frames = pipe.wait_for_frames(); //auto depth = frames.get_depth_frame(); #ifdef THREADSUB QMutex doStopMutex; #endif Timer time01; iTotalPoints = 0; theGLMessage.startDevices(); theGLMessage.startCPU(); glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1, 1); glDisable(GL_TEXTURE_2D); glEnable(GL_COLOR_MATERIAL); //qDebug() << QString("SafeMain::paintGL m_fDistEye=%1 yElev=%2 ").arg(m_fDistEye).arg(yElev); int iW = (width() * 0.5) + m_fDistEye; int iH = (height() * 0.5) + m_fDistEye; // glPushMatrix(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-iW, iW , -iH, iH, -10000, 10000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, yElev, 0); // qDebug() << QString("m_fDistEye=%1 yElev=%2 ").arg(m_fDistEye).arg(yElev); //glRotated(xRot / 16.0, 1.0, 0.0, 0.0); //glRotated(yRot / 16.0, 0.0, 1.0, 0.0); //glRotated(zRot / 16.0, 0.0, 0.0, 1.0); glRotated(xRot, 1.0, 0.0, 0.0); glRotated(yRot, 0.0, 1.0, 0.0); glRotated(zRot, 0.0, 0.0, 1.0); float fScale = 200.0; glScalef(fScale, fScale, fScale); yRot += 2.0; // qDebug() << QString("xRot=%1 yRot=%2 zRot=%3 ").arg(xRot).arg(yRot).arg(zRot); /* drawGear(gear1, -3.0, -2.0, 0.0, gear1Rot / 16.0); drawGear(gear2, +3.1, -2.0, 0.0, -2.0 * (gear1Rot / 16.0) - 9.0); glRotated(+90.0, 1.0, 0.0, 0.0); drawGear(gear3, -3.1, -1.8, -2.2, +2.0 * (gear1Rot / 16.0) - 2.0); //*/ float fPointThick = 3.0f; glPointSize(fPointThick); //float brt = 1.5; //float con = 2.0; //float sat = 1.5; #ifdef USE_CPU //GenerateCloud();// leer nuve de puntos de SUB Q_ASSERT(ViewerVertexBuffer1); //doStopM02.lock(); //for (int i = 0; i < 20; i++) { // qDebug() << QString("safeMain i=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 uID=0 ").arg(i).arg(mypcl[0][i].x).arg(mypcl[0][i].y).arg(mypcl[0][i].z).arg(mypcl[0][i].r).arg(mypcl[0][i].g).arg(mypcl[0][i].b); // qDebug() << QString("safeMain i=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 uID=1 ").arg(i).arg(mypcl[1][i].x).arg(mypcl[1][i].y).arg(mypcl[1][i].z).arg(mypcl[1][i].r).arg(mypcl[1][i].g).arg(mypcl[1][i].b); // qDebug() << QString("safeMain i=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 uID=2 ").arg(i).arg(mypcl[2][i].x).arg(mypcl[2][i].y).arg(mypcl[2][i].z).arg(mypcl[2][i].r).arg(mypcl[2][i].g).arg(mypcl[2][i].b); // qDebug() << QString("safeMain i=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 uID=3 ").arg(i).arg(mypcl[3][i].x).arg(mypcl[3][i].y).arg(mypcl[3][i].z).arg(mypcl[3][i].r).arg(mypcl[3][i].g).arg(mypcl[3][i].b); //} //doStopM02.unlock(); filePos = 0; //QVector3D* vVertex = ViewerVertexBuffer1->getPosns(); //QVector4Du* vColor = ViewerVertexBuffer1->getColors(); //IndexType* vIndices = ViewerVertexBuffer1->getIndices(); // float* vVertexFloat = ViewerVertexBuffer1->getPosnsFloat(); //ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, filePos, false); //ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, filePos, false); // qDebug() << QString("paintGL ---------------------------------- "); #ifdef THREADSUB doStopMutex.lock(); #endif // glColor3f(1.0, 0.0, 0.0); theGLMessage.startPaint(); //bool bDraw = false; //int iTest = 0; //int iNumAvat = 6; //FrameInfo* timestampInfo[NUMPCL]; #ifdef THREADSUB //processGeom(0.0, 12.0, 0.0); //processGeom(-10.0, 0.0, 0.0); processGeomTh(0.0, 0.0, 0.0); // processGeom(0.0, 0.0, 0.0); //void CapturSUB::processGeom(GLVertexBuffers *ViewerVertexBuffer1, GLMessages* theGLMessage, bool bSeeColor, float despX, float despY, float despZ) //processGeom(10.0, 0.0, 0.0); //processGeom(0.0, -12.0, 0.0); //processGeom(10.0, 12.0, 0.0); //processGeom(-10.0, 12.0, 0.0); //processGeom(10.0, -12.0, 0.0); //processGeom(-10.0, -12.0, 0.0); #else float despX1 = 1.5; mySUB01->read(0); mySUB01->processGeom(ViewerVertexBuffer1, &theGLMessage, bSeeColor, -1.2 + despX1, 0, 0); //mySUB02->read(1); //mySUB02->processGeom(ViewerVertexBuffer1, &theGLMessage, bSeeColor, 0 + despX1, 0, 0); //mySUB03->read(2); //mySUB03->processGeom(ViewerVertexBuffer1, &theGLMessage, bSeeColor, 1.2 + despX1, 0, 0); #endif /* for (int i = 0; i < getSUBThreadsNumber(); i++) { CapturSUBThread* thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 1; if (iTest && i == 0)bDraw = true; iTest = iAvatar & 2; if (iTest && i == 1)bDraw = true; iTest = iAvatar & 4; if (iTest && i == 2)bDraw = true; iTest = iAvatar & 8; if (iTest && i == 3)bDraw = true; iTest = iAvatar & 16; if (iTest && i == 4)bDraw = true; iTest = iAvatar & 32; if (iTest && i == 5)bDraw = true; iTest = iAvatar & 64; if (iTest && i == 6)bDraw = true; iTest = iAvatar & 128; if (iTest && i == 7)bDraw = true; iTest = iAvatar & 256; if (iTest && i == 8)bDraw = true; iTest = iAvatar & 512; if (iTest && i == 9)bDraw = true; iTest = iAvatar & 1024; if (iTest && i == 10)bDraw = true; iTest = iAvatar & 2048; if (iTest && i == 11)bDraw = true; // qDebug() << QString("iAvatar=%1 i=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { //ViewerVertexBuffer1->clearVertexBufferMem(64536, 1); //ViewerVertexBuffer1->clearColorBufferMem(64536, 1); int iposmat = 0; mypcl[i] = thNode->getPCL(); timestampInfo[i] = thNode->getInfo(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { for (int j1 = 0; j1 < 5; j1++) { iposmat = (i * 5) + j1; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); int uio = 0; } if (i >= 2) { iposmat = (i * 5) + 5; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); } } } bDraw = false; } //*/ theGLMessage.stopPaint(); /* int i = 0; CapturSUBThread* thNode = theSUBNodes.at(i); int iTest = 0; bDraw = false; iTest = iAvatar & 1; if (iTest && i == 0)bDraw = true; // qDebug() << QString("iAvatar=%1 i=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { mypcl[i] = thNode->getPCL(); FrameInfo* timestampInfo[NUMPCL]; timestampInfo[i] = thNode->getInfo(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} time01.start(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (i == 0) { vx -= 1.5; vy -= 1.5; } if (i == 1) { vx -= 1.5; vy += 1.5; } if (i == 2) { vx += 1.5; vy -= 1.5; } if (i == 3) { vx += 1.5; vy += 1.5; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } //*/ /* template <class T, class T2> T mix(const T &a, const T &b, const T2 &interp) { static constexpr T2 one = ((T2)1); return (a * (one - interp)) + (b * interp); } OPENCL __constant float3 LumCoeff = (float3)(0.2125, 0.7154, 0.0721); __constant float3 AvgLumin = (float3)(0.5, 0.5, 0.5); float3 brtColor = pixel1.xyz * brt; float3 intensity = (float3)(dot(brtColor, LumCoeff)); float3 satColor = mix(intensity, brtColor, sat); pixel1 = (float4)(mix(AvgLumin, satColor, con), 1.0); pixel1 = clamp(pixel1, 0.0, 1.0); CUDA float3 brtColor = pixel1 * brt; float3 intensity = make_float3(dot(brtColor, LumCoeff)); float3 satColor = lerp(intensity, brtColor, sat); pixel1 = lerp(AvgLumin, satColor, con); #define DOTPROD(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2]) Procedure Truncate(value) If value < 0 Then value = 0 If value > 255 Then value = 255 Return value EndProcedure factor = (259 * (contrast + 255)) / (255 * (259 - contrast)) colour = GetPixelColour(x, y) newRed = Truncate(factor * (Red(colour) - 128) + 128) newGreen = Truncate(factor * (Green(colour) - 128) + 128) newBlue = Truncate(factor * (Blue(colour) - 128) + 128) PutPixelColour(x, y) = RGB(newRed, newGreen, newBlue) */ /* //uint8_t cr = (255 - mypcl[i][i1].r) * 0.299; //uint8_t cg = (255 - mypcl[i][i1].g) * 0.587; //uint8_t cb = (255 - mypcl[i][i1].b) * 0.114; float crB = mypcl[i][i1].r * brt; float cgB = mypcl[i][i1].g * brt; float cbB = mypcl[i][i1].b * brt; float intR = crB * 0.215; float intG = cgB * 0.7154; float intB = cbB * 0.0721; // float3 satColor = lerp(intensity, brtColor, sat); float satR = mix(intR, crB, sat); float satG = mix(intG, cgB, sat); float satB = mix(intB, cbB, sat); // pixel1 = (float4)(mix(AvgLumin, satColor, con), 1.0); float outR = mix(0.5, satR, con); float outG = mix(0.5, satG, con); float outB = mix(0.5, satB, con); uint8_t cr = (uint8_t)outR; uint8_t cg = (uint8_t)outG; uint8_t cb = (uint8_t)outB; uint8_t ca = 255; if (i1 < 12) { qDebug() << QString("outR=%1 outG=%2 outB=%3 cr=%4 cg=%5 cb=%6 ").arg(outR).arg(outG).arg(outB).arg(cr).arg(cb).arg(cb); } //*/ /* uint8_t cr = (mypcl[i][i1].r) * (0.299 * 1.5); uint8_t cg = (mypcl[i][i1].g) * (0.3 * 1.5);// 0.587; uint8_t cb = (mypcl[i][i1].b) * (0.3 * 1.5);// 0.114; uint8_t ca = 255; //vColor[i1].setX(cb); //vColor[i1].setY(cg); //vColor[i1].setZ(cr); // cr = 0; cg = 255; cb = 0; ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); vColor[i1].setW(ca); if (i1 < 12) { qDebug() << QString("paintGL i1=%0 color=%1 %2 %3 %4 timestamp=%5 vColor=%6 %7 %8 %9 ") .arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()).arg(vColor[i1].w()).arg(timestampInfo[i]->timestamp) .arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()).arg(vColor[i1].w()); } } time01.stop(); // qDebug() << QString("time=%1 ").arg(time01.getElapsedTimeInMicroSec()); // ViewerVertexBuffer1->writeAllBuffer((uchar*)mypcl[i], iNumPoints[i], true); glPointSize(4.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, true); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); // ViewerVertexBuffer1->printSizes(); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); int uio = 0; } } //*/ /* i++; thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 2; if (iTest && i == 1)bDraw = true; // qDebug() << QString("iAvatar=%1 i=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { mypcl[i] = thNode->getPCL(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} time01.start(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (i == 0) { vx -= 1.5; vy -= 1.5; } if (i == 1) { vx -= 1.5; vy += 1.5; } if (i == 2) { vx += 1.5; vy -= 1.5; } if (i == 3) { vx += 1.5; vy += 1.5; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = mypcl[i][i1].r; uint8_t cg = mypcl[i][i1].g; uint8_t cb = mypcl[i][i1].b; //vColor[i1].setX(cb); //vColor[i1].setY(cg); //vColor[i1].setZ(cr); vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } time01.stop(); // qDebug() << QString("time=%1 ").arg(time01.getElapsedTimeInMicroSec()); // ViewerVertexBuffer1->writeAllBuffer((uchar*)mypcl[i], iNumPoints[i], true); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, filePos, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, filePos, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, filePos, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); int uio = 0; } } i++; thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 4; if (iTest && i == 2)bDraw = true; // qDebug() << QString("iAvatar=%1 i=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { mypcl[i] = thNode->getPCL(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} time01.start(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (i == 0) { vx -= 1.5; vy -= 1.5; } if (i == 1) { vx -= 1.5; vy += 1.5; } if (i == 2) { vx += 1.5; vy -= 1.5; } if (i == 3) { vx += 1.5; vy += 1.5; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = mypcl[i][i1].r; uint8_t cg = mypcl[i][i1].g; uint8_t cb = mypcl[i][i1].b; //vColor[i1].setX(cb); //vColor[i1].setY(cg); //vColor[i1].setZ(cr); vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } time01.stop(); // qDebug() << QString("time=%1 ").arg(time01.getElapsedTimeInMicroSec()); // ViewerVertexBuffer1->writeAllBuffer((uchar*)mypcl[i], iNumPoints[i], true); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, filePos, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, filePos, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, filePos, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); int uio = 0; } } i++; thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 8; if (iTest && i == 3)bDraw = true; // qDebug() << QString("iAvatar=%1 i=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { mypcl[i] = thNode->getPCL(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} time01.start(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (i == 0) { vx -= 1.5; vy -= 1.5; } if (i == 1) { vx -= 1.5; vy += 1.5; } if (i == 2) { vx += 1.5; vy -= 1.5; } if (i == 3) { vx += 1.5; vy += 1.5; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = mypcl[i][i1].r; uint8_t cg = mypcl[i][i1].g; uint8_t cb = mypcl[i][i1].b; //vColor[i1].setX(cb); //vColor[i1].setY(cg); //vColor[i1].setZ(cr); vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } time01.stop(); // qDebug() << QString("time=%1 ").arg(time01.getElapsedTimeInMicroSec()); // ViewerVertexBuffer1->writeAllBuffer((uchar*)mypcl[i], iNumPoints[i], true); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, filePos, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, filePos, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, filePos, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); int uio = 0; } } //*/ glDisable(GL_POLYGON_OFFSET_FILL); theGLMessage.stopCPU(); // float time02 = theGLMessage.getTimeMicrosegCPU(); #ifdef THREADSUB doStopMutex.unlock(); #endif //ViewerVertexBuffer1->bindVertexBuffer(); //ViewerVertexBuffer1->bindColorBuffer(); //ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false); //cwipc_point* mypcl[NUMPCL]; //int iNumPoints[NUMPCL]; //ViewerVertexBuffer1->bindIndexBufferAll(iNumPoints[0], (char*)mypcl[0], false, false, false); #endif #ifdef USE_CUDA_NOTH num_elems = MAX_X * MAX_Y; qDebug() << QString("num_elems=%1 ").arg(num_elems); // qDebug() << QString("VRtogetherWidget::paintGL vertexID=%1 colorID=%2 indicesID=%3 ").arg(vertexBuffer->bufferId()).arg(colorBuffer->bufferId()).arg(indicesBuffer->bufferId()); setVerticesCUDA(); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false); #endif #ifdef USE_CUDA_TREADS_ONE //unsigned int m = blockIdx.x * blockDim.x + threadIdx.x; //unsigned int n = blockIdx.y * blockDim.y + threadIdx.y; //if (m < MAX_X && n < MAX_Y2) //{ // uint iIndex = (n * MAX_X) + m; // uint iIndex1 = iPosStart + (iIndex * 3); // uint iIndex2 = iColStart + (iIndex * 4); qDebug() << QString("USE_CUDA_TREADS_ONE "); setVerticesCUDAMulti(); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); #endif // qDebug() << QString("VRtogetherWidget::paintGL num_elems=%1 m_fDistEye=%2 ").arg(num_elems).arg(m_fDistEye); //*/ //glPopMatrix(); /* (myTVMReceiver->*ptfptr)(drawed, myTVMReceiver->myMesh); myTVMReceiver->p_RegisterOnReceivedMeshCallBack(clientID, (myTVMReceiver->*tvmptr)(clientID, myTVMReceiver->myMesh)); qDebug() << QString("nVertices=%1 nTextures=%2 nTriangles=%3 ").arg(myTVMReceiver->myMesh.nVertices).arg(myTVMReceiver->myMesh.nTextures).arg(myTVMReceiver->myMesh.nTriangles); myTVMReceiver->p_RegisterOnConnectionErrorCallBack(clientID, (myTVMReceiver->*errorptr)(clientID) ); //*/ } void SafeMain::resizeGL(int width, int height) { qDebug() << QString("SafeMain::resizeGL w=%1 h=%2 ...................................... ").arg(width).arg(height); int side = qMin(width, height); glViewport((width - side) / 2, (height - side) / 2, side, side); int iW = (width * 0.5) + m_fDistEye; int iH = (height * 0.5) + m_fDistEye; glMatrixMode(GL_PROJECTION); glLoadIdentity(); // glFrustum(-1.0, +1.0, -1.0, 1.0, 0.1, 10000.0); // glOrtho(0, iW , 0, iH, -5000, 5000); glOrtho(-iW, iW, -iH, iH, -5000, 5000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // glTranslated(0.0, 0.0, -40.0); } void SafeMain::addIncMov() { incMov += moveUp; if (incMov >= 800)moveUp = -20; if (incMov <= -800)moveUp = +20; } //************************************************************************** void SafeMain::mousePressEvent(QMouseEvent *event) { setFocus(); lastPos = event->pos(); updateGL(); } void SafeMain::mouseMoveEvent(QMouseEvent *event) { setFocus(); int dx = event->x() - lastPos.x(); int dy = event->y() - lastPos.y(); dx *= 0.25; dy *= 0.25; if (event->buttons() & Qt::LeftButton) { setXRotation(xRot + dy);// +8 * dy); setYRotation(yRot + dx);// +8 * dx); } else if (event->buttons() & Qt::RightButton) { //setXRotation(xRot + dy);// +8 * dy); //setZRotation(zRot + dx);// +8 * dx); setYElev(-dy); } lastPos = event->pos(); updateGL(); } void SafeMain::wheelEvent(QWheelEvent* ptEvent) { setFocus(); QMutex doStopMutex; doStopMutex.lock(); setFocus(); int iNumDegrees = ptEvent->delta() / 8; int iDelta = (float)(iNumDegrees / 15); if (iDelta > 0) { incZoom(); } else { decZoom(); } doStopMutex.unlock(); updateGL(); } void SafeMain::keyPressEvent(QKeyEvent *e) { setFocus(); int iMod = e->modifiers(); if (e->key() == Qt::Key_Escape) { close(); } if (e->key() == Qt::Key_Space) { } if (iMod == Qt::NoModifier) { if (e->key() == Qt::Key_Plus) { /** Increments the wheel zoom factor */ m_fViewportZoomFactor = CONTROLLER_ZOOM_FACTOR; m_fDistEye += m_fViewportZoomFactor * 0.1f; } if (e->key() == Qt::Key_Minus) { /** Decremets the wheel zoom factor */ m_fViewportZoomFactor = -CONTROLLER_ZOOM_FACTOR; m_fDistEye += m_fViewportZoomFactor * 0.1f; } if (e->key() == Qt::Key_O) { if (bSeeColor)bSeeColor = false; else bSeeColor = true; update(); } if (e->key() == Qt::Key_0) { qDebug() << QString("Todos los Avatares "); glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (iAvatar == 0) iAvatar = 0xffffffff; else iAvatar = 0; bOnlyOne = false; //m_fDistEye = 150; m_fDistEye = 700.0; // m_fDistEye = 3150.0; yElev = -200; update(); } if (e->key() == Qt::Key_1) { qDebug() << QString("Avatar 1 "); glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 1; qDebug() << QString("iAvatar=%1 iTest=%2 ").arg(QString::number(iAvatar, 16)).arg(iTest); if (iTest) { qDebug() << QString("Avatar 1 in1 %1").arg(QString::number(iAvatar, 16)); iAvatar = iAvatar & 0xfffffffffffffffe; } else { qDebug() << QString("Avatar 1 in2 %1").arg(QString::number(iAvatar, 16)); iAvatar = iAvatar | 1; } qDebug() << QString("Avatar 1 out %1").arg(QString::number(iAvatar, 16)); update(); } if (e->key() == Qt::Key_2) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 2; if (iTest) iAvatar = iAvatar & 0xfffffffd; else iAvatar = iAvatar | 2; } if (e->key() == Qt::Key_3) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 4; if (iTest) iAvatar = iAvatar & 0xfffffffb; else iAvatar = iAvatar | 4; } if (e->key() == Qt::Key_4) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); int iTest = iAvatar & 8; if (iTest) iAvatar = iAvatar & 0xfffffff7; else iAvatar = iAvatar | 8; } if (e->key() == Qt::Key_A) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 1; if (iTest) iAvatar = iAvatar & 0xfffffffe; else iAvatar = iAvatar | 1; iAvatar = 1; bOnlyOne = true; m_fDistEye = -150; yElev = -200; } if (e->key() == Qt::Key_B) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 2; if (iTest) iAvatar = iAvatar & 0xfffffffd; else iAvatar = iAvatar | 2; iAvatar = 2; bOnlyOne = true; m_fDistEye = -150; yElev = -200; } if (e->key() == Qt::Key_C) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 4; if (iTest) iAvatar = iAvatar & 0xfffffffb; else iAvatar = iAvatar | 4; iAvatar = 4; bOnlyOne = true; m_fDistEye = -140; yElev = -200; } } if (iMod == Qt::ShiftModifier) { if (e->key() == Qt::Key_Up) { yElev += 10; update(); } if (e->key() == Qt::Key_Down) { yElev -= 10; update(); } } if (iMod == Qt::ControlModifier) { if (e->key() == Qt::Key_1) { xRot = 225.0; yRot = 0.0; zRot = 30.0; update(); } if (e->key() == Qt::Key_2) { xRot = 270.0; yRot = 0.0; zRot = 0.0; update(); } if (e->key() == Qt::Key_3) { xRot = 315.0; yRot = 0.0; zRot = 30.0; update(); } if (e->key() == Qt::Key_4) { xRot = 180.0; yRot = 0.0; zRot = 0.0; update(); } if (e->key() == Qt::Key_5) { xRot = 0.0; yRot = 90.0; zRot = 0.0; update(); } if (e->key() == Qt::Key_6) { xRot = 0; yRot = 0.0; zRot = 0.0; update(); } if (e->key() == Qt::Key_7) { xRot = 135.0; yRot = 0.0; zRot = 30.0; update(); } if (e->key() == Qt::Key_8) { xRot = 270.0; yRot = 0.0; zRot = 0.0; update(); } if (e->key() == Qt::Key_9) { xRot = 45.0; yRot = 0.0; zRot = 30.0; update(); } } QWidget::keyPressEvent(e); } //*/ void SafeMain::setBuffers() { iNumBlocks = NUMVERTICES; iMaxMem = 1024 * 1024 * 2; iFileMaxSize = 50000;//68000000;//5745000; if(iFileMaxSize > (BUFFERMEM * 1) && iFileMaxSize < (BUFFERMEM * 2))iMaxMem = BUFFERMEM * 2; if(iFileMaxSize > (BUFFERMEM * 2) && iFileMaxSize < (BUFFERMEM * 4))iMaxMem = BUFFERMEM * 4; if(iFileMaxSize > (BUFFERMEM * 4) && iFileMaxSize < (BUFFERMEM * 6))iMaxMem = BUFFERMEM * 6; // if(iFileMaxSize > (BUFFERMEM * 6) && iFileMaxSize < (BUFFERMEM * 8))iMaxMem = BUFFERMEM * 8; // if(iFileMaxSize > (BUFFERMEM * 8) && iFileMaxSize < (BUFFERMEM * 10))iMaxMem = BUFFERMEM * 10; // if(iFileMaxSize > (BUFFERMEM * 10) && iFileMaxSize < (BUFFERMEM * 12))iMaxMem = BUFFERMEM * 12; // if(iFileMaxSize > (BUFFERMEM * 12) && iFileMaxSize < (BUFFERMEM * 14))iMaxMem = BUFFERMEM * 14; // if(iFileMaxSize > (BUFFERMEM * 14) && iFileMaxSize < (BUFFERMEM * 16))iMaxMem = BUFFERMEM * 16; // if(iFileMaxSize > (BUFFERMEM * 16) && iFileMaxSize < (BUFFERMEM * 18))iMaxMem = BUFFERMEM * 18; // if(iFileMaxSize > (BUFFERMEM * 18) && iFileMaxSize < (BUFFERMEM * 20))iMaxMem = BUFFERMEM * 20; // if(iFileMaxSize > (BUFFERMEM * 20) && iFileMaxSize < (BUFFERMEM * 22))iMaxMem = BUFFERMEM * 22; // if(iFileMaxSize > (BUFFERMEM * 22) && iFileMaxSize < (BUFFERMEM * 24))iMaxMem = BUFFERMEM * 24; // if(iFileMaxSize > (BUFFERMEM * 24) && iFileMaxSize < (BUFFERMEM * 26))iMaxMem = BUFFERMEM * 26; // if(iFileMaxSize > (BUFFERMEM * 26) && iFileMaxSize < (BUFFERMEM * 28))iMaxMem = BUFFERMEM * 28; // if(iFileMaxSize > (BUFFERMEM * 28) && iFileMaxSize < (BUFFERMEM * 30))iMaxMem = BUFFERMEM * 30; // if(iFileMaxSize > (BUFFERMEM * 30) && iFileMaxSize < (BUFFERMEM * 32))iMaxMem = BUFFERMEM * 32; // if(iFileMaxSize > (BUFFERMEM * 32) && iFileMaxSize < (BUFFERMEM * 34))iMaxMem = BUFFERMEM * 34; // if(iFileMaxSize > (BUFFERMEM * 34) && iFileMaxSize < (BUFFERMEM * 36))iMaxMem = BUFFERMEM * 36; // if(iFileMaxSize > (BUFFERMEM * 36) && iFileMaxSize < (BUFFERMEM * 38))iMaxMem = BUFFERMEM * 38; // if(iFileMaxSize > (BUFFERMEM * 38) && iFileMaxSize < (BUFFERMEM * 40))iMaxMem = BUFFERMEM * 40; // if(iFileMaxSize > (BUFFERMEM * 40) && iFileMaxSize < (BUFFERMEM * 42))iMaxMem = BUFFERMEM * 42; // if(iFileMaxSize > (BUFFERMEM * 42) && iFileMaxSize < (BUFFERMEM * 44))iMaxMem = BUFFERMEM * 44; // if(iFileMaxSize > (BUFFERMEM * 44) && iFileMaxSize < (BUFFERMEM * 46))iMaxMem = BUFFERMEM * 46; // if(iFileMaxSize > (BUFFERMEM * 46) && iFileMaxSize < (BUFFERMEM * 48))iMaxMem = BUFFERMEM * 48; // if(iFileMaxSize > (BUFFERMEM * 48) && iFileMaxSize < (BUFFERMEM * 50))iMaxMem = BUFFERMEM * 50; // if(iFileMaxSize > (BUFFERMEM * 50) && iFileMaxSize < (BUFFERMEM * 52))iMaxMem = BUFFERMEM * 52; // if(iFileMaxSize > (BUFFERMEM * 52) && iFileMaxSize < (BUFFERMEM * 54))iMaxMem = BUFFERMEM * 54; // if(iFileMaxSize > (BUFFERMEM * 54) && iFileMaxSize < (BUFFERMEM * 56))iMaxMem = BUFFERMEM * 56; // if(iFileMaxSize > (BUFFERMEM * 56) && iFileMaxSize < (BUFFERMEM * 58))iMaxMem = BUFFERMEM * 58; // if(iFileMaxSize > (BUFFERMEM * 58) && iFileMaxSize < (BUFFERMEM * 60))iMaxMem = BUFFERMEM * 60; // if(iFileMaxSize > (BUFFERMEM * 60) && iFileMaxSize < (BUFFERMEM * 62))iMaxMem = BUFFERMEM * 62; // if(iFileMaxSize > (BUFFERMEM * 62) && iFileMaxSize < (BUFFERMEM * 64))iMaxMem = BUFFERMEM * 64; // if(iFileMaxSize > (BUFFERMEM * 64) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 66; // if(iFileMaxSize > (BUFFERMEM * 66) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 68; // if(iFileMaxSize > (BUFFERMEM * 68) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 70; // if(iFileMaxSize > (BUFFERMEM * 70) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 72; // if(iFileMaxSize > (BUFFERMEM * 72) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 74; // if(iFileMaxSize > (BUFFERMEM * 74) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 76; //qDebug() << QString("posns_size=%1").arg(iNumBlocks * iMaxMem * 3); //qDebug() << QString("colors_size=%1").arg(iNumBlocks * iMaxMem); //qDebug() << QString("indices_size=%1").arg(iNumBlocks * iMaxMem); #ifdef USE_CUDA_TREADS int iMaxMem2 = iMaxMem / iThreadsNumber; qDebug() << QString(" iFileMaxSize=%1 iNumBlocks=%2 iMaxMem2=%3 iThreadsNumber=%4 " ).arg(iFileMaxSize).arg(iNumBlocks).arg(iMaxMem2).arg(iThreadsNumber); qDebug(); for(int i=0; i<iThreadsNumber; i++){ ViewerVertexBufferTh[i]->allocVertexBufferMem(iMaxMem2, iNumBlocks);// posns ViewerVertexBufferTh[i]->allocColorBufferMem(iMaxMem2, iNumBlocks);// colors ViewerVertexBufferTh[i]->allocIndexBufferMem(iMaxMem2, iNumBlocks);// indices } #else // qDebug() << QString(" iFileMaxSize=%1 iNumBlocks=%2 iMaxMem=%3 sizeQVector3D=%4 " ).arg(iFileMaxSize).arg(iNumBlocks).arg(iMaxMem).arg(sizeof(QVector3D)); // qDebug(); ViewerVertexBuffer1->allocVertexBufferMem(iMaxMem + 1024, iNumBlocks);// posns ViewerVertexBuffer1->allocColorBufferMem(iMaxMem + 1024, iNumBlocks);// colors // ViewerVertexBuffer1->allocAllBufferMem(iMaxMem + 1024, iNumBlocks); ViewerVertexBuffer1->allocIndexBufferMem(iMaxMem + 1024, iNumBlocks);// indices #endif // qDebug("//********************************************************************** "); // ViewerVertexBuffer1->printSizes(); // qDebug("//********************************************************************** "); } void SafeMain::paintEvent(QPaintEvent *event) { //updateGL(); // QPainter painter(this); painter.begin(this); QFont serifFont("Times", 10, QFont::Bold); painter.setFont(serifFont); theGLMessage.setColorTextGL(7); float fpscap = 0.0; int iNumCapFrame = 0; qreal fps = 1.0 / theGLMessage.getTimeSegCPU(); // qDebug() << QString("fps=%1").arg(fps); // setVars1(100, 1000, 99000); theGLMessage.drawGLText(&painter, fps, fpscap, iTotalPoints, iNumCapFrame); painter.end(); } void SafeMain::setVars1(int iVal1, int iVal2, int iVal3) { theGLMessage.setSizePCL1comp(iVal1); theGLMessage.setReadedPCL1comp(iVal2); theGLMessage.setUncomp1(iVal3); } void SafeMain::cudaInfo() { #ifdef USE_CUDA int deviceCount = 0; cudaError_t error_id = cudaGetDeviceCount(&deviceCount); qDebug() << QString("............................ cudaInfo ................................ "); if (error_id != cudaSuccess) { // printf("cudaGetDeviceCount returned %d\n-> %s\n", (int)error_id, cudaGetErrorString(error_id)); // printf("Result = FAIL\n"); qDebug() << QString("cudaGetDeviceCount returned %1\n-> %2\n").arg((int)error_id).arg(cudaGetErrorString(error_id)); qDebug() << QString("Result = FAIL\n"); exit(EXIT_FAILURE); } // This function call returns 0 if there are no CUDA capable devices. if (deviceCount == 0) { //printf("There are no available device(s) that support CUDA\n"); qDebug("There are no available device(s) that support CUDA\n"); } else { // printf("Detected %d CUDA Capable device(s)\n", deviceCount); qDebug() << QString("Detected %1 CUDA Capable device(s)\n").arg(deviceCount); } int dev, driverVersion = 0, runtimeVersion = 0; for (dev = 0; dev < deviceCount; ++dev) { cudaSetDevice(dev); cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, dev); // printf("\nDevice %d: \"%s\"\n", dev, deviceProp.name); qDebug() << QString("\nDevice %1: \"%2\"\n").arg( dev).arg( deviceProp.name); // Console log cudaDriverGetVersion(&driverVersion); cudaRuntimeGetVersion(&runtimeVersion); // printf(" CUDA Driver Version / Runtime Version %d.%d / %d.%d\n", driverVersion/1000, (driverVersion%100)/10, runtimeVersion/1000, (runtimeVersion%100)/10); // printf(" CUDA Capability Major/Minor version number: %d.%d\n", deviceProp.major, deviceProp.minor); qDebug() << QString(" CUDA Driver Version / Runtime Version %1.%2 / %3.%4\n").arg( driverVersion/1000).arg( (driverVersion%100)/10).arg( runtimeVersion/1000).arg( (runtimeVersion%100)/10); qDebug() << QString(" CUDA Capability Major/Minor version number: %1.%2\n").arg( deviceProp.major).arg( deviceProp.minor); char msg[256]; sprintf(msg, " Total amount of global memory: %.0f MBytes (%llu bytes)\n", (float)deviceProp.totalGlobalMem/1048576.0f, (unsigned long long) deviceProp.totalGlobalMem); qDebug() << QString("%1").arg( msg); qDebug() << QString(" (%1) Multiprocessors, (%2) CUDA Cores/MP: %3 CUDA Cores\n") .arg(deviceProp.multiProcessorCount) .arg(_ConvertSMVer2Cores(deviceProp.major, deviceProp.minor)) .arg(_ConvertSMVer2Cores(deviceProp.major, deviceProp.minor) * deviceProp.multiProcessorCount); qDebug() << QString(" GPU Clock rate: %1 MHz (%2 GHz)\n").arg( deviceProp.clockRate * 1e-3f).arg( deviceProp.clockRate * 1e-6f); #if CUDART_VERSION >= 5000 // This is supported in CUDA 5.0 (runtime API device properties) qDebug() << QString(" Memory Clock rate: %1 Mhz\n").arg( deviceProp.memoryClockRate * 1e-3f); qDebug() << QString(" Memory Bus Width: %2-bit\n").arg(deviceProp.memoryBusWidth); if (deviceProp.l2CacheSize) { qDebug() << QString(" L2 Cache Size: %1 bytes\n").arg( deviceProp.l2CacheSize); } #else // This only available in CUDA 4.0-4.2 (but these were only exposed in the CUDA Driver API) int memoryClock; getCudaAttribute<int>(&memoryClock, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, dev); printf(" Memory Clock rate: %.0f Mhz\n", memoryClock * 1e-3f); int memBusWidth; getCudaAttribute<int>(&memBusWidth, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, dev); printf(" Memory Bus Width: %d-bit\n", memBusWidth); int L2CacheSize; getCudaAttribute<int>(&L2CacheSize, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, dev); if (L2CacheSize) { printf(" L2 Cache Size: %d bytes\n", L2CacheSize); } #endif qDebug() << QString(" Maximum Texture Dimension Size (x,y,z) 1D=(%1), 2D=(%2, %3), 3D=(%4, %5, %6)\n") .arg(deviceProp.maxTexture1D ).arg( deviceProp.maxTexture2D[0], deviceProp.maxTexture2D[1]) .arg(deviceProp.maxTexture3D[0]).arg( deviceProp.maxTexture3D[1]).arg( deviceProp.maxTexture3D[2]); qDebug() << QString(" Maximum Layered 1D Texture Size, (num) layers 1D=(%1), %2 layers\n") .arg(deviceProp.maxTexture1DLayered[0]).arg( deviceProp.maxTexture1DLayered[1]); qDebug() << QString(" Maximum Layered 2D Texture Size, (num) layers 2D=(%1, %2), %3 layers\n") .arg(deviceProp.maxTexture2DLayered[0]).arg( deviceProp.maxTexture2DLayered[1]).arg( deviceProp.maxTexture2DLayered[2]); qDebug() << QString(" Total amount of constant memory: %1 bytes\n").arg( deviceProp.totalConstMem); qDebug() << QString(" Total amount of shared memory per block: %1 bytes\n").arg( deviceProp.sharedMemPerBlock); qDebug() << QString(" Total number of registers available per block: %1\n").arg( deviceProp.regsPerBlock); qDebug() << QString(" Warp size: %1\n").arg( deviceProp.warpSize); qDebug() << QString(" Maximum number of threads per multiprocessor: %1\n").arg( deviceProp.maxThreadsPerMultiProcessor); qDebug() << QString(" Maximum number of threads per block: %1\n").arg( deviceProp.maxThreadsPerBlock); qDebug() << QString(" Max dimension size of a thread block (x,y,z): (%1, %2, %3)\n") .arg(deviceProp.maxThreadsDim[0]) .arg(deviceProp.maxThreadsDim[1]) .arg(deviceProp.maxThreadsDim[2]); qDebug() << QString(" Max dimension size of a grid size (x,y,z): (%1, %2, %3)\n") .arg(deviceProp.maxGridSize[0]) .arg(deviceProp.maxGridSize[1]) .arg(deviceProp.maxGridSize[2]); qDebug() << QString(" Maximum memory pitch: %1 bytes\n").arg( deviceProp.memPitch); qDebug() << QString(" Texture alignment: %1 bytes\n").arg( deviceProp.textureAlignment); qDebug() << QString(" Concurrent copy and kernel execution: %1 with %2 copy engine(s)\n").arg( (deviceProp.deviceOverlap ? "Yes" : "No")).arg( deviceProp.asyncEngineCount); qDebug() << QString(" Run time limit on kernels: %1\n").arg( deviceProp.kernelExecTimeoutEnabled ? "Yes" : "No"); qDebug() << QString(" Integrated GPU sharing Host Memory: %1\n").arg( deviceProp.integrated ? "Yes" : "No"); qDebug() << QString(" Support host page-locked memory mapping: %1\n").arg( deviceProp.canMapHostMemory ? "Yes" : "No"); qDebug() << QString(" Alignment requirement for Surfaces: %1\n").arg( deviceProp.surfaceAlignment ? "Yes" : "No"); qDebug() << QString(" Device has ECC support: %1\n").arg( deviceProp.ECCEnabled ? "Enabled" : "Disabled"); #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) qDebug() << QString(" CUDA Device Driver Mode (TCC or WDDM): %1\n").arg( deviceProp.tccDriver ? "TCC (Tesla Compute Cluster Driver)" : "WDDM (Windows Display Driver Model)"); #endif qDebug() << QString(" Device supports Unified Addressing (UVA): %1\n").arg( deviceProp.unifiedAddressing ? "Yes" : "No"); qDebug() << QString(" Device PCI Bus ID / PCI location ID: %1 / %2\n").arg( deviceProp.pciBusID).arg( deviceProp.pciDeviceID); const char *sComputeMode[] = { "Default (multiple host threads can use ::cudaSetDevice() with device simultaneously)", "Exclusive (only one host thread in one process is able to use ::cudaSetDevice() with this device)", "Prohibited (no host thread can use ::cudaSetDevice() with this device)", "Exclusive Process (many threads in one process is able to use ::cudaSetDevice() with this device)", "Unknown", NULL }; qDebug() << QString(" Compute Mode:\n"); qDebug() << QString(" < %1 >\n").arg( sComputeMode[deviceProp.computeMode]); } // csv masterlog info // ***************************** // exe and CUDA driver name qDebug() << QString("\n"); std::string sProfileString = "deviceQuery, CUDA Driver = CUDART"; char cTemp[16]; // driver version sProfileString += ", CUDA Driver Version = "; #if defined(_MSC_VER) sprintf_s(cTemp, 10, "%d.%d", driverVersion/1000, (driverVersion%100)/10); #else sprintf(cTemp, "%d.%d", driverVersion/1000, (driverVersion%100)/10); #endif sProfileString += cTemp; // Runtime version sProfileString += ", CUDA Runtime Version = "; #if defined(_MSC_VER) sprintf_s(cTemp, 10, "%d.%d", runtimeVersion/1000, (runtimeVersion%100)/10); #else sprintf(cTemp, "%d.%d", runtimeVersion/1000, (runtimeVersion%100)/10); #endif sProfileString += cTemp; // Device count sProfileString += ", NumDevs = "; #if defined(_MSC_VER) sprintf_s(cTemp, 10, "%d", deviceCount); #else sprintf(cTemp, "%d", deviceCount); #endif sProfileString += cTemp; // Print Out all device Names for (dev = 0; dev < deviceCount; ++dev) { #if defined(_MSC_VER) sprintf_s(cTemp, 13, ", Device%d = ", dev); #else sprintf(cTemp, ", Device%d = ", dev); #endif cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, dev); sProfileString += cTemp; sProfileString += deviceProp.name; } sProfileString += "\n"; // printf("%s", sProfileString.c_str()); qDebug() << QString("%1").arg(sProfileString.c_str()); qDebug() << QString("Result = PASS\n"); // finish // cudaDeviceReset causes the driver to clean up all state. While // not mandatory in normal operation, it is good practice. It is also // needed to ensure correct operation when the application is being // profiled. Calling cudaDeviceReset causes all profile data to be // flushed before the application exits cudaDeviceReset(); qDebug() << QString("\n\n"); #endif } #ifdef USE_CUDA /** * @brief BezierWidget3x3::setCudaParam */ void SafeMain::setCudaParam() { // int m_iUsize = drawParams->getUsize(); // int m_iVsize = drawParams->getVsize(); qDebug() << QString("VRtogetherWidget::setCudaParam Start ,,,,,,,,,,,,,,,,,,,,,,,,,, "); CUresult error; // Initialize CUDA Driver API error = cuInit(0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } setUseCUDA(true); // Get number of devices supporting CUDA int deviceCount = 0; error = cuDeviceGetCount(&deviceCount); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } if (deviceCount == 0) { qDebug() << QString("There is no device supporting CUDA.\r\n"); exit(0); } error = cuDeviceGet(&cuDevice, 0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to get the first device CUDA.\r\n"); exit(0); } // Create context error = cuGLCtxCreate(&cuContext, 0, cuDevice); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al crear contexto CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContext); cuCtxDestroy(cuContext); exit(0); } qDebug() << QString("VRtogetherWidget::setCudaParam cuContext=%1 cuDevice=%2 ").arg((ulong)cuContext).arg((ulong)cuDevice); // CU_FUNC_CACHE_PREFER_NONE CU_FUNC_CACHE_PREFER_SHARED CU_FUNC_CACHE_PREFER_L1 CU_FUNC_CACHE_PREFER_EQUAL error = cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_EQUAL); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to Set Cache Config CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContext); cuCtxDestroy(cuContext); exit(0); } // D:/i2cat_vrtogether/VRtogetherCUDA/vrtg01_cooda.ptx #ifdef Q_OS_WIN error = cuModuleLoad(&cuModule, "D:/i2cat_vrtogether/VRtogetherCUDA/vrtg01_cooda.ptx"); #else error = cuModuleLoad(&cuModule, "/home/juanpinto/QT_OpenCL/qt-labs-opencl_matrix3x3/demos/temp/bezierpatch3x3.ptx"); #endif if (error != CUDA_SUCCESS) { qDebug() << QString("Error al leer el archivo PTX error=%1 \r\n").arg(error); error = cuCtxDetach(cuContext); cuCtxDestroy(cuContext); exit(0); } // _Z7vrtogCUPfPcPif // _Z7vrtogCUPfPcPif error = cuModuleGetFunction(&vrtogCU, cuModule, "_Z7vrtogCUPfPcPif"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); exit(0); } /* sizeCU = 100 * sizeof(int); error= cuMemAlloc(&nothingmemCU, sizeCU); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc nothingmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); exit(0); } //*/ qDebug() << QString("PTX loaded ......................................................... "); #ifdef DEBUGVR sizeCU10 = 10000 * sizeof(int); debugmemCUbytes0 = (int *)malloc(sizeCU10); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU0, sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU0, reinterpret_cast<const void *>(debugmemCUbytes0), sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU11 = 10000 * sizeof(int); debugmemCUbytes1 = (int *)malloc(sizeCU11); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU1, sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU1, reinterpret_cast<const void *>(debugmemCUbytes1), sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU12 = 10000 * sizeof(int); debugmemCUbytes2 = (int *)malloc(sizeCU12); memset(debugmemCUbytes2, 0, sizeCU12); error = cuMemAlloc(&debugmemCU2, sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU2, reinterpret_cast<const void *>(debugmemCUbytes2), sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU20 = 10000 * sizeof(float); debugmemFloatCUbytes0 = (float *)malloc(sizeCU20); memset(debugmemFloatCUbytes0, 0, sizeCU20); error = cuMemAlloc(&debugmemFloatCU0, sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU0, reinterpret_cast<const void *>(debugmemFloatCUbytes0), sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU21 = 10000 * sizeof(float); debugmemFloatCUbytes1 = (float *)malloc(sizeCU21); memset(debugmemFloatCUbytes1, 0, sizeCU21); error = cuMemAlloc(&debugmemFloatCU1, sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU1, reinterpret_cast<const void *>(debugmemFloatCUbytes1), sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU22 = 10000 * sizeof(float); debugmemFloatCUbytes2 = (float *)malloc(sizeCU22); memset(debugmemFloatCUbytes2, 0, sizeCU22); error = cuMemAlloc(&debugmemFloatCU2, sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU2, reinterpret_cast<const void *>(debugmemFloatCUbytes2), sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU30 = 10000 * sizeof(char); debugmemCharCUbytes0 = (char *)malloc(sizeCU30); memset(debugmemCharCUbytes0, 0, sizeCU30); error = cuMemAlloc(&debugmemCharCU0, sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU0, reinterpret_cast<const void *>(debugmemCharCUbytes0), sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU31 = 10000 * sizeof(char); debugmemCharCUbytes1 = (char *)malloc(sizeCU31); memset(debugmemCharCUbytes1, 0, sizeCU31); error = cuMemAlloc(&debugmemCharCU1, sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU1, reinterpret_cast<const void *>(debugmemCharCUbytes1), sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU32 = 10000 * sizeof(char); debugmemCharCUbytes2 = (char *)malloc(sizeCU32); memset(debugmemCharCUbytes2, 0, sizeCU32); error = cuMemAlloc(&debugmemCharCU2, sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU2, reinterpret_cast<const void *>(debugmemCharCUbytes2), sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } #endif //*/ int n = 0; seedmemCUbytes = (int *)malloc(MAX_X * sizeof(int)); for (int j = 0; j < MAX_X; j++) { seedmemCUbytes[n] = rand(); n++; } error = cuMemAlloc(&seedmemCU, MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(seedmemCU, reinterpret_cast<const void *>(seedmemCUbytes), MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemAlloc(&seedmemCU, MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(seedmemCU, reinterpret_cast<const void *>(seedmemCUbytes), MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } //*/ /* int iFrameWidth = commonParams->getFrameWidth(); int iFrameHeight = commonParams->getFrameHeight(); bufferSize = iFrameWidth * iFrameHeight * sizeof(uchar3); error= cuMemAlloc(&bufferEffects1cu, bufferSize); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc bufferEffects1cu error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error= cuMemAlloc(&bufferEffects2cu, bufferSize); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc bufferEffects1cu error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } //*/ // setPBOcu(); qDebug() << QString("VRtogetherWidget::setCudaParam End "); qDebug() << QString("deviceCount=%1 \r\n").arg(deviceCount); } #endif #ifdef USE_CUDA /** * @brief BezierWidget3x3::setCudaParamMulti */ void SafeMain::setCudaParamMulti() { // int m_iUsize = drawParams->getUsize(); // int m_iVsize = drawParams->getVsize(); qDebug() << QString("VRtogetherWidget::setCudaParamMulti Start ,,,,,,,,,,,,,,,,,,,,,,,,,, "); CUresult error; // Initialize CUDA Driver API error = cuInit(0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } setUseCUDA(true); // Get number of devices supporting CUDA int deviceCount = 0; error = cuDeviceGetCount(&deviceCount); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } if (deviceCount == 0) { qDebug() << QString("There is no device supporting CUDA.\r\n"); exit(0); } error = cuDeviceGet(&cuDevice, 0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to get the first device CUDA.\r\n"); exit(0); } // Create context error = cuGLCtxCreate(&cuContextMulti, 0, cuDevice); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al crear contexto CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContextMulti); cuCtxDestroy(cuContextMulti); exit(0); } qDebug() << QString("VRtogetherWidget::setCudaParamMulti cuContextMulti=%1 cuDevice=%2 ").arg((uint)cuContextMulti).arg((uint)cuDevice); // CU_FUNC_CACHE_PREFER_NONE CU_FUNC_CACHE_PREFER_SHARED CU_FUNC_CACHE_PREFER_L1 CU_FUNC_CACHE_PREFER_EQUAL error = cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_EQUAL); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to Set Cache Config CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContextMulti); cuCtxDestroy(cuContextMulti); exit(0); } // D:/i2cat_vrtogether/VRtogetherCUDA/vrtg01_cooda.ptx #ifdef Q_OS_WIN error = cuModuleLoad(&cuModule, "D:/i2cat_vrtogether/v30_stable_qt5/getSUB/vrtg01_cooda.ptx"); #else error = cuModuleLoad(&cuModule, "/home/juanpinto/QT_OpenCL/qt-labs-opencl_matrix3x3/demos/temp/bezierpatch3x3.ptx"); #endif if (error != CUDA_SUCCESS) { qDebug() << QString("Error al leer el archivo PTX error=%1 \r\n").arg(error); error = cuCtxDetach(cuContextMulti); cuCtxDestroy(cuContextMulti); exit(0); } error = cuModuleGetFunction(&vrtogCU01, cuModule, "_Z9vrtogCU01PfPcPifjj"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU01 error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); exit(0); } error = cuModuleGetFunction(&vrtogCU02, cuModule, "_Z9vrtogCU02PfPcPifjj"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU02 error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); exit(0); } error = cuModuleGetFunction(&vrtogCU03, cuModule, "_Z9vrtogCU03PfPcPifjj"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU03 error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); exit(0); } error = cuModuleGetFunction(&vrtogCU04, cuModule, "_Z9vrtogCU04PfPcPifjj"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU04 error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); exit(0); } //*/ qDebug() << QString("PTX loaded ......................................................... "); #ifdef DEBUGVR sizeCU10 = 10000 * sizeof(int); debugmemCUbytes0 = (int *)malloc(sizeCU10); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU0, sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU0, reinterpret_cast<const void *>(debugmemCUbytes0), sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU11 = 10000 * sizeof(int); debugmemCUbytes1 = (int *)malloc(sizeCU11); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU1, sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU1, reinterpret_cast<const void *>(debugmemCUbytes1), sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU12 = 10000 * sizeof(int); debugmemCUbytes2 = (int *)malloc(sizeCU12); memset(debugmemCUbytes2, 0, sizeCU12); error = cuMemAlloc(&debugmemCU2, sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU2, reinterpret_cast<const void *>(debugmemCUbytes2), sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU20 = 10000 * sizeof(float); debugmemFloatCUbytes0 = (float *)malloc(sizeCU20); memset(debugmemFloatCUbytes0, 0, sizeCU20); error = cuMemAlloc(&debugmemFloatCU0, sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU0, reinterpret_cast<const void *>(debugmemFloatCUbytes0), sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU21 = 10000 * sizeof(float); debugmemFloatCUbytes1 = (float *)malloc(sizeCU21); memset(debugmemFloatCUbytes1, 0, sizeCU21); error = cuMemAlloc(&debugmemFloatCU1, sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU1, reinterpret_cast<const void *>(debugmemFloatCUbytes1), sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU22 = 10000 * sizeof(float); debugmemFloatCUbytes2 = (float *)malloc(sizeCU22); memset(debugmemFloatCUbytes2, 0, sizeCU22); error = cuMemAlloc(&debugmemFloatCU2, sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU2, reinterpret_cast<const void *>(debugmemFloatCUbytes2), sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU30 = 10000 * sizeof(char); debugmemCharCUbytes0 = (char *)malloc(sizeCU30); memset(debugmemCharCUbytes0, 0, sizeCU30); error = cuMemAlloc(&debugmemCharCU0, sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU0, reinterpret_cast<const void *>(debugmemCharCUbytes0), sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU31 = 10000 * sizeof(char); debugmemCharCUbytes1 = (char *)malloc(sizeCU31); memset(debugmemCharCUbytes1, 0, sizeCU31); error = cuMemAlloc(&debugmemCharCU1, sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU1, reinterpret_cast<const void *>(debugmemCharCUbytes1), sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU32 = 10000 * sizeof(char); debugmemCharCUbytes2 = (char *)malloc(sizeCU32); memset(debugmemCharCUbytes2, 0, sizeCU32); error = cuMemAlloc(&debugmemCharCU2, sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU2, reinterpret_cast<const void *>(debugmemCharCUbytes2), sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } #endif //*/ int n = 0; seedmemCUbytes = (int *)malloc(MAX_X * sizeof(int)); for (int j = 0; j < MAX_X; j++) { seedmemCUbytes[n] = rand(); n++; } error = cuMemAlloc(&seedmemCU, MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); return; } error = cuMemcpyHtoD(seedmemCU, reinterpret_cast<const void *>(seedmemCUbytes), MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); return; } //*/ /* int iFrameWidth = commonParams->getFrameWidth(); int iFrameHeight = commonParams->getFrameHeight(); bufferSize = iFrameWidth * iFrameHeight * sizeof(uchar3); error= cuMemAlloc(&bufferEffects1cu, bufferSize); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc bufferEffects1cu error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error= cuMemAlloc(&bufferEffects2cu, bufferSize); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc bufferEffects1cu error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } //*/ // setPBOcu(); qDebug() << QString("VRtogetherWidget::setCudaParamMulti End "); qDebug() << QString("deviceCount=%1 \r\n").arg(deviceCount); } #endif void SafeMain::setVerticesCUDA() { #ifdef USE_CUDA int n = 0; bool useCUDA = getUseCUDA(); if (useCUDA == true) { qDebug() << QString("VRtogetherWidget::setVerticesCUDA ............... incMov=%1 ").arg(incMov); gmr = cuGraphicsMapResources(1, &positionCUDABuffer, 0); gmr = cuGraphicsMapResources(1, &posColorCUDABuffer, 0); cuGraphicsResourceGetMappedPointer(&pDevPtr[0], &num_bytes[0], positionCUDABuffer); cuGraphicsResourceGetMappedPointer(&pDevPtr[1], &num_bytes[1], posColorCUDABuffer); cuGraphicsResourceGetMappedPointer(&pDevPtr[2], &num_bytes[2], indicesCUDABuffer); uint argTestSize; void *argsTest[64]; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &pDevPtr[2]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); // void *config[] = { // CU_LAUNCH_PARAM_BUFFER_POINTER, argsTest, // CU_LAUNCH_PARAM_BUFFER_SIZE, &argTestSize, // CU_LAUNCH_PARAM_END // }; int iValXocl = MAX_X; int iValYocl = MAX_Y; unsigned int blqY = iValYocl / block_size; unsigned int blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; gmr = cuLaunchKernel(vrtogCU, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error cuLaunchKernel=%1").arg(gmr); } cuGraphicsUnmapResources(1, &positionCUDABuffer, 0); cuGraphicsUnmapResources(1, &posColorCUDABuffer, 0); cuGraphicsUnmapResources(1, &indicesCUDABuffer, 0); // theGLMessage.stopCUDA(); #ifdef DEBUGVR // copy result from device to host gmr = cuMemcpyDtoH((int *)debugmemCUbytes0, debugmemCU0, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error10 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes1, debugmemCU1, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error11 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes2, debugmemCU2, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error12 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes0, debugmemFloatCU0, sizeCU20); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error20 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes1, debugmemFloatCU1, sizeCU21); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error21 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes2, debugmemFloatCU2, sizeCU22); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error22 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes0, debugmemCharCU0, sizeCU30); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error30 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes1, debugmemCharCU1, sizeCU31); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error31 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes2, debugmemCharCU2, sizeCU32); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error32 cuMemcpyDtoH=%1").arg(gmr); } #endif // for (int i = 1024; i < 1024+16; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 char=%8 %9 %10").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]) // .arg((uchar)debugmemCharCUbytes0[i]).arg((uchar)debugmemCharCUbytes1[i]).arg((uchar)debugmemCharCUbytes2[i]); // } // qDebug("\n"); } #endif } void SafeMain::freeVerticesCUDA() { qDebug("Deallocating Memory........................"); #ifdef USE_CUDA qDebug("Freeing CUDA buffers "); cuGraphicsUnregisterResource(positionCUDABuffer); cuGraphicsUnregisterResource(posColorCUDABuffer); cuGraphicsUnregisterResource(indicesCUDABuffer); #endif m_iNumVertices = 0; qDebug("Deallocated Memory........................"); } void SafeMain::setVerticesCUDAMulti() { #ifdef USE_CUDA int n = 0; ulong ulPosStart = 0; ulong ulColStart = 0; bool useCUDA = getUseCUDA(); if (useCUDA == true) { qDebug() << QString("VRtogetherWidget::setVerticesCUDAMulti ............... incMov=%1 ").arg(incMov); gmr = cuGraphicsMapResources(1, &positionCUDABuffer, 0); gmr = cuGraphicsMapResources(1, &posColorCUDABuffer, 0); gmr = cuGraphicsMapResources(1, &indicesCUDABuffer, 0); cuGraphicsResourceGetMappedPointer(&pDevPtr[0], &num_bytes[0], positionCUDABuffer); cuGraphicsResourceGetMappedPointer(&pDevPtr[1], &num_bytes[1], posColorCUDABuffer); cuGraphicsResourceGetMappedPointer(&pDevPtr[2], &num_bytes[2], indicesCUDABuffer); QGLBuffer *vertexBuffer = ViewerVertexBuffer1->getVertexBuffer(); QGLBuffer *colorBuffer = ViewerVertexBuffer1->getColorBuffer(); QGLBuffer *indexBuffer = ViewerVertexBuffer1->getIndexBuffer(); if (vertexBuffer) { vertexBuffer->bind(); glVertexPointer(3, GL_FLOAT, 0, 0); QVector3D *mappedV = (QVector3D *)vertexBuffer->map(QGLBuffer::WriteOnly); if (mappedV) { for (int q = 0; q < 32; q++)//iNumIndices; q++) { // if((q%3) == 0)qDebug(" \n"); // if((q % 4) == 0)qDebug() << " \n"; qDebug() << QString("GLVertexBuffers::bindVertexBuffer q=%0 vertex=%1 %2 %3 ").arg(q).arg(mappedV[q].x()).arg(mappedV[q].y()).arg(mappedV[q].z()); } } vertexBuffer->unmap(); vertexBuffer->release(); } pDevPtr[0][0]; uint argTestSize; void *argsTest[64]; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &pDevPtr[2]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; argsTest[n] = &ulPosStart; n++; argsTest[n] = &ulColStart; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); // void *config[] = { // CU_LAUNCH_PARAM_BUFFER_POINTER, argsTest, // CU_LAUNCH_PARAM_BUFFER_SIZE, &argTestSize, // CU_LAUNCH_PARAM_END // }; // glTranslatef(200, -100, 0); int iValXocl = MAX_X; int iValYocl = MAX_Y / 4; unsigned int blqY = iValYocl / block_size; unsigned int blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; qDebug() << QString("setVerticesCUDAMulti 1 iValYocl=%1 iValXocl=%2 blqY=%3 bkqX=%4 block_size=%5 ulPosStart=%6 ulColStart=%7 ") .arg(iValYocl).arg(iValXocl).arg(blqY).arg(blqX).arg(block_size).arg(ulPosStart).arg(ulColStart); if (!iAvatar || iAvatar == 1) { gmr = cuLaunchKernel(vrtogCU01, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDAMulti 1 Error cuLaunchKernel=%1").arg(gmr); } } ulPosStart = iValYocl * iValXocl; ulColStart = ulPosStart; n = 0; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &pDevPtr[2]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; argsTest[n] = &ulPosStart; n++; argsTest[n] = &ulColStart; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); iValXocl = MAX_X; iValYocl = MAX_Y / 4; blqY = iValYocl / block_size; blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; qDebug() << QString("setVerticesCUDAMulti 2 iValYocl=%1 iValXocl=%2 blqY=%3 bkqX=%4 block_size=%5 ulPosStart=%6 ulColStart=%7 ") .arg(iValYocl).arg(iValXocl).arg(blqY).arg(blqX).arg(block_size).arg(ulPosStart).arg(ulColStart); if (!iAvatar || iAvatar == 2) { gmr = cuLaunchKernel(vrtogCU02, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDAMulti 2 Error cuLaunchKernel=%1").arg(gmr); } } ulPosStart = (iValYocl * iValXocl) * 2; ulColStart = ulPosStart; n = 0; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &pDevPtr[2]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; argsTest[n] = &ulPosStart; n++; argsTest[n] = &ulColStart; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); iValXocl = MAX_X; iValYocl = MAX_Y / 4; blqY = iValYocl / block_size; blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; qDebug() << QString("setVerticesCUDAMulti 3 iValYocl=%1 iValXocl=%2 blqY=%3 bkqX=%4 block_size=%5 ulPosStart=%6 ulColStart=%7 ") .arg(iValYocl).arg(iValXocl).arg(blqY).arg(blqX).arg(block_size).arg(ulPosStart).arg(ulColStart); if (!iAvatar || iAvatar == 3) { gmr = cuLaunchKernel(vrtogCU03, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDAMulti 3 Error cuLaunchKernel=%1").arg(gmr); } } ulPosStart = (iValYocl * iValXocl) * 3; ulColStart = ulPosStart; n = 0; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &pDevPtr[2]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; argsTest[n] = &ulPosStart; n++; argsTest[n] = &ulColStart; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); // glTranslatef(-200, 100, 0); iValXocl = MAX_X; iValYocl = MAX_Y / 4; blqY = iValYocl / block_size; blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; qDebug() << QString("setVerticesCUDAMulti 4 iValYocl=%1 iValXocl=%2 blqY=%3 bkqX=%4 block_size=%5 ulPosStart=%6 ulColStart=%7 ") .arg(iValYocl).arg(iValXocl).arg(blqY).arg(blqX).arg(block_size).arg(ulPosStart).arg(ulColStart); if (!iAvatar || iAvatar == 4) { gmr = cuLaunchKernel(vrtogCU04, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDAMulti 4 Error cuLaunchKernel=%1").arg(gmr); } } //*/ //***************************************************************************************************************************** cuGraphicsUnmapResources(1, &positionCUDABuffer, 0); cuGraphicsUnmapResources(1, &posColorCUDABuffer, 0); cuGraphicsUnmapResources(1, &indicesCUDABuffer, 0); // theGLMessage.stopCUDA(); #ifdef DEBUGVR // copy result from device to host gmr = cuMemcpyDtoH((int *)debugmemCUbytes0, debugmemCU0, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error10 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes1, debugmemCU1, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error11 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes2, debugmemCU2, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error12 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes0, debugmemFloatCU0, sizeCU20); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error20 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes1, debugmemFloatCU1, sizeCU21); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error21 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes2, debugmemFloatCU2, sizeCU22); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error22 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes0, debugmemCharCU0, sizeCU30); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error30 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes1, debugmemCharCU1, sizeCU31); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error31 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes2, debugmemCharCU2, sizeCU32); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error32 cuMemcpyDtoH=%1").arg(gmr); } #endif // for (int i = 1024; i < 1024+16; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 char=%8 %9 %10").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]) // .arg((uchar)debugmemCharCUbytes0[i]).arg((uchar)debugmemCharCUbytes1[i]).arg((uchar)debugmemCharCUbytes2[i]); // } // qDebug("\n"); } #endif } void SafeMain::allocVerticesCUDA() { #ifdef USE_CUDA IndexType *indices = ViewerVertexBuffer1->getIndices(); int iIndex = 0; for (int i = 0; i < MAX_Y; i++) { for (int j = 0; j < MAX_X; j++) { indices[iIndex] = IndexType(iIndex); iIndex++; } } num_elems = iIndex; m_iNumVertices = iIndex; m_iNumVerticesPerThread = m_iNumVertices / iThreadsNumber; qDebug() << QString("VRtogetherWidget::allocVerticesCUDA ............................... m_iNumVertices=%1 m_iNumVerticesPerThread=%2").arg(m_iNumVertices).arg(m_iNumVerticesPerThread); filePos = 0; ViewerVertexBuffer1->writeIndexBuffer(indices, num_elems, false); qDebug() << QString("VRtogetherWidget::allocVerticesCUDA Allocating CUDA Buffers..."); QGLBuffer *vertexBuffer = ViewerVertexBuffer1->getVertexBuffer(); QGLBuffer *colorBuffer = ViewerVertexBuffer1->getColorBuffer(); QGLBuffer *indexBuffer = ViewerVertexBuffer1->getIndexBuffer(); qDebug() << QString("VRtogetherWidget::allocVerticesCUDA Setting CUDA interoperability ....."); qDebug() << QString("VRtogetherWidget::allocVerticesCUDA vertexID=%1 colorID=%2 ").arg(vertexBuffer->bufferId()).arg(colorBuffer->bufferId()); cuGraphicsGLRegisterBuffer(&positionCUDABuffer, vertexBuffer->bufferId(), CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD); cuGraphicsGLRegisterBuffer(&posColorCUDABuffer, colorBuffer->bufferId(), CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD); cuGraphicsGLRegisterBuffer(&indicesCUDABuffer, indexBuffer->bufferId(), CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD); qDebug() << QString("VRtogetherWidget::allocVerticesCUDA Finished CUDA interoperability setting ....."); #endif setAllocated(true); } #ifdef USE_CUDA /** * @brief BezierWidget3x3::setCudaParamThreads */ void SafeMain::setCudaParamThreads() { // int m_iUsize = drawParams->getUsize(); // int m_iVsize = drawParams->getVsize(); qDebug() << QString("VRtogetherWidget::setCudaParamThreads Start ,,,,,,,,,,,,,,,,,,,,,,,,,, "); CUresult error; // Initialize CUDA Driver API error = cuInit(0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } setUseCUDA(true); // Get number of devices supporting CUDA int deviceCount = 0; error = cuDeviceGetCount(&deviceCount); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } if (deviceCount == 0) { qDebug() << QString("There is no device supporting CUDA.\r\n"); exit(0); } error = cuDeviceGet(&cuDevice, 0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to get the first device CUDA.\r\n"); exit(0); } // Create context error = cuCtxCreate(&cuContextThread, 0, cuDevice); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al crear contexto CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContextThread); cuCtxDestroy(cuContextThread); exit(0); } qDebug() << QString("VRtogetherWidget::setCudaParamThreads cuContext=%1 cuDevice=%2 ").arg((uint)cuContextThread).arg((uint)cuDevice); HGLRC myContext1 = wglGetCurrentContext(); qDebug() << QString("VRtogetherWidget::setCudaParamThreads glContext1=%2 cuDevice=%1 ").arg(cuDevice).arg((qlonglong)myContext1); CUcontext cuContextT; cuCtxGetCurrent(&cuContextT); qDebug() << QString("VRtogetherWidget::setCudaParamThreads cuCtxGetCurrent=%1 ").arg((ulong)cuContextT); // CU_FUNC_CACHE_PREFER_NONE CU_FUNC_CACHE_PREFER_SHARED CU_FUNC_CACHE_PREFER_L1 CU_FUNC_CACHE_PREFER_EQUAL error = cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_EQUAL); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to Set Cache Config CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContextThread); cuCtxDestroy(cuContextThread); exit(0); } // D:/i2cat_vrtogether/VRtogetherCUDA/vrtg01_cooda.ptx #ifdef Q_OS_WIN error = cuModuleLoad(&cuModule, "D:/i2cat_vrtogether/VRtogetherCUDA/vrtg01_cooda.ptx"); #else error = cuModuleLoad(&cuModule, "/home/juanpinto/QT_OpenCL/qt-labs-opencl_matrix3x3/demos/temp/bezierpatch3x3.ptx"); #endif if (error != CUDA_SUCCESS) { qDebug() << QString("Error al leer el archivo PTX error=%1 \r\n").arg(error); error = cuCtxDetach(cuContextThread); cuCtxDestroy(cuContextThread); exit(0); } // _Z7vrtogCUPfPcPif // _Z7vrtogCUPfPcPif error = cuModuleGetFunction(&vrtogCU, cuModule, "_Z7vrtogCUPfPcPif"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContextThread); exit(0); } error = cuModuleGetFunction(&vrtogCU01, cuModule, "_Z9vrtogCU01PfPcPifjj"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU01 error=%1 \r\n").arg(error); cuCtxDestroy(cuContextThread); exit(0); } //error = cuMemAlloc(&pDevPtr[0], MAX_X * (MAX_Y / 4) * 3 * sizeof(float)); //if (error != CUDA_SUCCESS) { // qDebug() << QString("Error cuMemAlloc pDevPtr[0] error=%1 \r\n").arg(error); // cuCtxDestroy(cuContext); // return; //} /* sizeCU = 100 * sizeof(int); error= cuMemAlloc(&nothingmemCU, sizeCU); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc nothingmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); exit(0); } //*/ qDebug() << QString("PTX loaded ......................................................... "); #ifdef DEBUGVR sizeCU10 = 10000 * sizeof(int); debugmemCUbytes0 = (int *)malloc(sizeCU10); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU0, sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU0, reinterpret_cast<const void *>(debugmemCUbytes0), sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU11 = 10000 * sizeof(int); debugmemCUbytes1 = (int *)malloc(sizeCU11); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU1, sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU1, reinterpret_cast<const void *>(debugmemCUbytes1), sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU12 = 10000 * sizeof(int); debugmemCUbytes2 = (int *)malloc(sizeCU12); memset(debugmemCUbytes2, 0, sizeCU12); error = cuMemAlloc(&debugmemCU2, sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU2, reinterpret_cast<const void *>(debugmemCUbytes2), sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU20 = 10000 * sizeof(float); debugmemFloatCUbytes0 = (float *)malloc(sizeCU20); memset(debugmemFloatCUbytes0, 0, sizeCU20); error = cuMemAlloc(&debugmemFloatCU0, sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU0, reinterpret_cast<const void *>(debugmemFloatCUbytes0), sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU21 = 10000 * sizeof(float); debugmemFloatCUbytes1 = (float *)malloc(sizeCU21); memset(debugmemFloatCUbytes1, 0, sizeCU21); error = cuMemAlloc(&debugmemFloatCU1, sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU1, reinterpret_cast<const void *>(debugmemFloatCUbytes1), sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU22 = 10000 * sizeof(float); debugmemFloatCUbytes2 = (float *)malloc(sizeCU22); memset(debugmemFloatCUbytes2, 0, sizeCU22); error = cuMemAlloc(&debugmemFloatCU2, sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU2, reinterpret_cast<const void *>(debugmemFloatCUbytes2), sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU30 = 10000 * sizeof(char); debugmemCharCUbytes0 = (char *)malloc(sizeCU30); memset(debugmemCharCUbytes0, 0, sizeCU30); error = cuMemAlloc(&debugmemCharCU0, sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU0, reinterpret_cast<const void *>(debugmemCharCUbytes0), sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU31 = 10000 * sizeof(char); debugmemCharCUbytes1 = (char *)malloc(sizeCU31); memset(debugmemCharCUbytes1, 0, sizeCU31); error = cuMemAlloc(&debugmemCharCU1, sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU1, reinterpret_cast<const void *>(debugmemCharCUbytes1), sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU32 = 10000 * sizeof(char); debugmemCharCUbytes2 = (char *)malloc(sizeCU32); memset(debugmemCharCUbytes2, 0, sizeCU32); error = cuMemAlloc(&debugmemCharCU2, sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU2, reinterpret_cast<const void *>(debugmemCharCUbytes2), sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } #endif //*/ int n = 0; seedmemCUbytes = (int *)malloc(MAX_X * sizeof(int)); for (int j = 0; j < MAX_X; j++) { seedmemCUbytes[n] = rand(); n++; } error = cuMemAlloc(&seedmemCU, MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContextThread); return; } error = cuMemcpyHtoD(seedmemCU, reinterpret_cast<const void *>(seedmemCUbytes), MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContextThread); return; } //*/ // Here we must release the CUDA context from the thread context error = cuCtxPopCurrent(NULL); if (CUDA_SUCCESS != error) { qDebug() << QString("cuCtxPopCurrent failed error=%1 \r\n").arg(error); cuCtxDestroy(cuContextThread); exit(0); } qDebug() << QString("VRtogetherWidget::setCudaParamThreads End "); qDebug() << QString("deviceCount=%1 \r\n").arg(deviceCount); } #endif void SafeMain::setVerticesCUDAThreads(uint uThID) { Q_UNUSED(uThID); #ifdef USE_CUDAaaa int n = 0; ulong ulPosStart = 0; ulong ulColStart = 0; bool useCUDA = getUseCUDA(); if (useCUDA == true) { gmr = cuCtxPushCurrent(cuContext); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDAThreads Error cuCtxPushCurrent=%1").arg(gmr); } qDebug() << QString("VRtogetherWidget::setVerticesCUDAThreads ............... incMov=%1 ").arg(incMov); gmr = cuGraphicsMapResources(1, &positionCUDABufferTh[uThID], 0); gmr = cuGraphicsMapResources(1, &posColorCUDABufferTh[uThID], 0); cuGraphicsResourceGetMappedPointer(&pDevPtr[0], &num_bytes[0], positionCUDABufferTh[uThID]); cuGraphicsResourceGetMappedPointer(&pDevPtr[1], &num_bytes[1], posColorCUDABufferTh[uThID]); uint argTestSize; void *argsTest[64]; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; argsTest[n] = &ulPosStart; n++; argsTest[n] = &ulColStart; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); // void *config[] = { // CU_LAUNCH_PARAM_BUFFER_POINTER, argsTest, // CU_LAUNCH_PARAM_BUFFER_SIZE, &argTestSize, // CU_LAUNCH_PARAM_END // }; int iValXocl = MAX_X; int iValYocl = MAX_Y / 4; unsigned int blqY = iValYocl / block_size; unsigned int blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; gmr = cuLaunchKernel(vrtogCU01, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString(" VRtogetherWidget::setVerticesCUDAThreads Error cuLaunchKernel=%1 ID=%2").arg(gmr).arg(iBufferIDTh[uThID]); } cuCtxSynchronize(); cuGraphicsUnmapResources(1, &positionCUDABufferTh[uThID], 0); cuGraphicsUnmapResources(1, &posColorCUDABufferTh[uThID], 0); // theGLMessage.stopCUDA(); #ifdef DEBUGVR // copy result from device to host gmr = cuMemcpyDtoH((int *)debugmemCUbytes0, debugmemCU0, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error10 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes1, debugmemCU1, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error11 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes2, debugmemCU2, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error12 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes0, debugmemFloatCU0, sizeCU20); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error20 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes1, debugmemFloatCU1, sizeCU21); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error21 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes2, debugmemFloatCU2, sizeCU22); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error22 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes0, debugmemCharCU0, sizeCU30); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error30 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes1, debugmemCharCU1, sizeCU31); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error31 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes2, debugmemCharCU2, sizeCU32); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error32 cuMemcpyDtoH=%1").arg(gmr); } #endif cuCtxPopCurrent(NULL); // for (int i = 1024; i < 1024+16; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 char=%8 %9 %10").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]) // .arg((uchar)debugmemCharCUbytes0[i]).arg((uchar)debugmemCharCUbytes1[i]).arg((uchar)debugmemCharCUbytes2[i]); // } // qDebug("\n"); } #endif if (drawed > 12)exit(0); } void SafeMain::allocVerticesCUDAThreads(uint uThID) { #ifdef USE_CUDA IndexType *indices = ViewerVertexBufferTh[uThID]->getIndices(); int iIndex = 0; for (int i = 0; i < MAX_Y / iThreadsNumber; i++) { for (int j = 0; j < MAX_X; j++) { indices[iIndex] = IndexType(iIndex); iIndex++; } } num_elems = iIndex; m_iNumVertices = iIndex; m_iNumVerticesPerThread = m_iNumVertices;// / iThreadsNumber; qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads ............................... m_iNumVertices=%1 m_iNumVerticesPerThread=%2").arg(m_iNumVertices).arg(m_iNumVerticesPerThread); // filePos = 0; // ViewerVertexBufferTh[uThID]->writeIndexBuffer(indices, num_elems, filePos, false); // for(int i=0; i < iThreadsNumber; i++) // { qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads Allocating CUDA Buffers....... uThID=%1 ").arg(uThID); QGLBuffer *vertexBuffer = ViewerVertexBufferTh[uThID]->getVertexBuffer(); QGLBuffer *colorBuffer = ViewerVertexBufferTh[uThID]->getColorBuffer(); if (vertexBuffer->bind()) { if (vertexBuffer->map(QGLBuffer::WriteOnly)) { qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads vertexBuffer allocated ....................................... size=%1 ID=%2").arg(vertexBuffer->size()).arg(vertexBuffer->bufferId()); vertexBuffer->unmap(); vertexBuffer->release(); } } if (colorBuffer->bind()) { if (colorBuffer->map(QGLBuffer::WriteOnly)) { qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads colorBuffer allocated ....................................... size=%1 ID=%2").arg(colorBuffer->size()).arg(colorBuffer->bufferId()); colorBuffer->unmap(); colorBuffer->release(); } } qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads Setting CUDA interoperability ....."); qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads vertexID=%1 colorID=%2 ").arg(vertexBuffer->bufferId()).arg(colorBuffer->bufferId()); cuGraphicsGLRegisterBuffer(&positionCUDABufferTh[uThID], vertexBuffer->bufferId(), CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD); cuGraphicsGLRegisterBuffer(&posColorCUDABufferTh[uThID], colorBuffer->bufferId(), CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD); qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads Finished CUDA interoperability setting ....."); // } #endif setAllocated(true); } void SafeMain::freeVerticesCUDAThreads(uint uThID) { Q_UNUSED(uThID) qDebug("Deallocating Memory........................"); #ifdef USE_CUDA qDebug("Freeing CUDA buffers "); cuGraphicsUnregisterResource(positionCUDABuffer); cuGraphicsUnregisterResource(posColorCUDABuffer); cuGraphicsUnregisterResource(indicesCUDABuffer); #endif m_iNumVertices = 0; qDebug("Deallocated Memory........................"); } //****************************************************************************
[ "juan@alestilodepinto.com" ]
juan@alestilodepinto.com
ea8e4c0dfd8078e3e36ecf435a5c888514e74fbe
e8dc33fae8ff29d98e81660198caa55a691e42f1
/Common/toolBase.cxx
b7dfac046245241f0256d3f1cac218c6230228f1
[]
no_license
colddie/MICA
b1f0379cff203b7a088f028cc0488b06e2c0b30e
549b46818202a3901a66897aa966f46372c640c7
refs/heads/master
2020-05-28T03:23:09.098974
2013-12-13T07:24:34
2013-12-13T07:24:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
750
cxx
#include "toolBase.h" #include <algorithm> namespace std { const string trim (const string &str, const string &whitespace) { const size_t begin_str = str.find_first_not_of (whitespace); if (begin_str == string::npos) { // no content return ""; } const size_t end_str = str.find_last_not_of(whitespace); const size_t range = end_str - begin_str + 1; return str.substr (begin_str, range); } // find substring (case insensitive) size_t ci_find (const string& str1, const string& str2) { string::const_iterator it = search (str1.begin(), str1.end(), str2.begin(), str2.end(), my_equal()); if (it != str1.end()) return it - str1.begin(); else return string::npos; } }
[ "colddiesun@gmail.com" ]
colddiesun@gmail.com
2e4c9e80618ad5092697754b076045e4061b35f6
d9c3dc8d5cf025f4eda593990befc2de0bbcff62
/plugin/Source/NPClickOnce/plugin/NPApplicationLauncher.h
544d0c7287965893d2bbca9ef3ed341e94038e5f
[]
no_license
rajkosto/ChromeClickOnce
c6dbf12cd42acba851092a5650f2b02e9b3d19e6
53e1d7846af4b71a9f73f9856e7c23730b76ff22
refs/heads/master
2020-06-04T15:02:53.551335
2014-03-12T22:52:30
2014-03-12T22:52:30
17,578,073
3
2
null
null
null
null
UTF-8
C++
false
false
542
h
#pragma once #include "NPScriptableObject.h" class NPApplicationLauncher : public NPScriptableObject<NPApplicationLauncher> { public: NPApplicationLauncher(NPP instance); virtual ~NPApplicationLauncher(void); bool HasMethod(NPIdentifier method); bool Invoke(NPIdentifier method,const NPVariant* args,uint32_t argc,NPVariant* result); bool HasProperty(NPIdentifier name); bool GetProperty(NPIdentifier name,NPVariant* result); private: NPIdentifier launchIdentifier; NPIdentifier versionString; NPIdentifier clrVersionString; };
[ "admin@rajko.info" ]
admin@rajko.info
a18a242c63227c05609d7387ba746fd3dc0b9bb0
875e3a1668ef11a63033336abb81b78775a26488
/firmware/AD5254_example/AD5254_example.ino
5fd4c255bab65ebc1754fbc519f87b587cdeeb09
[]
no_license
jjculber/volume-control-board
77fbfaf1532746060fab95c072a516236f1e7046
88eb4743675034aa87c05a153bd3ff823560e8af
refs/heads/master
2020-04-20T13:12:43.093271
2019-04-20T01:05:22
2019-04-20T01:05:22
168,862,983
0
0
null
null
null
null
UTF-8
C++
false
false
7,380
ino
// Distributed with a free-will license. // Use it any way you want, profit or free, provided it fits in the licenses of its associated works. // AD5254 // This code is designed to work with the AD5254_I2CPOT_10K I2C Mini Module available from ControlEverything.com. // https://www.controleverything.com/content/Potentiometers?sku=AD5254_I2CPOT_10K#tabs-0-product_tabset-2 #include <Wire.h> #include <Encoder.h> // AD5254 I2C address is 0x2C(44) #define Addr 0x2F Encoder myEnc(1, 2); const int buttonPin = 0; // the number of the pushbutton pin const int ledPin = 13; // the number of the LED pin void setup() { // Initialise I2C communication as Master Wire.begin(); // Initialise serial communication, set baud rate = 9600 Serial.begin(9600); pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); mute(); unmute(); } unsigned int volume = 0; unsigned int muted = 0; long oldPosition = -999; int ledState = LOW; // the current state of the output pin int buttonState; // the current reading from the input pin int lastButtonState = LOW; // the previous reading from the input pin int registeredPress = 0; long lastDebounceTime = 0; // the last time the output pin was toggled long debounceDelay = 50; // the debounce time; increase if the output flickers void loop() { readPushButtonState(); readRotaryEncoderState(); } void readRotaryEncoderState() { long newPosition = myEnc.read(); if (newPosition < 0) { Serial.print("<0 = "); Serial.println(newPosition); newPosition = 0; myEnc.write(0); readAndPrintAllValues(); } if (newPosition > 255) { Serial.print(">255 = "); Serial.println(newPosition); newPosition = 255; myEnc.write(255); setAllValues(newPosition); readAndPrintAllValues(); } if (newPosition != oldPosition) { //unmute(); Serial.print("mid = "); Serial.println(newPosition); oldPosition = newPosition; setAllValues(newPosition); readAndPrintAllValues(); } } void readPushButtonState() { // read the state of the switch into a local variable: int reading = digitalRead(buttonPin); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited // long enough since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading != lastButtonState) { // reset the debouncing timer lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { // whatever the reading is at, it's been there for longer // than the debounce delay, so take it as the actual current state: buttonState = reading; if (buttonState == LOW && registeredPress == 0) { ledState = ((ledState == LOW) ? HIGH : LOW); registeredPress = 1; // set the LED using the state of the button: if (ledState == HIGH) { mute(); } else { unmute(); } } if (buttonState == HIGH && registeredPress == 1) { registeredPress = 0; } } // save the reading. Next time through the loop, // it'll be the lastButtonState: lastButtonState = reading; } void mute() { ledState = HIGH; digitalWrite(ledPin, ledState); //setAllValues(0); Wire.beginTransmission(Addr); Wire.write(0x00); Wire.write(0x00); Wire.endTransmission(); Wire.beginTransmission(Addr); Wire.write(0x01); Wire.write(0x00); Wire.endTransmission(); Wire.beginTransmission(Addr); Wire.write(0x02); Wire.write(0x00); Wire.endTransmission(); Wire.beginTransmission(Addr); Wire.write(0x03); Wire.write(0x00); Wire.endTransmission(); Wire.beginTransmission(Addr); Wire.write(0x80); Wire.endTransmission(); volume = 0; muted = 1; myEnc.write(0); Serial.println("muted"); readAndPrintAllValues(); } void unmute() { ledState = LOW; digitalWrite(ledPin, ledState); muted = 0; myEnc.write(1); setAllValues(1); Serial.println("unmuted"); readAndPrintAllValues(); } void readAndPrintAllValues() { unsigned int data = -1; // Start I2C transmission Wire.beginTransmission(Addr); // Select data register Wire.write(0x00); // Stop I2C transmission Wire.endTransmission(); // Request 1 byte of data Wire.requestFrom(Addr, 1); // Read 1 byte of data if (Wire.available() == 1) { data = Wire.read(); } // Convert the data float res_0 = (data / 256.0 ) * 10.0; // Start I2C transmission Wire.beginTransmission(Addr); // Select data register Wire.write(0x01); // Stop I2C transmission Wire.endTransmission(); // Request 1 byte of data Wire.requestFrom(Addr, 1); // Read 1 byte of data if (Wire.available() == 1) { data = Wire.read(); } // Convert the data float res_1 = (data / 256.0 ) * 10.0; // Start I2C transmission Wire.beginTransmission(Addr); // Select data register Wire.write(0x02); // Stop I2C transmission Wire.endTransmission(); // Request 1 byte of data Wire.requestFrom(Addr, 1); // Read 1 byte of data if (Wire.available() == 1) { data = Wire.read(); } // Convert the data float res_2 = (data / 256.0 ) * 10.0; // Start I2C transmission Wire.beginTransmission(Addr); // Select data register Wire.write(0x03); // Stop I2C transmission Wire.endTransmission(); // Request 1 byte of data Wire.requestFrom(Addr, 1); // Read 1 byte of data if (Wire.available() == 1) { data = Wire.read(); } // Convert the data float res_3 = (data / 256.0 ) * 10.0; // Output data to serial monitor Serial.print("Resistance Channel-0 : "); Serial.print(res_0); Serial.println(" K"); Serial.print("Resistance Channel-1 : "); Serial.print(res_1); Serial.println(" K"); Serial.print("Resistance Channel-2 : "); Serial.print(res_2); Serial.println(" K"); Serial.print("Resistance Channel-3 : "); Serial.print(res_3); Serial.println(" K"); } void setAllValues(unsigned int val) { if (muted == 1) { return; } uint8_t command = 0x80; // nop if (volume > val) { // decrease volume command = 0xb0; } else if (volume < val) { // increase volume command = 0xd8; } Serial.println(command); Wire.beginTransmission(Addr); Wire.write(command); Wire.endTransmission(); Wire.beginTransmission(Addr); Wire.write(0x80); Wire.endTransmission(); volume = val; return; // Start I2C transmission Wire.beginTransmission(Addr); // Send instruction for POT channel-0 Wire.write(0x00); // Input resistance value, 0x80(128) //Wire.write(val); // Stop I2C transmission Wire.endTransmission(); // Start I2C transmission Wire.beginTransmission(Addr); // Send instruction for POT channel-1 Wire.write(0x01); // Input resistance value, 0x80(128) Wire.write(val); // Stop I2C transmission Wire.endTransmission(); // Start I2C transmission Wire.beginTransmission(Addr); // Send instruction for POT channel-2 Wire.write(0x02); // Input resistance value, 0x80(128) Wire.write(val); // Stop I2C transmission Wire.endTransmission(); // Start I2C transmission Wire.beginTransmission(Addr); // Send instruction for POT channel-3 Wire.write(0x03); // Input resistance value, 0x80(128) Wire.write(val); // Stop I2C transmission Wire.endTransmission(); }
[ "jculberts@gmail.com" ]
jculberts@gmail.com
b37a9baefe63dba3e088ce3e1bbe0dace7878905
a86a8bfd545aa059202e4052e079d3353030364c
/src/client/cli/main.cc
b07624d869b471b37c4bb1ab4530857172a076aa
[ "MIT" ]
permissive
delizhang/spada
741623a2abc207e63337952f3ccbdd7b460138e7
f87e42c0c64b4d5fa2917df985f5403d8a7b3fd8
refs/heads/master
2021-01-01T19:21:31.561633
2017-07-27T18:29:12
2017-07-27T18:29:12
93,212,547
0
0
null
null
null
null
UTF-8
C++
false
false
503
cc
#include <iostream> #include "client/connector.h" #include "common/network/connection.h" int main(int argc, const char *argv[]) { Connector connector("127.0.0.1", DEFAULT_PORT); if(connector.Init()) { std::cout << "Sever connected" << std::endl; const int bufSize = 1024; char buffer[bufSize]; do{ std::cout << "Spada: "; std::cin.getline(buffer, bufSize); } while(connector.Send(buffer, bufSize)); } return 0; }
[ "deli.zhang@outlook.com" ]
deli.zhang@outlook.com
524e6aa676ce7263a6ee4586ef72dc84a72cbdcb
cae9edc918596933a9644033a89e3f27db534c3a
/Module_04/ex03/Cure.hpp
02f1e569a203fb51820176c699304975930201d0
[]
no_license
Tjobo-Hero/CPP
81c409e4c32cfd74ccd432d8dfec7d069a4f9ef2
93c5aae2be453e19e5e0948640a32ea6e32d55c8
refs/heads/master
2023-04-23T06:24:56.804387
2021-05-14T09:35:36
2021-05-14T09:35:36
309,345,777
0
0
null
null
null
null
UTF-8
C++
false
false
1,324
hpp
/* ************************************************************************** */ /* */ /* :::::::: */ /* Cure.hpp :+: :+: */ /* +:+ */ /* By: timvancitters <timvancitters@student.co +#+ */ /* +#+ */ /* Created: 2021/02/02 15:34:05 by timvancitte #+# #+# */ /* Updated: 2021/02/04 13:56:40 by timvancitte ######## odam.nl */ /* */ /* ************************************************************************** */ #ifndef CURE_HPP # define CURE_HPP #include "AMateria.hpp" #include "ICharacter.hpp" #include <iostream> #include <string> class Cure : public AMateria { public: Cure(void); Cure(Cure const &src); virtual ~Cure(void); Cure& operator=(Cure const &obj); std::string const& getType() const; unsigned int getXP(void) const; virtual Cure* clone(void) const; virtual void use(ICharacter &target); }; #endif
[ "timvancitters@Tims-MacBook-Pro.local" ]
timvancitters@Tims-MacBook-Pro.local
0baa26ae1375782d04f64c5f14aaa7de8a70bb98
64895fff118ac407357a050861297a395fa2fbc6
/CodeChef/Snackdown 17/coup.cpp
4dc8f8bea06e6363ad820c7e81aaf7998892d453
[]
no_license
whiz-Tuhin/Competitve
38df5475ba8f9e4ecfa96071e1a0b639bb2ab41e
f5fd063e31f0e5b6addc26c83e007eeb5ae7b89f
refs/heads/master
2020-04-06T03:46:19.820666
2017-08-01T08:02:00
2017-08-01T08:02:00
68,317,364
4
0
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
#include <iostream> #include <string> #include <vector> #include <cmath> #include <utility> using namespace std; typedef unsigned long long int ulli; int main(){ ios_base::sync_with_stdio(false); int t; cin>>t; while(t--){ int n; cin>>n; vector<string> grid(2); int count_s = 0; for(int i = 0; i < 2;i++){ string s; cin>>s; grid.push_back(s); } int h = 0,v = 0; for(int i = 0;i < n;i++){ if(grid[0][i] == '*' && grid[1][i] == '*'){ h++; break; } } for(int i = 0;i < n-1;i++){ if((grid[0][i] == '*' && grid[0][i+1] == '*') || (grid[1][i] == '*' && grid[1][i+1] == '*') || (grid[0][i] == '*' && grid[1][i+1] == '*') || (grid[1][i] == '*' && grid[0][i+1] == '*')){ v++; } } cout<<(h+v)<<endl; } return 0; }
[ "tuhinkhare3@gmail.com" ]
tuhinkhare3@gmail.com
d8744cd4f23815ad87e5f4e96a9307d2e1cc91f6
3d8c44ed73ec0d9776e7cbc2ffd11005a1a41579
/include/alds/sort/1_2_c_stable_sort.h
f33dfb8a9292831aae9e883bac3979f33f68c998
[]
no_license
eiji03aero/alds
490c5e9fa2f9f225d74a5fd5d9d91bc0c90c71d2
4f92fa114fc4dc6c23f8259cccbe606ddd31e56e
refs/heads/master
2023-01-10T14:32:57.661496
2020-11-08T13:01:32
2020-11-08T13:01:32
302,466,212
0
0
null
null
null
null
UTF-8
C++
false
false
1,022
h
#ifndef ALDS_SORT_1_1_D_STABLE_SORT_H_INCLUDED #define ALDS_SORT_1_1_D_STABLE_SORT_H_INCLUDED #include "alds/shared.h" #include <vector> namespace alds { namespace sort { void bubble_sort(std::vector<alds::Card> &input) { for (int i = 0; i < input.size(); i++) { for (int j = input.size() - 1; j >= i+1; j--) { if (input[j].value < input[j - 1].value) { std::swap(input[j], input[j - 1]); } } } } void selection_sort(std::vector<alds::Card> &input) { for (int i = 0; i < input.size(); i++) { int minj = i; for (int j = i; j < input.size(); j++) { if (input[j].value < input[minj].value) { minj = j; } } std::swap(input[i], input[minj]); } } bool is_stable(std::vector<alds::Card> v1, std::vector<alds::Card> v2) { for (int i = 0; i < v1.size(); i++) { if (v1[i].suit != v2[i].suit) { return false; } } return true; } } /* namespace sort */ } /* namespace alds */ #endif /* ifndef ALDS_SORT_1_1_D_STABLE_SORT_H_INCLUDED */
[ "eiji03aero@gmail.com" ]
eiji03aero@gmail.com
9d510591b91ce6941c2614dcf27a5aeccb578e9f
bfdc2ece38402bab75a83149cd09b16a67bc32fa
/ParseDataFile/DB_pwShuntSreact.cpp
dbb2b16b29468df3e30d11d37d792280aff411be
[]
no_license
wangdi190/avc_deyang
b6bc3c8051824a37c2ff147110b243d205101f1b
68dc6cc27caf8c76f928aff7450a82bf12461591
refs/heads/master
2021-01-19T04:49:10.599642
2016-09-28T09:19:24
2016-09-28T09:19:24
69,438,892
0
1
null
null
null
null
GB18030
C++
false
false
15,267
cpp
// DB_pwShuntSreact.cpp: implementation of the DB_pwShuntSreact class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ParseDataFile.h" #include "DB_pwShuntSreact.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// extern bool g_firstrun; DB_pwShuntSreact::DB_pwShuntSreact() { } DB_pwShuntSreact::~DB_pwShuntSreact() { } bool SortByShuntNu(PositionShunt a, PositionShunt b) { if(a.nu<b.nu) return true; else return false; } bool SortBySreactNu(PositionSreact a, PositionSreact b) { if(a.nu<b.nu) return true; else return false; } bool DB_pwShuntSreact::InitParam() { InitParam_Shunt(); InitParam_Sreact(); return true; } bool DB_pwShuntSreact::InitParam_Shunt() { m_nTableID_Shunt = g_DB.GetTableID("visualpw", "Shunt"); m_VecShunt.clear(); visualpw_Shunt *pDBShunt = (visualpw_Shunt*)g_DB.QueryRecord(m_nTableID_Shunt,NULL,m_recn); if(m_recn<0) return false; PositionShunt posShunt; for (int i=0; i<m_recn; i++) { memset(&posShunt, 0 , sizeof(PositionShunt)); posShunt.nPos = i; memcpy(&posShunt.rec, &pDBShunt[i], sizeof(visualpw_Shunt)); posShunt.nu = pDBShunt[i].NU; m_VecShunt.push_back(posShunt); } std::sort(m_VecShunt.begin(), m_VecShunt.end(), SortByShuntNu); return true; } bool DB_pwShuntSreact::InitParam_Sreact() { m_nTableID_Sreact = g_DB.GetTableID("visualpw", "Sreact"); m_VecSreact.clear(); visualpw_Sreact *pDBSreact = (visualpw_Sreact*)g_DB.QueryRecord(m_nTableID_Sreact,NULL,m_recn); if(m_recn<0) return false; PositionSreact posSreact; for (int i=0; i<m_recn; i++) { memset(&posSreact, 0 , sizeof(PositionSreact)); posSreact.nPos = i; memcpy(&posSreact.rec, &pDBSreact[i], sizeof(visualpw_Sreact)); posSreact.nu = pDBSreact[i].NU; m_VecSreact.push_back(posSreact); } std::sort(m_VecSreact.begin(), m_VecSreact.end(), SortBySreactNu); return true; } int DB_pwShuntSreact::BinaryFindShuntByNu(DWORD nu) { long lMin=0;long lMid=0; long lMax=m_VecShunt.size()-1; DWORD lid; while(lMin<=lMax) { lMid = (lMin+lMax)/2; if (lMid>=0) { lid= m_VecShunt.at(lMid).nu; if (lid<nu) lMin = lMid+1; else if(lid>nu) lMax = lMid-1; else return lMid; } else break; } return -1; } int DB_pwShuntSreact::BinaryFindSreactByNu(DWORD nu) { long lMin=0;long lMid=0; long lMax=m_VecSreact.size()-1; DWORD lid; while(lMin<=lMax) { lMid = (lMin+lMax)/2; if (lMid>=0) { lid= m_VecSreact.at(lMid).nu; if (lid<nu) lMin = lMid+1; else if(lid>nu) lMax = lMid-1; else return lMid; } else break; } return -1; } void DB_pwShuntSreact::RefreshModel(char *pData, int bufSize) { RC_DEVICE_Model *pRec = (RC_DEVICE_Model*)pData; visualpw_Shunt DBrec1, *pDBrec1; visualpw_Sreact DBrec2, *pDBrec2; visualpw_Station *pSta; bool bAddNew_Shunt = false, bAddNew_Sreact = false; for (int i=0; i<bufSize/sizeof(RC_DEVICE_Model); i++) { pSta = g_DataBase.m_pwStation.GetSubStationNameByID(pRec[i].fac_id); if(MatchKeyNo(pRec[i].rc_id, RC_DEVICE_MODEL) == false) { break; } if (pRec[i].rc_type == 1 || pRec[i].rc_type == 3) //电容 { ZeroMemory(&DBrec1, sizeof(DBrec1)); m_nRet = BinaryFindShuntByNu(pRec[i].rc_id); if (m_nRet == -1) { DBrec1.NU = pRec[i].rc_id; sprintf(DBrec1.Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec1.Station = pRec[i].fac_id; DBrec1.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec1.Station); sprintf(DBrec1.ID, "%d", pRec[i].rc_id); DBrec1.ele = 1-pRec[i].run_state; DBrec1.sta = 0; if (pRec[i].nd1_no<0) DBrec1.Node = 0; else DBrec1.Node = pRec[i].nd1_no; DBrec1.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec1.Qmax=pRec[i].qnom; DBrec1.RVol=pRec[i].vnom; //DBrec1.CtrlType=pRec[i].q_status; LSI_AppendRec("visualpw.Shunt", &DBrec1); bAddNew_Shunt = true; } else { pDBrec1 = &m_VecShunt.at(m_nRet).rec; sprintf(pDBrec1->Name, "%s.%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); pDBrec1->Station = pRec[i].fac_id; pDBrec1->ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec1.Station); sprintf(pDBrec1->ID, "%d", pRec[i].rc_id); pDBrec1->ele = 1-pRec[i].run_state; if (pRec[i].nd1_no<0) pDBrec1->Node = 0; else pDBrec1->Node = pRec[i].nd1_no; pDBrec1->VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); pDBrec1->Qmax=pRec[i].qnom; pDBrec1->RVol=pRec[i].vnom; g_DB.UpdateRealRecord("Shunt", m_VecShunt.at(m_nRet).nPos, &m_VecShunt.at(m_nRet).rec, "visualpw"); } } else if (pRec[i].rc_type == 2 || //电抗 pRec[i].rc_type == 4 || pRec[i].rc_type == 5) { m_nRet = BinaryFindSreactByNu(pRec[i].rc_id); if (m_nRet == -1) { DBrec2.NU = pRec[i].rc_id; sprintf(DBrec2.Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec2.Station = pRec[i].fac_id; DBrec2.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec2.Station); sprintf(DBrec2.ID, "%d", pRec[i].rc_id); DBrec2.ele = 1-pRec[i].run_state; DBrec2.sta = 1; if (pRec[i].nd1_no<0) DBrec2.Node1 = 0; else DBrec2.Node1 = pRec[i].nd1_no; if (pRec[i].nd2_no<0) DBrec2.Node2 = 0; else DBrec2.Node2 = pRec[i].nd2_no; DBrec2.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec2.Qmax=pRec[i].qnom; DBrec2.RVol=pRec[i].vnom; //DBrec2.CtrlType=pRec[i].q_status; LSI_AppendRec("visualpw.Sreact", &DBrec2); bAddNew_Sreact = true; } else { pDBrec2 = &m_VecSreact.at(m_nRet).rec; sprintf(pDBrec2->Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); pDBrec2->Station = pRec[i].fac_id; pDBrec2->ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec2.Station); sprintf(pDBrec2->ID, "%d", pRec[i].rc_id); pDBrec2->ele = 1-pRec[i].run_state; pDBrec2->sta = 1; if (pRec[i].nd1_no<0) pDBrec2->Node1 = 0; else pDBrec2->Node1 = pRec[i].nd1_no; if (pRec[i].nd2_no<0) pDBrec2->Node2 = 0; else pDBrec2->Node2 = pRec[i].nd2_no; pDBrec2->VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); pDBrec2->Qmax=pRec[i].qnom; pDBrec2->RVol=pRec[i].vnom; //DBrec2.CtrlType=pRec[i].q_status; g_DB.UpdateRealRecord("Sreact", m_VecSreact.at(m_nRet).nPos, &m_VecSreact.at(m_nRet).rec, "visualpw"); } } } if(bAddNew_Shunt) InitParam_Shunt(); if(bAddNew_Sreact) InitParam_Sreact(); } /*void DB_pwShuntSreact::RefreshModel(char *pData, int bufSize) { RC_DEVICE_Model *pRec = (RC_DEVICE_Model*)pData; visualpw_Shunt DBrec1, *pDBrec1; visualpw_Sreact DBrec2, *pDBrec2; visualpw_Station *pSta; for (int i=0; i<bufSize/sizeof(RC_DEVICE_Model); i++) { pSta = g_DataBase.m_pwStation.GetSubStationNameByID(pRec[i].fac_id); if(MatchKeyNo(pRec[i].rc_id, RC_DEVICE_MODEL) == false) { break; } if (pRec[i].rc_type == 1 || pRec[i].rc_type == 3) //电容 { ZeroMemory(&DBrec1, sizeof(DBrec1)); m_szTmp.Format("TABLE(visualpw.Shunt),WHERE(NU=%d)", pRec[i].rc_id); pDBrec1 = (visualpw_Shunt*)g_DB.QueryRecord("Shunt",m_szTmp.GetBuffer(0),m_recn,"visualpw"); if(pDBrec1 == NULL) { DBrec1.NU = pRec[i].rc_id; sprintf(DBrec1.Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec1.Station = pRec[i].fac_id; DBrec1.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec1.Station); sprintf(DBrec1.ID, "%d", pRec[i].rc_id); DBrec1.ele = 1-pRec[i].run_state; DBrec1.sta = 0; if (pRec[i].nd1_no<0) DBrec1.Node = 0; else DBrec1.Node = pRec[i].nd1_no; DBrec1.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec1.Qmax=pRec[i].qnom; DBrec1.RVol=pRec[i].vnom; //DBrec1.CtrlType=pRec[i].q_status; LSI_AppendRec("visualpw.Shunt", &DBrec1); } else { memcpy(&DBrec1, pDBrec1, sizeof(DBrec1)); sprintf(DBrec1.Name, "%s.%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec1.Station = pRec[i].fac_id; DBrec1.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec1.Station); sprintf(DBrec1.ID, "%d", pRec[i].rc_id); DBrec1.ele = 1-pRec[i].run_state; if (pRec[i].nd1_no<0) DBrec1.Node = 0; else DBrec1.Node = pRec[i].nd1_no; DBrec1.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec1.Qmax=pRec[i].qnom; DBrec1.RVol=pRec[i].vnom; //DBrec1.CtrlType=pRec[i].q_status; g_DB.UpdateRecord("Shunt", m_szTmp.GetBuffer(0), &DBrec1, "visualpw"); } } else if (pRec[i].rc_type == 2 || //电抗 pRec[i].rc_type == 4 || pRec[i].rc_type == 5) { ZeroMemory(&DBrec2, sizeof(DBrec2)); m_szTmp.Format("TABLE(visualpw.Sreact),WHERE(NU=%d)", pRec[i].rc_id); pDBrec2 = (visualpw_Sreact*)g_DB.QueryRecord("Sreact",m_szTmp.GetBuffer(0),m_recn,"visualpw"); if(pDBrec2 == NULL) { DBrec2.NU = pRec[i].rc_id; sprintf(DBrec2.Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec2.Station = pRec[i].fac_id; DBrec2.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec2.Station); sprintf(DBrec2.ID, "%d", pRec[i].rc_id); DBrec2.ele = 1-pRec[i].run_state; DBrec2.sta = 1; if (pRec[i].nd1_no<0) DBrec2.Node1 = 0; else DBrec2.Node1 = pRec[i].nd1_no; if (pRec[i].nd2_no<0) DBrec2.Node2 = 0; else DBrec2.Node2 = pRec[i].nd2_no; DBrec2.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec2.Qmax=pRec[i].qnom; DBrec2.RVol=pRec[i].vnom; //DBrec2.CtrlType=pRec[i].q_status; LSI_AppendRec("visualpw.Sreact", &DBrec2); } else { memcpy(&DBrec2, pDBrec2, sizeof(DBrec2)); sprintf(DBrec2.Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec2.Station = pRec[i].fac_id; DBrec2.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec2.Station); sprintf(DBrec2.ID, "%d", pRec[i].rc_id); DBrec2.ele = 1-pRec[i].run_state; DBrec2.sta = 1; if (pRec[i].nd1_no<0) DBrec2.Node1 = 0; else DBrec2.Node1 = pRec[i].nd1_no; if (pRec[i].nd2_no<0) DBrec2.Node2 = 0; else DBrec2.Node2 = pRec[i].nd2_no; DBrec2.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec2.Qmax=pRec[i].qnom; DBrec2.RVol=pRec[i].vnom; //DBrec2.CtrlType=pRec[i].q_status; g_DB.UpdateRecord("Sreact", m_szTmp.GetBuffer(0), &DBrec2, "visualpw"); } } } }*/ void DB_pwShuntSreact::RefreshRealTime(char *pData, int bufSize) { RC_DEVICE_Real *pRec = (RC_DEVICE_Real*)pData; PositionShunt *pPos1; PositionSreact *pPos2; visualpw_Shunt *pDBrec1; visualpw_Sreact *pDBrec2; for (int i=0; i<bufSize/sizeof(RC_DEVICE_Real); i++) { if (pRec[i].rc_type == RC_SHUNT || pRec[i].rc_type == RC_SERIESSHUNT) //电容 { m_nRet = BinaryFindShuntByNu(pRec[i].rc_id); if(m_nRet != -1) { pPos1 = &m_VecShunt.at(m_nRet); pDBrec1 = &m_VecShunt.at(m_nRet).rec; if (fabs(pDBrec1->Q - pRec[i].q_value)>0.01) { LSI_PutColVal(m_nTableID_Shunt, pPos1->nPos, "Q", (void*)&pRec[i].q_value); pDBrec1->Q = pRec[i].q_value; } BYTE Tsta=pDBrec1->Tsta; if(g_TimeFile.GetDay()!=pDBrec1->LogTime.GetDay()) //复位 Tsta=0; if(fabs((pDBrec1->Q - pRec[i].q_value)/pDBrec1->Qmax)>0.5) { if(g_firstrun==false) Tsta++; } if(Tsta!=pDBrec1->Tsta) //变位计数 { //g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "Tsta", (void*)&Tsta); LSI_PutColVal(m_nTableID_Shunt, pPos1->nPos, "Tsta", (void*)&Tsta); pDBrec1->Tsta = Tsta; } BYTE sta=0; if(fabs(pDBrec1->Q)>0.1||fabs(pDBrec1->I)>0.1) sta=1; if (pDBrec1->sta != sta) { LSI_PutColVal(m_nTableID_Shunt, pPos1->nPos, "sta", (void*)&sta); pDBrec1->sta = sta; } if (pDBrec1->LogTime != g_TimeFile) { LSI_PutColVal(m_nTableID_Shunt, pPos1->nPos, "LogTime", (void*)&g_TimeFile); pDBrec1->LogTime = g_TimeFile; } } } else if (pRec[i].rc_type == 2 || //电抗 pRec[i].rc_type == 4 || pRec[i].rc_type == 5) { m_nRet = BinaryFindSreactByNu(pRec[i].rc_id); if (m_nRet == -1) { pPos2 = &m_VecSreact.at(m_nRet); pDBrec2 = &m_VecSreact.at(m_nRet).rec; if (fabs(pDBrec2->Zx - pRec[i].q_value)>0.01) { LSI_PutColVal(m_nTableID_Sreact, pPos2->nPos, "Zx", (void*)&pRec[i].q_value); pDBrec2->Zx = pRec[i].q_value; } BYTE sta=0; if(fabs(pDBrec2->Zx)>0.1||fabs(pDBrec2->I)>0.1) sta=1; if (sta != pDBrec2->sta) { LSI_PutColVal(m_nTableID_Sreact, pPos2->nPos, "sta", (void*)&sta); pDBrec2->sta = sta; } if (pDBrec2->LogTime != g_TimeFile) { LSI_PutColVal(m_nTableID_Sreact, pPos2->nPos, "LogTime", (void*)&g_TimeFile); pDBrec2->LogTime = g_TimeFile; } } } } } /* void DB_pwShuntSreact::RefreshRealTime(char *pData, int bufSize) { // InitParam(); RC_DEVICE_Real *pRec = (RC_DEVICE_Real*)pData; visualpw_Shunt *pDBrec1; visualpw_Sreact *pDBrec2; for (int i=0; i<bufSize/sizeof(RC_DEVICE_Real); i++) { if (pRec[i].rc_type == RC_SHUNT || pRec[i].rc_type == RC_SERIESSHUNT) //电容 { m_szTmp.Format("TABLE(visualpw.Shunt),WHERE(NU=%d)", pRec[i].rc_id); pDBrec1 = (visualpw_Shunt*)g_DB.QueryRecord("Shunt",m_szTmp.GetBuffer(0),m_recn,"visualpw"); if(pDBrec1 != NULL) { if (fabs(pDBrec1->Q - pRec[i].q_value)>0.01) g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "Q", (void*)&pRec[i].q_value); BYTE Tsta=pDBrec1->Tsta; if(g_TimeFile.GetDay()!=pDBrec1->LogTime.GetDay()) //复位 Tsta=0; if(fabs((pDBrec1->Q - pRec[i].q_value)/pDBrec1->Qmax)>0.5) { if(g_firstrun==false) Tsta++; } if(Tsta!=pDBrec1->Tsta) //变位计数 g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "Tsta", (void*)&Tsta); BYTE sta=0; if(fabs(pDBrec1->Q)>0.1||fabs(pDBrec1->I)>0.1) sta=1; g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "sta", (void*)&sta); g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "LogTime", (void*)&g_TimeFile); } } else if (pRec[i].rc_type == 2 || //电抗 pRec[i].rc_type == 4 || pRec[i].rc_type == 5) { m_szTmp.Format("TABLE(visualpw.Sreact),WHERE(NU=%d)", pRec[i].rc_id); pDBrec2 = (visualpw_Sreact*)g_DB.QueryRecord("Sreact",m_szTmp.GetBuffer(0),m_recn,"visualpw"); if(pDBrec2 != NULL) { if (fabs(pDBrec2->Zx - pRec[i].q_value)>0.01) g_DB.ModifyRecord(m_nTableID_Sreact, m_szTmp.GetBuffer(0), "Zx", (void*)&pRec[i].q_value); BYTE sta=0; if(fabs(pDBrec2->Zx)>0.1||fabs(pDBrec2->I)>0.1) sta=1; g_DB.ModifyRecord(m_nTableID_Sreact, m_szTmp.GetBuffer(0), "sta", (void*)&sta); g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "LogTime", (void*)&g_TimeFile); } } } if(g_firstrun==true) g_firstrun=false; }*/
[ "wangdi190@qq.com" ]
wangdi190@qq.com
ef39a4f2774140b4d11cd79fdf8c8725981b50d5
2f685114f9dcf630673fc982380196ec0e4f8dd3
/ash/highlighter/highlighter_controller_unittest.cc
87368acad33cb182fa20c8d648cc35e127d7ceee
[ "BSD-3-Clause" ]
permissive
BitShekel/Tungsten
5ed9a6958f4d7147af42753ec6b85205394ce5fa
fd7caa325cbc10c6d88ce7e393d21c2e6941211c
refs/heads/master
2023-01-19T16:51:58.927691
2020-11-26T02:12:08
2020-11-26T02:12:08
133,874,738
0
0
null
null
null
null
UTF-8
C++
false
false
21,690
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/highlighter/highlighter_controller.h" #include <memory> #include "ash/components/fast_ink/fast_ink_points.h" #include "ash/highlighter/highlighter_controller_test_api.h" #include "ash/public/cpp/config.h" #include "ash/shell.h" #include "ash/system/palette/mock_palette_tool_delegate.h" #include "ash/system/palette/palette_tool.h" #include "ash/system/palette/tools/metalayer_mode.h" #include "ash/test/ash_test_base.h" #include "base/strings/stringprintf.h" #include "ui/aura/window_tree_host.h" #include "ui/compositor/test/draw_waiter_for_test.h" #include "ui/events/test/event_generator.h" namespace ash { namespace { class TestHighlighterObserver : public HighlighterController::Observer { public: TestHighlighterObserver() = default; ~TestHighlighterObserver() override = default; // HighlighterController::Observer: void OnHighlighterEnabledChanged(HighlighterEnabledState state) override { if (state == HighlighterEnabledState::kEnabled) { ++enabled_count_; } else if (state == HighlighterEnabledState::kDisabledByUser) { ++disabled_by_user_count_; } else { DCHECK_EQ(HighlighterEnabledState::kDisabledBySessionEnd, state); ++disabled_by_session_end_; } } int enabled_count_ = 0; int disabled_by_user_count_ = 0; int disabled_by_session_end_ = 0; private: DISALLOW_COPY_AND_ASSIGN(TestHighlighterObserver); }; class HighlighterControllerTest : public AshTestBase { public: HighlighterControllerTest() = default; ~HighlighterControllerTest() override = default; void SetUp() override { AshTestBase::SetUp(); controller_test_api_ = std::make_unique<HighlighterControllerTestApi>( Shell::Get()->highlighter_controller()); palette_tool_delegate_ = std::make_unique<MockPaletteToolDelegate>(); tool_ = std::make_unique<MetalayerMode>(palette_tool_delegate_.get()); } void TearDown() override { tool_.reset(); // This needs to be called first to reset the controller state before the // shell instance gets torn down. controller_test_api_.reset(); AshTestBase::TearDown(); } void UpdateDisplayAndWaitForCompositingEnded( const std::string& display_specs) { UpdateDisplay(display_specs); ui::DrawWaiterForTest::WaitForCompositingEnded( Shell::GetPrimaryRootWindow()->GetHost()->compositor()); } protected: void TraceRect(const gfx::Rect& rect) { GetEventGenerator().MoveTouch(gfx::Point(rect.x(), rect.y())); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(rect.right(), rect.y())); GetEventGenerator().MoveTouch(gfx::Point(rect.right(), rect.bottom())); GetEventGenerator().MoveTouch(gfx::Point(rect.x(), rect.bottom())); GetEventGenerator().MoveTouch(gfx::Point(rect.x(), rect.y())); GetEventGenerator().ReleaseTouch(); // The the events above will trigger a frame, so wait until a new // CompositorFrame is generated before terminating. ui::DrawWaiterForTest::WaitForCompositingEnded( Shell::GetPrimaryRootWindow()->GetHost()->compositor()); } std::unique_ptr<HighlighterControllerTestApi> controller_test_api_; std::unique_ptr<MockPaletteToolDelegate> palette_tool_delegate_; std::unique_ptr<PaletteTool> tool_; private: DISALLOW_COPY_AND_ASSIGN(HighlighterControllerTest); }; } // namespace // Test to ensure the class responsible for drawing the highlighter pointer // receives points from stylus movements as expected. TEST_F(HighlighterControllerTest, HighlighterRenderer) { // The highlighter pointer mode only works with stylus. GetEventGenerator().EnterPenPointerMode(); // When disabled the highlighter pointer should not be showing. GetEventGenerator().MoveTouch(gfx::Point(1, 1)); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); // Verify that by enabling the mode, the highlighter pointer should still not // be showing. controller_test_api_->SetEnabled(true); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); // Verify moving the stylus 4 times will not display the highlighter pointer. GetEventGenerator().MoveTouch(gfx::Point(2, 2)); GetEventGenerator().MoveTouch(gfx::Point(3, 3)); GetEventGenerator().MoveTouch(gfx::Point(4, 4)); GetEventGenerator().MoveTouch(gfx::Point(5, 5)); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); // Verify pressing the stylus will show the highlighter pointer and add a // point but will not activate fading out. GetEventGenerator().PressTouch(); EXPECT_TRUE(controller_test_api_->IsShowingHighlighter()); EXPECT_FALSE(controller_test_api_->IsFadingAway()); EXPECT_EQ(1, controller_test_api_->points().GetNumberOfPoints()); // Verify dragging the stylus 2 times will add 2 more points. GetEventGenerator().MoveTouch(gfx::Point(6, 6)); GetEventGenerator().MoveTouch(gfx::Point(7, 7)); EXPECT_EQ(3, controller_test_api_->points().GetNumberOfPoints()); // Verify releasing the stylus still shows the highlighter pointer, which is // fading away. GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->IsShowingHighlighter()); EXPECT_TRUE(controller_test_api_->IsFadingAway()); // Verify that disabling the mode right after the gesture completion does not // hide the highlighter pointer immediately but lets it play out the // animation. controller_test_api_->SetEnabled(false); EXPECT_TRUE(controller_test_api_->IsShowingHighlighter()); EXPECT_TRUE(controller_test_api_->IsFadingAway()); // Verify that disabling the mode mid-gesture hides the highlighter pointer // immediately. controller_test_api_->DestroyPointerView(); controller_test_api_->SetEnabled(true); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(6, 6)); EXPECT_TRUE(controller_test_api_->IsShowingHighlighter()); controller_test_api_->SetEnabled(false); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); // Verify that the highlighter pointer does not add points while disabled. GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(8, 8)); GetEventGenerator().ReleaseTouch(); GetEventGenerator().MoveTouch(gfx::Point(9, 9)); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); // Verify that the highlighter pointer does not get shown if points are not // coming from the stylus, even when enabled. GetEventGenerator().ExitPenPointerMode(); controller_test_api_->SetEnabled(true); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(10, 10)); GetEventGenerator().MoveTouch(gfx::Point(11, 11)); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); GetEventGenerator().ReleaseTouch(); } // Test to ensure the class responsible for drawing the highlighter pointer // handles prediction as expected when it receives points from stylus movements. TEST_F(HighlighterControllerTest, HighlighterPrediction) { controller_test_api_->SetEnabled(true); // The highlighter pointer mode only works with stylus. GetEventGenerator().EnterPenPointerMode(); GetEventGenerator().PressTouch(); EXPECT_TRUE(controller_test_api_->IsShowingHighlighter()); EXPECT_EQ(1, controller_test_api_->points().GetNumberOfPoints()); // Initial press event shouldn't generate any predicted points as there's no // history to use for prediction. EXPECT_EQ(0, controller_test_api_->predicted_points().GetNumberOfPoints()); // Verify dragging the stylus 3 times will add some predicted points. GetEventGenerator().MoveTouch(gfx::Point(10, 10)); GetEventGenerator().MoveTouch(gfx::Point(20, 20)); GetEventGenerator().MoveTouch(gfx::Point(30, 30)); EXPECT_NE(0, controller_test_api_->predicted_points().GetNumberOfPoints()); // Verify predicted points are in the right direction. for (const auto& point : controller_test_api_->predicted_points().points()) { EXPECT_LT(30, point.location.x()); EXPECT_LT(30, point.location.y()); } } // Test that stylus gestures are correctly recognized by HighlighterController. TEST_F(HighlighterControllerTest, HighlighterGestures) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); // A non-horizontal stroke is not recognized controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(100, 100)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(200, 200)); GetEventGenerator().ReleaseTouch(); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); // An almost horizontal stroke is recognized controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(100, 100)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(300, 102)); GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); // Horizontal stroke selection rectangle should: // have the same horizontal center line as the stroke bounding box, // be 4dp wider than the stroke bounding box, // be exactly 14dp high. EXPECT_EQ("98,94 204x14", controller_test_api_->selection().ToString()); // An insufficiently closed C-like shape is not recognized controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(100, 0)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(0, 0)); GetEventGenerator().MoveTouch(gfx::Point(0, 100)); GetEventGenerator().MoveTouch(gfx::Point(100, 100)); GetEventGenerator().ReleaseTouch(); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); // An almost closed G-like shape is recognized controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(200, 0)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(0, 0)); GetEventGenerator().MoveTouch(gfx::Point(0, 100)); GetEventGenerator().MoveTouch(gfx::Point(200, 100)); GetEventGenerator().MoveTouch(gfx::Point(200, 20)); GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("0,0 200x100", controller_test_api_->selection().ToString()); // A closed diamond shape is recognized controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(100, 50)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(200, 150)); GetEventGenerator().MoveTouch(gfx::Point(100, 250)); GetEventGenerator().MoveTouch(gfx::Point(0, 150)); GetEventGenerator().MoveTouch(gfx::Point(100, 50)); GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("0,50 200x200", controller_test_api_->selection().ToString()); } TEST_F(HighlighterControllerTest, HighlighterGesturesScaled) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); const gfx::Rect original_rect(200, 100, 400, 300); // Allow for rounding errors. gfx::Rect inflated(original_rect); inflated.Inset(-1, -1); constexpr float display_scales[] = {1.f, 1.5f, 2.0f}; constexpr float ui_scales[] = {0.5f, 0.67f, 1.0f, 1.25f, 1.33f, 1.5f, 1.67f, 2.0f}; for (size_t i = 0; i < sizeof(display_scales) / sizeof(float); ++i) { const float display_scale = display_scales[i]; for (size_t j = 0; j < sizeof(ui_scales) / sizeof(float); ++j) { const float ui_scale = ui_scales[j]; std::string display_spec = base::StringPrintf("1500x1000*%.2f@%.2f", display_scale, ui_scale); SCOPED_TRACE(display_spec); UpdateDisplayAndWaitForCompositingEnded(display_spec); controller_test_api_->ResetSelection(); TraceRect(original_rect); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); const gfx::Rect selection = controller_test_api_->selection(); EXPECT_TRUE(inflated.Contains(selection)); EXPECT_TRUE(selection.Contains(original_rect)); } } } // Test that stylus gesture recognition correctly handles display rotation TEST_F(HighlighterControllerTest, HighlighterGesturesRotated) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); const gfx::Rect trace(200, 100, 400, 300); // No rotation UpdateDisplayAndWaitForCompositingEnded("1500x1000"); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("200,100 400x300", controller_test_api_->selection().ToString()); // Rotate to 90 degrees UpdateDisplayAndWaitForCompositingEnded("1500x1000/r"); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("100,900 300x400", controller_test_api_->selection().ToString()); // Rotate to 180 degrees UpdateDisplayAndWaitForCompositingEnded("1500x1000/u"); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("900,600 400x300", controller_test_api_->selection().ToString()); // Rotate to 270 degrees UpdateDisplayAndWaitForCompositingEnded("1500x1000/l"); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("600,200 300x400", controller_test_api_->selection().ToString()); } // Test that a stroke interrupted close to the screen edge is treated as // contiguous. TEST_F(HighlighterControllerTest, InterruptedStroke) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); UpdateDisplayAndWaitForCompositingEnded("1500x1000"); // An interrupted stroke close to the screen edge should be recognized as a // contiguous stroke. controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(300, 100)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(0, 100)); GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->IsWaitingToResumeStroke()); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); EXPECT_FALSE(controller_test_api_->IsFadingAway()); GetEventGenerator().MoveTouch(gfx::Point(0, 200)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(300, 200)); GetEventGenerator().ReleaseTouch(); EXPECT_FALSE(controller_test_api_->IsWaitingToResumeStroke()); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("0,100 300x100", controller_test_api_->selection().ToString()); // Repeat the same gesture, but simulate a timeout after the gap. This should // force the gesture completion. controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(300, 100)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(0, 100)); GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->IsWaitingToResumeStroke()); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); EXPECT_FALSE(controller_test_api_->IsFadingAway()); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_FALSE(controller_test_api_->IsWaitingToResumeStroke()); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(controller_test_api_->IsFadingAway()); } // Test that the selection is never crossing the screen bounds. TEST_F(HighlighterControllerTest, SelectionInsideScreen) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); constexpr float display_scales[] = {1.f, 1.5f, 2.0f}; for (size_t i = 0; i < sizeof(display_scales) / sizeof(float); ++i) { std::string display_spec = base::StringPrintf("1000x1000*%.2f", display_scales[i]); SCOPED_TRACE(display_spec); UpdateDisplayAndWaitForCompositingEnded(display_spec); const gfx::Rect screen(0, 0, 1000, 1000); // Rectangle completely offscreen. controller_test_api_->ResetSelection(); TraceRect(gfx::Rect(-100, -100, 10, 10)); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); // Rectangle crossing the left edge. controller_test_api_->ResetSelection(); TraceRect(gfx::Rect(-100, 100, 200, 200)); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); // Rectangle crossing the top edge. controller_test_api_->ResetSelection(); TraceRect(gfx::Rect(100, -100, 200, 200)); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); // Rectangle crossing the right edge. controller_test_api_->ResetSelection(); TraceRect(gfx::Rect(900, 100, 200, 200)); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); // Rectangle crossing the bottom edge. controller_test_api_->ResetSelection(); TraceRect(gfx::Rect(100, 900, 200, 200)); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); // Horizontal stroke completely offscreen. controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(0, -100)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(1000, -100)); GetEventGenerator().ReleaseTouch(); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); // Horizontal stroke along the top edge of the screen. controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(0, 0)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(1000, 0)); GetEventGenerator().ReleaseTouch(); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); // Horizontal stroke along the bottom edge of the screen. controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(0, 999)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(1000, 999)); GetEventGenerator().ReleaseTouch(); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); } } // Test that a detached client does not receive notifications. TEST_F(HighlighterControllerTest, DetachedClient) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); UpdateDisplayAndWaitForCompositingEnded("1500x1000"); const gfx::Rect trace(200, 100, 400, 300); // Detach the client, no notifications should reach it. controller_test_api_->DetachClient(); controller_test_api_->ResetEnabledState(); controller_test_api_->SetEnabled(false); EXPECT_FALSE(controller_test_api_->HandleEnabledStateChangedCalled()); controller_test_api_->SetEnabled(true); EXPECT_FALSE(controller_test_api_->HandleEnabledStateChangedCalled()); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); // Attach the client again, notifications should be delivered normally. controller_test_api_->AttachClient(); controller_test_api_->ResetEnabledState(); controller_test_api_->SetEnabled(false); EXPECT_TRUE(controller_test_api_->HandleEnabledStateChangedCalled()); controller_test_api_->SetEnabled(true); EXPECT_TRUE(controller_test_api_->HandleEnabledStateChangedCalled()); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); } // Test enabling/disabling metalayer mode by selecting/deselecting on palette // tool and calling UpdateEnabledState notify observers properly. TEST_F(HighlighterControllerTest, UpdateEnabledState) { HighlighterController* controller = Shell::Get()->highlighter_controller(); TestHighlighterObserver observer; controller->AddObserver(&observer); ASSERT_EQ(0, observer.enabled_count_); ASSERT_EQ(0, observer.disabled_by_user_count_); ASSERT_EQ(0, observer.disabled_by_session_end_); tool_->OnEnable(); EXPECT_EQ(1, observer.enabled_count_); EXPECT_EQ(0, observer.disabled_by_user_count_); EXPECT_EQ(0, observer.disabled_by_session_end_); tool_->OnDisable(); EXPECT_EQ(1, observer.enabled_count_); EXPECT_EQ(1, observer.disabled_by_user_count_); EXPECT_EQ(0, observer.disabled_by_session_end_); tool_->OnEnable(); EXPECT_EQ(2, observer.enabled_count_); EXPECT_EQ(1, observer.disabled_by_user_count_); EXPECT_EQ(0, observer.disabled_by_session_end_); controller->UpdateEnabledState( HighlighterEnabledState::kDisabledBySessionEnd); EXPECT_EQ(2, observer.enabled_count_); EXPECT_EQ(1, observer.disabled_by_user_count_); EXPECT_EQ(1, observer.disabled_by_session_end_); controller->RemoveObserver(&observer); } } // namespace ash
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
0b322c53506beece77d4b7abecc3bb4b45ddc8be
f0c7faa78175bc3853f0c0a3cab6b8449ae0283d
/src/SpiralMatrixII.cpp
244261269034dc03b2e742d3fce69b56619e7fca
[]
no_license
lxstorm/LeetCode
7b4f76a7aad1931bdab729ec994bf3f21e6ccb37
02c8ed83651bc80ba5bd2e992947cb1bf4e3ef70
refs/heads/master
2020-04-06T08:03:08.355152
2016-11-16T09:55:05
2016-11-16T09:55:05
52,674,353
0
0
null
null
null
null
UTF-8
C++
false
false
780
cpp
class Solution { public: vector<vector<int>> generateMatrix(int n) { // we can use vector<vector<int>> result(n, vector<int>(n)); vector<int> tmp(n, 0); vector<vector<int>> result(n, tmp); vector<int> pos{0, -1}; vector<vector<int>> direction{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; vector<int> count{n, n - 1}; int step = 0; int num = 1; while(count[0] >= 0 && count[1] >= 0){ for(int i = 0;i < count[step % 2];++i){ pos[0] += direction[step % 4][0]; pos[1] += direction[step % 4][1]; result[pos[0]][pos[1]] = num; num++; } count[step % 2]--; step++; } return result; } };
[ "lxstormy@gmail.com" ]
lxstormy@gmail.com
5131d9e514f573a78e56346e8783217d69471721
b709bee6ad4d10b99d6ea442050b1d9b264786dc
/AOJ/alds1_12_b_single_source_shortest_path_II.cpp
b27370376a2b000d353b01ca2a333eab69dcbd54
[ "Apache-2.0" ]
permissive
konnase/algorithm
87addb227221ff36bbc6561d5fb3e085925c025a
628ebc03e211da76165349bb03758e991ee8fe18
refs/heads/master
2020-04-04T08:57:35.279553
2019-09-04T13:37:37
2019-09-04T13:37:37
155,801,089
0
0
null
2019-03-17T08:29:38
2018-11-02T02:05:48
C++
UTF-8
C++
false
false
2,818
cpp
// // Created by 李青坪 on 2018/11/8. // /* * 定义结构体Node表示结点编号和某结点到该结点的权重 * 由于优先级队列默认优先取最大值,所以要自定义Compare类,priority_queue<Node, vector<Node>, cmp> V_S; * 需要visited数组来记录结点是否被访问过 */ #include <cstdio> #include <algorithm> #include <queue> #include <vector> #define INFINITY 1<<21 #define NIL -1 #define MAXN 10000 using namespace std; struct Node{ int id; int weight; }; struct cmp{ bool operator ()(Node &a, Node &b){ return a.weight > b.weight; } }; bool comp(Node a, Node b){ return a.weight > b.weight; } vector<Node> graph[MAXN]; priority_queue<Node, vector<Node>, cmp> V_S; int n; int d[MAXN]; bool visited[MAXN]; void init(){ fill(d, d+MAXN, INFINITY); d[0] = 0; fill(visited, visited+MAXN, false); Node node; node.id = 0; node.weight = 0; V_S.push(node); } void updateMinWeight(Node u){ vector<Node>::iterator it; for (it = graph[u.id].begin(); it != graph[u.id].end(); ++it){ //遍历与u相连的所有结点,看有没有结点到S的距离减小了 if (visited[(*it).id]) continue; //与u相连的结点如果已经在S中了,就跳过 if (d[(*it).id] > d[u.id] + (*it).weight){ d[(*it).id] = d[u.id] + (*it).weight; Node node; node.id = (*it).id; node.weight = d[(*it).id]; V_S.push(node); } } } void dijkstra(){ while (!V_S.empty()){ Node u = V_S.top(); V_S.pop(); visited[u.id] = true; updateMinWeight(u); } } int main(){ scanf("%d", &n); int u, k; for (int i = 0; i < n; ++i) { scanf("%d %d", &u, &k); int v, w; Node node; for (int j = 0; j < k; ++j) { scanf("%d %d", &v, &w); node.id = v; node.weight = w; graph[u].push_back(node); } } init(); dijkstra(); for (int l = 0; l < n; ++l) { printf("%d %d\n", l, d[l]); } // Node node1, node2; // node1.id = 0; node1.weight = 5; // node2.id = 1; node2.weight = 3; // cmp cmp1; // printf("%d", cmp1.operator()(node1, node2)); // 测试升序优先级队列 // Node l[6]; // l[0].id = 0; l[0].weight = 3; // l[1].id = 1; l[1].weight = 2; // l[2].id = 2; l[2].weight = 5; // l[3].id = 3; l[3].weight = 3; // l[4].id = 4; l[4].weight = 4; // l[5].id = 5; l[5].weight = 2; // for (int i = 0; i < 6; ++i) { // V_S.push(l[i]); // } // for (int j = 0; j < 6; ++j) { // printf("id: %d weight: %d\n", V_S.top().id, V_S.top().weight); // V_S.pop(); // } } /* 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 */
[ "lqp19940918@163.com" ]
lqp19940918@163.com
44657c79cf47a5588b76620a680800d75a215196
7b99b71a2fe674c16ebdd8bf74f1782076bb10b0
/Init.h
9f36a5eaa837bc6fad663950238de274249f3296
[]
no_license
AplDGrape/GDGRAPX_Final_v1
485e482b1b02bf1f0009142cefa000ec207650f7
230281154be471207b4b85c1f82f7618a6e361b7
refs/heads/main
2023-07-30T01:51:49.974728
2021-09-17T12:23:20
2021-09-17T12:23:20
407,530,277
0
0
null
null
null
null
UTF-8
C++
false
false
981
h
#pragma once #include <stdio.h> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> GLFWwindow* Window; int width, height; GLFWwindow* initialize() { //initialize glfw if (glfwInit() != GLFW_TRUE) { fprintf(stderr, "Failed to initialized! \n"); return NULL; } width = 1366; height = 768; // set opengl version to 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // create window GLFWwindow* window; window = glfwCreateWindow(width, height, "Apolinar & Santonia", NULL, NULL); if (window == NULL) { fprintf(stderr, "Failed to load window! \n"); return NULL; } glfwMakeContextCurrent(window); //initialize glew glewExperimental = true; if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return NULL; } return Window; } int getWidth() { return width; } int getHeight() { return height; }
[ "raphaelapolinar16@yahoo.com" ]
raphaelapolinar16@yahoo.com
c5cb4baa3ed9e237fa15c99ded9c22e39f42b194
7acc93d31b1fad7f0f71625116a7d372ca37c80c
/thirdparty/vilib/visual_lib/test/src/test_base.cpp
e3108fe1300bc0645810f10a349daa7b16aecc68
[ "MIT", "BSD-3-Clause" ]
permissive
KMS-TEAM/vi_slam
bcb4b4b7393e395d8861e1c4aae24622f0b0d7b0
4cb5ae94bfecef5758f809d84e135e574b4fb860
refs/heads/main
2023-06-14T18:21:14.431529
2021-07-12T17:08:56
2021-07-12T17:08:56
384,636,583
1
1
null
null
null
null
UTF-8
C++
false
false
10,199
cpp
/* * Base class for testing various functionalities * test_base.cpp * * Copyright (c) 2019-2020 Balazs Nagy, * Robotics and Perception Group, University of Zurich * 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. */ #include <iostream> #include <fstream> #include <sys/types.h> #include <sys/stat.h> #include <opencv2/highgui.hpp> #include "test/test_base.h" #include "test/common.h" #include "test/arguments.h" #include "vilib/benchmark.h" #include "vilib/feature_detection/detector_benchmark.h" using namespace vilib; TestBase::TestBase(const char * name, const char * file_path, const int max_image_num): name_(name), file_path_(file_path), max_image_num_(max_image_num), success_(true), evaluated_(false) { // std::cout << file_path << std::endl; is_list_ = is_list_file(file_path); } TestBase::~TestBase(void) { } bool TestBase::evaluate(void) { std::cout << "### " << name_ << std::endl; success_ = this->run(); // std::cerr << "error" << std::endl; std::cout << " Success: " << (success_?TEXT_OK:TEXT_FAIL) << std::endl; evaluated_ = true; return success_; } void TestBase::load_image(int load_flags, bool display_image, bool display_info) { this->load_image_to(file_path_,load_flags,image_); if(display_image) { this->display_image(image_,"Original image"); } image_width_ = image_.cols; image_height_ = image_.rows; image_channels_ = image_.channels(); image_size_ = image_width_ * image_height_ * image_channels_; if(display_info) { std::cout << "Image width: " << image_width_ << " px" << std::endl; std::cout << "Image height: " << image_height_ << " px" << std::endl; std::cout << "Image channels: " << image_channels_ << std::endl; std::cout << "Image size: " << image_size_ << " bytes" << std::endl; } } bool TestBase::load_image_dimensions(const std::size_t & width_default, const std::size_t & height_default) { if(!verify_path(file_path_)) { std::cout << " The specified file does not exist (" << file_path_ << ")" << std::endl; return false; } if(is_list_) { // this is a list file, read out the resolution from the first 2 lines std::ifstream list_file(file_path_); std::string list_line; for(int i=0;i<2;++i) { if(!std::getline(list_file,list_line)) { // error reading the line image_width_ = 0; image_height_ = 0; } if(i==0) { image_width_ = std::stoi(list_line); } else if(i==1) { image_height_ = std::stoi(list_line); } } } else if(file_path_ != NULL) { // this is a regular image cv::Mat temp_img; load_image_to(file_path_,cv::IMREAD_GRAYSCALE,temp_img); image_width_ = temp_img.cols; image_height_ = temp_img.rows; } else { assert(width_default > 0); assert(height_default > 0); // use the default arguments image_width_ = width_default; image_height_ = height_default; } return true; } void TestBase::load_image_to(const char * image_path, int load_flags, cv::Mat & dst_image) { // modify image path if it is not an absolute path std::string image_path_abs; if(image_path[0] != '/') { // relative path was given image_path_abs = get_executable_folder_path(); image_path_abs += '/'; image_path_abs += image_path; } else { // absolute path was given image_path_abs = image_path; } dst_image = cv::imread(image_path_abs.c_str(),load_flags); } void TestBase::save_image(const cv::Mat & image, const char * image_path) const { cv::imwrite(image_path,image); } void TestBase::display_image(const cv::Mat & image, const char * image_title) const { cv::imshow(image_title, image); cv::waitKey(); } bool TestBase::compare_images(const cv::Mat & image1, const cv::Mat & image2, unsigned int diff_threshold, bool display_difference, bool display_difference_image, int skip_first_n_rows, int skip_first_n_cols, int skip_last_n_rows, int skip_last_n_cols) const { std::size_t difference_count = 0; cv::Mat difference_image; if(display_difference_image) { difference_image = cv::Mat(image1.rows,image1.cols,CV_8UC1); } bool success = true; do { if (image1.empty() && image2.empty()) { break; } if (image1.cols != image2.cols || image1.rows != image2.rows) { success = false; break; } for(int r=skip_first_n_rows;r<(image1.rows-skip_last_n_rows);++r) { for(int c=skip_first_n_cols;c<(image1.cols-skip_last_n_cols);++c) { unsigned int diff = std::abs(((int)image1.at<unsigned char>(r,c)) - ((int)image2.at<unsigned char>(r,c))); if(diff > diff_threshold) { success = false; if(display_difference) { std::cout << diff << std::endl; } if(display_difference_image) { difference_image.at<unsigned char>(r,c) = 0xFF; } ++difference_count; } } } } while(0); if(!success) { if(display_difference_image) { display_image(difference_image,"Difference image"); } std::cout << " Difference count: " << difference_count << std::endl; } return success; } bool TestBase::compare_image_pyramid(const std::vector<cv::Mat> & image_pyramid1, const std::vector<cv::Mat> & image_pyramid2, unsigned int diff_threshold) const { if(image_pyramid1.size() != image_pyramid2.size()) { std::cout << " Number of pyramid levels differs (image_pyramid1=" << image_pyramid1.size() << ",image_pyramid2=" << image_pyramid2.size() << ")" << std::endl; return false; } for(unsigned int l=0;l<image_pyramid1.size();++l) { if(!this->compare_images(image_pyramid1[l], image_pyramid2[l], diff_threshold)) { std::cout << " Difference on level " << l << std::endl; return false; } } return true; } bool TestBase::run_benchmark(std::vector<Statistics> &, std::vector<Statistics> &) { // Descendant test suites should add proper implementation return true; } bool TestBase::is_list_file(const char * file_path) { const char * list_extensions[] = {".txt"}; const std::size_t list_extension_n = sizeof(list_extensions)/sizeof(char*); // find the extension const char * file_extension = NULL; { const char * cur_file_path = file_path; while(cur_file_path != NULL) { file_extension = cur_file_path; cur_file_path = strchr(cur_file_path+1,'.'); } } if(file_extension == NULL) { return false; } for(std::size_t i=0;i<list_extension_n;++i) { if(!strcmp(list_extensions[i],file_extension)) { return true; } } return false; } bool TestBase::verify_path(const char * path) { struct stat info; return (stat(path,&info) == 0); } bool TestBase::run_benchmark_suite(std::vector<Statistics> & stat_cpu, std::vector<Statistics> & stat_gpu) { bool result = true; #if BENCHMARK_ENABLE DetectorBenchmark::init(); #endif /* BENCHMARK_ENABLE */ if(is_list_) { // Evaluate the entire list instead of 1 image // file_path_ holds the path to the list std::ifstream list_file(file_path_); std::string list_line; unsigned int line_count = 0, image_count = 0; while(std::getline(list_file,list_line) && image_count < (unsigned int)max_image_num_) { // skip first 2 lines because they encode the image resolution ++line_count; if(line_count <= 2) { continue; } // load image ++image_count; load_image_to(list_line.c_str(),cv::IMREAD_GRAYSCALE,image_); // run benchmark result = run_benchmark(stat_cpu,stat_gpu) && result; } } else { // Load image 1x this->load_image(cv::IMREAD_GRAYSCALE,false,false); result = result && run_benchmark(stat_cpu,stat_gpu); } // Display all statistics if(stat_cpu.size()) { std::cout << " CPU ---" << std::endl; for(Statistics & stat : stat_cpu) { stat.display(); } } if(stat_gpu.size()) { std::cout << " GPU ---" << std::endl; for(Statistics & stat : stat_gpu) { stat.display(); } } // Display all benchmarks #if BENCHMARK_ENABLE DetectorBenchmark::displayAll(); #endif /* BENCHMARK_ENABLE */ return result; }
[ "00sao00ios00@gmail.com" ]
00sao00ios00@gmail.com
2b439b32ad6b1acf9e86353a8fb43743f5725733
7fe4d5465da2b1d1169495849d946df2ba39aad7
/PointLigth.cpp
c67b9daea09844baa3ff9d57c558ed85b0722845
[]
no_license
QianMang/OpenGL-learning
be54a7ed9b5d902bec4122778f94a694b102019a
ace7c72fbcef7aae13f73cf9560667ffc6c45921
refs/heads/master
2020-04-05T18:51:29.265154
2018-11-11T19:51:18
2018-11-11T19:51:18
157,115,020
0
0
null
null
null
null
UTF-8
C++
false
false
1,162
cpp
#include "PointLight.h" PointLight::PointLight():Light() { position = glm::vec3(0.0f, 0.0f, 0.0f); constant = 1.0f; linear = 0.0f; exponent = 0.0f; } PointLight::PointLight(GLfloat red, GLfloat green, GLfloat blue, GLfloat aIntensity, GLfloat dIntensity, GLfloat xPos, GLfloat yPos, GLfloat zPos, GLfloat con, GLfloat lin, GLfloat exp):Light(red,green,blue,aIntensity,dIntensity) { position = glm::vec3(xPos, yPos, zPos); constant = con; linear = lin; exponent = exp; } void PointLight::UseLight(GLuint ambientIntensityLocaiton, GLuint ambientColourLocation, GLuint diffuseIntensityLocation, GLuint positionLocation, GLuint constantLocation, GLuint linearLocation, GLuint exponentLocation) { glUniform3f(ambientColourLocation, colour.x, colour.y, colour.z); glUniform1f(ambientIntensityLocaiton, ambientIntensity); glUniform1f(diffuseIntensityLocation, diffuseIntensity); glUniform3f(positionLocation, position.x, position.y, position.z); glUniform1f(constantLocation, constant); glUniform1f(linearLocation, linear); glUniform1f(exponentLocation, exponent); } PointLight::~PointLight() { }
[ "noreply@github.com" ]
QianMang.noreply@github.com
bf6b0d51ae6dbd61c103eef05b8194c5ae05a5ac
ca32936825c3cbae13e4db108ad97d670e0a9264
/src/adapter.cc
ddcab60ffb5ccc1f0b2fc7996019a037e0a72975
[]
no_license
zqqiang/node-cad
7b783fb758dcacb5b1e1b8276c73dfe0942adfbb
739ff348b4d2c77b275c3a0fe87682c14ffd8181
refs/heads/master
2021-01-14T08:03:53.991041
2016-12-23T19:07:33
2016-12-23T19:07:33
46,592,925
5
0
null
null
null
null
UTF-8
C++
false
false
339
cc
#include <iostream> #include "adapter.h" #include "core.h" using namespace std; Adapter::Adapter() { } Adapter::~Adapter() { } void Adapter::Execute(int edge, int faceA, int faceB) { cout << " Adapter::Execute edge => " << edge << " faceA => " << faceA << " faceB => " << faceB << endl; Core *core = new Core(); core->Compute(); }
[ "qiangzhaoqing@gmail.com" ]
qiangzhaoqing@gmail.com
a2e35a62b0bcc374e5e3bb8f22889e8830ab51df
7b177b9c7e66d3812a8605f593349038350c1a42
/c++/16.3_recursiveSubstrings.cpp
04d989d2bba322a0181c244a14ccd07a70d4826c
[]
no_license
enola3011/HacktoberFest2k21
bac1cff6c62fa2ac5d10f3fad643d5dd4c57ca00
bea0f643b878772acb9c7e72168b0a9081e05070
refs/heads/main
2023-09-01T06:18:17.031940
2021-10-25T18:10:08
2021-10-25T18:10:08
421,132,416
1
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
#include <bits/stdc++.h> using namespace std; void subString(string s, string ans) { if (s.length() == 0) { cout << ans << endl; return; } char ch = s[0]; string ros = s.substr(1); subString(ros, ans); subString(ros, ans + ch); } int main() { subString("ABC", " "); cout << endl; return 0; }
[ "vandanadewangan1999@gmail.com" ]
vandanadewangan1999@gmail.com
d7b136f76d1e00af355ac8776cbc6c9d245ec792
2543612ab825ee3e0b11cfc31c149492488a7ba2
/squirrel/squirrel/sqobject.h
31d26a02a86c9bcd3434944d14ffe3c3959aa73f
[ "MIT" ]
permissive
albertodemichelis/visualsquirrel
6e29941228d9f238aa2f3224e60023aafc49861f
357a2a826ee45325615cc2da72bc8e795a4b2653
refs/heads/master
2020-04-05T20:55:22.687865
2018-11-12T10:28:04
2018-11-12T10:28:04
157,200,205
3
0
MIT
2018-11-12T11:01:58
2018-11-12T11:01:57
null
UTF-8
C++
false
false
9,847
h
/* see copyright notice in squirrel.h */ #ifndef _SQOBJECT_H_ #define _SQOBJECT_H_ #include "squtils.h" #ifdef _SQ64 #define UINT_MINUS_ONE (0xFFFFFFFFFFFFFFFF) #else #define UINT_MINUS_ONE (0xFFFFFFFF) #endif #define SQ_CLOSURESTREAM_HEAD (('S'<<24)|('Q'<<16)|('I'<<8)|('R')) #define SQ_CLOSURESTREAM_PART (('P'<<24)|('A'<<16)|('R'<<8)|('T')) #define SQ_CLOSURESTREAM_TAIL (('T'<<24)|('A'<<16)|('I'<<8)|('L')) struct SQSharedState; enum SQMetaMethod{ MT_ADD=0, MT_SUB=1, MT_MUL=2, MT_DIV=3, MT_UNM=4, MT_MODULO=5, MT_SET=6, MT_GET=7, MT_TYPEOF=8, MT_NEXTI=9, MT_CMP=10, MT_CALL=11, MT_CLONED=12, MT_NEWSLOT=13, MT_DELSLOT=14, MT_TOSTRING=15, MT_NEWMEMBER=16, MT_INHERITED=17, MT_LAST = 18 }; #define MM_ADD _SC("_add") #define MM_SUB _SC("_sub") #define MM_MUL _SC("_mul") #define MM_DIV _SC("_div") #define MM_UNM _SC("_unm") #define MM_MODULO _SC("_modulo") #define MM_SET _SC("_set") #define MM_GET _SC("_get") #define MM_TYPEOF _SC("_typeof") #define MM_NEXTI _SC("_nexti") #define MM_CMP _SC("_cmp") #define MM_CALL _SC("_call") #define MM_CLONED _SC("_cloned") #define MM_NEWSLOT _SC("_newslot") #define MM_DELSLOT _SC("_delslot") #define MM_TOSTRING _SC("_tostring") #define MM_NEWMEMBER _SC("_newmember") #define MM_INHERITED _SC("_inherited") #define _CONSTRUCT_VECTOR(type,size,ptr) { \ for(SQInteger n = 0; n < ((SQInteger)size); n++) { \ new (&ptr[n]) type(); \ } \ } #define _DESTRUCT_VECTOR(type,size,ptr) { \ for(SQInteger nl = 0; nl < ((SQInteger)size); nl++) { \ ptr[nl].~type(); \ } \ } #define _COPY_VECTOR(dest,src,size) { \ for(SQInteger _n_ = 0; _n_ < ((SQInteger)size); _n_++) { \ dest[_n_] = src[_n_]; \ } \ } #define _NULL_SQOBJECT_VECTOR(vec,size) { \ for(SQInteger _n_ = 0; _n_ < ((SQInteger)size); _n_++) { \ vec[_n_].Null(); \ } \ } #define MINPOWER2 4 struct SQRefCounted { SQUnsignedInteger _uiRef; struct SQWeakRef *_weakref; SQRefCounted() { _uiRef = 0; _weakref = NULL; } virtual ~SQRefCounted(); SQWeakRef *GetWeakRef(SQObjectType type); virtual void Release()=0; }; struct SQWeakRef : SQRefCounted { void Release(); SQObject _obj; }; #define _realval(o) (type((o)) != OT_WEAKREF?(SQObject)o:_weakref(o)->_obj) struct SQObjectPtr; #define __AddRef(type,unval) if(ISREFCOUNTED(type)) \ { \ unval.pRefCounted->_uiRef++; \ } #define __Release(type,unval) if(ISREFCOUNTED(type) && ((--unval.pRefCounted->_uiRef)==0)) \ { \ unval.pRefCounted->Release(); \ } #define __ObjRelease(obj) { \ if((obj)) { \ (obj)->_uiRef--; \ if((obj)->_uiRef == 0) \ (obj)->Release(); \ (obj) = NULL; \ } \ } #define __ObjAddRef(obj) { \ (obj)->_uiRef++; \ } #define type(obj) ((obj)._type) #define is_delegable(t) (type(t)&SQOBJECT_DELEGABLE) #define raw_type(obj) _RAW_TYPE((obj)._type) #define _integer(obj) ((obj)._unVal.nInteger) #define _float(obj) ((obj)._unVal.fFloat) #define _string(obj) ((obj)._unVal.pString) #define _table(obj) ((obj)._unVal.pTable) #define _array(obj) ((obj)._unVal.pArray) #define _closure(obj) ((obj)._unVal.pClosure) #define _generator(obj) ((obj)._unVal.pGenerator) #define _nativeclosure(obj) ((obj)._unVal.pNativeClosure) #define _userdata(obj) ((obj)._unVal.pUserData) #define _userpointer(obj) ((obj)._unVal.pUserPointer) #define _thread(obj) ((obj)._unVal.pThread) #define _funcproto(obj) ((obj)._unVal.pFunctionProto) #define _class(obj) ((obj)._unVal.pClass) #define _instance(obj) ((obj)._unVal.pInstance) #define _delegable(obj) ((SQDelegable *)(obj)._unVal.pDelegable) #define _weakref(obj) ((obj)._unVal.pWeakRef) #define _outer(obj) ((obj)._unVal.pOuter) #define _refcounted(obj) ((obj)._unVal.pRefCounted) #define _rawval(obj) ((obj)._unVal.raw) #define _stringval(obj) (obj)._unVal.pString->_val #define _userdataval(obj) ((SQUserPointer)sq_aligning((obj)._unVal.pUserData + 1)) #define tofloat(num) ((type(num)==OT_INTEGER)?(SQFloat)_integer(num):_float(num)) #define tointeger(num) ((type(num)==OT_FLOAT)?(SQInteger)_float(num):_integer(num)) ///////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////// #if defined(SQUSEDOUBLE) && !defined(_SQ64) || !defined(SQUSEDOUBLE) && defined(_SQ64) #define SQ_REFOBJECT_INIT() SQ_OBJECT_RAWINIT() #else #define SQ_REFOBJECT_INIT() #endif #define _REF_TYPE_DECL(type,_class,sym) \ SQObjectPtr(_class * x) \ { \ SQ_OBJECT_RAWINIT() \ _type=type; \ _unVal.sym = x; \ assert(_unVal.pTable); \ _unVal.pRefCounted->_uiRef++; \ } \ inline SQObjectPtr& operator=(_class *x) \ { \ SQObjectType tOldType; \ SQObjectValue unOldVal; \ tOldType=_type; \ unOldVal=_unVal; \ _type = type; \ SQ_REFOBJECT_INIT() \ _unVal.sym = x; \ _unVal.pRefCounted->_uiRef++; \ __Release(tOldType,unOldVal); \ return *this; \ } #define _SCALAR_TYPE_DECL(type,_class,sym) \ SQObjectPtr(_class x) \ { \ SQ_OBJECT_RAWINIT() \ _type=type; \ _unVal.sym = x; \ } \ inline SQObjectPtr& operator=(_class x) \ { \ __Release(_type,_unVal); \ _type = type; \ SQ_OBJECT_RAWINIT() \ _unVal.sym = x; \ return *this; \ } struct SQObjectPtr : public SQObject { SQObjectPtr() { SQ_OBJECT_RAWINIT() _type=OT_NULL; _unVal.pUserPointer=NULL; } SQObjectPtr(const SQObjectPtr &o) { _type = o._type; _unVal = o._unVal; __AddRef(_type,_unVal); } SQObjectPtr(const SQObject &o) { _type = o._type; _unVal = o._unVal; __AddRef(_type,_unVal); } _REF_TYPE_DECL(OT_TABLE,SQTable,pTable) _REF_TYPE_DECL(OT_CLASS,SQClass,pClass) _REF_TYPE_DECL(OT_INSTANCE,SQInstance,pInstance) _REF_TYPE_DECL(OT_ARRAY,SQArray,pArray) _REF_TYPE_DECL(OT_CLOSURE,SQClosure,pClosure) _REF_TYPE_DECL(OT_NATIVECLOSURE,SQNativeClosure,pNativeClosure) _REF_TYPE_DECL(OT_OUTER,SQOuter,pOuter) _REF_TYPE_DECL(OT_GENERATOR,SQGenerator,pGenerator) _REF_TYPE_DECL(OT_STRING,SQString,pString) _REF_TYPE_DECL(OT_USERDATA,SQUserData,pUserData) _REF_TYPE_DECL(OT_WEAKREF,SQWeakRef,pWeakRef) _REF_TYPE_DECL(OT_THREAD,SQVM,pThread) _REF_TYPE_DECL(OT_FUNCPROTO,SQFunctionProto,pFunctionProto) _SCALAR_TYPE_DECL(OT_INTEGER,SQInteger,nInteger) _SCALAR_TYPE_DECL(OT_FLOAT,SQFloat,fFloat) _SCALAR_TYPE_DECL(OT_USERPOINTER,SQUserPointer,pUserPointer) SQObjectPtr(bool bBool) { SQ_OBJECT_RAWINIT() _type = OT_BOOL; _unVal.nInteger = bBool?1:0; } inline SQObjectPtr& operator=(bool b) { __Release(_type,_unVal); SQ_OBJECT_RAWINIT() _type = OT_BOOL; _unVal.nInteger = b?1:0; return *this; } ~SQObjectPtr() { __Release(_type,_unVal); } inline SQObjectPtr& operator=(const SQObjectPtr& obj) { SQObjectType tOldType; SQObjectValue unOldVal; tOldType=_type; unOldVal=_unVal; _unVal = obj._unVal; _type = obj._type; __AddRef(_type,_unVal); __Release(tOldType,unOldVal); return *this; } inline SQObjectPtr& operator=(const SQObject& obj) { SQObjectType tOldType; SQObjectValue unOldVal; tOldType=_type; unOldVal=_unVal; _unVal = obj._unVal; _type = obj._type; __AddRef(_type,_unVal); __Release(tOldType,unOldVal); return *this; } inline void Null() { SQObjectType tOldType = _type; SQObjectValue unOldVal = _unVal; _type = OT_NULL; _unVal.raw = (SQRawObjectVal)NULL; __Release(tOldType ,unOldVal); } private: SQObjectPtr(const SQChar *){} //safety }; inline void _Swap(SQObject &a,SQObject &b) { SQObjectType tOldType = a._type; SQObjectValue unOldVal = a._unVal; a._type = b._type; a._unVal = b._unVal; b._type = tOldType; b._unVal = unOldVal; } ///////////////////////////////////////////////////////////////////////////////////// #ifndef NO_GARBAGE_COLLECTOR #define MARK_FLAG 0x80000000 struct SQCollectable : public SQRefCounted { SQCollectable *_next; SQCollectable *_prev; SQSharedState *_sharedstate; virtual SQObjectType GetType()=0; virtual void Release()=0; virtual void Mark(SQCollectable **chain)=0; void UnMark(); virtual void Finalize()=0; static void AddToChain(SQCollectable **chain,SQCollectable *c); static void RemoveFromChain(SQCollectable **chain,SQCollectable *c); }; #define ADD_TO_CHAIN(chain,obj) AddToChain(chain,obj) #define REMOVE_FROM_CHAIN(chain,obj) {if(!(_uiRef&MARK_FLAG))RemoveFromChain(chain,obj);} #define CHAINABLE_OBJ SQCollectable #define INIT_CHAIN() {_next=NULL;_prev=NULL;_sharedstate=ss;} #else #define ADD_TO_CHAIN(chain,obj) ((void)0) #define REMOVE_FROM_CHAIN(chain,obj) ((void)0) #define CHAINABLE_OBJ SQRefCounted #define INIT_CHAIN() ((void)0) #endif struct SQDelegable : public CHAINABLE_OBJ { bool SetDelegate(SQTable *m); virtual bool GetMetaMethod(SQVM *v,SQMetaMethod mm,SQObjectPtr &res); SQTable *_delegate; }; SQUnsignedInteger TranslateIndex(const SQObjectPtr &idx); typedef sqvector<SQObjectPtr> SQObjectPtrVec; typedef sqvector<SQInteger> SQIntVec; const SQChar *GetTypeName(const SQObjectPtr &obj1); const SQChar *IdType2Name(SQObjectType type); #endif //_SQOBJECT_H_
[ "david@qnsoftware.com" ]
david@qnsoftware.com
94f45f1eb5462105aaa10f73dba9d7cc0b402e70
624511f6ad0cf17a2ba1a1ea1f25c3b139ce4295
/baselib/lib/Lsc/alloc/Lsc_alloc.h
0ec1e994c6b0e8f37641fa634956e04ac32051ea
[]
no_license
lightchainone/lightchain
7d90338d4a4e8d31d550c07bf380c06580941334
6fc7019c76a8b60d4fd63fba58fa79858856f66b
refs/heads/master
2021-05-11T05:47:17.672527
2019-12-16T09:51:39
2019-12-16T09:51:39
117,969,593
23
6
null
null
null
null
GB18030
C++
false
false
3,142
h
#ifndef BSL_ALLOC_H__ #define BSL_ALLOC_H__ #include <cstdio> #include <cstdlib> #include <new> #include <algorithm> namespace Lsc { /** * * This is precisely the allocator defined in the C++ Standard. * - all allocation calls malloc * - all deallocation calls free */ template < typename _Tp > class Lsc_alloc { plclic: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp *pointer; typedef const _Tp *const_pointer; typedef _Tp & reference; typedef const _Tp & const_reference; typedef _Tp value_type; typedef Lsc_alloc<_Tp> pool_type; template < typename _Tp1 > struct rebind { typedef Lsc_alloc < _Tp1 > other; }; static const bool recycle_space;// = false; //在alloc析构的时候,是否释放空间 static const bool thread_safe;// = true; //空间分配器是否线程安全 Lsc_alloc() { create(); } Lsc_alloc(const Lsc_alloc &) { create(); } template < typename _Tp1 > Lsc_alloc(const Lsc_alloc < _Tp1 > &) { create(); } ~Lsc_alloc() { destroy(); } pointer address(reference __x) const { return &__x; } const_pointer address(const_reference __x) const { return &__x; } //NB:__n is permitted to be 0. The C++ standard says nothing // about what the return value is when __n == 0. pointer allocate(size_type __n, const void * = 0) { pointer __ret = static_cast < _Tp * >(malloc(__n * sizeof(_Tp))); return __ret; } pointer reallocate(size_type __n, void * ptr = 0) { if (ptr == NULL) { return allocate(__n, ptr); } return static_cast < _Tp * >(realloc(ptr, __n * sizeof(_Tp))); } //__p is not permitted to be a null pointer. void deallocate(pointer __p, size_type) { free(static_cast < void *>(__p)); } size_type max_size() const { return size_t(-1) / sizeof(_Tp); } //_GLIBCXX_RESOLVE_LIB_DEFECTS //402. wrong new expression in[some_] allocator: : construct void construct(pointer __p, const _Tp & __val) { ::new(__p) value_type(__val); } void destroy(pointer __p) { __p->~ _Tp(); } int create() { return 0; } int destroy() { return 0; } void swap (Lsc_alloc<_Tp> &) { } int merge(Lsc_alloc<_Tp> &){ return 0; } value_type * getp(pointer __p) const { return __p; } }; template < typename _Tp > inline bool operator == (const Lsc_alloc < _Tp > &, const Lsc_alloc < _Tp > &) { return true; } template < typename _Tp, class _Alloc2 > inline bool operator == (const Lsc_alloc <_Tp > &, const _Alloc2 &) { return false; } template < typename _Tp > inline bool operator != (const Lsc_alloc < _Tp > &, const Lsc_alloc < _Tp > &) { return false; } template < typename _Tp, class _Alloc2 > inline bool operator != (const Lsc_alloc <_Tp > &, const _Alloc2 &) { return true; } template <typename _Tp> const bool Lsc_alloc<_Tp>::recycle_space = false; template <typename _Tp> const bool Lsc_alloc<_Tp>::thread_safe = true; } #endif // xalloc_h__
[ "lightchainone@hotmail.com" ]
lightchainone@hotmail.com
171b46953de5381bd23df20c0b07220ae393ea4e
9a4b3c039dbe14d357fc6051136214f07851dd4c
/user/MIT_Controller/FSM_States/ControlFSM.cpp
801d888b219d1c212e94daba81d7713e0b171a6c
[ "MIT" ]
permissive
YisongCai666/Cheetah-Software
34cd716a6dac9bd7eab1042d991a121db22a14b3
2b99a85c5307a182a8fb719a6a6f0690e38c0367
refs/heads/master
2020-09-04T08:17:18.683458
2019-10-25T17:07:18
2019-10-25T17:07:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,558
cpp
/*============================ Control FSM ============================*/ /** * The Finite State Machine that manages the robot's controls. Handles * calls to the FSM State functions and manages transitions between all * of the states. */ #include "ControlFSM.h" /** * Constructor for the Control FSM. Passes in all of the necessary * data and stores it in a struct. Initializes the FSM with a starting * state and operating mode. * * @param _quadruped the quadruped information * @param _stateEstimator contains the estimated states * @param _legController interface to the leg controllers * @param _gaitScheduler controls scheduled foot contact modes * @param _desiredStateCommand gets the desired COM state trajectories * @param controlParameters passes in the control parameters from the GUI */ template <typename T> ControlFSM<T>::ControlFSM(Quadruped<T>* _quadruped, StateEstimatorContainer<T>* _stateEstimator, LegController<T>* _legController, GaitScheduler<T>* _gaitScheduler, DesiredStateCommand<T>* _desiredStateCommand, RobotControlParameters* controlParameters, VisualizationData* visualizationData, MIT_UserParameters* userParameters) { // Add the pointers to the ControlFSMData struct data._quadruped = _quadruped; data._stateEstimator = _stateEstimator; data._legController = _legController; data._gaitScheduler = _gaitScheduler; data._desiredStateCommand = _desiredStateCommand; data.controlParameters = controlParameters; data.visualizationData = visualizationData; data.userParameters = userParameters; // Initialize and add all of the FSM States to the state list statesList.invalid = nullptr; statesList.passive = new FSM_State_Passive<T>(&data); statesList.jointPD = new FSM_State_JointPD<T>(&data); statesList.impedanceControl = new FSM_State_ImpedanceControl<T>(&data); statesList.standUp = new FSM_State_StandUp<T>(&data); statesList.balanceStand = new FSM_State_BalanceStand<T>(&data); statesList.locomotion = new FSM_State_Locomotion<T>(&data); safetyChecker = new SafetyChecker<T>(&data); // Initialize the FSM with the Passive FSM State initialize(); } /** * Initialize the Control FSM with the default settings. SHould be set to * Passive state and Normal operation mode. */ template <typename T> void ControlFSM<T>::initialize() { // Initialize a new FSM State with the control data currentState = statesList.passive; // Enter the new current state cleanly currentState->onEnter(); // Initialize to not be in transition nextState = currentState; // Initialize FSM mode to normal operation operatingMode = FSM_OperatingMode::NORMAL; } /** * Called each control loop iteration. Decides if the robot is safe to * run controls and checks the current state for any transitions. Runs * the regular state behavior if all is normal. */ template <typename T> void ControlFSM<T>::runFSM() { // Check the robot state for safe operation operatingMode = safetyPreCheck(); // Run the robot control code if operating mode is not unsafe if (operatingMode != FSM_OperatingMode::ESTOP) { // Run normal controls if no transition is detected if (operatingMode == FSM_OperatingMode::NORMAL) { // Check the current state for any transition nextStateName = currentState->checkTransition(); // Detect a commanded transition if (nextStateName != currentState->stateName) { // Set the FSM operating mode to transitioning operatingMode = FSM_OperatingMode::TRANSITIONING; // Get the next FSM State by name nextState = getNextState(nextStateName); // Print transition initialized info printInfo(1); } else { // Run the iteration for the current state normally currentState->run(); } } // Run the transition code while transition is occuring if (operatingMode == FSM_OperatingMode::TRANSITIONING) { transitionData = currentState->transition(); // Check the robot state for safe operation safetyPostCheck(); // Run the state transition if (transitionData.done) { // Exit the current state cleanly currentState->onExit(); // Print finalizing transition info printInfo(2); // Complete the transition currentState = nextState; // Enter the new current state cleanly currentState->onEnter(); // Return the FSM to normal operation mode operatingMode = FSM_OperatingMode::NORMAL; } } else { // Check the robot state for safe operation safetyPostCheck(); } } else { currentState = statesList.passive; currentState->onEnter(); nextStateName = currentState->stateName; } // Print the current state of the FSM printInfo(0); } /** * Checks the robot state for safe operation conditions. If it is in * an unsafe state, it will not run the normal control code until it * is safe to operate again. * * @return the appropriate operating mode */ template <typename T> FSM_OperatingMode ControlFSM<T>::safetyPreCheck() { // Check for safe orientation if the current state requires it if (currentState->checkSafeOrientation) { if (!safetyChecker->checkSafeOrientation()) { operatingMode = FSM_OperatingMode::ESTOP; std::cout << "broken" << std::endl; } } // Default is to return the current operating mode return operatingMode; } /** * Checks the robot state for safe operation commands after calculating the * control iteration. Prints out which command is unsafe. Each state has * the option to enable checks for commands that it cares about. * * Should this EDamp / EStop or just continue? * Should break each separate check into its own function for clarity * * @return the appropriate operating mode */ template <typename T> FSM_OperatingMode ControlFSM<T>::safetyPostCheck() { // Check for safe desired foot positions if (currentState->checkPDesFoot) { safetyChecker->checkPDesFoot(); } // Check for safe desired feedforward forces if (currentState->checkForceFeedForward) { safetyChecker->checkForceFeedForward(); } // Default is to return the current operating mode return operatingMode; } /** * Returns the approptiate next FSM State when commanded. * * @param next commanded enumerated state name * @return next FSM state */ template <typename T> FSM_State<T>* ControlFSM<T>::getNextState(FSM_StateName stateName) { // Choose the correct FSM State by enumerated state name switch (stateName) { case FSM_StateName::INVALID: return statesList.invalid; case FSM_StateName::PASSIVE: return statesList.passive; case FSM_StateName::JOINT_PD: return statesList.jointPD; case FSM_StateName::IMPEDANCE_CONTROL: return statesList.impedanceControl; case FSM_StateName::STAND_UP: return statesList.standUp; case FSM_StateName::BALANCE_STAND: return statesList.balanceStand; case FSM_StateName::LOCOMOTION: return statesList.locomotion; default: return statesList.invalid; } } /** * Prints Control FSM info at regular intervals and on important events * such as transition initializations and finalizations. Separate function * to not clutter the actual code. * * @param printing mode option for regular or an event */ template <typename T> void ControlFSM<T>::printInfo(int opt) { switch (opt) { case 0: // Normal printing case at regular intervals // Increment printing iteration printIter++; // Print at commanded frequency if (printIter == printNum) { std::cout << "[CONTROL FSM] Printing FSM Info...\n"; std::cout << "---------------------------------------------------------\n"; if (operatingMode == FSM_OperatingMode::NORMAL) { std::cout << "Operating Mode: NORMAL in " << currentState->stateString << "\n"; } else if (operatingMode == FSM_OperatingMode::TRANSITIONING) { std::cout << "Operating Mode: TRANSITIONING from " << currentState->stateString << " to " << nextState->stateString << "\n"; } else if (operatingMode == FSM_OperatingMode::ESTOP) { std::cout << "Operating Mode: ESTOP\n"; } std::cout << "Gait Type: " << data._gaitScheduler->gaitData.gaitName << "\n"; std::cout << std::endl; // Reset iteration counter printIter = 0; } // Print robot info about the robot's status // data._gaitScheduler->printGaitInfo(); // data._desiredStateCommand->printStateCommandInfo(); break; case 1: // Initializing FSM State transition std::cout << "[CONTROL FSM] Transition initialized from " << currentState->stateString << " to " << nextState->stateString << "\n" << std::endl; break; case 2: // Finalizing FSM State transition std::cout << "[CONTROL FSM] Transition finalizing from " << currentState->stateString << " to " << nextState->stateString << "\n" << std::endl; break; } } // template class ControlFSM<double>; This should be fixed... need to make // RobotRunner a template template class ControlFSM<float>;
[ "humanoid@mit.edu" ]
humanoid@mit.edu
9def4216287ac715010445c417f8aff0f5daa7ff
8c8820fb84dea70d31c1e31dd57d295bd08dd644
/Experimental/Chaos/Public/Chaos/TrackedGeometryManager.h
ec2168cb41318f62081abcec84ab2f040958fca1
[]
no_license
redisread/UE-Runtime
e1a56df95a4591e12c0fd0e884ac6e54f69d0a57
48b9e72b1ad04458039c6ddeb7578e4fc68a7bac
refs/heads/master
2022-11-15T08:30:24.570998
2020-06-20T06:37:55
2020-06-20T06:37:55
274,085,558
3
0
null
null
null
null
UTF-8
C++
false
false
2,065
h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once namespace Chaos { class FImplicitObject; class CHAOS_API FTrackedGeometryManager { public: static FTrackedGeometryManager& Get() { static FTrackedGeometryManager Singleton; return Singleton; } void DumpMemoryUsage(FOutputDevice* Ar) const { struct FMemInfo { uint32 NumBytes; FString DebugInfo; FString ToString; bool operator<(const FMemInfo& Other) const { return NumBytes < Other.NumBytes; } }; TArray<FMemInfo> MemEntries; uint32 TotalBytes = 0; for (const auto& Itr : SharedGeometry) { FMemInfo Info; Info.DebugInfo = Itr.Value; TArray<uint8> Data; FMemoryWriter MemAr(Data); FChaosArchive ChaosAr(MemAr); FImplicitObject* NonConst = const_cast<FImplicitObject*>(Itr.Key.Get()); //only doing this to write out, serialize is non const for read in NonConst->Serialize(ChaosAr); Info.ToString = NonConst->ToString(); Info.NumBytes = Data.Num(); MemEntries.Add(Info); TotalBytes += Info.NumBytes; } MemEntries.Sort(); Ar->Logf(TEXT("")); Ar->Logf(TEXT("Chaos Tracked Geometry:")); Ar->Logf(TEXT("")); for (const FMemInfo& Info : MemEntries) { Ar->Logf(TEXT("%-10d %s ToString:%s"), Info.NumBytes, *Info.DebugInfo, *Info.ToString); } Ar->Logf(TEXT("%-10d Total"), TotalBytes); } private: TMap<TSerializablePtr<FImplicitObject>, FString> SharedGeometry; FCriticalSection CriticalSection; friend FImplicitObject; //These are private because of various threading considerations. ImplicitObject does the cleanup because it needs extra information void AddGeometry(TSerializablePtr<FImplicitObject> Geometry, const FString& DebugInfo) { FScopeLock Lock(&CriticalSection); SharedGeometry.Add(Geometry, DebugInfo); } void RemoveGeometry(const FImplicitObject* Geometry) { FScopeLock Lock(&CriticalSection); TSerializablePtr<FImplicitObject> Dummy; Dummy.SetFromRawLowLevel(Geometry); SharedGeometry.Remove(Dummy); } }; }
[ "wujiahong19981022@outlook.com" ]
wujiahong19981022@outlook.com
5b12307122e47bcf65c58be7e47c42cb975ed72a
8a4c011199dc4f3250da99f84f0353b2fef1d2ea
/ColorsBase.h
3e9ca0ec30cbc7602a3d83160ed76c6ed04c3960
[ "Apache-2.0" ]
permissive
yuanyuanxiang/3DCode
87bd35b6a48338fc643b9d7f43187d02959b87eb
8d4c14ea67a3a7ed263074595bd67bc384d8e783
refs/heads/master
2020-06-11T19:56:26.102972
2020-01-02T12:52:33
2020-01-02T12:52:33
75,626,401
12
9
null
null
null
null
GB18030
C++
false
false
3,239
h
/** * @file ColorsBase.h * @brief 彩色二维码彩色编码解码基类 * @date 2016/10/15 */ #pragma once #include "DataTypes.h" #include <vector> using namespace std; #ifndef MAX_MODULESIZE #define MAX_MODULESIZE 177 /**< QR码最大尺寸 */ #endif /** * @enum EncodeModule * @brief 彩色编码模块 * @details 1 - 在白色模块编码;0 - 在黑色模块编码 */ enum EncodeModule { BlackModule = 0, /**< 在前景色编码(黑色) */ WhiteModule = 1, /**< 在背景色编码(白色) */ }; /// 掩码操作 const static int HEADER_MASK[90] = { // 16 x 3 前48位为 Color Infomation 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, // 14 x 3 后42位为 Logo & Version 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}; /// 采用新版 #define NEW_VERSION 1 /** * @class ColorsBase * @brief 彩色二维码编码解码基类 */ class ColorsBase { protected: BYTE* m_pBitMatrix[MAX_MODULESIZE]; /**< 原二维码 */ int m_nSymbolSize; /**< 二维码尺寸 */ vector<CPixelPoint> m_HeaderIndex; /**< 数据头索引 */ CLogoRect m_LogoRect; /**< 二维码LOGO */ private: EncodeModule m_EncodeModule;/**< 彩色编码模块(1,默认为白色) */ vector<CPixelPoint> m_vColorsModuleIndex; /**< 彩色模块索引 */ public: /** * @brief 创建一个彩色编码解码基类对象 * @param[in] bMatrix 二维码数据 * @param[in] nSymbolSize 二维码尺寸 */ ColorsBase(qrMat bMatrix[MAX_MODULESIZE], int nSymbolSize) { /// 采用for循环,将bMatrix的每行拷贝给m_pBitMatrix /// @note 只能采用循环,不能使用memcpy for (int i = 0; i < nSymbolSize; ++i) { m_pBitMatrix[i] = bMatrix[i]; } /// 构造的对象默认无LOGO m_LogoRect = 0; /// 默认在白色模块编码色彩 m_EncodeModule = WhiteModule; m_nSymbolSize = nSymbolSize; } /// 默认的析构函数 ~ColorsBase() { } /// 设置编码模块 inline void SetEncodeModule(EncodeModule Module) { m_EncodeModule = Module; } /// 获取编码模块 inline EncodeModule GetEncodeModule() const { return m_EncodeModule; } /// 设置二维码LOGO inline void SetLogoRect(CMyRect logo) { m_LogoRect = logo; } /// 获取二维码LOGO inline CMyRect GetLogoRect() const { return m_LogoRect; } /// 获取模块总数 inline int GetModulesCount() const { return m_nSymbolSize * m_nSymbolSize - m_LogoRect.Width() * m_LogoRect.Height(); } // 获取编码模块总数 int GetColorsMoudlesCount() const { return m_vColorsModuleIndex.size(); } /// 获取编码模块的索引 const vector<CPixelPoint>& GetColorsModuleIndex() const { return m_vColorsModuleIndex; } /// 获取彩色编码起始位置 int GetColorsStartIndex() const { return m_EncodeModule ? 0 : 90; } // 初始化编码模块的索引 void InitColorsModuleIndex(BOOL bFore = TRUE); // (row, col)非数据头索引 BOOL NotHeaderIndex(int row, int col) const; // 获取彩色数据头的索引 virtual void GetDataHeaderIndex() = 0; };
[ "962914132@qq.com" ]
962914132@qq.com
df50e9bf58037695343a33cd0d1609864e3308d6
e7c4e1edff2fd264f66d16f6261bf3ac5c9ce80c
/src/Step1_Models.cpp
377bf75aa6c617e0ecb621e6fb0328efde6a8f8e
[ "MIT", "BSL-1.0" ]
permissive
QinFinnUK/regenie
e5aa7757ee6d86429c370afeebac86bda7c67764
934b7352018d1c4328982845e7d1563c6c9ea737
refs/heads/master
2023-07-13T17:15:54.680946
2021-08-13T13:08:27
2021-08-13T13:08:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
46,015
cpp
/* This file is part of the regenie software package. Copyright (c) 2020-2021 Joelle Mbatchou, Andrey Ziyatdinov & Jonathan Marchini Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Regenie.hpp" #include "Files.hpp" #include "Geno.hpp" #include "Joint_Tests.hpp" #include "Step1_Models.hpp" #include "Step2_Models.hpp" #include "HLM.hpp" #include "Pheno.hpp" #include "Masks.hpp" #include "Data.hpp" using namespace std; using namespace Eigen; using namespace boost; void fit_null_logistic(const int& chrom, struct param* params, struct phenodt* pheno_data, struct ests* m_ests, struct in_files* files, mstream& sout) { sout << " -fitting null logistic regression on binary phenotypes..." << flush; auto t1 = std::chrono::high_resolution_clock::now(); ArrayXd betaold, etavec, pivec, loco_offset, wvec; MatrixXd XtW; if(params->w_interaction || params->firth) m_ests->bhat_start.resize(pheno_data->new_cov.cols(), params->n_pheno); for(int i = 0; i < params->n_pheno; ++i ){ MapArXd Y (pheno_data->phenotypes_raw.col(i).data(), pheno_data->phenotypes_raw.rows()); MapArXb mask (pheno_data->masked_indivs.col(i).data(), pheno_data->masked_indivs.rows()); if(params->test_mode) loco_offset = m_ests->blups.col(i).array() * mask.cast<double>(); else loco_offset = ArrayXd::Zero(Y.size(), 1); // starting values pivec = ( 0.5 + Y ) / 2; etavec = mask.select( log(pivec/ (1-pivec)), 0); betaold = ArrayXd::Zero(pheno_data->new_cov.cols()); betaold(0) = etavec.mean() - loco_offset.mean(); if(!fit_logistic(Y, pheno_data->new_cov, loco_offset, mask, pivec, etavec, betaold, params, sout)) throw "logistic regression did not converge for phenotype " + files->pheno_names[i] + ". Perhaps increase --niter?"; else if( (mask && (pivec < params->numtol_eps || pivec > 1 - params->numtol_eps)).any() ) sout << "\n WARNING: Fitted probabilities numerically 0/1 occured (phenotype #" << files->pheno_names[i] <<")."; if(params->test_mode){ m_ests->Y_hat_p.col(i) = pivec.matrix() ; get_wvec(pivec, wvec, mask, params->l1_ridge_eps); m_ests->Gamma_sqrt.col(i) = wvec.sqrt().matrix(); m_ests->X_Gamma[i] = ( pheno_data->new_cov.array().colwise() * (m_ests->Gamma_sqrt.col(i).array() * mask.cast<double>()) ).matrix(); m_ests->Xt_Gamma_X_inv[i] = (m_ests->X_Gamma[i].transpose() * m_ests->X_Gamma[i]).colPivHouseholderQr().inverse(); if(params->w_interaction || params->firth) m_ests->bhat_start.col(i) = betaold.matrix(); } else m_ests->offset_logreg.col(i) = etavec; /* Files fstar; fstar.openForWrite("offsets.txt", sout); fstar << etavec; fstar.closeFile(); */ } sout << "done"; auto t2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1); sout << " (" << duration.count() << "ms) "<< endl; } bool fit_logistic(const Ref<const ArrayXd>& Y1, const Ref<const MatrixXd>& X1, const Ref<const ArrayXd>& offset, const Ref<const ArrayXb>& mask, ArrayXd& pivec, ArrayXd& etavec, ArrayXd& betavec, struct param const* params, mstream& sout) { int niter_cur = 0; double dev_old, dev_new=0; ArrayXd score, betanew, wvec_sqrt, wvec, zvec; MatrixXd XtW, XtWX; dev_old = get_logist_dev(Y1, pivec, mask); //cerr << dev_old << endl << pivec.head(5)<<"\n--\n"; while(niter_cur++ < params->niter_max){ // p*(1-p) and check for zeroes if( get_wvec(pivec, wvec, mask, params->numtol_eps) ){ if(params->verbose) sout << "ERROR: Zeros occured in Var(Y) during logistic regression.\n"; return false; } wvec_sqrt = mask.select(wvec.sqrt(), 0); XtW = X1.transpose() * wvec_sqrt.matrix().asDiagonal(); XtWX = XtW * XtW.transpose(); // working vector z = X*beta + (Y-p)/(p*(1-p)) // and multiply by sqrt(p*(1-p)) zvec = wvec_sqrt * mask.select(etavec - offset + (Y1 - pivec) / wvec, 0); // parameter estimate betanew = ( XtWX ).colPivHouseholderQr().solve( XtW * zvec.matrix() ).array(); // start step-halving for( int niter_search = 1; niter_search <= params->niter_max_line_search; niter_search++ ){ get_pvec(etavec, pivec, betanew, offset, X1, params->numtol_eps); dev_new = get_logist_dev(Y1, pivec, mask); /* cerr << "\n\n" << std::boolalpha << ((pivec > 0) && (pivec < 1)).all() << " " << pivec.minCoeff() << "-" << pivec.maxCoeff() << "-> " << betanew.head(3).matrix().transpose() << "--" << dev_new << " #" << niter_cur << "(" << niter_search << ")\n"; */ if( ((pivec > 0) && (pivec < 1)).all() ) break; // adjust step size betanew = (betavec + betanew) / 2; } score = X1.transpose() * mask.select(Y1 - pivec, 0).matrix(); // stopping criterion if( (score.abs().maxCoeff() < params->tol) || (abs(dev_new - dev_old)/(0.1 + abs(dev_new)) < params->tol) ) break; betavec = betanew; dev_old = dev_new; } //sout << "Took "<< niter_cur << " iterations." << endl; // If didn't converge if(niter_cur > params->niter_max) return false; betavec = betanew; //cerr << endl << betavec.matrix().transpose() << "\n\n" << score.matrix().transpose() << "\n\n"; return true; } double get_logist_dev(const Ref<const ArrayXd>& Y, const Ref<const ArrayXd>& pi, const Ref<const ArrayXb>& mask){ double dev = 0; for( int i = 0; i < Y.size(); i++){ if(mask(i)) dev -= (Y(i) == 1) ? log(pi(i)) : log(1-pi(i)); } return 2 * dev; // -2 log.lik } ///////////////////////////////////////////////// ///////////////////////////////////////////////// //// level 0 models ///////////////////////////////////////////////// ///////////////////////////////////////////////// void ridge_level_0(const int& block, struct in_files* files, struct param* params, struct filter* filters, struct ests* m_ests, struct geno_block* Gblock, struct phenodt* pheno_data, vector<snp>& snpinfo, struct ridgel0* l0, struct ridgel1* l1, vector<MatrixXb>& masked_in_folds, mstream& sout) { sout << " -calc level 0 ridge..." << flush; auto t2 = std::chrono::high_resolution_clock::now(); int bs = l0->GGt.rows(); int block_eff = params->write_l0_pred ? 0 : block; string op_name, out_pheno; ofstream ofile; MatrixXd ww1, ww2, beta, pred, vmat, dvec, Xout; MatrixXd ident_l0 = MatrixXd::Identity(bs, bs); MatrixXd p_sum = MatrixXd::Zero(params->n_ridge_l0, params->n_pheno); MatrixXd p_sum2 = MatrixXd::Zero(params->n_ridge_l0, params->n_pheno); if(!params->within_sample_l0 && params->print_block_betas) { for(int ph = 0; ph < params->n_pheno; ++ph ) params->beta_print_out[ph] = MatrixXd::Zero(params->n_ridge_l0, bs); } uint32_t cum_size_folds = 0; for(int i = 0; i < params->cv_folds; ++i ) { // assign masking within folds masked_in_folds[i] = pheno_data->masked_indivs.block(cum_size_folds, 0, params->cv_sizes(i), pheno_data->masked_indivs.cols()); ww1 = l0->GGt - l0->G_folds[i]; SelfAdjointEigenSolver<MatrixXd> eig(ww1); vmat = eig.eigenvectors(); dvec = eig.eigenvalues(); //if(i == 0)sout << ww1 << endl; ww2 = vmat.transpose() * (l0->GTY - l0->GtY[i]); for(int j = 0; j < params->n_ridge_l0; ++j ) { // b = U (D+sI)^(-1) U^t GtY beta = vmat * (dvec.array() + params->lambda[j]).inverse().matrix().asDiagonal() * ww2; // save beta for each phenotype (only when using out-of-sample pred) if(!params->within_sample_l0 && params->print_block_betas) for(int ph = 0; ph < params->n_pheno; ++ph ) params->beta_print_out[ph].row(j) += beta.col(ph).transpose(); // out-of-sample predictions (mask missing) pred = ( (beta.transpose() * Gblock->Gmat.block(0, cum_size_folds, bs, params->cv_sizes(i))).array() * masked_in_folds[i].transpose().array().cast<double>() ).matrix(); p_sum.row(j) += pred.rowwise().sum(); p_sum2.row(j) += pred.rowwise().squaredNorm(); // store predictions for(int ph = 0; ph < params->n_pheno; ++ph ) { l1->test_mat[ph][i].col(block_eff * params->n_ridge_l0 + j) = pred.row(ph).transpose(); l1->test_pheno[ph][i].col(0) = pheno_data->phenotypes.block(cum_size_folds, ph, params->cv_sizes(i), 1); if (params->binary_mode && (block == 0) && (j == 0) ) { l1->test_pheno_raw[ph][i].col(0) = pheno_data->phenotypes_raw.block(cum_size_folds, ph, params->cv_sizes(i), 1); l1->test_offset[ph][i].col(0) = m_ests->offset_logreg.block(cum_size_folds, ph, params->cv_sizes(i), 1); } } } cum_size_folds += params->cv_sizes(i); } // center and scale using the whole sample for(int ph = 0; ph < params->n_pheno; ++ph ) { RowVectorXd p_mean, p_invsd; p_mean = p_sum.col(ph).transpose() / pheno_data->Neff(ph); p_invsd = sqrt( (pheno_data->Neff(ph) - 1) / (p_sum2.col(ph).transpose().array() - pheno_data->Neff(ph) * p_mean.array().square()) ); // scale printed estimates by the sd if(params->print_block_betas) params->beta_print_out[ph].array().colwise() *= p_invsd.transpose().array(); if(params->write_l0_pred) Xout = MatrixXd::Zero(params->n_samples, params->n_ridge_l0); cum_size_folds = 0; for(int i = 0; i < params->cv_folds; ++i ) { l1->test_mat[ph][i].block(0, block_eff * params->n_ridge_l0, params->cv_sizes(i), params->n_ridge_l0).rowwise() -= p_mean; l1->test_mat[ph][i].block(0, block_eff * params->n_ridge_l0, params->cv_sizes(i), params->n_ridge_l0).array().rowwise() *= p_invsd.array(); if(params->write_l0_pred) { Xout.block(cum_size_folds, 0, params->cv_sizes(i), params->n_ridge_l0) = l1->test_mat[ph][i].block(0, block_eff * params->n_ridge_l0, params->cv_sizes(i), params->n_ridge_l0); cum_size_folds += params->cv_sizes(i); } } // write predictions to file if specified if(params->write_l0_pred) { write_l0_file(files->write_preds_files[ph].get(), Xout, sout); //if(block ==0 && ph == 0 ) sout << endl << "Out " << endl << Xout.block(0, 0, 3, 3) << endl; } } // if printing betas to file (average over folds) [assume snp IDs are unique] // -> separate file for each block (params->n_ridge_l0 rows & (2+bs) columns) if(!params->within_sample_l0 && params->print_block_betas) { op_name = files->out_file + "_block" + to_string(block+1) + ".betas"; openStream(&ofile, op_name, std::ios::out, sout); // Header: [TRAIT PARAM snpID1 ... snpIDk] ofile << "TRAIT PARAM " ; for(int i = 0; i < bs; ++i ) ofile << snpinfo[params->print_snpcount++].ID << " "; ofile << endl; // Each line: [pheno# ridge# beta1 ... betak] for(int ph = 0; ph < params->n_pheno; ++ph ){ params->beta_print_out[ph] /= params->cv_folds; for(int j = 0; j < params->n_ridge_l0; ++j ) { ofile << ph + 1 << " " << j + 1 << " "; for(int i = 0; i < bs; ++i ) ofile << params->beta_print_out[ph](j,i) << " "; ofile << endl; } } ofile.close(); } sout << "done"; auto t3 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t3 - t2); sout << " (" << duration.count() << "ms) "<< endl; } void ridge_level_0_loocv(const int block, struct in_files* files, struct param* params, struct filter* filters, struct ests* m_ests, struct geno_block* Gblock, struct phenodt* pheno_data, vector<snp>& snpinfo, struct ridgel0* l0, struct ridgel1* l1, mstream& sout) { sout << " -calc level 0 ridge..." << flush; auto t2 = std::chrono::high_resolution_clock::now(); int bs = l0->GGt.rows(); int block_eff = params->write_l0_pred ? 0 : block; // if writing to file string out_pheno; ofstream ofile; VectorXd z1, gvec; MatrixXd VtG, z2, pred, Xout; RowVectorXd p_mean, p_sd; /* if(bs > params->n_samples) throw "block size must be smaller than the number of samples to perform LOOCV!"; */ // make matrix of (eigen-value + lambda)^(-1) Map<RowVectorXd> Lmap(params->lambda.data(), params->n_ridge_l0); MatrixXd dl = l0->GGt_eig_val.asDiagonal() * MatrixXd::Ones(bs, params->n_ridge_l0); dl.rowwise() += Lmap; MatrixXd DL_inv = dl.array().inverse().matrix(); uint64 max_bytes = params->chunk_mb * 1e6; // amount of RAM used < max_mb [ creating (bs * target_size) matrix ] int nchunk = ceil( params->cv_folds * bs * sizeof(double) * 1.0 / max_bytes ); if (params->verbose) sout << nchunk << " chunks..." << flush; int chunk, size_chunk, target_size = params->cv_folds / nchunk; int j_start; for(chunk = 0; chunk < nchunk; ++chunk ) { size_chunk = chunk == nchunk - 1? params->cv_folds - target_size * chunk : target_size; j_start = chunk * target_size; VtG = l0->GGt_eig_vec.transpose() * Gblock->Gmat.block(0, j_start, bs, size_chunk); for(int i = 0; i < size_chunk; ++i ) { z1 = VtG.col(i); z2 = DL_inv.array().colwise() * z1.array(); gvec = z2.transpose() * z1; pred = z2.transpose() * l0->Wmat - gvec * pheno_data->phenotypes.row(j_start + i); pred.array().colwise() /= 1 - gvec.array(); for(int ph = 0; ph < params->n_pheno; ++ph ) l1->test_mat_conc[ph].block(j_start + i, block_eff * params->n_ridge_l0, 1, params->n_ridge_l0) = pred.col(ph).transpose(); } } // center and scale within the block for(int ph = 0; ph < params->n_pheno; ++ph ) { // mask missing first l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).array().colwise() *= pheno_data->masked_indivs.col(ph).array().cast<double>(); p_mean = l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).colwise().sum() / pheno_data->Neff(ph); //if(i == 0)sout << i << " " << p_mean << endl; l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).rowwise() -= p_mean; // mask missing again l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).array().colwise() *= pheno_data->masked_indivs.col(ph).array().cast<double>(); p_sd = l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).colwise().norm() / sqrt(pheno_data->Neff(ph) -1); //if(i == 0)sout << i << " " << p_sd << endl; l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).array().rowwise() /= p_sd.array(); if(params->write_l0_pred) { Xout = l1->test_mat_conc[ph].block(0, 0, params->n_samples, params->n_ridge_l0); write_l0_file(files->write_preds_files[ph].get(), Xout, sout); //if(block < 2 && ph == 0 ) sout << endl << "Out " << endl << Xout.block(0, 0, 5, Xout.cols()) << endl; } } sout << "done"; auto t3 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t3 - t2); sout << " (" << duration.count() << "ms) "<< endl; } void write_l0_file(ofstream* ofs, MatrixXd& Xout, mstream& sout){ ofs->write( reinterpret_cast<char *> (&Xout(0,0)), Xout.size() * sizeof(double) ); if( ofs->fail() ) throw "cannot successfully write temporary level 0 predictions to disk"; } ///////////////////////////////////////////////// ///////////////////////////////////////////////// //// level 1 models ///////////////////////////////////////////////// ///////////////////////////////////////////////// void set_mem_l1(struct in_files* files, struct param* params, struct filter* filters, struct ests* m_ests, struct geno_block* Gblock, struct phenodt* pheno_data, struct ridgel1* l1, vector<MatrixXb>& masked_in_folds, mstream& sout){ // when l0 was run in parallel // store pheno info for l1 if(!params->use_loocv) { uint32_t low = 0, high = 0; uint32_t i_total = 0, cum_size_folds = 0; for(int i = 0; i < params->cv_folds; ++i ) { // assign masking within folds for(int j = 0; j < params->cv_sizes(i); ++j) { masked_in_folds[i].row(j) = pheno_data->masked_indivs.row(i_total); i_total++; } // set lower and upper index bounds for fold if(i>0) low += params->cv_sizes(i-1); high += params->cv_sizes(i); // store predictions uint32_t jj = 0; for(size_t k = 0; k < params->n_samples; ++k ) { if( (k >= low) && (k < high) ) { for(int ph = 0; ph < params->n_pheno; ++ph ) { l1->test_pheno[ph][i](jj, 0) = pheno_data->phenotypes(k, ph); if (params->binary_mode) { l1->test_pheno_raw[ph][i](jj, 0) = pheno_data->phenotypes_raw(k, ph); l1->test_offset[ph][i](jj, 0) = m_ests->offset_logreg(k, ph); } } jj++; } } cum_size_folds += params->cv_sizes(i); } } } void ridge_level_1(struct in_files* files, struct param* params, struct ridgel1* l1, mstream& sout) { sout << endl << " Level 1 ridge..." << endl << flush; int bs_l1 = params->total_n_block * params->n_ridge_l0; int ph_eff; string in_pheno; ifstream infile; MatrixXd X1, X2, beta_l1, p1, vmat, dvec, dl_inv; VectorXd VtX2; MatrixXd XtX_sum, XtY_sum; MatrixXd ident_l1 = MatrixXd::Identity(bs_l1,bs_l1); Map<RowVectorXd> Lmap(params->tau.data(), params->n_ridge_l1); // to compute Rsq and MSE of predictions for (int i = 0; i < 5; i++) l1->cumsum_values[i].setZero(params->n_pheno, params->n_ridge_l1); for(int ph = 0; ph < params->n_pheno; ++ph ) { sout << " -on phenotype " << ph+1 <<" (" << files->pheno_names[ph] << ")..." << flush; auto ts1 = std::chrono::high_resolution_clock::now(); ph_eff = params->write_l0_pred ? 0 : ph; // read in level 0 predictions from file if(params->write_l0_pred){ // allocate memory if(ph == 0) { for( int i = 0; i < params->cv_folds; ++i ) l1->test_mat[ph_eff][i] = MatrixXd::Zero(params->cv_sizes(i), bs_l1); } read_l0(ph, ph_eff, files, params, l1, sout); //if(ph == 0) sout << endl << "In:\n" << l1->test_mat[ph_eff][0].block(0,0,5,6) << endl; } // compute XtX and Xty for each fold and cum. sum using test_mat's if (!params->within_sample_l0){ XtX_sum.setZero(bs_l1, bs_l1); XtY_sum.setZero(bs_l1, 1); for( int i = 0; i < params->cv_folds; ++i ) { l1->X_folds[i] = l1->test_mat[ph_eff][i].transpose() * l1->test_mat[ph_eff][i]; l1->XtY[i] = l1->test_mat[ph_eff][i].transpose() * l1->test_pheno[ph][i]; XtX_sum += l1->X_folds[i]; XtY_sum += l1->XtY[i]; } } for(int i = 0; i < params->cv_folds; ++i ) { // use either in-sample or out-of-sample predictions if (params->within_sample_l0) { X1 = l1->pred_mat[ph][i].transpose() * l1->pred_mat[ph][i]; X2 = l1->pred_mat[ph][i].transpose() * l1->pred_pheno[ph][i]; } else{ X1 = XtX_sum - l1->X_folds[i]; X2 = XtY_sum - l1->XtY[i]; } SelfAdjointEigenSolver<MatrixXd> eigX1(X1); vmat = eigX1.eigenvectors(); dvec = eigX1.eigenvalues(); VtX2 = vmat.transpose() * X2; // compute solutions for all ridge parameters at once // p1 is Nfold x nridge_l1 matrix dl_inv = ( (dvec.asDiagonal() * MatrixXd::Ones(bs_l1, params->n_ridge_l1)).rowwise() + Lmap).array().inverse().matrix(); dl_inv.array().colwise() *= VtX2.array(); beta_l1 = vmat * dl_inv; if(!params->within_sample_l0) l1->beta_hat_level_1[ph][i] = beta_l1; p1 = l1->test_mat[ph_eff][i] * beta_l1; l1->cumsum_values[0].row(ph) += p1.colwise().sum(); l1->cumsum_values[1].row(ph).array() += l1->test_pheno[ph][i].array().sum(); l1->cumsum_values[2].row(ph) += p1.array().square().matrix().colwise().sum(); l1->cumsum_values[3].row(ph).array() += l1->test_pheno[ph][i].array().square().sum(); l1->cumsum_values[4].row(ph) += (p1.array().colwise() * l1->test_pheno[ph][i].col(0).array()).matrix().colwise().sum() ; } sout << "done"; auto ts2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1); sout << " (" << duration.count() << "ms) "<< endl; } sout << endl; } void ridge_level_1_loocv(struct in_files* files, struct param* params, struct phenodt* pheno_data, struct ridgel1* l1, mstream& sout) { sout << endl << " Level 1 ridge..." << flush; int bs_l1 = params->total_n_block * params->n_ridge_l0; int ph_eff; string in_pheno; ifstream infile; MatrixXd Xmat_chunk, Yvec_chunk, Z1, Z2, dl, dl_inv, xtx; VectorXd wvec, zvec; RowVectorXd calFactor, pred; for (int i = 0; i < 5; i++) l1->cumsum_values[i].setZero(params->n_pheno, params->n_ridge_l1); // make matrix of (eigen-values + tau)^(-1) Map<RowVectorXd> Lmap(params->tau.data(), params->n_ridge_l1); uint64 max_bytes = params->chunk_mb * 1e6; // amount of RAM used < max_mb [ creating (target_size * bs_l1) matrix ] int nchunk = ceil( params->cv_folds * bs_l1 * sizeof(double) * 1.0 / max_bytes ); if (params->verbose) sout << nchunk << " chunks..."; sout << endl; int chunk, size_chunk, target_size = params->cv_folds / nchunk; int j_start; for(int ph = 0; ph < params->n_pheno; ++ph ) { sout << " -on phenotype " << ph+1 <<" (" << files->pheno_names[ph] <<")..." << flush; auto ts1 = std::chrono::high_resolution_clock::now(); ph_eff = params->write_l0_pred ? 0 : ph; // read in level 0 predictions from file if(params->write_l0_pred){ // allocate memory (re-use same matrix for all traits) if(ph == 0) l1->test_mat_conc[ph_eff] = MatrixXd::Zero(params->n_samples, bs_l1); read_l0(ph, ph_eff, files, params, l1, sout); } xtx = l1->test_mat_conc[ph_eff].transpose() * l1->test_mat_conc[ph_eff]; SelfAdjointEigenSolver<MatrixXd> eigX(xtx); dl = eigX.eigenvalues().asDiagonal() * MatrixXd::Ones(bs_l1, params->n_ridge_l1); dl.rowwise() += Lmap; dl_inv = dl.array().inverse().matrix(); zvec = l1->test_mat_conc[ph_eff].transpose() * pheno_data->phenotypes.col(ph); wvec = eigX.eigenvectors().transpose() * zvec; for(chunk = 0; chunk < nchunk; ++chunk ) { size_chunk = chunk == nchunk - 1? params->cv_folds - target_size * chunk : target_size; j_start = chunk * target_size; Xmat_chunk = l1->test_mat_conc[ph_eff].block(j_start, 0, size_chunk, bs_l1); Yvec_chunk = pheno_data->phenotypes.block(j_start, ph, size_chunk, 1); Z1 = (Xmat_chunk * eigX.eigenvectors()).transpose(); for(int i = 0; i < size_chunk; ++i ) { Z2 = (dl_inv.array().colwise() * Z1.col(i).array()).matrix(); calFactor = Z1.col(i).transpose() * Z2; pred = wvec.transpose() * Z2; pred -= Yvec_chunk(i, 0) * calFactor; pred.array() /= 1 - calFactor.array(); //if( ph == 0) sout << pred.head(5) << endl; // compute mse and rsq l1->cumsum_values[0].row(ph) += pred; // Sx // Y is centered so Sy = 0 l1->cumsum_values[2].row(ph) += pred.array().square().matrix(); // Sx2 // Y is scaled so Sy2 = params->n_samples - ncov l1->cumsum_values[4].row(ph).array() += pred.array() * Yvec_chunk(i,0); // Sxy } } sout << "done"; auto ts2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1); sout << " (" << duration.count() << "ms) "<< endl; } l1->cumsum_values[3].array().colwise() += pheno_data->Neff - params->ncov; // Sy2 sout << endl; } // Logistic models void ridge_logistic_level_1(struct in_files* files, struct param* params, struct phenodt* pheno_data, struct ridgel1* l1, vector<MatrixXb>& masked_in_folds, mstream& sout) { sout << endl << " Level 1 ridge with logistic regression..." << endl << flush; int niter_cur; int bs_l1 = params->total_n_block * params->n_ridge_l0; int ph_eff; string in_pheno; ifstream infile; ArrayXd Y1, W1, p1, score; ArrayXd betaold, etavec, pivec, wvec, zvec, betanew, etatest; MatrixXd X1, XtW, XtWX, XtWZ; l1->pheno_l1_not_converged = ArrayXb::Constant(params->n_pheno, false); MatrixXd ident_l1 = MatrixXd::Identity(bs_l1,bs_l1); for (int i = 0; i < 6; i++) l1->cumsum_values[i].setZero(params->n_pheno, params->n_ridge_l1); for(int ph = 0; ph < params->n_pheno; ++ph ) { sout << " -on phenotype " << ph+1 <<" (" << files->pheno_names[ph] <<")..." << flush; auto ts1 = std::chrono::high_resolution_clock::now(); ph_eff = params->write_l0_pred ? 0 : ph; // read in level 0 predictions from file if(params->write_l0_pred){ // allocate memory if(ph == 0) { for( int i = 0; i < params->cv_folds; ++i ) l1->test_mat[ph_eff][i] = MatrixXd::Zero(params->cv_sizes(i), bs_l1); } read_l0(ph, ph_eff, files, params, l1, sout); } for(int i = 0; i < params->cv_folds; ++i ) { if( l1->pheno_l1_not_converged(ph) ) break; if( params->within_sample_l0 ){ X1 = l1->pred_mat[ph][i]; Y1 = l1->pred_pheno_raw[ph][i]; W1 = l1->pred_offset[ph][i]; } // starting values for each trait betaold = betanew = ArrayXd::Zero(bs_l1); for(int j = 0; j < params->n_ridge_l1; ++j ) { if( l1->pheno_l1_not_converged(ph) ) break; niter_cur = 0; // use warm starts (i.e. set final beta of previous ridge param // as initial beta for current ridge param) betaold = betanew; while(niter_cur++ < params->niter_max_ridge){ if(params->within_sample_l0) { etavec = W1 + (X1 * betaold.matrix()).array(); pivec = 1 - 1/(etavec.exp() + 1); wvec = pivec * (1 - pivec); // check none of the values are 0 if( ( wvec == 0 ).count() > 0 ){ sout << "ERROR: Zeros occured in Var(Y) during ridge logistic regression! (Try with --loocv)" << endl; l1->pheno_l1_not_converged(ph) = true; break; } zvec = (etavec - W1) + (Y1 - pivec) / wvec; XtW = X1.transpose() * wvec.matrix().asDiagonal(); betanew = (XtW * X1 + params->tau[j] * ident_l1).colPivHouseholderQr().solve(XtW * zvec.matrix()).array(); // get the score etavec = W1 + (X1 * betanew.matrix()).array(); pivec = 1 - 1/(etavec.exp() + 1); score = (X1.transpose() * (Y1 - pivec).matrix()).array() - params->tau[j] * betanew; } else { XtWX = MatrixXd::Zero(bs_l1, bs_l1); XtWZ = MatrixXd::Zero(bs_l1, 1); for(int k = 0; k < params->cv_folds; ++k ) { if( k != i) { // get w=p*(1-p) and check none of the values are 0 get_pvec(etavec, pivec, betaold, l1->test_offset[ph][k].array(), l1->test_mat[ph_eff][k], params->numtol_eps); if( get_wvec(pivec, wvec, masked_in_folds[k].col(ph).array(), params->l1_ridge_eps) ){ sout << "ERROR: Zeros occured in Var(Y) during ridge logistic regression! (Try with --loocv)" << endl; l1->pheno_l1_not_converged(ph) = true; break; } zvec = (masked_in_folds[k].col(ph).array()).select((etavec - l1->test_offset[ph][k].array()) + (l1->test_pheno_raw[ph][k].array() - pivec) / wvec, 0); XtW = l1->test_mat[ph_eff][k].transpose() * wvec.matrix().asDiagonal(); XtWX += XtW * l1->test_mat[ph_eff][k]; XtWZ += XtW * zvec.matrix(); } } if( l1->pheno_l1_not_converged(ph) ) break; betanew = ((XtWX + params->tau[j] * ident_l1).llt().solve(XtWZ)).array(); // start step-halving for( int niter_search = 1; niter_search <= params->niter_max_line_search_ridge; niter_search++ ){ bool invalid_wvec = false; for(int k = 0; k < params->cv_folds; ++k ) { if( k != i) { // get w=p*(1-p) and check none of the values are 0 get_pvec(etavec, pivec, betanew, l1->test_offset[ph][k].array(), l1->test_mat[ph_eff][k], params->numtol_eps); invalid_wvec = get_wvec(pivec, wvec, masked_in_folds[k].col(ph).array(), params->l1_ridge_eps); if( invalid_wvec ) break; // do another halving } } if( !invalid_wvec ) break; // halve step size betanew = (betaold + betanew) / 2; } // compute score score = ArrayXd::Zero(bs_l1); for(int k = 0; k < params->cv_folds; ++k ) { if( k != i) { // get w=p*(1-p) and check none of the values are 0 get_pvec(etavec, pivec, betanew, l1->test_offset[ph][k].array(), l1->test_mat[ph_eff][k], params->numtol_eps); if( get_wvec(pivec, wvec, masked_in_folds[k].col(ph).array(), params->l1_ridge_eps) ){ sout << "ERROR: Zeros occured in Var(Y) during ridge logistic regression! (Try with --loocv)" << endl; l1->pheno_l1_not_converged(ph) = true; break; } score += (l1->test_mat[ph_eff][k].transpose() * masked_in_folds[k].col(ph).array().select(l1->test_pheno_raw[ph][k].array() - pivec, 0).matrix()).array(); } } score -= params->tau[j] * betanew; } // stopping criterion if( (score.abs().maxCoeff() < params->l1_ridge_tol) || l1->pheno_l1_not_converged(ph)) break; betaold = betanew; } //cerr << "\nFold=" << i << " tau = " << params->tau[j] << " beta=" << betanew.matrix().transpose().array() << endl; //if(i==1) exit(EXIT_FAILURE); if(niter_cur > params->niter_max_ridge){ sout << "WARNING: Penalized logistic regression did not converge! (Increase --niter)\n"; l1->pheno_l1_not_converged(ph) = true; break; } else if(l1->pheno_l1_not_converged(ph)) break; //sout << "Converged in "<< niter_cur << " iterations. Score max = " << score.abs().maxCoeff() << endl; etatest = l1->test_offset[ph][i].array() + (l1->test_mat[ph_eff][i] * betanew.matrix()).array(); p1 = (1 - 1/(etatest.exp() + 1)); if(!params->within_sample_l0) l1->beta_hat_level_1[ph][i].col(j) = betanew; // compute mse for(int l = 0; l < params->cv_sizes(i); l++){ if(!masked_in_folds[i](l,ph)) continue; // if p is within eps of 0/1, set to eps/1-eps if( p1(l) < params->l1_ridge_eps ) p1(l) = params->l1_ridge_eps; else if( p1(l) > (1-params->l1_ridge_eps) ) p1(l) = 1 - params->l1_ridge_eps; l1->cumsum_values[0](ph,j) += p1(l); // Sx l1->cumsum_values[1](ph,j) += l1->test_pheno_raw[ph][i](l,0); // Sy l1->cumsum_values[2](ph,j) += p1(l) * p1(l); // Sx2 l1->cumsum_values[3](ph,j) += l1->test_pheno_raw[ph][i](l,0) * l1->test_pheno_raw[ph][i](l,0); // Sy2 l1->cumsum_values[4](ph,j) += p1(l) * l1->test_pheno_raw[ph][i](l,0); // Sxy l1->cumsum_values[5](ph,j) += compute_log_lik(l1->test_pheno_raw[ph][i](l,0), p1(l)); // LL } } } sout << "done"; auto ts2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1); sout << " (" << duration.count() << "ms) "<< endl; } sout << endl; } void ridge_logistic_level_1_loocv(struct in_files* files, struct param* params, struct phenodt* pheno_data, struct ests* m_ests, struct ridgel1* l1, mstream& sout) { sout << endl << " Level 1 ridge with logistic regression..." << flush; int ph_eff, bs_l1 = params->total_n_block * params->n_ridge_l0; double v2, pred, p1; string in_pheno; ifstream infile; ArrayXd beta, pivec, wvec; MatrixXd XtWX, V1, b_loo; LLT<MatrixXd> Hinv; l1->pheno_l1_not_converged = ArrayXb::Constant(params->n_pheno, false); MatrixXd ident_l1 = MatrixXd::Identity(bs_l1,bs_l1); for (int i = 0; i < 6; i++) l1->cumsum_values[i].setZero(params->n_pheno, params->n_ridge_l1); uint64 max_bytes = params->chunk_mb * 1e6; // amount of RAM used < max_mb [ creating (bs_l1 * target_size) matrix ] int nchunk = ceil( params->cv_folds * bs_l1 * sizeof(double) * 1.0 / max_bytes ); int j_start, chunk, size_chunk, target_size = params->cv_folds / nchunk; sout << (params->verbose ? to_string(nchunk) + " chunks..." : "" ) << endl; for(int ph = 0; ph < params->n_pheno; ++ph ) { sout << " -on phenotype " << ph+1 << " (" << files->pheno_names[ph] <<")..." << flush; auto ts1 = std::chrono::high_resolution_clock::now(); ph_eff = params->write_l0_pred ? 0 : ph; // read in level 0 predictions from file if(params->write_l0_pred){ // allocate memory (re-use same matrix for all traits) if(ph == 0) l1->test_mat_conc[ph_eff] = MatrixXd::Zero(params->n_samples, bs_l1); read_l0(ph, ph_eff, files, params, l1, sout); } MapArXd Y (pheno_data->phenotypes_raw.col(ph).data(), pheno_data->phenotypes_raw.rows()); MapMatXd X (l1->test_mat_conc[ph_eff].data(), pheno_data->phenotypes_raw.rows(), bs_l1); MapArXd offset (m_ests->offset_logreg.col(ph).data(), pheno_data->phenotypes_raw.rows()); MapArXb mask (pheno_data->masked_indivs.col(ph).data(), pheno_data->masked_indivs.rows()); // starting values for each trait beta = ArrayXd::Zero(bs_l1); for(int j = 0; j < params->n_ridge_l1; ++j ) { // using warm starts (i.e. set final beta of previous ridge param // as initial beta for current ridge param) if( params->use_adam ) // run ADAM to get close to max run_log_ridge_loocv_adam(ph, params->tau[j], beta, pivec, wvec, Y, X, offset, mask, params, sout); if(!run_log_ridge_loocv(params->tau[j], target_size, nchunk, beta, pivec, wvec, Y, X, offset, mask, params, sout)){ sout << "WARNING: Ridge logistic regression did not converge! (Increase --niter)\n"; l1->pheno_l1_not_converged(ph) = true; break; } // compute Hinv // zvec = (pheno_data->masked_indivs.col(ph).array()).select( (etavec - m_ests->offset_logreg.col(ph).array()) + (pheno_data->phenotypes_raw.col(ph).array() - pivec) / wvec, 0); XtWX = MatrixXd::Zero(bs_l1, bs_l1); for(chunk = 0; chunk < nchunk; ++chunk){ size_chunk = ( chunk == nchunk - 1 ? params->cv_folds - target_size * chunk : target_size ); j_start = chunk * target_size; Ref<MatrixXd> Xmat_chunk = X.block(j_start, 0, size_chunk, bs_l1); // n x k Ref<MatrixXd> w_chunk = wvec.matrix().block(j_start, 0, size_chunk,1); XtWX += Xmat_chunk.transpose() * w_chunk.asDiagonal() * Xmat_chunk; } Hinv.compute( XtWX + params->tau[j] * ident_l1 ); // LOOCV estimates for(chunk = 0; chunk < nchunk; ++chunk ) { size_chunk = ( chunk == nchunk - 1 ? params->cv_folds - target_size * chunk : target_size ); j_start = chunk * target_size; Ref<MatrixXd> Xmat_chunk = X.block(j_start, 0, size_chunk, bs_l1); // n x k Ref<MatrixXd> Yvec_chunk = Y.matrix().block(j_start, 0, size_chunk, 1); Ref<MatrixXb> mask_chunk = mask.matrix().block(j_start, 0, size_chunk,1); V1 = Hinv.solve( Xmat_chunk.transpose() ); // k x n for(int i = 0; i < size_chunk; ++i ) { if(!mask_chunk(i,0)) continue; v2 = Xmat_chunk.row(i) * V1.col(i); v2 *= wvec(j_start + i); b_loo = (beta - V1.col(i).array() * (Yvec_chunk(i,0) - pivec(j_start + i)) / (1 - v2)).matrix(); pred = Xmat_chunk.row(i) * b_loo.col(0); pred += offset(j_start + i); p1 = 1 - 1/ ( exp(pred) + 1 ); // if p is within eps of 0/1, set to eps/1-eps if( p1 < params->l1_ridge_eps ) p1 = params->l1_ridge_eps; else if( p1 > (1-params->l1_ridge_eps) ) p1 = 1 - params->l1_ridge_eps; // compute mse and rsq l1->cumsum_values[0](ph,j) += p1; // Sx l1->cumsum_values[1](ph,j) += Yvec_chunk(i,0); // Sy l1->cumsum_values[2](ph,j) += p1 * p1; // Sx2 l1->cumsum_values[3](ph,j) += Yvec_chunk(i,0) * Yvec_chunk(i,0); // Sy2 l1->cumsum_values[4](ph,j) += p1 * Yvec_chunk(i,0); // Sxy l1->cumsum_values[5](ph,j) += compute_log_lik(Yvec_chunk(i,0), p1); // Sxy } } } sout << "done"; auto ts2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1); sout << " (" << duration.count() << "ms) "<< endl; } sout << endl; } bool run_log_ridge_loocv(const double& lambda, const int& target_size, const int& nchunk, ArrayXd& betaold, ArrayXd& pivec, ArrayXd& wvec, const Ref<const ArrayXd>& Y, Ref<MatrixXd> X, const Ref<const ArrayXd>& offset, const Ref<const ArrayXb>& mask, struct param* params, mstream& sout) { int bs_l1 = params->total_n_block * params->n_ridge_l0; int niter_cur = 0, j_start, chunk, size_chunk; ArrayXd etavec, zvec, betanew, score; MatrixXd XtWX, XtWZ, V1; LLT<MatrixXd> Hinv; MatrixXd ident_l1 = MatrixXd::Identity(bs_l1,bs_l1); while(niter_cur++ < params->niter_max_ridge) { // get w=p*(1-p) and check none of the values are 0 get_pvec(etavec, pivec, betaold, offset, X, params->numtol_eps); if( get_wvec(pivec, wvec, mask, params->l1_ridge_eps) ){ sout << "ERROR: Zeros occured in Var(Y) during ridge logistic regression.\n"; return false; } zvec = mask.select( (etavec - offset) + (Y - pivec) / wvec, 0); // compute XtWX and XtWZ in chunks XtWX = MatrixXd::Zero(bs_l1, bs_l1); XtWZ = MatrixXd::Zero(bs_l1, 1); for(chunk = 0; chunk < nchunk; ++chunk ) { size_chunk = ( chunk == nchunk - 1 ? params->cv_folds - target_size * chunk : target_size ); j_start = chunk * target_size; Ref<MatrixXd> Xmat_chunk = X.block(j_start, 0, size_chunk, bs_l1); // n x k Ref<MatrixXd> w_chunk = wvec.matrix().block(j_start, 0, size_chunk,1); Ref<MatrixXd> z_chunk = zvec.matrix().block(j_start, 0, size_chunk,1); V1 = Xmat_chunk.transpose() * w_chunk.asDiagonal(); XtWX += V1 * Xmat_chunk; XtWZ += V1 * z_chunk; } Hinv.compute( XtWX + lambda * ident_l1 ); betanew = Hinv.solve(XtWZ).array(); // get w=p*(1-p) and check none of the values are 0 get_pvec(etavec, pivec, betanew, offset, X, params->numtol_eps); if( get_wvec(pivec, wvec, mask, params->l1_ridge_eps) ){ sout << "ERROR: Zeros occured in Var(Y) during ridge logistic regression.\n"; return false; } // get the score score = ( X.transpose() * mask.select(Y - pivec, 0).matrix()).array() ; score -= lambda * betanew; if( score.abs().maxCoeff() < params->l1_ridge_tol ) break; betaold = betanew; } if(niter_cur > params->niter_max_ridge) return false; //sout << "Converged in "<< niter_cur << " iterations. Score max = " << score.abs().maxCoeff() << endl; betaold = betanew; return true; } // Ridge logistic with ADAM using mini batch void run_log_ridge_loocv_adam(const int& ph, const double& lambda, ArrayXd& betavec, ArrayXd& pivec, ArrayXd& wvec, const Ref<const ArrayXd>& Y, Ref<MatrixXd> X, const Ref<const ArrayXd>& offset, const Ref<const ArrayXb>& mask, struct param* params, mstream& sout) { int niter_cur = 0, index; double p_alpha = params->adam_alpha, p_beta1 = params->adam_beta1, p_beta2 = params->adam_beta2, p_eps = params->adam_eps, p_alpha_t; double eta, phat; //cerr << p_alpha << " " << p_beta1 << " " << p_beta2 << " " << p_eps << endl; std::uniform_int_distribution<> d(0, mask.count() - 1); std::mt19937 gen; ArrayXd etavec, gradient_f, mt, vt, step_size; // starting values for ADAM params mt = vt = betavec * 0; gradient_f.resize( betavec.size() ); while(niter_cur++ < params->niter_max_ridge_adam) { gradient_f = lambda * betavec; if(params->adam_mini){ // ADAM using mini-batch for (int i = 0; i < params->adam_batch_size; i++){ index = params->adam_indices[ph](d(gen)); eta = offset(index) + X.row(index) * betavec.matrix(); phat = 1 - 1/(exp(eta) + 1); gradient_f -= X.row(index).transpose().array() * (Y(index)-phat); } gradient_f /= params->adam_batch_size; } else { get_pvec(etavec, pivec, betavec, offset, X, params->numtol_eps); gradient_f -= ( X.transpose() * mask.select(Y - pivec, 0).matrix()).array() ; } //if(niter_cur%100 == 1) sout << "At iteration #"<< niter_cur << "; score max = " << gradient_f.abs().maxCoeff() << endl; mt = p_beta1 * mt + (1 - p_beta1) * gradient_f; vt = p_beta2 * vt + (1 - p_beta2) * gradient_f.square(); p_alpha_t = p_alpha * sqrt(1 - pow(p_beta2, niter_cur)) / (1 - pow(p_beta1, niter_cur)); step_size = p_alpha_t * mt / (vt.sqrt() + p_eps); if( step_size.abs().maxCoeff() < params->numtol ) break; betavec -= step_size; } if(params->verbose) sout << "ADAM took "<< niter_cur << " iterations (score max = " << gradient_f.abs().maxCoeff() << ")..."; } bool get_wvec(ArrayXd& pivec, ArrayXd& wvec, const Ref<const ArrayXb>& mask, const double& tol){ wvec = ArrayXd::Ones( mask.size() );// set all entries to 1 // avoid 0 weights by setting w to eps when p is within eps of 0/1 // (strategy used in glmnet) for (int i = 0; i < mask.size(); i++){ if( !mask(i) ) continue; if( pivec(i) < tol) { pivec(i) = 0; wvec(i) = tol; } else if ( pivec(i) > (1-tol) ){ pivec(i) = 1; wvec(i) = tol; } else wvec(i) = pivec(i) * (1-pivec(i)); } //wvec = masks.col(ph).array().select(pivec * (1 - pivec), 1); return (wvec == 0).any(); } void get_pvec(ArrayXd& etavec, ArrayXd& pivec, const Ref<const ArrayXd>& beta, const Ref<const ArrayXd>& offset, const Ref<const MatrixXd>& Xmat, double const& eps){ etavec = offset + (Xmat * beta.matrix()).array(); pivec.resize(etavec.size(),1); // strategy used in glm for (int i = 0; i < pivec.size(); i++){ if(etavec(i) > ETAMAXTHR) pivec(i) = 1 / (1 + eps); else if(etavec(i) < ETAMINTHR) pivec(i) = eps / (1 + eps); else pivec(i) = 1 - 1/(exp(etavec(i)) + 1); } } double compute_log_lik(const double& y, const double& p){ // negative log likelihood for bernoulli double ll; ll = - y * log(p) - (1 - y) * log(1-p); return(ll); } void read_l0(int const& ph, int const& ph_eff, struct in_files* files, struct param* params, struct ridgel1* l1, mstream& sout){ int start, np; string fin; // all blocks in same file if(!params->run_l1_only){ start = 0; np = params->total_n_block * params->n_ridge_l0; fin = files->loco_tmp_prefix; read_l0_chunk(ph, ph_eff, start, np, fin, params, l1, sout); } else { // blocks in separate file for(size_t i = 0; i < files->bstart.size(); i++){ start = files->bstart[i] * params->n_ridge_l0; np = files->btot[i] * params->n_ridge_l0; fin = files->mprefix[i]; read_l0_chunk(ph, ph_eff, start, np, fin, params, l1, sout); } } } // read in l0 predictors in columns [start,start+np) void read_l0_chunk(int const& ph, int const& ph_eff, int const& start, int const& np, const string& prefix, struct param* params, struct ridgel1* l1, mstream& sout){ string in_pheno = prefix + "_l0_Y" + to_string(ph+1); ifstream infile; openStream(&infile, in_pheno, ios::in | ios::binary, sout); if( getSize(in_pheno) != (sizeof(double) * params->n_samples * np )) throw "file " + in_pheno + " is not the right size." ; //cerr << in_pheno << " " << getSize(in_pheno) << endl; // store back values in test_mat if(params->use_loocv) { infile.read( reinterpret_cast<char *> (&l1->test_mat_conc[ph_eff](0, start)), params->n_samples * np * sizeof(double) ); //if(ph == 0) sout << endl << "In:\n" << l1->test_mat_conc[ph_eff].block(0,0,5,6) << endl; } else { int nt = 0; for( int m = start; nt < np; nt++, m++ ) for( int i = 0; i < params->cv_folds; ++i ) for( int k = 0; k < params->cv_sizes(i); ++k ) infile.read( reinterpret_cast<char *> (&l1->test_mat[ph_eff][i](k,m)), sizeof(double) ); //if(start==0) cerr << endl <<l1->test_mat[ph_eff][0].block(0,0,3,3) << endl; } infile.close(); } uint64 getSize(string const& fname){ struct stat stat_buf; int rc = stat(fname.c_str(), &stat_buf); return ( rc == 0 ? stat_buf.st_size : 0); }
[ "joelle.mbatchou@regeneron.com" ]
joelle.mbatchou@regeneron.com
71ec932a3dcc2177d58750dac9ce17f49b5c9d78
2153c572a578bd13aec501a34ebcbef9d31aa187
/Launch/LeLaunch.cpp
bc51c4996a5e5386e6d78f60b241682c6d7af069
[]
no_license
ZcHuer/LMPlayer
e579f0718e61789cc15d77b4976379276813085c
da2fe595a8121b3d3c2feec91c461a38d9909bca
refs/heads/master
2022-04-09T22:07:15.900773
2020-03-17T08:10:19
2020-03-17T08:10:19
null
0
0
null
null
null
null
GB18030
C++
false
false
10,600
cpp
// LMPlayer.cpp : 定义应用程序的入口点。 // #include "stdafx.h" #include <ShlObj.h> #include <shellapi.h> #include <TlHelp32.h> #include <ImageHlp.h> #include <string> #include "../SDK/FLog/FileLog.h" #include "../Include/LeReport.h" #include "../Include/Data_RealTime.h" using namespace std; #define LMPLAYER_MUTEX_STRING L"{A974FD90-34FE-4B69-A509-75E43255FE49}" #define LEUPDATE_MUTEX_STRING L"{95209F0E-6D08-48BE-B660-5161524B371F}" // 杀掉进程 BOOL KillProcess(LPCTSTR lpProcessName) { HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 pe; pe.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hSnapShot, &pe)) { return FALSE; } CString strProcessName = lpProcessName; strProcessName.MakeLower(); while (Process32Next(hSnapShot, &pe)) { CString scTmp = pe.szExeFile; scTmp.MakeLower(); if (!scTmp.Compare(strProcessName)) { DWORD dwProcessID = pe.th32ProcessID; HANDLE hProcess = ::OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessID); ::TerminateProcess(hProcess, 0); CloseHandle(hProcess); } scTmp.ReleaseBuffer(); } strProcessName.ReleaseBuffer(); return TRUE; } typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); /** * Don't use the function IsWow64Process as a static function, * you should load it by function GetProcAddress, because * it is not available on all version of Windows. */ LPFN_ISWOW64PROCESS fnIsWow64Process = NULL; /** * This function tells if your application is a x64 program. */ BOOL Isx64Application() { return (sizeof(LPFN_ISWOW64PROCESS) == 8) ? TRUE : FALSE; } /** * This function tells if you're under Windows x64. */ BOOL IsWow64() { BOOL bIsWow64 = FALSE; if (!fnIsWow64Process) fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process"); if (fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) return FALSE; } return bIsWow64; } static BOOL MakeDirExist(LPCWSTR lpwsDir) { if (NULL == lpwsDir) return FALSE; int nLen = lstrlen(lpwsDir); if (nLen <= 0) return FALSE; LPWSTR pwsBuf = new WCHAR[MAX_PATH];; memset(pwsBuf, 0, MAX_PATH); memcpy_s(pwsBuf, MAX_PATH, lpwsDir, nLen*2); BOOL bRtn = PathFileExists(lpwsDir); if (!bRtn) { PathRemoveFileSpec(pwsBuf); if (MakeDirExist(pwsBuf)) { bRtn = CreateDirectory(lpwsDir, NULL); } } delete[] pwsBuf; return bRtn; } #ifndef SAFE_DELETE #define SAFE_DELETE(ptr) do{ if(ptr) {delete ptr; ptr=NULL;} }while(0) #endif #ifndef SAFE_CREATELP #define SAFE_CREATELP(a,b,c) a *b = new a[c + 1]; memset(b,0,sizeof(a) * (c + 1)) #endif #ifndef DELETE_LP_NULL #define DELETE_LP_NULL(x) if(x){delete [] x;x = NULL;} #endif #ifndef SAFE_CREATEARRAY #define SAFE_CREATEARRAY(a,b,c) a b[c]; memset(b,0,sizeof(a) * c); #endif #ifndef SAFE_INITLP #define SAFE_INITLP(a,b,c)b = new a[c+1]; memset(b,0,sizeof(a) * (c+1)); #endif #ifndef SAFE_lP #define SAFE_lP(a,b) a * b = NULL; #endif string ws2s(wstring str) { string s = ""; if (!str.empty()) { int nStrLen = str.length(); SAFE_CREATELP(char, lpBuff, nStrLen * 2); WideCharToMultiByte(CP_ACP, 0, str.c_str(), nStrLen, lpBuff, nStrLen * 2, 0, 0); s = lpBuff; SAFE_DELETE(lpBuff); } return s; } wstring s2ws(string str) { wstring ws = L""; if (!str.empty()) { int nStrLen = str.length(); SAFE_CREATELP(WCHAR, lpBuff, nStrLen); MultiByteToWideChar(CP_ACP, 0, str.c_str(), nStrLen, lpBuff, nStrLen); ws = lpBuff; SAFE_DELETE(lpBuff); } return ws; } // 杀掉进程-lmplayer等,杀n次 void Killlmplayer(int n) { FLOG(_T("Killlmplayer begin")); int i = n; bool bKillLePlayer = false; while (i-- > 0) { CHandle hLePlayerMutex; hLePlayerMutex.Attach(::CreateMutexW(NULL, TRUE, LMPLAYER_MUTEX_STRING)); if (GetLastError() == ERROR_ALREADY_EXISTS) { KillProcess(L"lmp.exe"); } else bKillLePlayer = true; if (bKillLePlayer) break; Sleep(1000); } FLOG(_T("Killlmplayer end")); return; } // 获取一系列变量 void GetVerAndExePath(HINSTANCE hInstance, wstring& wstrCfg, wstring& wstrCurVer, wstring& wstrNewVer, wstring& wstrRun, wstring& wstrVer, wstring& wstrRunExe, wstring& wstrVersionExe) { // 获取当前配置文件路径 WCHAR wcPath_Cfg[MAX_PATH] = { 0 }; ::GetModuleFileName(hInstance, wcPath_Cfg, MAX_PATH); PathRemoveFileSpecW(wcPath_Cfg); PathAppendW(wcPath_Cfg, L"\\Config.ini"); wstrCfg = wcPath_Cfg; // 获取当前版本号 WCHAR wcCurVer[MAX_PATH] = { 0 }; ::GetPrivateProfileStringW(L"Update", L"CurVer", L"", wcCurVer, MAX_PATH, wcPath_Cfg); wstrCurVer = wcCurVer; // 获取新版本号 WCHAR wcNewVer[MAX_PATH] = { 0 }; ::GetPrivateProfileStringW(L"Update", L"NewVer", L"", wcNewVer, MAX_PATH, wcPath_Cfg); wstrNewVer = wcNewVer; WCHAR wcPath_Run[MAX_PATH] = { 0 }; ::GetModuleFileNameW(hInstance, wcPath_Run, MAX_PATH); PathRemoveFileSpecW(wcPath_Run); wstrRun = wcPath_Run; wstrRun += L"\\run"; wstrVer = wcPath_Run; wstrVer += L"\\"; wstrVer += wcNewVer; wstrVersionExe = wstrVer; wstrVersionExe += L"\\lmp.exe"; wstrRunExe = wcPath_Run; wstrRunExe += L"\\run\\lmp.exe"; return; } // 删除run文件夹,并改名新版本文件夹为run BOOL RemoveRunAndRename(wstring wstrRun, wstring wstrVer) { FLOG(_T("RemoveRunAndRename begin")); // 删除run文件夹 SHFILEOPSTRUCTW fop; ZeroMemory(&fop, sizeof(SHFILEOPSTRUCT)); fop.wFunc = FO_DELETE; TCHAR tchTmp[MAX_PATH + 1]; ZeroMemory(tchTmp, (MAX_PATH + 1) * sizeof(TCHAR)); _tcscpy(tchTmp, wstrRun.c_str()); tchTmp[wstrRun.length()] = _T('\0'); tchTmp[wstrRun.length() + 1] = _T('\0'); fop.pFrom = tchTmp; fop.pTo = NULL; fop.fFlags |= FOF_SILENT; /*不显示进度*/ fop.fFlags |= FOF_NOERRORUI; /*不报告错误信息*/ fop.fFlags |= FOF_NOCONFIRMATION;/*不进行确认*/ fop.fFlags &= ~FOF_ALLOWUNDO; fop.hNameMappings = NULL; fop.hwnd = NULL; fop.lpszProgressTitle = NULL; int n = SHFileOperationW(&fop); for (int i = 0; i < 5; i++)// 防止异步操作改不了名字 { //文件夹不存在 if (!PathFileExistsW(wstrRun.c_str())) { // 把版本号更名为run ZeroMemory(&fop, sizeof(fop)); fop.wFunc = FO_RENAME; TCHAR tchTmp_From[MAX_PATH + 1]; ZeroMemory(tchTmp_From, (MAX_PATH + 1) * sizeof(TCHAR)); _tcscpy(tchTmp_From, wstrVer.c_str()); tchTmp_From[wstrVer.length()] = _T('\0'); tchTmp_From[wstrVer.length() + 1] = _T('\0'); fop.pFrom = tchTmp_From; TCHAR tchTmp_To[MAX_PATH + 1]; ZeroMemory(tchTmp_To, (MAX_PATH + 1) * sizeof(TCHAR)); _tcscpy(tchTmp_To, wstrRun.c_str()); tchTmp_To[wstrRun.length()] = _T('\0'); tchTmp_To[wstrRun.length() + 1] = _T('\0'); fop.pTo = tchTmp_To; fop.fFlags |= FOF_SILENT; /*不显示进度*/ fop.fFlags |= FOF_NOERRORUI; /*不报告错误信息*/ fop.fFlags |= FOF_NOCONFIRMATION;/*不进行确认*/ fop.fFlags &= ~FOF_ALLOWUNDO; fop.hNameMappings = NULL; fop.hwnd = NULL; fop.lpszProgressTitle = NULL; int n = SHFileOperationW(&fop); if (0 == n) { FLOG(_T("Rename true")); return TRUE; } else { FLOG(_T("Rename false")); return FALSE; } } Sleep(300); FLOG(_T("Sleep(300)")); } FLOG(_T("RemoveRunAndRename end")); return FALSE; } // 运行lmplayer(是否需要更新版本,是否切换成功,配置文件路径,新版本路径,旧版本exe路径,新版本exe路径,命令行) void Runlmplayer(BOOL bNeedUpdate, BOOL bSwitchOk, wstring wstrCfg, wstring wstrNewVer, wstring wstrRunExe, wstring wstrVersionExe, CString cstrCommand) { FLOG(_T("RunLeplayer begin")); if (bNeedUpdate) { FLOG(_T("bNeedUpdate 1")); if (bSwitchOk) { FLOG(_T("bSwitchOk 1")); WritePrivateProfileStringW(L"Update", L"CurVer", wstrNewVer.c_str(), wstrCfg.c_str()); if (PathFileExistsW(wstrRunExe.c_str())) ::ShellExecuteW(NULL, L"open", wstrRunExe.c_str(), cstrCommand.GetString(), NULL, SW_SHOW); else ::MessageBox(NULL, L"本地文件错误, 请重新下载安装!https://sta.vgs.lenovo.com.cn/leplayer.html", L"提示", MB_OK); // 这里报数:替换成功 CLeReport::GetInstance()->SendRTD_Eeventsync(RTD_UPDATE, "1", "4replace"); } else { FLOG(_T("bSwitchOk 0")); if (PathFileExistsW(wstrVersionExe.c_str())) ::ShellExecuteW(NULL, L"open", wstrVersionExe.c_str(), cstrCommand.GetString(), NULL, SW_SHOW); else ::MessageBox(NULL, L"本地文件错误, 请重新下载安装!https://sta.vgs.lenovo.com.cn/leplayer.html", L"提示", MB_OK); // 这里报数:替换失败 CLeReport::GetInstance()->SendRTD_Eeventsync(RTD_UPDATE, "1", "4replacefail"); } } else { FLOG(_T("bNeedUpdate 0")); if (PathFileExistsW(wstrRunExe.c_str())) ::ShellExecuteW(NULL, L"open", wstrRunExe.c_str(), cstrCommand.GetString(), NULL, SW_SHOW); else ::MessageBox(NULL, L"本地文件错误, 请重新下载安装!https://sta.vgs.lenovo.com.cn/leplayer.html", L"提示", MB_OK); } FLOG(_T("Runlmplayer end")); return; } int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { //初始化日志路径 TCHAR buff_log[MAX_PATH] = { 0 }; GetModuleFileName(NULL, buff_log, sizeof(buff_log)); wstring wslog = buff_log; wslog.append(L".log"); LOGINIT(wslog.c_str()); FLOG(_T("wWinMain begin")); FLOG(L">>>启动,命令行:%s", lpCmdLine); UNREFERENCED_PARAMETER(lpCmdLine); CString cstrCommand = lpCmdLine; // 命令行-启动新版本 if (cstrCommand.Find(L"runnew") != -1) Killlmplayer(3); wstring wstrCfg; // 配置文件路径 wstring wstrCurVer; // 当前版本号 wstring wstrNewVer; // 新版本号 wstring wstrRun; // run路径 wstring wstrVer; // 新版本路径 wstring wstrRunExe; // run下exe路径 wstring wstrVersionExe; // 新版本下exe路径 GetVerAndExePath(hInstance, wstrCfg, wstrCurVer, wstrNewVer, wstrRun, wstrVer, wstrRunExe, wstrVersionExe); BOOL bNeedUpdate = FALSE; BOOL bSwitchOk = FALSE; // 如果两个版本不一样 if (0 != StrCmpW(wstrCurVer.c_str(), wstrNewVer.c_str()) && wstrNewVer.length() != 0 && PathFileExistsW(wstrVersionExe.c_str())) { bNeedUpdate = TRUE; Killlmplayer(1); bSwitchOk = RemoveRunAndRename(wstrRun, wstrVer); } // 运行lmplayer(是否需要更新版本,是否切换成功,配置文件路径,新版本路径,旧版本exe路径,新版本exe路径,命令行) Runlmplayer(bNeedUpdate, bSwitchOk, wstrCfg, wstrNewVer, wstrRunExe, wstrVersionExe, cstrCommand); FLOG(_T("wWinMain end")); return 0; }
[ "liuhs10@lenovo.com" ]
liuhs10@lenovo.com
d9f5e53ad443bd5d09cb49e5fb0c1eca5f47682c
8d9a1ef810a2369e0285b4ee30188c8b7ba201a2
/containers/R/rclipper_serve/src/r_models.cpp
9a0bef6e1da45e53f20774e039a8cb9c8b4e78ac
[ "Apache-2.0" ]
permissive
RehanSD/clipper
7da926005b0d6774958ee77e655dda4b329b9c2c
90cde6c87d804f595a56f1614942ed620bb85ff0
refs/heads/develop
2020-03-19T23:00:14.113566
2019-03-12T17:20:04
2019-03-12T17:20:04
136,989,102
1
2
Apache-2.0
2018-07-09T19:47:32
2018-06-11T22:48:34
C++
UTF-8
C++
false
false
3,536
cpp
#include <iostream> #include "r_models.hpp" #include <Rcpp.h> #include "datatypes.hpp" namespace container { RNumericVectorModel::RNumericVectorModel(const Rcpp::Function function) : function_(function) { } std::vector<std::string> RNumericVectorModel::predict(const std::vector<DoubleVector> inputs) const { std::vector<std::string> outputs; std::vector<Rcpp::NumericVector> numeric_inputs; for(auto const& input : inputs) { Rcpp::NumericVector numeric_input(input.get_data(), input.get_data() + input.get_length()); numeric_inputs.push_back(std::move(numeric_input)); } Rcpp::List list = function_(Rcpp::wrap(numeric_inputs)); for(Rcpp::List::iterator it = list.begin(); it != list.end(); ++it) { outputs.push_back(Rcpp::as<std::string>(*it)); } return outputs; } RIntegerVectorModel::RIntegerVectorModel(const Rcpp::Function function) : function_(function) { } std::vector<std::string> RIntegerVectorModel::predict(const std::vector<IntVector> inputs) const { std::vector<std::string> outputs; std::vector<Rcpp::IntegerVector> integer_inputs; for(auto const& input : inputs) { Rcpp::IntegerVector integer_input(input.get_data(), input.get_data() + input.get_length()); integer_inputs.push_back(std::move(integer_input)); } Rcpp::List list = function_(Rcpp::wrap(integer_inputs)); for(Rcpp::List::iterator it = list.begin(); it != list.end(); ++it) { outputs.push_back(Rcpp::as<std::string>(*it)); } return outputs; } RRawVectorModel::RRawVectorModel(const Rcpp::Function function) : function_(function) { } std::vector<std::string> RRawVectorModel::predict(const std::vector<ByteVector> inputs) const { std::vector<std::string> outputs; std::vector<Rcpp::RawVector> raw_inputs; for(auto const& input : inputs) { Rcpp::RawVector raw_input(input.get_data(), input.get_data() + input.get_length()); raw_inputs.push_back(std::move(raw_input)); } Rcpp::List list = function_(Rcpp::wrap(raw_inputs)); for(Rcpp::List::iterator it = list.begin(); it != list.end(); ++it) { outputs.push_back(Rcpp::as<std::string>(*it)); } return outputs; } RCharacterVectorModel::RCharacterVectorModel(const Rcpp::Function function) : function_(function) { } std::vector<std::string> RCharacterVectorModel::predict(const std::vector<SerializableString> inputs) const { std::vector<std::string> outputs; std::vector<Rcpp::RawVector> raw_inputs; for(auto const& input : inputs) { Rcpp::RawVector raw_input(input.get_data(), input.get_data() + input.get_length()); raw_inputs.push_back(std::move(raw_input)); } Rcpp::List list = function_(Rcpp::wrap(raw_inputs)); for(Rcpp::List::iterator it = list.begin(); it != list.end(); ++it) { outputs.push_back(Rcpp::as<std::string>(*it)); } return outputs; } RSerializedInputModel::RSerializedInputModel(const Rcpp::Function function) : function_(function) { } std::vector<std::string> RSerializedInputModel::predict(const std::vector<SerializableString> inputs) const { std::vector<std::string> outputs; std::vector<Rcpp::RawVector> serialized_inputs; for(auto const& input : inputs) { Rcpp::RawVector serialized_input(input.get_data(), input.get_data() + input.get_length()); serialized_inputs.push_back(std::move(serialized_input)); } Rcpp::List list = function_(Rcpp::wrap(serialized_inputs)); for(Rcpp::List::iterator it = list.begin(); it != list.end(); ++it) { outputs.push_back(Rcpp::as<std::string>(*it)); } return outputs; } } // namespace container
[ "dscrankshaw@gmail.com" ]
dscrankshaw@gmail.com
87c3a393d2b68de573da304c5ceec39158dc8672
f0de6c3ffc999616a0a9580a8a3678aef283cdf5
/chromeos/components/tether/disconnect_tethering_request_sender_impl.cc
a25b705621f5d75fb0d4519b168a1b6327433d8b
[ "BSD-3-Clause" ]
permissive
r00tk1ts/chromium
db18e3940667da7aa76baff69c229788baa5d706
a3cef2a9d2ba64068c1fe7de81500d9d33cf4f87
refs/heads/master
2023-02-23T04:57:23.997581
2018-03-28T10:54:29
2018-03-28T10:54:29
127,127,996
1
0
null
2018-03-28T11:07:29
2018-03-28T11:07:28
null
UTF-8
C++
false
false
5,140
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/components/tether/disconnect_tethering_request_sender_impl.h" #include <memory> #include "base/memory/ptr_util.h" #include "chromeos/components/tether/ble_connection_manager.h" #include "chromeos/components/tether/tether_host_fetcher.h" #include "components/proximity_auth/logging/logging.h" namespace chromeos { namespace tether { // static DisconnectTetheringRequestSenderImpl::Factory* DisconnectTetheringRequestSenderImpl::Factory::factory_instance_ = nullptr; // static std::unique_ptr<DisconnectTetheringRequestSender> DisconnectTetheringRequestSenderImpl::Factory::NewInstance( BleConnectionManager* ble_connection_manager, TetherHostFetcher* tether_host_fetcher) { if (!factory_instance_) factory_instance_ = new Factory(); return factory_instance_->BuildInstance(ble_connection_manager, tether_host_fetcher); } // static void DisconnectTetheringRequestSenderImpl::Factory::SetInstanceForTesting( Factory* factory) { factory_instance_ = factory; } std::unique_ptr<DisconnectTetheringRequestSender> DisconnectTetheringRequestSenderImpl::Factory::BuildInstance( BleConnectionManager* ble_connection_manager, TetherHostFetcher* tether_host_fetcher) { return base::WrapUnique(new DisconnectTetheringRequestSenderImpl( ble_connection_manager, tether_host_fetcher)); } DisconnectTetheringRequestSenderImpl::DisconnectTetheringRequestSenderImpl( BleConnectionManager* ble_connection_manager, TetherHostFetcher* tether_host_fetcher) : ble_connection_manager_(ble_connection_manager), tether_host_fetcher_(tether_host_fetcher), weak_ptr_factory_(this) {} DisconnectTetheringRequestSenderImpl::~DisconnectTetheringRequestSenderImpl() { for (auto const& entry : device_id_to_operation_map_) entry.second->RemoveObserver(this); } void DisconnectTetheringRequestSenderImpl::SendDisconnectRequestToDevice( const std::string& device_id) { if (base::ContainsKey(device_id_to_operation_map_, device_id)) return; num_pending_host_fetches_++; tether_host_fetcher_->FetchTetherHost( device_id, base::Bind(&DisconnectTetheringRequestSenderImpl::OnTetherHostFetched, weak_ptr_factory_.GetWeakPtr(), device_id)); } bool DisconnectTetheringRequestSenderImpl::HasPendingRequests() { return !device_id_to_operation_map_.empty() || num_pending_host_fetches_ > 0; } void DisconnectTetheringRequestSenderImpl::OnTetherHostFetched( const std::string& device_id, std::unique_ptr<cryptauth::RemoteDevice> tether_host) { num_pending_host_fetches_--; DCHECK(num_pending_host_fetches_ >= 0); if (!tether_host) { PA_LOG(ERROR) << "Could not fetch device with ID " << cryptauth::RemoteDevice::TruncateDeviceIdForLogs(device_id) << ". Unable to send DisconnectTetheringRequest."; return; } PA_LOG(INFO) << "Attempting to send DisconnectTetheringRequest to device " << "with ID " << cryptauth::RemoteDevice::TruncateDeviceIdForLogs(device_id); std::unique_ptr<DisconnectTetheringOperation> disconnect_tethering_operation = DisconnectTetheringOperation::Factory::NewInstance( *tether_host, ble_connection_manager_); // Add to the map. device_id_to_operation_map_.emplace( device_id, std::move(disconnect_tethering_operation)); // Start the operation; OnOperationFinished() will be called when finished. device_id_to_operation_map_.at(device_id)->AddObserver(this); device_id_to_operation_map_.at(device_id)->Initialize(); } void DisconnectTetheringRequestSenderImpl::OnOperationFinished( const std::string& device_id, bool success) { if (success) { PA_LOG(INFO) << "Successfully sent DisconnectTetheringRequest to device " << "with ID " << cryptauth::RemoteDevice::TruncateDeviceIdForLogs(device_id); } else { PA_LOG(ERROR) << "Failed to send DisconnectTetheringRequest to device " << "with ID " << cryptauth::RemoteDevice::TruncateDeviceIdForLogs( device_id); } bool had_pending_requests = HasPendingRequests(); if (base::ContainsKey(device_id_to_operation_map_, device_id)) { // Regardless of success/failure, unregister as a listener and delete the // operation. device_id_to_operation_map_.at(device_id)->RemoveObserver(this); device_id_to_operation_map_.erase(device_id); } else { PA_LOG(ERROR) << "Operation finished, but device with ID " << cryptauth::RemoteDevice::TruncateDeviceIdForLogs(device_id) << " was not being tracked by DisconnectTetheringRequestSender."; } // If there were pending reqests but now there are none, notify the Observers. if (had_pending_requests && !HasPendingRequests()) NotifyPendingDisconnectRequestsComplete(); } } // namespace tether } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
8653926be38dd078d7012422cb4253d9e71392df
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/printscan/faxsrv/clientconsole/errordlg.h
39bc6034e1c0daa5f33ab9970e72aba766b5772d
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
2,056
h
#if !defined(AFX_ERRORDLG_H__E6A84A73_2471_4E02_848B_2263C157998A__INCLUDED_) #define AFX_ERRORDLG_H__E6A84A73_2471_4E02_848B_2263C157998A__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ErrorDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // CErrorDlg dialog class CErrorDlg : public CDialog { // Construction public: CErrorDlg( DWORD dwWin32ErrCode, DWORD dwFileId, int iLineNumber ); // Dialog Data //{{AFX_DATA(CErrorDlg) enum { IDD = IDD_ERROR }; CStatic m_staticSeperator; BOOL m_bDetails; CString m_cstrDetails; CString m_cstrErrorText; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CErrorDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CErrorDlg) afx_msg void OnDetails(); virtual void OnOK(); virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: void FillErrorText (); CRect m_rcBig; CRect m_rcSmall; DWORD m_dwWin32ErrCode; int m_iLineNumber; DWORD m_dwFileId; }; #define PopupError(err) { CMainFrame *pFrm = GetFrm(); \ if (pFrm) \ pFrm->PostMessage (WM_POPUP_ERROR, \ WPARAM(err), \ MAKELPARAM(__LINE__, __FILE_ID__)); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ERRORDLG_H__E6A84A73_2471_4E02_848B_2263C157998A__INCLUDED_)
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
c6291f540bcfc75251249df6bbfd25dc5077420c
f85fdd8b8e779ec564abb52876b82ebea9337bcf
/hw7-1/sorted_array_main.cc
ff3e66e0c13a0bae7d8094a8ce76a892b8f99c9a
[ "MIT" ]
permissive
revsic/HYU-ITE1015
0a02b5ee014d9cec8b83fed6ef55a5515afea17f
b2d2d210f4b936be0fd94bd258e15b6c16c432fe
refs/heads/master
2020-04-06T09:11:54.463873
2019-03-07T08:36:00
2019-03-07T08:36:00
157,332,436
1
0
null
null
null
null
UTF-8
C++
false
false
1,051
cc
#include "sorted_array.h" #include <iostream> #include <sstream> int main() { std::string given; SortedArray sorted_array; while (true) { std::cin >> given; if (given == "ascend") { for (int i : sorted_array.GetSortedAscending()) { std::cout << i << ' '; } std::cout << std::endl; } else if (given == "descend") { for (int i : sorted_array.GetSortedDescending()) { std::cout << i << ' '; } std::cout << std::endl; } else if (given == "max") { std::cout << sorted_array.GetMax() << std::endl; } else if (given == "min") { std::cout << sorted_array.GetMin() << std::endl; } else if (given == "quit") { break; } else { std::stringstream sstream(given); int num = 0; sstream >> num; sorted_array.AddNumber(num); } } return 0; }
[ "revsic99@gmail.com" ]
revsic99@gmail.com
4ba411b8aec7235aee157a1ab5700da8a96e0a80
6198a19968f36832cdeed2721f09bd9146e55d3f
/Linkit7697_RobotShieldV2_TANK_GO_MP3_V410/Linkit7697_RobotShieldV2_TANK_GO_MP3_V410.ino
52221a7b7899bde2903763983f611d2d5c3593cb
[]
no_license
GeorgeChiou/Robot-Shield-V2.0
3ba3b2612148353fa29968fd9a325db6dd1bc2eb
04549a8a0c7a9fec60240f8116baeb80a843eadd
refs/heads/master
2021-05-01T13:09:37.452676
2020-01-01T09:16:11
2020-01-01T09:16:11
121,072,400
16
5
null
null
null
null
UTF-8
C++
false
false
20,440
ino
// 最後編輯 2019-5-08 by ShinWei Chiou // 移除 搖桿 提供比賽 // 中文化 提供比賽 // 最後編輯 2019-5-06 by ShinWei Chiou // 移除 修復按鈕 提供比賽 // 最後編輯 2018-4-18 by ShinWei Chiou // 搖桿控制 LRemoteJoyStick // 最後編輯 2018-4-15 by ShinWei Chiou // 橫向控制 Change to Use RC_LANDSCAPE // 最後編輯 2018-4-02 by Mason // Add tank_name = "TANK"+ tank_address.substring(0,2) +tank_address.substring(3,5); // 最後編輯 2018-3-27 by ShinWei Chiou // DFPlayer mini mp3 module. // github as default source provider // https://github.com/DFRobot/DFPlayer-Mini-mp3 // For Linkit-7697 + Robot Shield V2.1 // Left Motor : P10 P12,Right Motor : P13 P17 // Servo : P5 // Buzzer : P14 // IR Test Button : P6 // IR Receiver : P9 // IR LED : P11 , P15 // DFplayer TX : P4 #include <Servo.h> #include <LRemote.h> #include <SoftwareSerial.h> #define Right_Wheel_A 12 #define Right_Wheel_B 10 #define Left_Wheel_A 17 #define Left_Wheel_B 13 #define Buzzer_Pin 14 #define Servo_Pin 5 #define IR_LED_Pin1 11 #define IR_LED_Pin2 15 #define IR_Button_Pin 6 #define IR_Receiver_Pin 9 // DFplayer #include <DFPlayer_Mini_Mp3.h> // On LinkIt 7697, the RX pin must be one of the EINT pins. // There are no limitations on TX pin. SoftwareSerial mp3Serial(2, 4); // RX, TX // Label LRemoteLabel Titlelabel; LRemoteLabel HPlabelT; LRemoteLabel HPlabelS; LRemoteLabel AMlabelT; LRemoteLabel AMlabelS; // JoyStick LRemoteJoyStick joystickDirection; // Button LRemoteButton forwardbutton; LRemoteButton backwardbutton; LRemoteButton turnleftbutton; LRemoteButton turnrightbutton; LRemoteButton firebutton; LRemoteButton reloadbutton; LRemoteButton repairsbutton; LRemoteSlider turretslider; LRemoteButton turretcenterbutton; LRemoteButton musicbutton1; LRemoteButton musicbutton2; LRemoteButton musicbutton3; LRemoteButton musicbutton4; LRemoteButton musicbutton5; LRemoteButton musicbutton6; LRemoteButton musicbutton7; LRemoteButton musicbutton8; LRemoteButton volmaxbutton; LRemoteButton volminbutton; LRemoteButton mutebutton; // Servo const int TurretTurnCenter = 90; const int TurretTurnMax = 160; const int TurretTurnMin = 10; int Turret_Turn_Value = TurretTurnCenter; // IR Battle System const int Damage_Value = 25; const int Tank_AM_MaxValue = 5; int Tank_HP_Value = 100; int Tank_AM_Value = Tank_AM_MaxValue; int IR_Value = 0; // Music const int VolumeMax = 30; const int VolumeMin = 5; int Volume_Value = 15; // Create Servo object Servo TurretServo; /*------------------------------------------------------------*/ // IR Send Code 38kHz void IR_Send_Code_1() { for (int i16t = 0; i16t < 16; i16t++) { for (int i37k = 0; i37k < 125; i37k++) { digitalWrite(IR_LED_Pin1, HIGH); delayMicroseconds(12); digitalWrite(IR_LED_Pin1, LOW); delayMicroseconds(12); } delay(2); } } void IR_Send_Code_2() { for (int i16t = 0; i16t < 16; i16t++) { for (int i37k = 0; i37k < 125; i37k++) { digitalWrite(IR_LED_Pin2, HIGH); delayMicroseconds(12); digitalWrite(IR_LED_Pin2, LOW); delayMicroseconds(12); } delay(2); } } /*------------------------------------------------------------*/ // Ray Gun Sound void Ray_Gun_Sound() { for (int i = 0; i < 300; i++) { digitalWrite(Buzzer_Pin, HIGH); delayMicroseconds(i); digitalWrite(Buzzer_Pin, LOW); delayMicroseconds(i); } } /*------------------------------------------------------------*/ void Move_Forward() { digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, LOW); digitalWrite(Left_Wheel_B, HIGH); } void Move_Backward() { digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(Left_Wheel_B, LOW); } void Move_TurnRight() { digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(Left_Wheel_B, LOW); } void Move_TurnLeft() { digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, LOW); digitalWrite(Left_Wheel_B, HIGH); } void Motor_Break() { digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(13, HIGH); delay(100); digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, LOW); digitalWrite(Left_Wheel_B, LOW); } void Move_Fire() { digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(13, LOW); delay(50); digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, LOW); digitalWrite(13, HIGH); delay(50); digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(Left_Wheel_B, HIGH); } void Move_Damage() { digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(Left_Wheel_B, LOW); delay(100); digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, LOW); digitalWrite(Left_Wheel_B, HIGH); delay(100); digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(Left_Wheel_B, HIGH); delay(50); digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, LOW); digitalWrite(Left_Wheel_B, LOW); TurretServo.write(60); delay(300); TurretServo.write(120); delay(300); TurretServo.write(Turret_Turn_Value); delay(300); } /*------------------------------------------------------------*/ void SteerDirection(int x, int y) { const int x_termP = 50; const int x_termN = -50; const int y_termP = 10; const int y_termN = -10; if (y > y_termP ) { if (x >= x_termP) { Move_TurnRight(); } else if (x <= x_termN) { Move_TurnLeft(); } else { Move_Forward(); } } else if (y < y_termN) { if (x >= x_termP) { Move_TurnRight(); } else if (x <= x_termN) { Move_TurnLeft(); } else { Move_Backward(); } } else { if (x >= x_termP) { Move_TurnRight(); } else if (x <= x_termN) { Move_TurnLeft(); } else { Motor_Break(); } } } /*------------------------------------------------------------*/ void setup() { // Initialize serial communications at 9600 bps: Serial.begin(9600); // Set the data rate for the SoftwareSerial port mp3Serial.begin(9600); // Add for DFplayer mp3_set_serial (mp3Serial); // set Serial for DFPlayer-mini mp3 module // Motor PIN Set pinMode(10, OUTPUT); pinMode(12, OUTPUT); pinMode(13, OUTPUT); pinMode(17, OUTPUT); // IR PIN Set pinMode(IR_Receiver_Pin, INPUT); pinMode(IR_Button_Pin, INPUT); pinMode(IR_LED_Pin1, OUTPUT); pinMode(IR_LED_Pin2, OUTPUT); // Initialize Servo TurretServo.attach(Servo_Pin); TurretServo.write(90); // Initialize BLE subsystem & get BLE address LBLE.begin(); while (!LBLE.ready()) { delay(100); } Serial.print("Device Address = ["); LBLEAddress ble_address; String tank_address; ble_address = LBLE.getDeviceAddress(); tank_address = ble_address.toString(); Serial.print(tank_address); Serial.println("]"); String tank_name; tank_name = "TANK" + tank_address.substring(0, 2) + tank_address.substring(3, 5); // Setup the Remote Control's Name LRemote.setName(tank_name); // Setup the Remote Control's UI canvas LRemote.setOrientation(RC_LANDSCAPE); LRemote.setGrid(16, 9); // Add a text Title label Titlelabel.setText("Infrared Battle Tank V4.1"); Titlelabel.setPos(2, 0); Titlelabel.setSize(14, 1); Titlelabel.setColor(RC_GREY); LRemote.addControl(Titlelabel); // Add a text HP label HPlabelT.setText("血量"); HPlabelT.setPos(0, 1); HPlabelT.setSize(2, 1); HPlabelT.setColor(RC_GREY); LRemote.addControl(HPlabelT); HPlabelS.setText("100%"); HPlabelS.setPos(0, 2); HPlabelS.setSize(2, 1); HPlabelS.setColor(RC_GREY); LRemote.addControl(HPlabelS); // Add a text AMMO label AMlabelT.setText("彈量"); AMlabelT.setPos(5, 1); AMlabelT.setSize(2, 1); AMlabelT.setColor(RC_GREY); LRemote.addControl(AMlabelT); AMlabelS.setText(String(Tank_AM_Value, 10)); AMlabelS.setPos(5, 2); AMlabelS.setSize(2, 1); AMlabelS.setColor(RC_GREY); LRemote.addControl(AMlabelS); // Add Joystick Direction //joystickDirection.setPos(0, 3); //joystickDirection.setSize(7, 6); //joystickDirection.setColor(RC_BLUE); //LRemote.addControl(joystickDirection); // Add a Forward button forwardbutton.setText("前進"); forwardbutton.setPos(2, 3); forwardbutton.setSize(3, 3); forwardbutton.setColor(RC_BLUE); LRemote.addControl(forwardbutton); // Add a Backward button backwardbutton.setText("後退"); backwardbutton.setPos(2, 6); backwardbutton.setSize(3, 3); backwardbutton.setColor(RC_BLUE); LRemote.addControl(backwardbutton); // Add a TurnLeft button turnleftbutton.setText("左轉"); turnleftbutton.setPos(0, 4); turnleftbutton.setSize(2, 4); turnleftbutton.setColor(RC_BLUE); LRemote.addControl(turnleftbutton); // Add a TurnRight button turnrightbutton.setText("右轉"); turnrightbutton.setPos(5, 4); turnrightbutton.setSize(2, 4); turnrightbutton.setColor(RC_BLUE); LRemote.addControl(turnrightbutton); // Add a Reload button reloadbutton.setText("塡彈"); reloadbutton.setPos(13, 1); reloadbutton.setSize(3, 2); reloadbutton.setColor(RC_GREEN); LRemote.addControl(reloadbutton); // Add a Fire button firebutton.setText("發射"); firebutton.setPos(13, 3); //firebutton.setSize(3, 4); firebutton.setSize(3, 6); firebutton.setColor(RC_PINK); LRemote.addControl(firebutton); // Add a Repairs button //repairsbutton.setText("REPAIRS"); //repairsbutton.setPos(13, 7); //repairsbutton.setSize(3, 2); //repairsbutton.setColor(RC_GREEN); //LRemote.addControl(repairsbutton); // Add a Turret center button turretcenterbutton.setText("砲塔回正"); turretcenterbutton.setPos(2, 1); turretcenterbutton.setSize(3, 2); turretcenterbutton.setColor(RC_ORANGE); LRemote.addControl(turretcenterbutton); // Add a Turret slider turretslider.setText("砲塔旋轉"); turretslider.setPos(7, 6); turretslider.setSize(6, 3); turretslider.setColor(RC_ORANGE); turretslider.setValueRange(TurretTurnMin, TurretTurnMax, TurretTurnCenter); LRemote.addControl(turretslider); // Add a Music button musicbutton1.setText("♫1"); musicbutton1.setPos(8, 1); musicbutton1.setSize(2, 1); musicbutton1.setColor(RC_GREY); LRemote.addControl(musicbutton1); musicbutton2.setText("♫2"); musicbutton2.setPos(8, 2); musicbutton2.setSize(2, 1); musicbutton2.setColor(RC_GREY); LRemote.addControl(musicbutton2); musicbutton3.setText("♫3"); musicbutton3.setPos(8, 3); musicbutton3.setSize(2, 1); musicbutton3.setColor(RC_GREY); LRemote.addControl(musicbutton3); musicbutton4.setText("♫4"); musicbutton4.setPos(8, 4); musicbutton4.setSize(2, 1); musicbutton4.setColor(RC_GREY); LRemote.addControl(musicbutton4); musicbutton5.setText("♫5"); musicbutton5.setPos(10, 1); musicbutton5.setSize(2, 1); musicbutton5.setColor(RC_GREY); LRemote.addControl(musicbutton5); musicbutton6.setText("♫6"); musicbutton6.setPos(10, 2); musicbutton6.setSize(2, 1); musicbutton6.setColor(RC_GREY); LRemote.addControl(musicbutton6); musicbutton7.setText("♫7"); musicbutton7.setPos(10, 3); musicbutton7.setSize(2, 1); musicbutton7.setColor(RC_GREY); LRemote.addControl(musicbutton7); musicbutton8.setText("♫8"); musicbutton8.setPos(10, 4); musicbutton8.setSize(2, 1); musicbutton8.setColor(RC_GREY); LRemote.addControl(musicbutton8); volmaxbutton.setText("大聲"); volmaxbutton.setPos(8, 5); volmaxbutton.setSize(2, 1); volmaxbutton.setColor(RC_GREY); LRemote.addControl(volmaxbutton); volminbutton.setText("小聲"); volminbutton.setPos(10, 5); volminbutton.setSize(2, 1); volminbutton.setColor(RC_GREY); LRemote.addControl(volminbutton); mutebutton.setText("靜音"); mutebutton.setPos(0, 0); mutebutton.setSize(2, 1); mutebutton.setColor(RC_GREY); LRemote.addControl(mutebutton); // Start broadcasting our remote contoller LRemote.begin(); Serial.println("LRemote begin ..."); } /*------------------------------------------------------------*/ void loop() { // BLE central device, e.g. an mobile app if (!LRemote.connected()) { Serial.println("Waiting for connection ..."); delay(10); } else { delay(10); } // Process the incoming BLE write request LRemote.process(); // Tank HP Limit if (Tank_HP_Value >= 1) { /*----------------------------------*/ // Move //if (joystickDirection.isValueChanged()) //{ // auto dir = joystickDirection.getValue(); // // Serial.println(dir); // // SteerDirection(dir.x, dir.y); //} if (forwardbutton.getValue()) { Move_Forward(); } else if (backwardbutton.getValue()) { Move_Backward(); } else if (turnleftbutton.getValue()) { Move_TurnLeft(); } else if (turnrightbutton.getValue()) { Move_TurnRight(); } else { Motor_Break(); } /*----------------------------------*/ // Turret if (turretcenterbutton.isValueChanged()) { if (turretcenterbutton.getValue() == 1) { Turret_Turn_Value = TurretTurnCenter; TurretServo.write(TurretTurnCenter); delay(100); } } if (turretslider.isValueChanged()) { Titlelabel.updateText("Tank Go!"); Turret_Turn_Value = 180 - turretslider.getValue(); TurretServo.write(Turret_Turn_Value); } /*----------------------------------*/ // Fire if (firebutton.isValueChanged()) { if (firebutton.getValue() == 1) { if ( Tank_AM_Value >= 1) { mp3_set_volume (Volume_Value); delay(10); mp3_play (1); Titlelabel.updateText("!!! FIRE !!!"); Tank_AM_Value--; IR_Send_Code_1(); IR_Send_Code_2(); Move_Fire(); delay (700); mp3_stop (); } if ( Tank_AM_Value <= 0) { Titlelabel.updateText("!!! Reload !!!"); } AMlabelS.updateText(String(Tank_AM_Value, 10)); Serial.print("Tank_AT_Value = "); Serial.println(Tank_AM_Value); } else { Motor_Break(); } } /*----------------------------------*/ // Reload if (reloadbutton.isValueChanged()) { if (reloadbutton.getValue() == 1) { if ( Tank_AM_Value < Tank_AM_MaxValue) { mp3_set_volume (Volume_Value); delay(10); mp3_play (3); Titlelabel.updateText("Please Wait ..."); for (int iAM = Tank_AM_Value; iAM <= Tank_AM_MaxValue; iAM++) { Tank_AM_Value = iAM; AMlabelS.updateText(String(Tank_AM_Value, 10)); delay(200); } Titlelabel.updateText("Completed !"); Serial.println("Reload Tank_AT_Value"); delay(100); mp3_stop (); } else { Titlelabel.updateText("Full Ammo !"); } } } } /*----------------------------------*/ // IR Test Button if (digitalRead(IR_Button_Pin) == HIGH) { IR_Send_Code_1(); Ray_Gun_Sound(); IR_Send_Code_2(); Serial.println("IR Send Test Code"); } /*----------------------------------*/ // IR Battle System if (digitalRead(IR_Receiver_Pin) == LOW) { IR_Value = pulseIn(IR_Receiver_Pin, LOW); if ( IR_Value >= 2700 && IR_Value <= 3400 ) { mp3_set_volume (Volume_Value); delay(10); mp3_play (2); delay (100); Titlelabel.updateText("Damage !"); if ( Tank_HP_Value >= 1) { Tank_HP_Value = Tank_HP_Value - Damage_Value; Move_Damage(); } if ( Tank_HP_Value <= Damage_Value) { Titlelabel.updateText("!!! Repairs !!!"); } HPlabelS.updateText(String(Tank_HP_Value, 10) + "%"); Serial.print("IR_Value = "); Serial.print(IR_Value); Serial.print(" , Tank_HP_Value = "); Serial.println(Tank_HP_Value); delay (100); mp3_stop (); } } /*----------------------------------*/ // Repairs if (repairsbutton.isValueChanged()) { if (repairsbutton.getValue() == 1) { if ( Tank_HP_Value < 100) { mp3_set_volume (Volume_Value); delay(10); mp3_play (4); Titlelabel.updateText("Please Wait ..."); for (int iHP = Tank_HP_Value; iHP <= 100; iHP++) { Tank_HP_Value = iHP; HPlabelS.updateText(String(Tank_HP_Value, 10) + "%"); delay(20); } Titlelabel.updateText("Completed !"); Serial.println("Repair Tank_HP_Value"); delay(100); mp3_stop (); } else { Titlelabel.updateText("No Damage !"); } } } /*----------------------------------*/ // Mute Music if (mutebutton.isValueChanged()) { if (mutebutton.getValue() == 1) { Titlelabel.updateText("!!! Mute !!!"); mp3_stop (); } } // Adjust Volume Music if (volmaxbutton.isValueChanged()) { if (volmaxbutton.getValue() == 1) { if (Volume_Value < 30) { Volume_Value = Volume_Value + 5; Titlelabel.updateText("Volume = " + String(Volume_Value, 10)); mp3_set_volume (Volume_Value); delay(10); } else { Titlelabel.updateText("Volume = Max"); } } } if (volminbutton.isValueChanged()) { if (volminbutton.getValue() == 1) { if (Volume_Value > 5) { Volume_Value = Volume_Value - 5; Titlelabel.updateText("Volume = " + String(Volume_Value, 10)); mp3_set_volume (Volume_Value); delay(10); } else { Titlelabel.updateText("Volume = Min"); } } } /*----------------------------------*/ // Play Music 1 if (musicbutton1.isValueChanged()) { if (musicbutton1.getValue() == 1) { Titlelabel.updateText("Katyusha"); mp3_set_volume (Volume_Value); delay(10); mp3_play (10); } } // Play Music 2 if (musicbutton2.isValueChanged()) { if (musicbutton2.getValue() == 1) { Titlelabel.updateText("Panzerlied"); mp3_set_volume (Volume_Value); delay(10); mp3_play (11); } } // Play Music 3 if (musicbutton3.isValueChanged()) { if (musicbutton3.getValue() == 1) { Titlelabel.updateText("Marching"); mp3_set_volume (Volume_Value); delay(10); mp3_play (12); } } // Play Music 4 if (musicbutton4.isValueChanged()) { if (musicbutton4.getValue() == 1) { Titlelabel.updateText("Engine Start !"); mp3_set_volume (Volume_Value); delay(10); mp3_play (13); } } // Play Music 5 if (musicbutton5.isValueChanged()) { if (musicbutton5.getValue() == 1) { Titlelabel.updateText("No File !"); mp3_set_volume (Volume_Value); delay(10); mp3_play (14); } } // Play Music 6 if (musicbutton6.isValueChanged()) { if (musicbutton6.getValue() == 1) { Titlelabel.updateText("No File !"); mp3_set_volume (Volume_Value); delay(10); mp3_play (15); } } // Play Music 7 if (musicbutton7.isValueChanged()) { if (musicbutton7.getValue() == 1) { Titlelabel.updateText("No File !"); mp3_set_volume (Volume_Value); delay(10); mp3_play (16); } } // Play Music 8 if (musicbutton8.isValueChanged()) { if (musicbutton8.getValue() == 1) { Titlelabel.updateText("No File !"); mp3_set_volume (Volume_Value); delay(10); mp3_play (17); } } }
[ "shinwei@iMac-4072.local" ]
shinwei@iMac-4072.local
3944a8ffb68706b8baf7fe597cf6135fbb785792
e7ef7af13648aac13fc39c8f065c53ac7d387505
/libyara.NET/GCHandleWrapper.h
87d54abbbf9bac4f32afa47b22616b2dd334086a
[]
permissive
microsoft/libyara.NET
a09e4f6a42694fefacf7188934c1aa9d253efb96
e5c3524ab82689640c93ce8486d4f386f5751589
refs/heads/master
2023-06-22T06:20:11.322873
2023-06-19T21:37:39
2023-06-19T21:37:39
61,913,596
31
17
BSD-3-Clause
2023-06-19T21:37:41
2016-06-24T21:34:18
C++
UTF-8
C++
false
false
985
h
#pragma once #include <stdexcept> using namespace System; using namespace System::Runtime::InteropServices; namespace libyaraNET { /// <summary> /// RAII wrapper for a GCHandle that frees the handle on scope exit. /// </summary> ref class GCHandleWrapper { GCHandle handle; public: /// <summary> /// Create a GCHandle that points to the specified object. /// </summary> GCHandleWrapper(Object^ value) { handle = GCHandle::Alloc(value); } ~GCHandleWrapper() { handle.Free(); } /// <summary> /// Get the underlying GCHandle /// </summary> GCHandle^ GetHandle() { return handle; } /// <summary> /// Get the underlying GCHandle as a void* /// </summary> void* GetPointer() { return GCHandle::ToIntPtr(handle).ToPointer(); } }; }
[ "kylereed@microsoft.com" ]
kylereed@microsoft.com
7bdcabd191590e83c10f09b372428447b2184da8
e50b5f066628ef65fd7f79078b4b1088f9d11e87
/llvm/tools/clang/test/PCH/cxx-char-literal.cpp
d540720307dd7723342b3fc1c460d2c390120df8
[ "NCSA" ]
permissive
uzleo/coast
1471e03b2a1ffc9883392bf80711e6159917dca1
04bd688ac9a18d2327c59ea0c90f72e9b49df0f4
refs/heads/master
2020-05-16T11:46:24.870750
2019-04-23T13:57:53
2019-04-23T13:57:53
183,025,687
0
0
null
2019-04-23T13:52:28
2019-04-23T13:52:27
null
UTF-8
C++
false
false
409
cpp
// RUN: %clang_cc1 -emit-pch -std=c++1z -o %t %s // RUN: %clang_cc1 -std=c++1z -x ast -ast-print %t | FileCheck %s // Ensure that character literals are properly surfaced through PCH. char a = '0'; // CHECK: char a = '0'; char b = L'1'; // CHECK: char b = L'1'; char c = u8'2'; // CHECK: char c = u8'2'; char d = U'3'; // CHECK: char d = U'3'; char e = u'4'; // CHECK: char e = u'4';
[ "jeffrey.goeders@gmail.com" ]
jeffrey.goeders@gmail.com
94352804703f0f7be19cff404381dec5ba7ab566
719ca866888053c63c4f76207f3792b0a46b5c8a
/Libraries/FiringRateSim/PacemakerNeuron.h
da27a8c42be746e490a18e4d21c57b03529469f9
[]
no_license
silicondosa/AnimatLabPublicSource
08e71f28c221881bf8527bb95df8cf530c455ca0
c5b23f8898513582afb7891eb994a7bd40a89f08
refs/heads/master
2023-03-20T02:16:00.390767
2016-10-04T18:17:59
2016-10-04T18:17:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,789
h
/** \file PacemakerNeuron.h \brief Declares the pacemaker neuron class. **/ #pragma once namespace FiringRateSim { namespace Neurons { class FAST_NET_PORT PacemakerNeuron : public Neuron { protected: /// The hyperpolarizing current that brings the membrane potential back down after it has been firing. float m_fltIl; /// The slope of the linear function that is used to calculate the length of time that Il current remains active. float m_fltIh; /// A lower steady state threshold. If the steady state voltage of the neuron goes below this value then the Il current is locked on until that voltage rises above this threshold. float m_fltVssm; /// The slope of the linear function that is used to calculate the length of time that Il current remains active. float m_fltMtl; /// The intercept of the linear function that is used to calculate the length of time that Il current remains active. float m_fltBtl; /// This is the length of time that the Ih current remains active. float m_fltTh; /// Time that the current intrinsic current mode is active. float m_fltITime; /// The interburst interval float m_fltInterburstInterval; /// The steady state voltage float m_fltVss; /// Type of the intrinsic current that is active. (HI or LOW) unsigned char m_iIntrinsicType; void HighCurrentOn(); void LowCurrentOn(float fltVss); virtual float CalculateIntrinsicCurrent(FiringRateModule *lpModule, float fltInputCurrent); public: PacemakerNeuron(); virtual ~PacemakerNeuron(); float Il(); void Il(float fltVal); float Ih(); void Ih(float fltVal); float Vssm(); void Vssm(float fltVal); float Mtl(); void Mtl(float fltVal); float Btl(); void Btl(float fltVal); float Th(); void Th(float fltVal); float ITime(); void ITime(float fltVal); unsigned char IntrinsicType(); void IntrinsicType(unsigned char iVal); virtual unsigned char NeuronType(); virtual void Copy(CStdSerialize *lpSource); virtual void ResetSimulation(); virtual void StepSimulation(); virtual float *GetDataPointer(const std::string &strDataType); virtual bool SetData(const std::string &strDataType, const std::string &strValue, bool bThrowError = true); virtual void QueryProperties(CStdPtrArray<TypeProperty> &aryProperties); #pragma region SnapshotMethods virtual long CalculateSnapshotByteSize(); virtual void SaveKeyFrameSnapshot(byte *aryBytes, long &lIndex); virtual void LoadKeyFrameSnapshot(byte *aryBytes, long &lIndex); #pragma endregion virtual void Load(CStdXml &oXml); }; } //Neurons } //FiringRateSim
[ "dcofer@NeuroRoboticTech.com" ]
dcofer@NeuroRoboticTech.com
10b00f1d7deb884ddc3369c0e9da346139ac88a5
85bfbbc8ecff945026ca735fa70b6b07029efef3
/PA4/mycode/expression_validation.h
42a061fdfc69ac7f2b1105c78d9a59625be916d3
[]
no_license
dafidi/cs143
3febf7a4b6a50f38c79a13ca32f39d4f291e2111
7336deac87625f90f57d731bc8346d7e40c90481
refs/heads/master
2020-07-13T00:36:50.471457
2019-09-06T01:22:33
2019-09-06T01:22:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,698
h
#pragma once #include "cool-tree.h" #include "symtab.h" #include "typechecking.h" #include <stack> #include <algorithm> namespace mycode { bool object_in_ancestry_attribs(Symbol sym, const Symbol c, SymbolTable<Symbol, symbol_table_data>*& sym_tab); bool validate_exp_assign(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_static_dispatch(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_dispatch(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_cond(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_loop(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_typcase(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_block(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_let(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_plus(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_sub(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_mul(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_divide(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_neg(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_lt(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_eq(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_leq(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_comp(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_int_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_bool_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_string_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_new_(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_isvoid(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_no_expr(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_object(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_case(Class_ in_class, Feature in_feature, Case e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_expression(Class_ in_class, Feature in_feature, Expression& e, SymbolTable<Symbol, symbol_table_data>*& sym_tab) { bool expression_is_valid = true; switch (e->get_expr_type()) { case expr_type::EXP_ASSIGN: { assign_class* assign_exp = (assign_class*) e; expression_is_valid = validate_exp_assign(in_class, in_feature, assign_exp, sym_tab); break; } case expr_type::EXP_STATIC_DISPATCH: { static_dispatch_class* static_dispatch_exp = (static_dispatch_class*) e; expression_is_valid = validate_exp_static_dispatch(in_class, in_feature, static_dispatch_exp, sym_tab); break; } case expr_type::EXP_DISPATCH: { dispatch_class* dispatch_exp = (dispatch_class*) e; expression_is_valid = validate_exp_dispatch(in_class, in_feature, dispatch_exp, sym_tab); break; } case expr_type::EXP_COND: { cond_class* cond_exp = (cond_class*) e; expression_is_valid = validate_exp_cond(in_class, in_feature, cond_exp, sym_tab); break; } case expr_type::EXP_LOOP: { loop_class* loop_exp = (loop_class*) e; expression_is_valid = validate_exp_loop(in_class, in_feature, loop_exp, sym_tab); break; } case expr_type::EXP_TYPCASE: { typcase_class* typcase_exp = (typcase_class*) e; expression_is_valid = validate_exp_typcase(in_class, in_feature, typcase_exp, sym_tab); break; } case expr_type::EXP_BLOCK: { block_class* block_exp = (block_class*) e; expression_is_valid = validate_exp_block(in_class, in_feature, block_exp, sym_tab); break; } case expr_type::EXP_LET: { let_class* let_exp = (let_class*) e; expression_is_valid = validate_exp_let(in_class, in_feature, let_exp, sym_tab); break; } case expr_type::EXP_PLUS: { plus_class* plus_exp = (plus_class*) e; expression_is_valid = validate_exp_plus(in_class, in_feature, plus_exp, sym_tab); break; } case expr_type::EXP_SUB: { sub_class* sub_exp = (sub_class*) e; expression_is_valid = validate_exp_sub(in_class, in_feature, sub_exp, sym_tab); break; } case expr_type::EXP_MUL: { mul_class* mul_exp = (mul_class*) e; expression_is_valid = validate_exp_mul(in_class, in_feature, mul_exp, sym_tab); break; } case expr_type::EXP_DIVIDE: { divide_class* divide_exp = (divide_class*) e; expression_is_valid = validate_exp_divide(in_class, in_feature, divide_exp, sym_tab); break; } case expr_type::EXP_NEG: { neg_class* neg_exp = (neg_class*) e; expression_is_valid = validate_exp_comp(in_class, in_feature, neg_exp, sym_tab); break; } case expr_type::EXP_LT: { lt_class* lt_exp = (lt_class*) e; expression_is_valid = validate_exp_lt(in_class, in_feature, lt_exp, sym_tab); break; } case expr_type::EXP_EQ: { eq_class* eq_exp = (eq_class*) e; expression_is_valid = validate_exp_eq(in_class, in_feature, eq_exp, sym_tab); break; } case expr_type::EXP_LEQ: { leq_class* leq_exp = (leq_class*) e; expression_is_valid = validate_exp_leq(in_class, in_feature, leq_exp, sym_tab); break; } case expr_type::EXP_COMP: { comp_class* comp_exp = (comp_class*) e; expression_is_valid = validate_exp_neg(in_class, in_feature, comp_exp, sym_tab); break; } case expr_type::EXP_INT_CONST: { expression_is_valid = true; break; } case expr_type::EXP_BOOL_CONST: { expression_is_valid = true; break; } case expr_type::EXP_STRING_CONST: { expression_is_valid = true; break; } case expr_type::EXP_NEW_: { new__class* new__exp = (new__class*) e; expression_is_valid = validate_exp_new_(in_class, in_feature, new__exp, sym_tab); break; } case expr_type::EXP_ISVOID: { isvoid_class* isvoid_exp = (isvoid_class*) e; expression_is_valid = validate_exp_isvoid(in_class, in_feature, isvoid_exp, sym_tab); break; } case expr_type::EXP_NO_EXPR: { expression_is_valid = true; break; } case expr_type::EXP_OBJECT: { object_class* object_exp = (object_class*) e->copy_Expression(); expression_is_valid = validate_exp_object(in_class, in_feature, object_exp, sym_tab); break; } defualt: { expression_is_valid = false; } } if (Symbol expr_type = get_expression_type(in_class, e, sym_tab)) { e->set_type(idtable.add_string(expr_type->get_string())); } else { e->set_type(idtable.add_string(Object->get_string())); } if (!expression_is_valid) { DEBUG_ACTION(std::cout << "Expression class(#) " << (int) e->get_expr_type() << " was faulty." << std::endl); } return expression_is_valid; } bool validate_exp_assign(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { assign_class* assign_exp = (assign_class*) e; Symbol type; Symbol assignee_name = assign_exp->get_name(); Expression assign_rhs_expr = assign_exp->get_expr(); symbol_table_data* assignee_data = sym_tab->lookup(assignee_name); bool still_valid = true; // The assignee must either be in scope (case I) or an attribute inherited from one of in_class's ancestors (case II). if (assignee_data || object_in_ancestry_attribs(assignee_name, in_class->get_name(), sym_tab)) { // The expression being assigned to the assignee must be valid by itself within the current scope. still_valid = validate_expression(in_class, in_feature, assign_rhs_expr, sym_tab); // Case I if (assignee_data) { type = assignee_data->get_type(); // If the in-scope variable is declared as SELF_TYPE, substitute the class's name for it. if (type == SELF_TYPE) { type = in_class->get_name(); } // The expression may be the type exactly, or a subtype of it. return still_valid && (type == get_expression_type(in_class, assign_rhs_expr, sym_tab) || is_super_type_of(type, get_expression_type(in_class, assign_rhs_expr, sym_tab), sym_tab)); } // Case II else { type = find_type_of_attribute_in_class_or_ancestry(assignee_name, in_class->get_name(), sym_tab); // If it is declared as SELF_TYPE in the ancestor, substitute the class's name for it. if (type == SELF_TYPE) { type = in_class->get_name(); } // The expression may be the type exactly, or a subtype of it. return still_valid && (type == get_expression_type(in_class, assign_rhs_expr, sym_tab) || is_super_type_of(type, get_expression_type(in_class, assign_rhs_expr, sym_tab), sym_tab)); } } else { return false; } } bool validate_exp_static_dispatch(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { static_dispatch_class* s_dispatch_exp = (static_dispatch_class*) e; Expression expr = s_dispatch_exp->get_expr(); Symbol func_name = s_dispatch_exp->get_name(); Symbol type_name = s_dispatch_exp->get_type_name(); Expressions args = s_dispatch_exp->get_args(); Symbol expr_type = get_expression_type(in_class, expr, sym_tab); bool still_valid = validate_expression(in_class, in_feature, expr, sym_tab); if (!is_super_type_of(type_name, expr_type, sym_tab)) { still_valid = false; } if (!find_type_of_method_in_class_or_ancestry(func_name, type_name, sym_tab)) { still_valid = false; } else { // The method has to be defined in the exact class named by type_name. method_class* desired_method = (method_class*) get_method_from_class_or_ancestry(func_name, type_name , sym_tab); if (desired_method) { // Number of arguments should be the same as number of parameters in function declaration. Formals desired_formals = desired_method->get_formals(); if (desired_formals->len() != args->len()) { still_valid = false; } // Finally, the types of the arguments must match the declared parameter types. for (int i = args->first(); args->more(i); i = args->next(i)) { Expression nth_exp = args->nth(i); still_valid = validate_expression(in_class, in_feature, nth_exp, sym_tab) \ && (desired_formals->nth(i)->get_type() == get_expression_type(in_class, args->nth(i), sym_tab) \ || is_super_type_of(desired_formals->nth(i)->get_type(), get_expression_type(in_class, args->nth(i), sym_tab), sym_tab)) \ && still_valid; } } else { still_valid = false; } } return still_valid; } bool validate_exp_dispatch(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { dispatch_class* dispatch_exp = (dispatch_class*) e; Expression expr = dispatch_exp->get_expr(); Symbol func_name = dispatch_exp->get_name(); Expressions args = dispatch_exp->get_args(); Symbol expr_type = get_expression_type(in_class, expr, sym_tab); bool still_valid = validate_expression(in_class, in_feature, expr, sym_tab); if (expr_type == SELF_TYPE) { expr_type = in_class->get_name(); } // If the method is not defined on the class or its ancestors, it's a bad expression. if (method_class* desired_method = (method_class*) get_method_from_class_or_ancestry(func_name, expr_type, sym_tab)) { Formals desired_formals = desired_method->get_formals(); //Ha! now it's formals vs arguments. if (desired_formals->len() != args->len()) { return false; } for (int i = args->first(); args->more(i); i = args->next(i)) { Expression nth_exp = args->nth(i); Symbol nth_exp_type = get_expression_type(in_class, args->nth(i), sym_tab); if (nth_exp_type == SELF_TYPE) {nth_exp_type = in_class->get_name();} bool okay = validate_expression(in_class, in_feature, nth_exp, sym_tab) \ && (desired_formals->nth(i)->get_type() == nth_exp_type || is_super_type_of(desired_formals->nth(i)->get_type(), nth_exp_type, sym_tab)); still_valid = okay && still_valid; } } else { still_valid = false; } return still_valid; } bool validate_exp_cond(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { cond_class* cond_exp = (cond_class*) e; Expression pred = cond_exp->get_pred(); Expression then_exp = cond_exp->get_then_exp(); Expression else_exp = cond_exp->get_else_exp(); bool still_valid = validate_expression(in_class, in_feature, pred, sym_tab) && \ validate_expression(in_class, in_feature, then_exp, sym_tab) && \ validate_expression(in_class, in_feature, else_exp, sym_tab); still_valid = still_valid && Bool == get_expression_type(in_class, pred, sym_tab); return still_valid; } bool validate_exp_loop(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { loop_class* loop_exp = (loop_class*) e; Expression pred = loop_exp->get_pred(); Expression body = loop_exp->get_body(); bool still_valid = validate_expression(in_class, in_feature, pred, sym_tab) && \ validate_expression(in_class, in_feature, body, sym_tab); /* May need to possibly add pred variables to scope for body. Maybe. */ still_valid = still_valid && Bool == get_expression_type(in_class, pred, sym_tab); return still_valid; } bool validate_exp_typcase(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { typcase_class* typcase_exp = (typcase_class*) e; Expression expr = typcase_exp->get_expr(); Cases cases = typcase_exp->get_cases(); bool still_valid = true; std::vector<Symbol> types_seen_so_far; still_valid = validate_expression(in_class, in_feature, expr, sym_tab); for (int i = cases->first(); cases->more(i); i = cases->next(i)) { branch_class* nth_branch = (branch_class*)cases->nth(i); Symbol nth_branch_decl_type = nth_branch->get_type_decl(); bool okay = validate_case(in_class, in_feature, nth_branch, sym_tab); if (std::find(types_seen_so_far.begin(), types_seen_so_far.end(), nth_branch_decl_type) == types_seen_so_far.end()) { types_seen_so_far.push_back(nth_branch_decl_type); } else { still_valid = false; } still_valid = okay && still_valid; } return still_valid; } bool validate_case(Class_ in_class, Feature in_feature, Case c, SymbolTable<Symbol, symbol_table_data>* sym_tab) { branch_class* case_branch = (branch_class*) c; Symbol branch_id = case_branch->get_name(); Symbol branch_type = case_branch->get_type_decl() == SELF_TYPE ? in_class->get_name() : case_branch->get_type_decl(); Expression branch_expression = case_branch->get_expr(); symbol_table_data* data = new symbol_table_data({NULL, NULL, branch_type, NULL}); bool still_valid = true; sym_tab->enterscope(); sym_tab->addid(branch_id, data); still_valid = validate_expression(in_class, in_feature, branch_expression, sym_tab); Symbol s = get_expression_type(in_class, branch_expression, sym_tab); still_valid = still_valid && is_super_type_of(branch_type, s, sym_tab); sym_tab->exitscope(); return still_valid; } bool validate_exp_block(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { block_class* block_exp = (block_class*) e; Expressions expressions = block_exp->get_expressions(); bool still_valid = true; for (int i = expressions->first(); expressions->more(i); i = expressions->next(i)) { Expression nth_exp = expressions->nth(i); bool okay = validate_expression(in_class, in_feature, nth_exp, sym_tab) && still_valid; still_valid = okay && still_valid; } // DEBUG_ACTION(std::cout << "Block just validated says: " << still_valid << std::endl); return still_valid; } bool validate_exp_let(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { let_class* let_exp = (let_class*) e; Symbol id = let_exp->get_identifier(); Symbol type_decl = let_exp->get_type_decl(); Expression init_expr = let_exp->get_init_expr(); Expression body = let_exp->get_body(); bool still_valid = sym_tab->lookup(type_decl) != NULL ? true : false; still_valid = id != self && still_valid; Symbol init_expr_type = get_expression_type(in_class, init_expr, sym_tab); still_valid = (init_expr_type == No_type || (type_decl == init_expr_type) || is_super_type_of(type_decl, init_expr_type, sym_tab)) && still_valid; symbol_table_data* data = new symbol_table_data({NULL, NULL, type_decl, NULL}); sym_tab->enterscope(); sym_tab->addid(id, data); still_valid = validate_expression(in_class, in_feature, init_expr, sym_tab) && still_valid; still_valid = validate_expression(in_class, in_feature, body, sym_tab) && still_valid; sym_tab->exitscope(); return still_valid; } bool validate_exp_plus(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { plus_class* plus_exp = (plus_class*) e; bool still_valid = validate_expression(in_class, in_feature, plus_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, plus_exp->get_second_expression(), sym_tab); still_valid = still_valid && \ Int == get_expression_type(in_class, plus_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, plus_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_sub(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { sub_class* sub_exp = (sub_class*) e; bool still_valid = validate_expression(in_class, in_feature, sub_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, sub_exp->get_second_expression(), sym_tab); still_valid = still_valid && \ Int == get_expression_type(in_class, sub_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, sub_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_mul(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { mul_class* mul_exp = (mul_class*) e; bool still_valid = validate_expression(in_class, in_feature, mul_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, mul_exp->get_second_expression(), sym_tab); still_valid = still_valid && \ Int == get_expression_type(in_class, mul_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, mul_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_divide(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { divide_class* divide_exp = (divide_class*) e; bool still_valid = validate_expression(in_class, in_feature, divide_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, divide_exp->get_second_expression(), sym_tab); still_valid = still_valid && \ Int == get_expression_type(in_class, divide_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, divide_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_neg(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { neg_class* neg_exp = (neg_class*) e; bool still_valid = validate_expression(in_class, in_feature, neg_exp->get_expr(), sym_tab); still_valid = still_valid && Bool == get_expression_type(in_class, neg_exp->get_expr(), sym_tab); return still_valid; } bool validate_exp_lt(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { lt_class* lt_exp = (lt_class*) e; bool still_valid = validate_expression(in_class, in_feature, lt_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, lt_exp->get_second_expression(), sym_tab); still_valid = Int == get_expression_type(in_class, lt_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, lt_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_eq(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { eq_class* eq_exp = (eq_class*) e; bool still_valid = validate_expression(in_class, in_feature, eq_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, eq_exp->get_second_expression(), sym_tab); Symbol type_1 = get_expression_type(in_class, eq_exp->get_first_expression(), sym_tab); Symbol type_2 = get_expression_type(in_class, eq_exp->get_second_expression(), sym_tab); if (type_1 != type_2) { still_valid = still_valid && type_1 != Bool && type_2 != Bool && type_1 != Int && type_2 != Int && type_1 != Str && type_2 != Str; } return still_valid; } bool validate_exp_leq(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { leq_class* leq_exp = (leq_class*) e; bool still_valid = validate_expression(in_class, in_feature, leq_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, leq_exp->get_second_expression(), sym_tab); still_valid = Int == get_expression_type(in_class, leq_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, leq_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_comp(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { comp_class* comp_exp = (comp_class*) e; bool still_valid = validate_expression(in_class, in_feature, comp_exp->get_expression(), sym_tab); still_valid = still_valid && Int == get_expression_type(in_class, comp_exp->get_expression(), sym_tab); return still_valid; } bool validate_exp_int_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { return true; } bool validate_exp_bool_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { return true; } bool validate_exp_string_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { return true; } bool validate_exp_new_(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { new__class* new__exp = (new__class*)e; if (sym_tab->lookup(new__exp->get_type_name())) { return true; } return false; } bool validate_exp_isvoid(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { isvoid_class* isvoid_exp = (isvoid_class*) e; return validate_expression(in_class, in_feature, isvoid_exp->get_expr(), sym_tab); } bool validate_exp_no_expr(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { return true; } bool validate_exp_object(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { bool still_valid = true; object_class* object_exp = (object_class*) e; if (sym_tab->lookup(object_exp->get_name())) { if (object_exp->get_name() == in_feature->get_name() && !object_in_ancestry_attribs(object_exp->get_name(), in_class->get_name(), sym_tab)) { still_valid = false; if (object_exp->get_name() == self) { still_valid = true; } } // still_valid = true; } else if (object_in_ancestry_attribs(object_exp->get_name(), in_class->get_name(), sym_tab)) { still_valid = true; } else { still_valid = false; } return still_valid; } /** * This function checks whether a symbol is a feature of any class in the * ancestry of that object. Of course, it needs the symbol table to do this. * * @param sym The symbol being checked for (maybe an attribute or a method.) * It must surely be an object identifier (attribute or method). * @param c The class whose ancestors are being checked. It must surely be a * type (class) identifier * @param sym_tab The symbol table (pointer to it). */ bool object_in_ancestry_attribs(Symbol sym, const Symbol c, SymbolTable<Symbol, symbol_table_data>*& sym_tab) { symbol_table_data* class_data = sym_tab->lookup(c); symbol_table_data* class_parent_data = sym_tab->lookup(class_data->parent); if (class_parent_data) { for (int i = class_parent_data->features->first(); class_parent_data->features->more(i); i = class_parent_data->features->next(i)) { if (sym == class_parent_data->features->nth(i)->get_name()) { return true; } } return object_in_ancestry_attribs(sym, class_data->parent, sym_tab); } return false; } }
[ "david.awogbemila@bison.howard.edu" ]
david.awogbemila@bison.howard.edu
ff497c137921789684bd803496fd6c4c26c3b8f8
016dcc77cade4d5df23387dea4a4038c7ed2e683
/src/pluginmanager.h
1ec51037b8672ee9c0fce80ea06c2d8206c74547
[]
no_license
wyrover/akview
aeeb971e14a3065378a3b9d05fa5eb8607375d64
c10e6f92ec57260e6bc7fc5e1d9d9e0f3bbe37e6
refs/heads/master
2021-01-15T09:53:15.401278
2015-01-04T11:02:54
2015-01-04T11:02:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
909
h
#ifndef PLUGINMANAGER_H #define PLUGINMANAGER_H #include "actionthread.h" #include "plugin.h" #include "progressbardialog.h" namespace mv { class PluginManager : public QObject { Q_OBJECT public: PluginManager(); bool loadPlugin(const QString& folderPath); void loadPlugins(const QString& folderPath); PluginVector plugins() const; void execAction(const QString& actionName, const QStringList& filePaths); private: PluginVector plugins_; QString afterPackageInstallationAction_; QStringList afterPackageInstallationFilePaths_; QScriptEngine* scriptEngine_; QStringList replaceVariables(const QStringList& command); QObject* jsConsole_; QObject* jsImaging_; QObject* jsSystem_; ActionThread* actionThread_; bool canceling_; public slots: void packageManager_installationDone(); void actionThread_finished(); void mainWindow_cancelButtonClicked(); }; } #endif // PLUGINMANAGER_H
[ "laurent@pogopixels.com" ]
laurent@pogopixels.com
ca8b6e51e5d3a3af26031114629f6229f6e48b99
0e9c066441c87fb9381b1d1f2084298a46fb4d33
/KeePass/WinGUI/Plugins/KpUtilitiesImpl.cpp
d452a21ba4cea12e8cd9b84053e406f80fd575e3
[ "MIT" ]
permissive
rrvt/KeePassLastPass
8c8207cc6cfb009a45220a404298a874c6317348
ea4b27a9e5e5fbd7220feb55aa2534cd3fe740be
refs/heads/main
2023-04-13T03:28:56.899812
2023-04-11T21:44:29
2023-04-11T21:44:29
422,981,282
0
1
null
null
null
null
UTF-8
C++
false
false
9,785
cpp
/* KeePass Password Safe - The Open-Source Password Manager Copyright (C) 2003-2022 Dominik Reichl <dominik.reichl@t-online.de> 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "StdAfx.h" #include <tchar.h> #include <assert.h> #include "KpUtilitiesImpl.h" #include "../../KeePassLibCpp/PwManager.h" #include "../../KeePassLibCpp/Crypto/ARCFour.h" #include "../../KeePassLibCpp/Util/AppUtil.h" #include "../../KeePassLibCpp/Util/StrUtil.h" #include "../../KeePassLibCpp/Util/MemUtil.h" #include "../../KeePassLibCpp/Util/PwQualityEst.h" #include "../../KeePassLibCpp/Util/PwUtil.h" #include "../../KeePassLibCpp/Util/Base64.h" #include "../Util/WinUtil.h" #include "../Util/CmdLine/FullPathName.h" KP_IMPL_STDREFIMPL_NODELETE(CKpUtilitiesImpl) CKpUtilitiesImpl::CKpUtilitiesImpl() { KP_IMPL_CONSTRUCT; } CKpUtilitiesImpl& CKpUtilitiesImpl::Instance() { static CKpUtilitiesImpl singletonObject; return singletonObject; } STDMETHODIMP CKpUtilitiesImpl::QueryInterface(REFIID riid, void** ppvObject) { KP_REQ_OUT_PTR(ppvObject); KP_SUPPORT_INTERFACE(IID_IKpUnknown, IKpUnknown); KP_SUPPORT_INTERFACE(IID_IKpUtilities, IKpUtilities); *ppvObject = NULL; return E_NOINTERFACE; } STDMETHODIMP CKpUtilitiesImpl::ShowFileDialog(BOOL bOpenMode, LPCTSTR lpSuffix, LPTSTR lpStoreBuf, DWORD dwBufLen) { return ((WU_GetFileNameSz(bOpenMode, lpSuffix, lpStoreBuf, dwBufLen) == FALSE) ? E_ABORT : S_OK); } STDMETHODIMP_(char*) CKpUtilitiesImpl::UnicodeToMultiByte(const WCHAR* lpwString) { return _StringToAnsi(lpwString); } STDMETHODIMP_(WCHAR*) CKpUtilitiesImpl::MultiByteToUnicode(const char* lpString) { return _StringToUnicode(lpString); } STDMETHODIMP_(UTF8_BYTE*) CKpUtilitiesImpl::StringToUTF8(LPCTSTR lpSourceString) { return _StringToUTF8(lpSourceString); } STDMETHODIMP_(DWORD) CKpUtilitiesImpl::UTF8NumChars(const UTF8_BYTE* pUTF8String) { return _UTF8NumChars(pUTF8String); } STDMETHODIMP_(DWORD) CKpUtilitiesImpl::UTF8BytesNeeded(LPCTSTR lpString) { return _UTF8BytesNeeded(lpString); } STDMETHODIMP_(LPTSTR) CKpUtilitiesImpl::UTF8ToString(const UTF8_BYTE* pUTF8String) { return _UTF8ToString(pUTF8String); } STDMETHODIMP_(BOOL) CKpUtilitiesImpl::IsUTF8String(const UTF8_BYTE* pUTF8String) { return _IsUTF8String(pUTF8String); } #pragma warning(push) #pragma warning(disable: 4996) // _tcscpy unsafe STDMETHODIMP CKpUtilitiesImpl::UuidToString(const BYTE* pUuid, LPTSTR lpOutBuf) { if((pUuid == NULL) || (lpOutBuf == NULL)) return E_POINTER; CString str; _UuidToString(pUuid, &str); _tcscpy(lpOutBuf, (LPCTSTR)str); return S_OK; } #pragma warning(pop) STDMETHODIMP CKpUtilitiesImpl::StringToUuid(LPCTSTR lpSource, BYTE* pUuid) { _StringToUuid(lpSource, pUuid); return S_OK; } STDMETHODIMP_(INT) CKpUtilitiesImpl::ShellOpenLocalFile(LPCTSTR lpFile, INT nMode) { return _OpenLocalFile(lpFile, nMode); } STDMETHODIMP CKpUtilitiesImpl::OpenUrl(LPCTSTR lpURL, HWND hParent) { if(lpURL == NULL) return E_POINTER; OpenUrlEx(lpURL, hParent); return S_OK; } STDMETHODIMP CKpUtilitiesImpl::OpenAppHelp(LPCTSTR lpTopicFile) { return ((WU_OpenAppHelp(lpTopicFile, NULL) == FALSE) ? E_FAIL : S_OK); } STDMETHODIMP CKpUtilitiesImpl::Base64Encode(const BYTE* pbIn, DWORD cbInLen, BYTE* pbOut, DWORD* pcbOutLen) { if(pbIn == NULL) return E_POINTER; if(cbInLen == 0) return E_INVALIDARG; if((pbOut == NULL) || (pcbOutLen == NULL)) return E_POINTER; return (CBase64Codec::Encode(pbIn, cbInLen, pbOut, pcbOutLen) ? S_OK : E_FAIL); } STDMETHODIMP CKpUtilitiesImpl::Base64Decode(const BYTE* pbIn, DWORD cbInLen, BYTE* pbOut, DWORD* pcbOutLen) { if(pbIn == NULL) return E_POINTER; if(cbInLen == 0) return E_INVALIDARG; if((pbOut == NULL) || (pcbOutLen == NULL)) return E_POINTER; return (CBase64Codec::Decode(pbIn, cbInLen, pbOut, pcbOutLen) ? S_OK : E_FAIL); } STDMETHODIMP CKpUtilitiesImpl::GetApplicationDirectory(LPTSTR lpStoreBuf, DWORD dwBufLen, BOOL bFilterSpecial, BOOL bMakeURL) { if(lpStoreBuf == NULL) return E_POINTER; return ((AU_GetApplicationDirectory(lpStoreBuf, dwBufLen, bFilterSpecial, bMakeURL) == FALSE) ? E_FAIL : S_OK); } STDMETHODIMP_(LPTSTR) CKpUtilitiesImpl::MakeRelativePath(LPCTSTR lpBaseFile, LPCTSTR lpTargetFile) { if((lpBaseFile == NULL) || (lpTargetFile == NULL)) return NULL; CString str = MakeRelativePathEx(lpBaseFile, lpTargetFile); return _TcsSafeDupAlloc((LPCTSTR)str); } STDMETHODIMP_(LPTSTR) CKpUtilitiesImpl::GetShortestAbsolutePath(LPCTSTR lpFilePath) { if(lpFilePath == NULL) return NULL; CString str = ::GetShortestAbsolutePath(lpFilePath); return _TcsSafeDupAlloc((LPCTSTR)str); } STDMETHODIMP_(BOOL) CKpUtilitiesImpl::IsAbsolutePath(LPCTSTR lpPath) { if(lpPath == NULL) return FALSE; return WU_IsAbsolutePath(lpPath); } STDMETHODIMP_(BOOL) CKpUtilitiesImpl::ValidatePath(LPCTSTR lpPath, DWORD dwOptions) { if(lpPath == NULL) return FALSE; std_string str = lpPath; const FullPathName fpn(str); if(fpn.getState() == FullPathName::INVALID_PATH) return FALSE; if((dwOptions & KPVPF_MUST_EXIST) != 0) { const DWORD dwAttrib = ::GetFileAttributes(lpPath); if(dwAttrib == INVALID_FILE_ATTRIBUTES) return FALSE; if(((dwOptions & KPVPF_TYPE_DIRECTORY) != 0) && ((dwAttrib & FILE_ATTRIBUTE_DIRECTORY) == 0)) return FALSE; if(((dwOptions & KPVPF_TYPE_FILE) != 0) && ((dwAttrib & FILE_ATTRIBUTE_DIRECTORY) != 0)) return FALSE; } if((dwOptions & KPVPF_REGULAR_NAME) != 0) { LPCTSTR lpScan = lpPath; while(*lpScan != 0) { const TCHAR tch = *lpScan; if((tch == _T('<')) || (tch == _T('>')) || (tch == _T('\"')) || (tch == _T('/')) || (tch == _T('|')) || (tch == _T('?')) || (tch == _T('*'))) return FALSE; if((tch >= 0) && (tch <= 31)) return FALSE; ++lpScan; } } return TRUE; } STDMETHODIMP_(LPTSTR) CKpUtilitiesImpl::GetQuotedPath(LPCTSTR lpPath) { if(lpPath == NULL) return NULL; const std::basic_string<TCHAR> str = lpPath; const std::basic_string<TCHAR> strPath = SU_GetQuotedPath(str); return _TcsSafeDupAlloc(strPath.c_str()); } STDMETHODIMP CKpUtilitiesImpl::CreateDirectoryTree(LPCTSTR lpDirPath, DWORD dwOptions) { UNREFERENCED_PARAMETER(dwOptions); return WU_CreateDirectoryTree(lpDirPath); } STDMETHODIMP CKpUtilitiesImpl::FlushStorageBuffers(LPCTSTR lpFileOnStorage, BOOL bOnlyIfRemovable) { if(lpFileOnStorage == NULL) return E_POINTER; return ((WU_FlushStorageBuffersEx(lpFileOnStorage, bOnlyIfRemovable) == FALSE) ? E_FAIL : S_OK); } STDMETHODIMP CKpUtilitiesImpl::SecureDeleteFile(LPCTSTR lpFilePath) { if(lpFilePath == NULL) return E_POINTER; return ((AU_SecureDeleteFile(lpFilePath) == FALSE) ? E_FAIL : S_OK); } STDMETHODIMP CKpUtilitiesImpl::WriteFile(LPCTSTR lpFilePath, const BYTE* pData, DWORD dwDataSize) { if(lpFilePath == NULL) return E_POINTER; if(pData == NULL) return E_POINTER; const int nResult = AU_WriteBigFile(lpFilePath, pData, dwDataSize, FALSE); if(nResult == PWE_SUCCESS) return S_OK; if(nResult == PWE_NOFILEACCESS_WRITE) return E_ACCESSDENIED; return E_FAIL; } STDMETHODIMP_(INT) CKpUtilitiesImpl::CompareTimes(const PW_TIME* pTime1, const PW_TIME* pTime2) { if((pTime1 == NULL) || (pTime2 == NULL)) return 0; return _pwtimecmp(pTime1, pTime2); } STDMETHODIMP CKpUtilitiesImpl::HashFileSHA256(LPCTSTR lpFile, BYTE* pHashBuf) { if((lpFile == NULL) || (pHashBuf == NULL)) return E_POINTER; return ((SHA256_HashFile(lpFile, pHashBuf) == FALSE) ? E_FAIL : S_OK); } STDMETHODIMP_(DWORD) CKpUtilitiesImpl::EstimatePasswordBits(LPCTSTR lpPassword) { return CPwQualityEst::EstimatePasswordBits(lpPassword); } STDMETHODIMP_(BOOL) CKpUtilitiesImpl::IsTANEntry(const PW_ENTRY* pEntry) { return CPwUtil::IsTANEntry(pEntry); } STDMETHODIMP CKpUtilitiesImpl::SHA256CreateContext(void** pOutNewContext) { if(pOutNewContext == NULL) return E_POINTER; sha256_ctx* pContext = new sha256_ctx; sha256_begin(pContext); *pOutNewContext = pContext; return S_OK; } STDMETHODIMP CKpUtilitiesImpl::SHA256Init(void* pContext) { if(pContext == NULL) return E_POINTER; sha256_begin((sha256_ctx*)pContext); return S_OK; } STDMETHODIMP CKpUtilitiesImpl::SHA256Hash(void* pContext, const BYTE* pData, DWORD dwDataLength) { if((pContext == NULL) || (pData == NULL)) return E_POINTER; sha256_hash(pData, dwDataLength, (sha256_ctx*)pContext); return S_OK; } STDMETHODIMP CKpUtilitiesImpl::SHA256Final(void* pContext, BYTE* pOutHashBuf) { if((pContext == NULL) || (pOutHashBuf == NULL)) return E_POINTER; sha256_end(pOutHashBuf, (sha256_ctx*)pContext); return S_OK; } STDMETHODIMP CKpUtilitiesImpl::EncryptMemory(BYTE* pbBuf, DWORD dwBufLen, const BYTE* pbKey, DWORD dwKeyLen) { if((pbBuf == NULL) || (pbKey == NULL)) return E_POINTER; ARCFourCrypt(pbBuf, dwBufLen, pbKey, dwKeyLen); return S_OK; } STDMETHODIMP CKpUtilitiesImpl::DecryptMemory(BYTE* pbBuf, DWORD dwBufLen, const BYTE* pbKey, DWORD dwKeyLen) { // ARCFour is self-inverse return CKpUtilitiesImpl::EncryptMemory(pbBuf, dwBufLen, pbKey, dwKeyLen); }
[ "rrvt@swde.com" ]
rrvt@swde.com
68044e1b9135c455a0053b9d059b8c6a8a65a193
65abf609c59993d49b12dfbaa8d1665f4cfc2208
/test/alpha_svr/phxrpc_alphasvr_tool.cpp
71c935596da5e6e3fdd1b665cf2879c0e3106d81
[]
no_license
brandongbyd/phxrpctest
4244bbd89c987bd29bdede01f5f921d5d909adca
feb0203382925a7aca51964edfd112ab7f615a6c
refs/heads/master
2020-07-17T22:12:40.810679
2019-09-03T16:23:43
2019-09-03T16:23:43
206,110,381
2
0
null
null
null
null
UTF-8
C++
false
false
745
cpp
/* phxrpc_alphasvr_tool.cpp Generated by phxrpc_pb2tool from alpha_svr.proto Please DO NOT edit unless you know exactly what you are doing. */ #include "phxrpc_alphasvr_tool.h" #include "phxrpc/file.h" #include "alphasvr_client.h" using namespace phxrpc; AlphaSvrTool::AlphaSvrTool() { } AlphaSvrTool::~AlphaSvrTool() { } int AlphaSvrTool::PHXEcho(phxrpc::OptMap &/* opt_map */) { printf("\n *** PHXEcho unimplement ***\n"); return -1; } int AlphaSvrTool::AddTwoDigits(phxrpc::OptMap &/* opt_map */) { printf("\n *** AddTwoDigits unimplement ***\n"); return -1; } int AlphaSvrTool::AddSomeDigits(phxrpc::OptMap &/* opt_map */) { printf("\n *** AddSomeDigits unimplement ***\n"); return -1; }
[ "brandong@foxmail.xom" ]
brandong@foxmail.xom
fb3fa2d5257395499d9453dbdb0595eeb7db1edb
75d6d834a098b58c944f216b6d2e8533b9eadf60
/Lineseg_Cylinder_3D (inefficient)/Lineseg_Cylinder_3D/main.cpp
2f65a916d6922872eee615990104dbbd3a240a37
[]
no_license
IGME-RIT/physics-lineSeg-Cylinder3D
98e78e92de8e083a6fc05b0d81de42ddf1655a58
023e19c8e3a3fff001f12843ff2fef614d2e0d37
refs/heads/master
2020-12-25T09:38:14.356166
2016-06-03T16:33:12
2016-06-03T16:33:12
60,354,588
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
29,230
cpp
/* Title: Line Segment - Cylinder 3D collision Detection File Name: main.cpp Copyright © 2015 Original authors: Srinivasan Thiagarajan Written under the supervision of David I. Schwartz, Ph.D., and supported by a professional development seed grant from the B. Thomas Golisano College of Computing & Information Sciences (https://www.rit.edu/gccis) at the Rochester Institute of Technology. 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/>. Description: This is a example to detect collision between a linesegnt and a cylinder. It finds the closest points on the two lines and finds if the distance between them is less than radius. Ifso, the ncollision is detected. This is a inefficient test because it has a lot of edge cases, but its easier to understand and implement. References: Real time collision Detection by Ericson AABB-2D by Brockton Roth */ #include "GLIncludes.h" // We change this variable upon detecting collision float blue = 0.0f; float threshold = 0.001f; glm::vec3* currentlySelected; short int pointChange = 1; short int lineChange = 1; glm::mat4 MVP1, MVP2; glm::vec3 aaa, bbb; //This struct consists of the basic stuff needed for getting the shape on the screen. struct stuff_for_drawing{ //This stores the address the buffer/memory in the GPU. It acts as a handle to access the buffer memory in GPU. GLuint vbo; //This will be used to tell the GPU, how many vertices will be needed to draw during drawcall. int numberOfVertices; //This function gets the number of vertices and all the vertex values and stores them in the buffer. void initBuffer(int numVertices, VertexFormat* vertices) { numberOfVertices = numVertices; // This generates buffer object names // The first parameter is the number of buffer objects, and the second parameter is a pointer to an array of buffer objects (yes, before this call, vbo was an empty variable) glGenBuffers(1, &vbo); //// Binds a named buffer object to the specified buffer binding point. Give it a target (GL_ARRAY_BUFFER) to determine where to bind the buffer. //// There are several different target parameters, GL_ARRAY_BUFFER is for vertex attributes, feel free to Google the others to find out what else there is. //// The second paramter is the buffer object reference. If no buffer object with the given name exists, it will create one. //// Buffer object names are unsigned integers (like vbo). Zero is a reserved value, and there is no default buffer for each target (targets, like GL_ARRAY_BUFFER). //// Passing in zero as the buffer name (second parameter) will result in unbinding any buffer bound to that target, and frees up the memory. glBindBuffer(GL_ARRAY_BUFFER, vbo); //// Creates and initializes a buffer object's data. //// First parameter is the target, second parameter is the size of the buffer, third parameter is a pointer to the data that will copied into the buffer, and fourth parameter is the //// expected usage pattern of the data. Possible usage patterns: GL_STREAM_DRAW, GL_STREAM_READ, GL_STREAM_COPY, GL_STATIC_DRAW, GL_STATIC_READ, GL_STATIC_COPY, GL_DYNAMIC_DRAW, //// GL_DYNAMIC_READ, or GL_DYNAMIC_COPY //// Stream means that the data will be modified once, and used only a few times at most. Static means that the data will be modified once, and used a lot. Dynamic means that the data //// will be modified repeatedly, and used a lot. Draw means that the data is modified by the application, and used as a source for GL drawing. Read means the data is modified by //// reading data from GL, and used to return that data when queried by the application. Copy means that the data is modified by reading from the GL, and used as a source for drawing. glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * numVertices, vertices, GL_STATIC_DRAW); //// By default, all client-side capabilities are disabled, including all generic vertex attribute arrays. //// When enabled, the values in a generic vertex attribute array will be accessed and used for rendering when calls are made to vertex array commands (like glDrawArrays/glDrawElements) //// A GL_INVALID_VALUE will be generated if the index parameter is greater than or equal to GL_MAX_VERTEX_ATTRIBS glEnableVertexAttribArray(0); //// Defines an array of generic vertex attribute data. Takes an index, a size specifying the number of components (in this case, floats)(has a max of 4) //// The third parameter, type, can be GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_FIXED, or GL_FLOAT //// The fourth parameter specifies whether to normalize fixed-point data values, the fifth parameter is the stride which is the offset (in bytes) between generic vertex attributes //// The fifth parameter is a pointer to the first component of the first generic vertex attribute in the array. If a named buffer object is bound to GL_ARRAY_BUFFER (and it is, in this case) //// then the pointer parameter is treated as a byte offset into the buffer object's data. glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)16); //// You'll note sizeof(VertexFormat) is our stride, because each vertex contains data that adds up to that size. //// You'll also notice we offset this parameter by 16 bytes, this is because the vec3 position attribute is after the vec4 color attribute. A vec4 has 4 floats, each being 4 bytes //// so we offset by 4*4=16 to make sure that our first attribute is actually the position. The reason we put position after color in the struct has to do with padding. //// For more info on padding, Google it. //// This is our color attribute, so the offset is 0, and the size is 4 since there are 4 floats for color. glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)0); } }; // The basic structure for a Circle. We need a center, a radius, and VBO and total number of vertices. struct Line{ glm::mat4 MVP; glm::vec3 point1; glm::vec3 point2; stuff_for_drawing base; }line; struct Cylinder{ glm::mat4 MVP; float radius; glm::vec3 point1; glm::vec3 point2; stuff_for_drawing base; }cylinder; // This function return the value between min and mx with the least distance value to x. This is called clamping. float clamp_on_range(float x, float min, float max) { if (x < min) return min; if (x > max) return max; return x; } //Convert the circle's position from world coordinate system to the box's model cordinate system. bool is_colliding(Line &l1, Cylinder &c1) { // We Change the line equation to parametric form. /* Assume that P1 and P2 are the closest points on line 1 and 2 respectively. So, P1 = L1(s) = point1 + (s* d1) P2 = L2(t) = point1 + (t* d2) for some constant s and t. the vector joining P1 and P2 is v. thus, v(s,t) = L1(s) + L2(t) So, since v is perpendicular to both L1 and L2. d1.v(s,t) = 0 d2.v(s,t) = 0 substituting the parametric equation for v(s,t) and expanding them gives us: (d1.d1)s - (d1.d2)t = -(d1.r) and (d2.d1)s - (d2.d2)t = -(d2.r) where r = l1.point1 - l2.point1 this can also be written as : |a -b| |s| = |-c| |b -c| |t| |-f| where; a =d1.d1 b= d1.d2 c = d1.r e = d2.d2 f = d2.r d = ae - b^2; solving this system of equation we get: s = (bf -ce)/d t = (af -bc)/d substituting these values in the quation gives us the closest point between two line segments. We can then check if these points lie on the line segment or outside. We then compute the distance between these points, and if the distance is less than a specified threshold then a collision is said to have occoured. If you want more detailed explanations, check the book Real-time Collision detection by Ericson, page 146. */ glm::vec3 d1, d2, r; d1 = l1.point2 - l1.point1; d2 = c1.point2 - c1.point1; r = l1.point1 - c1.point1; float a = glm::dot(d1, d1); float b = glm::dot(d1, d2); float c = glm::dot(d1, r); float e = glm::dot(d2, d2); float f = glm::dot(d2, r); float d = (a*e) - (b*b); float s = ((b*f) - (c*e)) / d; float t = ((a*f) - (b*c)) / d; //consider the equation of the line in parametric form: // P = Point1 + t * directionVector; // Where t is the constant, such that P lies on the on the plane /* since its a parametric representation, if the constants s and t are greater than 1, then the point lies along the vectorPQ but farther down the line i.e not on the line segment. And if the constants are less than 0, then the point lies along the vector -PQ, but after P, so not on the line segment PQ. Thus we can bail at this point knowing no collision occoured. collision detection between two Lines whcih extend infinitly will not have this check. */ glm::vec3 p1, p2; s = clamp_on_range(s, 0.0f, 1.0f); t = clamp_on_range(t, 0.0f, 1.0f); p1 = l1.point1 + (s * d1); p2 = c1.point1 + (t * d2); if (s == 0.0f || s == 1.0f) { //When the nearest point is between the two planes containing the the circles at the end of the cylinder, //We find the projection of that point on the line joining the centers of the cylinder. d = glm::dot(p1 - c1.point1, d2); t = d / glm::length(d2); t = clamp_on_range(t, 0.0f, 1.0f); p2 = c1.point1 + (t * d2); } aaa = p1; bbb = p2; if (t == 0.0f || t == 1.0f) { //If the closest point is near the end of the cylinder, we need to detect if the line intersects the the circle or not. glm::vec3 n = glm::normalize(glm::cross(d1, d2)); glm::vec3 RadiusVec = glm::normalize(glm::cross(n, d2)) * c1.radius; glm::vec3 pointA, pointB; pointA = p2 + RadiusVec; pointB = p2 - RadiusVec; glm::vec3 AR, BR; glm::vec3 diameter = pointB - pointA; AR = glm::normalize(glm::cross(pointA - l1.point1, diameter)); BR = glm::normalize(glm::cross(diameter, pointA - l1.point2)); //If both the end points of the line segment are on the same side of the circle,then the line segment is not intersecting the circle. if (glm::dot(AR, BR) < 0.0f) return false; // Early exit. The line and the cylinder are not colliding. // get the plane contating the two lines, and find the two points on the edge of tcylinder(diameter). //If the end points of the diameter are on the same side of the line l1, then the line intersects cylinder AR = glm::normalize(glm::cross(pointA - l1.point1,d1)); BR = glm::normalize(glm::cross(d1,pointB - l1.point1)); if (glm::dot(AR, BR) >= 0.0f) { aaa = pointA; bbb = pointB; return true; //early quit. the line intersects the cylinder } else return false; // Early quit. they do not intersect. } float dis = glm::distance(p1, p2); if (dis <= cylinder.radius) // If the closest point is closer than the distance of a radius, the objects are colliding. { return true; } else return false; } //This function sets up the two shapes we need for this example. void setup() { int NumberOfDivisions = 20; line.point1 = glm::vec3(-0.5f, 0.5f, 0.0f); line.point2 = glm::vec3(-0.5f, -0.5f, 0.0f); float radius = 0.25f; cylinder.radius = radius; cylinder.point1 = glm::vec3(0.0f, 0.5f, 0.0f); cylinder.point2 = glm::vec3(0.0f, -0.5f, 0.0f); VertexFormat center1(cylinder.point1, glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)); VertexFormat center2(cylinder.point2, glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)); std::vector<VertexFormat> vertices; float height = glm::distance(cylinder.point1, cylinder.point2); float theta = 360.0f / NumberOfDivisions; VertexFormat A, B, C, D; //Circle vertex generation //In this example we are not implementing the proper the code for indices. We are just going to produce redundant information in the buffer. //since we are only having a small number of objects on the screen currently, this redundancy should not matter. for (int i = 0; i < NumberOfDivisions; i++) { A = VertexFormat(glm::vec3(radius * cos(glm::radians(i*theta)),0.5f, radius * sin(glm::radians(i*theta))), glm::vec4(0.7f, 0.20f, 0.0f, 1.0f)); B = VertexFormat(glm::vec3(radius * cos(glm::radians((i + 1)*theta)), 0.5f, radius * sin(glm::radians((i + 1)*theta))), glm::vec4(0.7f, 0.20f, 0.0f, 1.0f)); C = VertexFormat(glm::vec3(radius * cos(glm::radians(i*theta)), -0.5f, radius * sin(glm::radians(i*theta))), glm::vec4(0.0f, 0.20f, 0.7f, 1.0f)); D = VertexFormat(glm::vec3(radius * cos(glm::radians((i + 1)*theta)), -0.5f, radius * sin(glm::radians((i + 1)*theta))), glm::vec4(0.0f, 0.20f, 0.7f, 1.0f)); //In every iteration, the center, the point at angle theta and at angle (theta+delta) are fed into the buffer. vertices.push_back(center1); vertices.push_back(A); vertices.push_back(B); vertices.push_back(center2); vertices.push_back(C); vertices.push_back(D); vertices.push_back(A); vertices.push_back(C); vertices.push_back(B); vertices.push_back(C); vertices.push_back(D); vertices.push_back(B); } cylinder.base.initBuffer(12 * NumberOfDivisions, &vertices[0]); } // Global data members #pragma region Global Data member // This is your reference to your shader program. // This will be assigned with glCreateProgram(). // This program will run on your GPU. GLuint program; // These are your references to your actual compiled shaders GLuint vertex_shader; GLuint fragment_shader; // This is a reference to your uniform MVP matrix in your vertex shader GLuint uniMVP; GLuint color; glm::mat4 view; glm::mat4 proj; glm::mat4 PV; glm::mat4 MVP; // Reference to the window object being created by GLFW. GLFWwindow* window; #pragma endregion // Functions called only once every time the program is executed. #pragma region Helper_functions std::string readShader(std::string fileName) { std::string shaderCode; std::string line; // We choose ifstream and std::ios::in because we are opening the file for input into our program. // If we were writing to the file, we would use ofstream and std::ios::out. std::ifstream file(fileName, std::ios::in); // This checks to make sure that we didn't encounter any errors when getting the file. if (!file.good()) { std::cout << "Can't read file: " << fileName.data() << std::endl; // Return so we don't error out. return ""; } // ifstream keeps an internal "get" position determining the location of the element to be read next // seekg allows you to modify this location, and tellg allows you to get this location // This location is stored as a streampos member type, and the parameters passed in must be of this type as well // seekg parameters are (offset, direction) or you can just use an absolute (position). // The offset parameter is of the type streamoff, and the direction is of the type seekdir (an enum which can be ios::beg, ios::cur, or ios::end referring to the beginning, // current position, or end of the stream). file.seekg(0, std::ios::end); // Moves the "get" position to the end of the file. shaderCode.resize((unsigned int)file.tellg()); // Resizes the shaderCode string to the size of the file being read, given that tellg will give the current "get" which is at the end of the file. file.seekg(0, std::ios::beg); // Moves the "get" position to the start of the file. // File streams contain two member functions for reading and writing binary data (read, write). The read function belongs to ifstream, and the write function belongs to ofstream. // The parameters are (memoryBlock, size) where memoryBlock is of type char* and represents the address of an array of bytes are to be read from/written to. // The size parameter is an integer that determines the number of characters to be read/written from/to the memory block. file.read(&shaderCode[0], shaderCode.size()); // Reads from the file (starting at the "get" position which is currently at the start of the file) and writes that data to the beginning // of the shaderCode variable, up until the full size of shaderCode. This is done with binary data, which is why we must ensure that the sizes are all correct. file.close(); // Now that we're done, close the file and return the shaderCode. return shaderCode; } // This method will consolidate some of the shader code we've written to return a GLuint to the compiled shader. // It only requires the shader source code and the shader type. GLuint createShader(std::string sourceCode, GLenum shaderType) { // glCreateShader, creates a shader given a type (such as GL_VERTEX_SHADER) and returns a GLuint reference to that shader. GLuint shader = glCreateShader(shaderType); const char *shader_code_ptr = sourceCode.c_str(); // We establish a pointer to our shader code string const int shader_code_size = sourceCode.size(); // And we get the size of that string. // glShaderSource replaces the source code in a shader object // It takes the reference to the shader (a GLuint), a count of the number of elements in the string array (in case you're passing in multiple strings), a pointer to the string array // that contains your source code, and a size variable determining the length of the array. glShaderSource(shader, 1, &shader_code_ptr, &shader_code_size); glCompileShader(shader); // This just compiles the shader, given the source code. GLint isCompiled = 0; // Check the compile status to see if the shader compiled correctly. glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled); if (isCompiled == GL_FALSE) { char infolog[1024]; glGetShaderInfoLog(shader, 1024, NULL, infolog); // Print the compile error. std::cout << "The shader failed to compile with the error:" << std::endl << infolog << std::endl; // Provide the infolog in whatever manor you deem best. // Exit with failure. glDeleteShader(shader); // Don't leak the shader. // NOTE: I almost always put a break point here, so that instead of the program continuing with a deleted/failed shader, it stops and gives me a chance to look at what may // have gone wrong. You can check the console output to see what the error was, and usually that will point you in the right direction. } return shader; } // Initialization code void init() { // Initializes the glew library glewInit(); // Enables the depth test, which you will want in most cases. You can disable this in the render loop if you need to. glEnable(GL_DEPTH_TEST); // Read in the shader code from a file. std::string vertShader = readShader("VertexShader.glsl"); std::string fragShader = readShader("FragmentShader.glsl"); // createShader consolidates all of the shader compilation code vertex_shader = createShader(vertShader, GL_VERTEX_SHADER); fragment_shader = createShader(fragShader, GL_FRAGMENT_SHADER); // A shader is a program that runs on your GPU instead of your CPU. In this sense, OpenGL refers to your groups of shaders as "programs". // Using glCreateProgram creates a shader program and returns a GLuint reference to it. program = glCreateProgram(); glAttachShader(program, vertex_shader); // This attaches our vertex shader to our program. glAttachShader(program, fragment_shader); // This attaches our fragment shader to our program. // This links the program, using the vertex and fragment shaders to create executables to run on the GPU. glLinkProgram(program); // End of shader and program creation // Creates the view matrix using glm::lookAt. // First parameter is camera position, second parameter is point to be centered on-screen, and the third paramter is the up axis. view = glm::lookAt(glm::vec3(0.0f, 0.0f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); // Creates a projection matrix using glm::perspective. // First parameter is the vertical FoV (Field of View), second paramter is the aspect ratio, 3rd parameter is the near clipping plane, 4th parameter is the far clipping plane. proj = glm::perspective(45.0f, 800.0f / 800.0f, 0.1f, 100.0f); //proj = glm::ortho(0.0f,800.0f, 0.0f, 800.0f,0.1f,100.0f); PV = proj * view; glm::mat4 translation = glm::translate(glm::vec3(0.0f, 0.0f, 0.0f)); MVP = PV* translation; MVP1 = MVP; view = glm::lookAt(glm::vec3(0.0f, 3.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)); //Create another position and perspective for camera, and compute the MVP matrix for that position. //Since we'll be just interchanging between two positions of the camera, there is no point in computing the MVP every frame. We will do that later while implementing camera controls. MVP2 = (proj * view) * translation; MVP2 = glm::mat4(1); // This gets us a reference to the uniform variable in the vertex shader, which is called "color". // We're using this variable to change color during runtime, without changing the buffer values. // Only 2 parameters required: A reference to the shader program and the name of the uniform variable within the shader code. uniMVP = glGetUniformLocation(program, "MVP"); color = glGetUniformLocation(program, "blue"); // This is not necessary, but I prefer to handle my vertices in the clockwise order. glFrontFace defines which face of the triangles you're drawing is the front. // Essentially, if you draw your vertices in counter-clockwise order, by default (in OpenGL) the front face will be facing you/the screen. If you draw them clockwise, the front face // will face away from you. By passing in GL_CW to this function, we are saying the opposite, and now the front face will face you if you draw in the clockwise order. // If you don't use this, just reverse the order of the vertices in your array when you define them so that you draw the points in a counter-clockwise order. glFrontFace(GL_CCW); // This is also not necessary, but more efficient and is generally good practice. By default, OpenGL will render both sides of a triangle that you draw. By enabling GL_CULL_FACE, // we are telling OpenGL to only render the front face. This means that if you rotated the triangle over the X-axis, you wouldn't see the other side of the triangle as it rotated. //glEnable(GL_CULL_FACE); //We are disabling hte cull face, because we wish to see both the front and back of the objects in wireframe mode for better understanding the depth. // Determines the interpretation of polygons for rasterization. The first parameter, face, determines which polygons the mode applies to. // The face can be either GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK // The mode determines how the polygons will be rasterized. GL_POINT will draw points at each vertex, GL_LINE will draw lines between the vertices, and // GL_FILL will fill the area inside those lines. //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } #pragma endregion // Functions called between every frame. game logic #pragma region util_functions // This runs once every physics timestep. void update() { // if the objects are colliding then change color, else recvet back to original color if (is_colliding(line, cylinder)) { blue = 1.0f; } else { blue = 0.0f; } // Get the cursor position with respect ot hte window. double x, y; glfwGetCursorPos(window, &x, &y); //Since the cursor posiiton is represented in pixel values, //dividing it by the window specs will reduce the position to 0-1 range. //multiplying it with 2 and then subtracting it with 1 wil bring the //mouse position to -1 ot 1. // Since the screen's origin is on the top, we need to negate the y values. x = x / 800.0f; y = y * (-1.0f) / 800.0f; x = (x * 2) - 1; y = (y * 2) + 1; //the Pointchange variable is used to interchange between the two points of the same line if (pointChange > 0) { currentlySelected = &(line.point1); line.point1.x = x; line.point1.y = y; } else { currentlySelected = &(line.point2); line.point2.x = x; line.point2.y = y; } } // This function runs every frame void renderScene() { // Clear the color buffer and the depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the screen to white glClearColor(1.0 -blue, 1.0-blue, 1.0-blue, 1.0); // Tell OpenGL to use the shader program you've created. glUseProgram(program); //since we are not removing the program currently in use, these primitive functions will also use the same shader. // Thus the MVP and color will be set in shader. Thus the lines will be in perspective projection // Set the uniform matrix in our shader to our MVP matrix for the line. glUniformMatrix4fv(uniMVP, 1, GL_FALSE, glm::value_ptr(MVP)); glLineWidth(2.5f); glUniform3f(color, 0.0f,0.0f,blue); glBegin(GL_LINES); glVertex3fv((float*)&line.point1); glVertex3fv((float*)&line.point2); glEnd(); //Drawing the cylinder glUniform3f(color, blue, blue, blue); glBindBuffer(GL_ARRAY_BUFFER ,cylinder.base.vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)16); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)0); glDrawArrays(GL_TRIANGLES, 0, cylinder.base.numberOfVertices); //drawing the x,yand z axis glLineWidth(0.7f); //x-axis (red Color) glUniform3f(color, 1.0f, 0.0f, 0.0f); glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(100.0f, 0.0f, 0.0f); glEnd(); //y-axis (green color) glUniform3f(color, 0.0f, 1.0f, 0.0f); glBegin(GL_LINES); glVertex3f(0.0f, 100.0f,0.0f); glVertex3f(0.0f, 0.0f, 0.0f); glEnd(); //z-axis (cyan color) glUniform3f(color, 0.0f, 1.0f, 1.0f); glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 100.0f); glVertex3f(0.0f, 0.0f, 0.0f); glEnd(); } // This function is used to handle key inputs. // It is a callback funciton. i.e. glfw takes the pointer to this function (via function pointer) and calls this function every time a key is pressed in the during event polling. void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { float moverate = 0.25f; ////This set of controls are used to move one point (point1) of the line. if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) lineChange *= -1; if (key == GLFW_KEY_LEFT_SHIFT && action == GLFW_PRESS) pointChange *= -1; if (key == GLFW_KEY_W && action == GLFW_PRESS) currentlySelected->z -= 0.05f; if (key == GLFW_KEY_S && action == GLFW_PRESS) currentlySelected->z += 0.05f; //This changes the MVP (modelViewProjection Matrix) in current use, This results in change in camera if (key == GLFW_KEY_LEFT_CONTROL && action == GLFW_PRESS) { if (MVP == MVP1) MVP = MVP2; else MVP = MVP1; } } #pragma endregion void main() { glfwInit(); // Creates a window given (width, height, title, monitorPtr, windowPtr). // Don't worry about the last two, as they have to do with controlling which monitor to display on and having a reference to other windows. Leaving them as nullptr is fine. window = glfwCreateWindow(800, 800, "Line segment-Cylinder collision detection in 3D", nullptr, nullptr); std::cout << "\n This is a collision test between a cylinder and Line segment in 3D.\n\n\n\n\n"; std::cout << "Use Mouse to move in x-y plane, and \"w and s\" to move in z axis.\n"; std::cout << "Use left Shift to change the prespective of the camera between, perspective and orthagonal.\n"; std::cout << "Use \"left shift\" to change betweeen the vertices in contrl "; // Makes the OpenGL context current for the created window. glfwMakeContextCurrent(window); // Sets the number of screen updates to wait before swapping the buffers. // Setting this to zero will disable VSync, which allows us to actually get a read on our FPS. Otherwise we'd be consistently getting 60FPS or lower, // since it would match our FPS to the screen refresh rate. // Set to 1 to enable VSync. glfwSwapInterval(0); // Initializes most things needed before the main loop init(); // Sends the funtion as a funtion pointer along with the window to which it should be applied to. glfwSetKeyCallback(window, key_callback); setup(); // Enter the main loop. while (!glfwWindowShouldClose(window)) { // Call to update() which will update the gameobjects. update(); // Call the render function. renderScene(); // Swaps the back buffer to the front buffer // Remember, you're rendering to the back buffer, then once rendering is complete, you're moving the back buffer to the front so it can be displayed. glfwSwapBuffers(window); // Checks to see if any events are pending and then processes them. glfwPollEvents(); } // After the program is over, cleanup your data! glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteProgram(program); // Note: If at any point you stop using a "program" or shaders, you should free the data up then and there. // Frees up GLFW memory glfwTerminate(); }
[ "lunalovecraft@gmail.com" ]
lunalovecraft@gmail.com
3db8a68b433891379fc8804f5949ef73a2268a34
1c4108ffbfe03be4d4b1914775192750af930e29
/src/texture_handler.cpp
a3323e5bcbdf00c83280893086d4b212796ccbf9
[]
no_license
tropuq/SFMLVisualizer
659f04d1bd6ea3cdd1c15ef6a2fd29a7cda0fc90
07dd3b844edc2c71ce62cee5f16a4b594c2a2132
refs/heads/master
2020-03-10T22:00:23.046059
2018-10-26T11:04:20
2018-10-26T11:04:20
129,608,059
0
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
#include "../include/texture_handler.h" #include <cassert> #include <iostream> using namespace sf; using namespace std; TextureHandler::TextureHandler(const string &dir) { icon_directory = dir; } Texture* TextureHandler::getTexture(const string &name) { if (mp.find(name) == mp.end()) assert(mp[name].loadFromFile(icon_directory + '/' + name)); return &mp[name]; }
[ "niciejewski98@gmail.com" ]
niciejewski98@gmail.com
a6b620657a6039399bd3a0225a7c6305d8d91ee9
966818603978f073d4f4ed85709ec1ad0c794be4
/INSIGHTV2_1_3/include/ACE_Wrappers/ace/OS_NS_arpa_inet.cpp
3d046c7bf28352c14246f4cb8bb11ff4a941b946
[]
no_license
lastvangogh/YANGZE
c337743e29dafadbfb1ed532f6c9ce35ce7f24df
870eb6066b360036a49ebe40bd9435cdd31ff5ac
refs/heads/master
2020-09-01T13:43:02.027589
2019-11-06T08:40:09
2019-11-06T08:40:09
218,970,441
0
0
null
null
null
null
UTF-8
C++
false
false
2,907
cpp
// -*- C++ -*- #include "ace/OS_NS_arpa_inet.h" #if !defined (ACE_HAS_INLINED_OSCALLS) # include "ace/OS_NS_arpa_inet.inl" #endif /* ACE_HAS_INLINED_OSCALLS */ #include "ace/Basic_Types.h" #include <cstdlib> ACE_BEGIN_VERSIONED_NAMESPACE_DECL int ACE_OS::inet_aton (const char *host_name, struct in_addr *addr) { #if defined (ACE_LACKS_INET_ATON) # if defined (ACE_WIN32) // Windows Server 2003 changed the behavior of a zero-length input // string to inet_addr(). It used to return 0 (INADDR_ANY) but now // returns -1 (INADDR_NONE). It will return INADDR_ANY for a 1-space // string, though, as do previous versions of Windows. if (host_name == 0 || host_name[0] == '\0') host_name = " "; # endif /* ACE_WIN32 */ # if defined (ACE_LACKS_INET_ADDR) if (!host_name) return 0; ACE_UINT32 ip = 0; int part = 0; for (const char *dot; *host_name; host_name = *dot ? dot + 1 : dot, ++part) { if (part > 3) return 0; dot = ACE_OS::strchr (host_name, '.'); if (!dot) dot = host_name + ACE_OS::strlen (host_name); char *last; const unsigned long n = std::strtoul (host_name, &last, 0); if (last != dot) return 0; if (!*dot) switch (part) { case 0: # if ACE_SIZEOF_LONG > 4 if (n > 0xffffffff) return 0; # endif ip = static_cast<ACE_UINT32> (n); continue; case 1: if (n > 0xffffff) return 0; ip <<= 24; ip |= n; continue; case 2: if (n > 0xffff) return 0; ip <<= 16; ip |= n; continue; } if (n > 0xff) return 0; ip <<= 8; ip |= n; } addr->s_addr = ACE_HTONL (ip); return 1; # else unsigned long ip_addr = ACE_OS::inet_addr (host_name); if (ip_addr == INADDR_NONE // Broadcast addresses are weird... && ACE_OS::strcmp (host_name, "255.255.255.255") != 0) return 0; else if (addr == 0) return 0; else { addr->s_addr = ip_addr; // Network byte ordered return 1; } # endif // ACE_LACKS_INET_ADDR #elif defined (ACE_VXWORKS) && (ACE_VXWORKS <= 0x690) // inet_aton() returns OK (0) on success and ERROR (-1) on failure. // Must reset errno first. Refer to WindRiver SPR# 34949, SPR# 36026 ::errnoSet(0); int result = ERROR; ACE_OSCALL (::inet_aton (const_cast <char*>(host_name), addr), int, ERROR, result); return (result == ERROR) ? 0 : 1; #else // inet_aton() returns 0 upon failure, not -1 since -1 is a valid // address (255.255.255.255). ACE_OSCALL_RETURN (::inet_aton (host_name, addr), int, 0); #endif /* ACE_LACKS_INET_ATON */ } ACE_END_VERSIONED_NAMESPACE_DECL
[ "zhangzhuo@yangzeinvest.com" ]
zhangzhuo@yangzeinvest.com
f4387807bccd638890b8515557eb8ec83e463bd9
bf7de51feafa43db6b94d95266cf88a7fbb58387
/Summary/libs/pdftron/SDF/DocSnapshot.h
7c39d115b8846c0ac422623173667a0d9938349c
[]
no_license
Napomosh/SummaryWork
39b7521d28a9008fe222e724e8ed114b6060beb3
e26b4e0797dd6039292b86fbfb2f0cd0878c177b
refs/heads/master
2023-05-14T14:12:57.414048
2021-06-07T23:38:20
2021-06-07T23:38:20
341,829,260
0
0
null
null
null
null
UTF-8
C++
false
false
1,843
h
//--------------------------------------------------------------------------------------- // Copyright (c) 2001-2020 by PDFTron Systems Inc. All Rights Reserved. // Consult legal.txt regarding legal and license information. //--------------------------------------------------------------------------------------- // !Warning! This file is autogenerated, modify the .codegen file, not this one // (any changes here will be wiped out during the autogen process) #ifndef PDFTRON_H_CPPSDFDocSnapshot #define PDFTRON_H_CPPSDFDocSnapshot #include <pdftron/C/SDF/TRN_DocSnapshot.h> #include <pdftron/Common/BasicTypes.h> #include <pdftron/Common/UString.h> #include <pdftron/PDF/PDFDoc.h> namespace pdftron { namespace SDF { /** * The class DocSnapshot. * Represents a state of the document. */ class DocSnapshot { public: DocSnapshot(const DocSnapshot& other); DocSnapshot(TRN_DocSnapshot impl); DocSnapshot& operator= (const DocSnapshot& other); ~DocSnapshot(); void Destroy(); //methods: /** * Returns a hash that is unique to particular document states. * * @return A hash that is unique to particular document states. */ UInt32 GetHash() const; /** * Returns whether this snapshot is valid. * * @return Whether this snapshot is valid. */ bool IsValid() const; /** * Returns whether this snapshot's document state is equivalent to another. * * @param snapshot -- the other snapshot with which to compare. * @return Whether this snapshot's document state is equivalent to another. */ bool Equals(DocSnapshot snapshot) const; // Internal use only DocSnapshot(); #ifndef SWIGHIDDEN TRN_DocSnapshot m_impl; #endif private: #ifndef SWIGHIDDEN mutable bool m_owner; #endif }; #include "pdftron/Impl/DocSnapshot.inl" } //end pdftron } //end SDF #endif //PDFTRON_H_CPPSDFDocSnapshot
[ "sashulik999@gmail.com" ]
sashulik999@gmail.com
79bf5485d5fe4e7f7f47d4a8d2f20ae20505eb0b
4b99e2c54be595e3fa107e59c5da9a2bfa632531
/NativeLogic/src/GameLogic/MetalOrb.h
770df748e76b7b54f60aed6996a019c409d719f4
[]
no_license
SE346-H11-NT/Project
f0789a6896b47a5e358458eb430c67e15c1e6890
a1038d9f6104df5096a57e5a289233a603f3b7a7
refs/heads/master
2020-08-03T19:10:01.653852
2016-12-25T16:59:43
2016-12-25T16:59:43
73,538,873
0
0
null
null
null
null
UTF-8
C++
false
false
761
h
#ifndef MetalOrb_h__ #define MetalOrb_h__ #include "Mobs.h" #define METAL_ORB_BOUND_SIZE Size(16.0F, 16.0F) #define METAL_ORB_RESOURCE_LINK (tstring(_T("Resource//Bosses//ShadowEntrance//MetalOrb")) + EXTENSION_PICTURE) #define METAL_ORB_RESOURCE_ROWS 1 #define METAL_ORB_RESOURCE_COLUMNS 1 class MetalOrb : public Mobs { public: MetalOrb(){} MetalOrb(T6Vec3 position); virtual ~MetalOrb(); virtual unsigned int getScore(); virtual void waitUpdate(); virtual void activateUpdate(); virtual void deadUpdate(); virtual bool affect(Object* obj, DWORD key); virtual void setBasicProperties(); virtual void deadEffect(); void setPos(T6Vec3 newPos); virtual void draw(); }; #endif // MetalOrb_h__
[ "tranminhtuan11a1@gmail.com" ]
tranminhtuan11a1@gmail.com
5f6583e42da0bc327d71f953a19ada985498edc8
795535d17e9da8afe6d103dcf8f3dea8d435201f
/src/GameObjects/ObjectThemer.cpp
28b1e701344b82582806941bfb00e2dc7352e4f2
[]
no_license
LiudmilaMashkina/Runner
4696033ac36a677d3a9001b913e11285721bcccf
abdcd83098bc3bac58ea315cdb563e3899426e11
refs/heads/master
2021-05-12T03:01:00.709510
2018-02-27T00:47:30
2018-02-27T00:47:30
117,604,929
0
0
null
null
null
null
UTF-8
C++
false
false
441
cpp
#pragma warning(push, 0) #pragma warning(pop) #include "ObjectThemer.h" #include "Utils/Environment.h" ObjectThemer::ObjectThemer() {} ObjectThemer::ThemeId ObjectThemer::getTheme() { int start = static_cast<int>(ObjectThemer::ThemeId::EnumStart) + 1; int end = static_cast<int>(ObjectThemer::ThemeId::EnumEnd) - 1; return static_cast<ObjectThemer::ThemeId>(Environment::generateIntRand(start, end)); }
[ "liudmilamashkina@gmail.com" ]
liudmilamashkina@gmail.com
223c34dbc43733d6d6060719f222b933a809b20e
5fd214ad737974f864ec2c055495e9696bbf24eb
/examples/mechanics/flexible_body/linear_external_ffr_spatial_beam/system.h
caff8a8c4ca89bd1f0242ec81d42ce51e2e5dcb0
[]
no_license
tsschindler/mbsim
28ede3f2035592532738b833fefe6a8755dfd59e
97fdb10cfe9e22fb962b7522a9b758d1cdc571ce
refs/heads/master
2021-01-15T10:18:44.245224
2015-06-05T11:37:17
2015-06-05T11:37:17
36,926,919
1
0
null
2015-06-05T11:37:18
2015-06-05T10:29:23
C++
UTF-8
C++
false
false
411
h
#ifndef _SYSTEM_H #define _SYSTEM_H #include "mbsim/dynamic_system_solver.h" #include "mbsimFlexibleBody/flexible_body/flexible_body_linear_external_ffr.h" #include "mbsim/rigid_body.h" #include <string> class System : public MBSim::DynamicSystemSolver { public: System(const std::string &projectName); private: MBSimFlexibleBody::FlexibleBodyLinearExternalFFR *test; }; #endif /* _SYSTEM_H */
[ "kgrundl@gmail.com@c123ba7f-e748-9643-39d5-9b7b2de17e7a" ]
kgrundl@gmail.com@c123ba7f-e748-9643-39d5-9b7b2de17e7a
d3f389ce64e2952fa0d2b731adc18d44f3113945
15bb0920fecafb9c6fe37e6b30e90f8277c9a710
/devel/include/sar_localization/Csi.h
7cf8da9502c54d3225e7a612711cb213b60d3f64
[]
no_license
ClarenceZSK/Root-catkin_ws
673a20c560958197bc7b783873ff71fbc39623f2
6a1886e6fee42a1d4209595765294191c0440709
refs/heads/master
2020-12-30T10:50:06.238611
2015-09-03T12:59:12
2015-09-03T12:59:12
31,320,005
0
0
null
null
null
null
UTF-8
C++
false
false
6,074
h
// Generated by gencpp from file sar_localization/Csi.msg // DO NOT EDIT! #ifndef SAR_LOCALIZATION_MESSAGE_CSI_H #define SAR_LOCALIZATION_MESSAGE_CSI_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> #include <std_msgs/Float64.h> namespace sar_localization { template <class ContainerAllocator> struct Csi_ { typedef Csi_<ContainerAllocator> Type; Csi_() : header() , cos_value() { } Csi_(const ContainerAllocator& _alloc) : header(_alloc) , cos_value(_alloc) { } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef ::std_msgs::Float64_<ContainerAllocator> _cos_value_type; _cos_value_type cos_value; typedef boost::shared_ptr< ::sar_localization::Csi_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::sar_localization::Csi_<ContainerAllocator> const> ConstPtr; }; // struct Csi_ typedef ::sar_localization::Csi_<std::allocator<void> > Csi; typedef boost::shared_ptr< ::sar_localization::Csi > CsiPtr; typedef boost::shared_ptr< ::sar_localization::Csi const> CsiConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::sar_localization::Csi_<ContainerAllocator> & v) { ros::message_operations::Printer< ::sar_localization::Csi_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace sar_localization namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'sar_localization': ['/home/clarence/catkin_ws/src/sar_localization/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::sar_localization::Csi_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::sar_localization::Csi_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::sar_localization::Csi_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::sar_localization::Csi_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::sar_localization::Csi_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::sar_localization::Csi_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::sar_localization::Csi_<ContainerAllocator> > { static const char* value() { return "243b6b66f6697b18c3d1b19c55371a5a"; } static const char* value(const ::sar_localization::Csi_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x243b6b66f6697b18ULL; static const uint64_t static_value2 = 0xc3d1b19c55371a5aULL; }; template<class ContainerAllocator> struct DataType< ::sar_localization::Csi_<ContainerAllocator> > { static const char* value() { return "sar_localization/Csi"; } static const char* value(const ::sar_localization::Csi_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::sar_localization::Csi_<ContainerAllocator> > { static const char* value() { return "Header header\n\ std_msgs/Float64 cos_value\n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ \n\ ================================================================================\n\ MSG: std_msgs/Float64\n\ float64 data\n\ "; } static const char* value(const ::sar_localization::Csi_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::sar_localization::Csi_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.cos_value); } ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct Csi_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::sar_localization::Csi_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::sar_localization::Csi_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "cos_value: "; s << std::endl; Printer< ::std_msgs::Float64_<ContainerAllocator> >::stream(s, indent + " ", v.cos_value); } }; } // namespace message_operations } // namespace ros #endif // SAR_LOCALIZATION_MESSAGE_CSI_H
[ "shengkai.zhang@gmail.com" ]
shengkai.zhang@gmail.com
750a38bce1f914031c9f1fce234c20854d33d47d
65ff0d6c1d995fbcc3402708fce77c6bf451998d
/calc_nPE/calc_nPE.cpp
e923c5aca83c2a6afc83707dae9011cbd1e078ce
[]
no_license
mabrow05/ParallelAnalyzer
de1b11d7718ab06bae579a5eebcc9bab3e890436
ad0855caae19ed61cd915ee66ef3b7b55976a6ab
refs/heads/master
2021-01-19T11:35:27.998125
2015-12-21T15:48:01
2015-12-21T15:48:01
34,797,061
0
0
null
null
null
null
UTF-8
C++
false
false
8,889
cpp
#include <iostream> #include <fstream> #include <cmath> #include <cstdlib> #include <sstream> // ROOT libraries #include "TRandom3.h" #include <TTree.h> #include <TFile.h> #include <TH1F.h> #include <TH2F.h> #include <TF1.h> #include <TH1D.h> #include "fullTreeVariables.h" #include "MWPCGeometry.h" #include "pedestals.h" #include "cuts.h" #include "basic_reconstruction.h" #include "replay_pass2.h" #include "replay_pass3.h" using namespace std; int main(int argc, char *argv[]) { //cout.setf(ios::fixed, ios::floatfield); //cout.precision(12); // Run number integer istringstream ss(argv[1]); int runNumber; ss >> runNumber; cout << "runNumber = " << runNumber << endl; // Read source list int nSources = 0; string sourceName[3]; char tempList[500]; sprintf(tempList, "%s/source_list_%s.dat",getenv("SOURCE_LIST"), argv[1]); //cout << tempList << endl; ifstream fileList(tempList); if (fileList.is_open()) fileList >> nSources; cout << " ... Number of sources: " << nSources << endl; for (int n=0; n<nSources; n++) { fileList >> sourceName[n]; cout << " " << sourceName[n] << endl; } //Adding in here that we are only using runs with Sn bool correctSource = false; bool useSource[3] = {false,false,false}; for (int n=0; n<nSources; n++) { if (sourceName[n]=="Sn") { correctSource = true; useSource[n]=true; continue; } } if (!correctSource) { cout << "Source run with no Sn\n"; exit(0); } // Open output ntuple char tempOut[500]; sprintf(tempOut, "%s/nPE_weights_%s.root",getenv("NPE_WEIGHTS"), argv[1]); TFile *fileOut = new TFile(tempOut,"RECREATE"); // Read source positions double xEast[3], yEast[3], sigmaEast[3]; double xWest[3], yWest[3], sigmaWest[3]; char tempPos[500]; sprintf(tempPos, "%s/source_positions_%s.dat",getenv("SOURCE_POSITIONS"), argv[1]); ifstream filePos(tempPos); cout << " ... Reading source positions" << endl; for (int n=0; n<nSources; n++) { filePos >> xEast[n] >> yEast[n] >> sigmaEast[n] >> xWest[n] >> yWest[n] >> sigmaWest[n]; cout << xEast[n] << " " << yEast[n] << " " << sigmaEast[n] << " " << xWest[n] << " " << yWest[n] << " " << sigmaWest[n] << endl; } // Output histograms int nBin = 400; TH1F *his[8]; his[0] = new TH1F("his1_E0", "", nBin,0.0,4000.0); his[1] = new TH1F("his1_E1", "", nBin,0.0,4000.0); his[2] = new TH1F("his1_E2", "", nBin,0.0,4000.0); his[3] = new TH1F("his1_E3", "", nBin,0.0,4000.0); his[4] = new TH1F("his1_W0", "", nBin,0.0,4000.0); his[5] = new TH1F("his1_W1", "", nBin,0.0,4000.0); his[6] = new TH1F("his1_W2", "", nBin,0.0,4000.0); his[7] = new TH1F("his1_W3", "", nBin,0.0,4000.0); /*his[1][0] = new TH1F("his2_E0", "", nBin,0.0,4000.0); his[1][1] = new TH1F("his2_E1", "", nBin,0.0,4000.0); his[1][2] = new TH1F("his2_E2", "", nBin,0.0,4000.0); his[1][3] = new TH1F("his2_E3", "", nBin,0.0,4000.0); his[1][4] = new TH1F("his2_W0", "", nBin,0.0,4000.0); his[1][5] = new TH1F("his2_W1", "", nBin,0.0,4000.0); his[1][6] = new TH1F("his2_W2", "", nBin,0.0,4000.0); his[1][7] = new TH1F("his2_W3", "", nBin,0.0,4000.0); his[2][0] = new TH1F("his3_E0", "", nBin,0.0,4000.0); his[2][1] = new TH1F("his3_E1", "", nBin,0.0,4000.0); his[2][2] = new TH1F("his3_E2", "", nBin,0.0,4000.0); his[2][3] = new TH1F("his3_E3", "", nBin,0.0,4000.0); his[2][4] = new TH1F("his3_W0", "", nBin,0.0,4000.0); his[2][5] = new TH1F("his3_W1", "", nBin,0.0,4000.0); his[2][6] = new TH1F("his3_W2", "", nBin,0.0,4000.0); his[2][7] = new TH1F("his3_W3", "", nBin,0.0,4000.0);*/ // Open input ntuple char tempIn[500]; sprintf(tempIn, "%s/replay_pass3_%s.root",getenv("REPLAY_PASS3"), argv[1]); TFile *fileIn = new TFile(tempIn, "READ"); TTree *Tin = (TTree*)(fileIn->Get("pass3")); // Variables Tin->SetBranchAddress("pmt0_pass3", &pmt_pass3[0]); Tin->SetBranchAddress("pmt1_pass3", &pmt_pass3[1]); Tin->SetBranchAddress("pmt2_pass3", &pmt_pass3[2]); Tin->SetBranchAddress("pmt3_pass3", &pmt_pass3[3]); Tin->SetBranchAddress("pmt4_pass3", &pmt_pass3[4]); Tin->SetBranchAddress("pmt5_pass3", &pmt_pass3[5]); Tin->SetBranchAddress("pmt6_pass3", &pmt_pass3[6]); Tin->SetBranchAddress("pmt7_pass3", &pmt_pass3[7]); Tin->SetBranchAddress("xE_pass3", &xE_pass3); Tin->SetBranchAddress("yE_pass3", &yE_pass3); Tin->SetBranchAddress("xW_pass3", &xW_pass3); Tin->SetBranchAddress("yW_pass3", &yW_pass3); Tin->SetBranchAddress("PID_pass3", &PID_pass3); Tin->SetBranchAddress("type_pass3", &type_pass3); Tin->SetBranchAddress("side_pass3", &side_pass3); Tin->SetBranchAddress("posError_pass3", &posError_pass3); int nEvents = Tin->GetEntries(); cout << "Processing " << argv[1] << " ... " << endl; cout << "... nEvents = " << nEvents << endl; // Loop over events for (int i=0; i<nEvents; i++) { Tin->GetEvent(i); // Use Type 0 events if (type_pass3 != 0) continue; // First source (x,y) if (useSource[0]) { if (side_pass3 == 0) { if ( (xE_pass3 - xEast[0])*(xE_pass3 - xEast[0]) + (yE_pass3 - yEast[0])*(yE_pass3 - yEast[0]) < (2.*sigmaEast[0])*(2.*sigmaEast[0]) ) { for (int p=0; p<4; p++) { his[p]->Fill(pmt_pass3[p]); } } } if (side_pass3 == 1) { if ( (xW_pass3 - xWest[0])*(xW_pass3 - xWest[0]) + (yW_pass3 - yWest[0])*(yW_pass3 - yWest[0]) < (2.*sigmaWest[0])*(2.*sigmaWest[0]) ) { for (int p=4; p<8; p++) { his[p]->Fill(pmt_pass3[p]); } } } } // Second source (x,y) if (nSources > 1 && useSource[1]) { if (side_pass3 == 0) { if ( (xE_pass3 - xEast[1])*(xE_pass3 - xEast[1]) + (yE_pass3 - yEast[1])*(yE_pass3 - yEast[1]) < (2.*sigmaEast[1])*(2.*sigmaEast[1]) ) { for (int p=0; p<4; p++) { his[p]->Fill(pmt_pass3[p]); } } } if (side_pass3 == 1) { if ( (xW_pass3 - xWest[1])*(xW_pass3 - xWest[1]) + (yW_pass3 - yWest[1])*(yW_pass3 - yWest[1]) < (2.*sigmaWest[1])*(2.*sigmaWest[1]) ) { for (int p=4; p<8; p++) { his[p]->Fill(pmt_pass3[p]); } } } } // Third source (x,y) if (nSources > 2 && useSource[2]) { if (side_pass3 == 0) { if ( (xE_pass3 - xEast[2])*(xE_pass3 - xEast[2]) + (yE_pass3 - yEast[2])*(yE_pass3 - yEast[2]) < (2.*sigmaEast[2])*(2.*sigmaEast[2]) ) { for (int p=0; p<4; p++) { his[p]->Fill(pmt_pass3[p]); } } } if (side_pass3 == 1) { if ( (xW_pass3 - xWest[2])*(xW_pass3 - xWest[2]) + (yW_pass3 - yWest[2])*(yW_pass3 - yWest[2]) < (2.*sigmaWest[2])*(2.*sigmaWest[2]) ) { for (int p=4; p<8; p++) { his[p]->Fill(pmt_pass3[p]); } } } } } // Find maximum bin double maxBin[8]; double maxCounts[8]; for (int j=0; j<8; j++) { maxCounts[j] = -1.0; } double binCenter[8]; double binCenterMax[8]; double binCounts[8]; for (int i=0; i<nBin; i++) { for (int j=0; j<8; j++) { binCenter[j] = his[j]->GetBinCenter(i+1); binCounts[j] = his[j]->GetBinContent(i+1); if (binCounts[j] > maxCounts[j]) { maxCounts[j] = binCounts[j]; maxBin[j] = i; binCenterMax[j] = binCenter[j]; } } } // Define histogram fit ranges double xLow[8], xHigh[8]; for (int j=0; j<8; j++) { for (int i=maxBin[j]; i<nBin; i++) { if (his[j]->GetBinContent(i+1) < 0.5*maxCounts[j]) { xHigh[j] = his[j]->GetBinCenter(i+1); break; } } for (int i=maxBin[j]; i>0; i--) { if (his[j]->GetBinContent(i+1) < 0.5*maxCounts[j]) { xLow[j] = his[j]->GetBinCenter(i+1); break; } } } // Fit histograms TF1 *gaussian_fit[8]; double fitMean[8], fitSigma[8], nPE[8], nPE_per_channel[8]; for (int j=0; j<8; j++) { char fitName[500]; sprintf(fitName, "gaussian_fit_%i", j); gaussian_fit[j] = new TF1(fitName, "gaus", xLow[j], xHigh[j]); gaussian_fit[j]->SetParameter(0,maxCounts[j]); gaussian_fit[j]->SetParameter(1,binCenterMax[j]); gaussian_fit[j]->SetParameter(2,100.0); gaussian_fit[j]->SetParLimits(1,xLow[j],xHigh[j]); his[j]->Fit(fitName, "LRQ"); fitMean[j] = gaussian_fit[j]->GetParameter(1); fitSigma[j] = gaussian_fit[j]->GetParameter(2); nPE[j] = (fitMean[j]*fitMean[j])/(fitSigma[j]*fitSigma[j]); nPE_per_channel[j] = nPE[j]/fitMean[j]; } // Write results to file char tempResults[500]; sprintf(tempResults, "%s/nPE_weights_%s.dat",getenv("NPE_WEIGHTS"), argv[1]); ofstream outResults(tempResults); for (int j=0; j<8; j++) { outResults << fitMean[j] << " " << fitSigma[j] << " " << nPE[j] << " " << nPE_per_channel[j] << endl; } // Write output ntuple fileOut->Write(); fileOut->Close(); return 0; }
[ "michael.brown1@uky.edu" ]
michael.brown1@uky.edu
2cc25c996c5245c742c1531af7ef5ef897b5153b
576f46f49ddb06a20e0a24ccf12b998c4becbbee
/48_array_string_type.cpp
38b209b943fbc03a37317553de455eefc45d4b49
[]
no_license
yejoons2022/C
322c1070f927bcbdd1d5bdb6de58a26e077161f5
e932dc1437ac2b5267f3e4d20d544cf86f7c61c3
refs/heads/main
2023-02-21T05:52:29.398464
2021-01-28T11:44:36
2021-01-28T11:44:36
333,740,250
0
0
null
null
null
null
UHC
C++
false
false
316
cpp
#include <stdio.h> main() { char str[] = {"Good morning!"}; printf ("배열 str의 크기: %d \n", sizeof(str)); printf ("널 문자 문자형 출력: %c \n", str[13]); printf ("널 문자 정수형 출력: %d \n", str[13]); str[12] = '~'; printf ("문자열 출력: %s \n", str); return 0; }
[ "noreply@github.com" ]
yejoons2022.noreply@github.com
061ebd52d14edc14fe1319db07ba47d2d7e115c5
80fd548163c024b42111d63fb0877e079e61cdda
/targetFeature.cpp
04ab5053a70dc4300a7d7eb4050e572351267c4e
[]
no_license
Cxx0822/NAO_GolfVision_ML_C
b5859322e71c68a94e2db1aa2d0c28aa64a2dd42
38dcae05da5c34b03c820417915ee15a394372d4
refs/heads/master
2020-07-14T08:16:12.700494
2019-08-30T02:13:28
2019-08-30T02:13:28
205,281,108
2
0
null
null
null
null
GB18030
C++
false
false
2,409
cpp
#include "targetFeature.h" /*颜色特征提取类定义*/ ColorFeature::ColorFeature() { } ColorFeature::ColorFeature(Mat img, int number) { this->_img = img; this->_number = number; } ColorFeature::~ColorFeature() { } /*分离区间*/ Mat ColorFeature::split_interval(Mat &img) { Mat_<Vec3b>::iterator it = img.begin<Vec3b>(); Mat_<Vec3b>::iterator itend = img.end<Vec3b>(); // 将每个像素划分到各自的区间 for (; it != itend; ++it) { (*it)[0] = (*it)[0] / this->_number; // 例像素值20,20/16=1,即区间数为1 (*it)[1] = (*it)[1] / this->_number; (*it)[2] = (*it)[2] / this->_number; } return img; } /*颜色特征提取*/ vector<float> ColorFeature::color_extract() { vector<Mat> channels; vector<int> temp_channel; splited_img = split_interval(_img); split(splited_img, channels); // 分离通道 // 遍历3个通道,分别统计个数,并计算概率 for (int i = 0; i < channels.size(); i++) { temp_channel = channels.at(i).reshape(1, 1); // 转为vector for (int j = 0; j < this->_number; j++) { result = int(count(temp_channel.begin(), temp_channel.end(), j)); // 统计出现的次数 color_vector.push_back(float(result) / temp_channel.size()); // 计算概率(0-1) } } // 总特征维度为48,即16*3,每个通道16个区间。 return color_vector; } /*HOG特征提取类定义*/ HogFeature::HogFeature() { } HogFeature::HogFeature(Mat img, Size windowSize) { _img = img; _windowSize = windowSize; } HogFeature::~HogFeature() { } /*HOG特征提取*/ vector<float> HogFeature::hog_extract() { Mat img_gray; // 窗口大小=块大小=步长,即只检测一次,即原图,这样方便统一特征维度 // 总特征数为 4 * 8 = 32, 4是因为块大小是元胞大小的4倍,8是因为bins=8 blockSize = this->_windowSize; // 块大小 cellSize = blockSize / 2; // 元胞大小 blockStrideSize = blockSize; // 步长 nbins = 8; // 直方图bin的数量 HOGDescriptor hog(this->_windowSize, blockSize, blockStrideSize, cellSize, nbins); // 实例化hog类 vector<float> hog_vector; // HOG描述子向量 cvtColor(this->_img, img_gray, CV_BGR2GRAY); // HOG需要灰度图 hog.compute(img_gray, hog_vector, Size(4, 4), Size(0, 0)); // 计算hog特征向量 return hog_vector; }
[ "1556464090@qq.com" ]
1556464090@qq.com
9231be6a36383b9579e83435371c9f0e4b0e42ea
8559edef3b57407ac5d11cb23df68b50b07b7911
/Best_Online Judge solution/Code force online judge/Game.cpp
1522d16b86c4e4c13c1aecbbf5889b12725ec5b1
[]
no_license
mijanur-rahman-40/C-C-plus-plus-Online-Judge-Algorithms-Practise-Programming
2a031b0743356ba4c8670623aaa87b57f0b43f27
254924e4bd890e2f6d434abcc9ef52ef3e209211
refs/heads/master
2023-02-13T06:26:20.422678
2021-01-13T14:20:21
2021-01-13T14:20:21
329,330,528
1
0
null
null
null
null
UTF-8
C++
false
false
237
cpp
#include<bits/stdc++.h> using namespace std; int main() { int num; scanf("%d",&num); int arr[num]; for(int i=0; i<num; i++){ scanf("%d",&arr[i]); } sort(arr,arr+num); cout<<arr[(num-1)/2]<<endl; }
[ "mijanurrahman31416@gmail.com" ]
mijanurrahman31416@gmail.com
5652bf087213054cbcb8db5e486113b3597c3150
f1caf5e677329b4b3263f4638089253f56e6891d
/lib/handsfree_hw/include/handsfree_hw/transport_serial.h
4cc0b16ec4a9f6b77b8f32014aa42f83c86c0055
[]
no_license
SiChiTong/handsfree_gui
9a40361db664dab54a5cc369ff304aafb97698c6
2280ef79946419760f37d54363861de2e56d1877
refs/heads/master
2021-01-21T21:05:19.572620
2017-04-10T03:37:11
2017-04-10T03:37:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,196
h
/*********************************************************************************************************************** * Copyright (c) Hands Free Team. All rights reserved. * FileName: hf_link.cpp * Contact: QQ Exchange Group -- 521037187 * Version: V2.0 * * LICENSING TERMS: * The Hands Free is licensed generally under a permissive 3-clause BSD license. * Contributions are requiredto be made under the same license. * * History: * <author> <time> <version> <desc> * luke liao 2016.4.1 V1.0 creat this file * * Description: define handfree transport serial method ***********************************************************************************************************************/ #ifndef TRANSPORT_SERIAL_H_ #define TRANSPORT_SERIAL_H_ #include <handsfree_hw/transport.h> namespace handsfree_hw { class SerialParams { public: std::string serialPort; unsigned int baudRate; unsigned int flowControl; unsigned int parity; unsigned int stopBits; SerialParams() : serialPort(), baudRate(921600), flowControl(0), parity(0), stopBits(0) { } SerialParams( std::string _serialPort, unsigned int _baudRate, unsigned int _flowControl, unsigned int _parity, unsigned int _stopBits ) : serialPort(_serialPort), baudRate(_baudRate), flowControl(_flowControl), parity(_parity), stopBits(_stopBits) { } }; class TransportSerial : public Transport { public: TransportSerial (); TransportSerial (std::string url); virtual Buffer readBuffer(); virtual void writeBuffer(Buffer &data); virtual void setParam(const TransportParam &param) ; virtual void enable(bool enable) ; private: boost::shared_ptr<boost::asio::serial_port> port_; SerialParams params_; // for async read Buffer temp_read_buf_; bool enable_use ; boost::thread thread_; // locks boost::mutex port_mutex_; boost::mutex write_mutex_; boost::mutex read_mutex_; bool initializeSerial(); void mainRun(); void start_a_read(); void start_a_write(); void readHandler(const boost::system::error_code &ec, size_t bytesTransferred); void writeHandler(const boost::system::error_code &ec); }; } #endif /* TRANSPORT_SERIAL_H_ */
[ "cp_vin@126.com" ]
cp_vin@126.com
b36cba653ce9b7516c17855670d67210ceead005
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/TFunction_HArray1OfDataMapOfGUIDDriver.hxx
67792c1568c7e876cbff93975c3931bd2169bbae
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
3,078
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _TFunction_HArray1OfDataMapOfGUIDDriver_HeaderFile #define _TFunction_HArray1OfDataMapOfGUIDDriver_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_TFunction_HArray1OfDataMapOfGUIDDriver_HeaderFile #include <Handle_TFunction_HArray1OfDataMapOfGUIDDriver.hxx> #endif #ifndef _TFunction_Array1OfDataMapOfGUIDDriver_HeaderFile #include <TFunction_Array1OfDataMapOfGUIDDriver.hxx> #endif #ifndef _MMgt_TShared_HeaderFile #include <MMgt_TShared.hxx> #endif #ifndef _Standard_Integer_HeaderFile #include <Standard_Integer.hxx> #endif class Standard_RangeError; class Standard_DimensionMismatch; class Standard_OutOfRange; class Standard_OutOfMemory; class TFunction_DataMapOfGUIDDriver; class TFunction_Array1OfDataMapOfGUIDDriver; class TFunction_HArray1OfDataMapOfGUIDDriver : public MMgt_TShared { public: TFunction_HArray1OfDataMapOfGUIDDriver(const Standard_Integer Low,const Standard_Integer Up); TFunction_HArray1OfDataMapOfGUIDDriver(const Standard_Integer Low,const Standard_Integer Up,const TFunction_DataMapOfGUIDDriver& V); void Init(const TFunction_DataMapOfGUIDDriver& V) ; Standard_Integer Length() const; Standard_Integer Lower() const; Standard_Integer Upper() const; void SetValue(const Standard_Integer Index,const TFunction_DataMapOfGUIDDriver& Value) ; const TFunction_DataMapOfGUIDDriver& Value(const Standard_Integer Index) const; TFunction_DataMapOfGUIDDriver& ChangeValue(const Standard_Integer Index) ; const TFunction_Array1OfDataMapOfGUIDDriver& Array1() const; TFunction_Array1OfDataMapOfGUIDDriver& ChangeArray1() ; DEFINE_STANDARD_RTTI(TFunction_HArray1OfDataMapOfGUIDDriver) protected: private: TFunction_Array1OfDataMapOfGUIDDriver myArray; }; #define ItemHArray1 TFunction_DataMapOfGUIDDriver #define ItemHArray1_hxx <TFunction_DataMapOfGUIDDriver.hxx> #define TheArray1 TFunction_Array1OfDataMapOfGUIDDriver #define TheArray1_hxx <TFunction_Array1OfDataMapOfGUIDDriver.hxx> #define TCollection_HArray1 TFunction_HArray1OfDataMapOfGUIDDriver #define TCollection_HArray1_hxx <TFunction_HArray1OfDataMapOfGUIDDriver.hxx> #define Handle_TCollection_HArray1 Handle_TFunction_HArray1OfDataMapOfGUIDDriver #define TCollection_HArray1_Type_() TFunction_HArray1OfDataMapOfGUIDDriver_Type_() #include <TCollection_HArray1.lxx> #undef ItemHArray1 #undef ItemHArray1_hxx #undef TheArray1 #undef TheArray1_hxx #undef TCollection_HArray1 #undef TCollection_HArray1_hxx #undef Handle_TCollection_HArray1 #undef TCollection_HArray1_Type_ // other Inline functions and methods (like "C++: function call" methods) #endif
[ "litao1009@gmail.com" ]
litao1009@gmail.com
be44745e414dc5e16aa1091044586c4c7321c009
7410fa7a1a42137891fc976c83a8ebd189ea301b
/bob_alice.cpp
184a43c3099bbba2de6d021896929f41a7b1367a
[]
no_license
plab0n/OJ_solutions
729f031ad309f7e1f65e6e9b851d83e68ae91150
8152d55407bb6621fa47e72321c05057996af4c0
refs/heads/master
2020-03-11T21:21:05.683854
2018-08-12T07:18:40
2018-08-12T07:18:40
130,262,509
0
0
null
null
null
null
UTF-8
C++
false
false
337
cpp
#include <bits/stdc++.h> using namespace std; int main() { int a,b; while(cin>>a>>b) { int cnt=0; while(1) { ++cnt; a*=3; b*=2; if(a>b) { break; } } cout<<cnt<<endl; } }
[ "noreply@github.com" ]
plab0n.noreply@github.com
fab97f754f579937b6d529b3b76feec16e064ca8
33c12d0d070363dec10a3c79d1fc85d41cd8939c
/BCIREBORN/L_Utilities/Stack16.h
823209487ca1ad990cbb4ebd12e5dcb5375c2250
[]
no_license
jwnicholas99/Brain-Computer-Interface-for-Detection-of-Emotions
ca0e4748a08b301f268a14fb03ec07819fed86ce
8efb4c116fa4d47f5fe73e15000d97492c747d2c
refs/heads/master
2020-04-18T15:13:21.289269
2019-01-28T04:39:33
2019-01-28T04:39:33
167,564,848
0
0
null
null
null
null
UTF-8
C++
false
false
2,660
h
/* File: Stack16.h Description: Stack class definition header file. This module contains the class definition and member function definitions for supporting dynamic list objects with 16 bit labels. */ #ifndef rStack16_H #define rStack16_H #include "ConstDef.h" class Stack16; typedef Stack16 * Stack16P; // Class definition class Stack16 { public: Stack16 (long inCount = 50, long growCount = 0); ~Stack16 (void); long MemoryUsage (void); void Clear (void); long Push (Ptr16 item); Ptr16 Pop (void); Ptr16 Get (long index); void Set (long index, Ptr16 item); void Insert (long index, Ptr16 item); Stack16 * Copy (Stack16 * inList = NULL); Ptr16 First (void) { return Get (0); } Ptr16 Last (void) { return Get (fCount - 1); } long GetLength (void) { return fCount; } long GetCount (void) { return fCount; } Ptr16 * GetStorage (void) { return fStorage; } private: long fCount; long fMaxCount; long fGrowCount; long fRange; Ptr16 * fStorage; }; /*=============================================================================== Public Functions Stack (long inCount, long growCount = 0) Constructor. Makes an instance of an Stack and returns it. The initial size of the list as well as the grow size (for expanding the list) are user-specifiable. ~Stack (void) Destructor MemoryUsage (void) Returns the memory used by the dynamic list. Clear (void) Clears the list for reuse by reseting it's count index to 0. Copy (Stack * inList = NULL) Returns a copy of the list. If the optional inList is provided, copies the list into inList, and returns it. Push (Ptr16 item) Pushes an item onto the end of the list. Allocates more memory if necessary using fGrowCount. Pop (void) Pops an item off the end of the list, and returns. The item will no longer be on the list. Get (long index) Returns the item at index. If index is beyond range, returns kNoItem. Set (long index, Ptr16 item) Places the item in the list at location provided by index. Insert (long index, Ptr16 item) Inserts an item in the list. Pushes other items down, allocating more memory if necessary. First (void) Returns the first item on the list. Last (void) Returns the last item on the list. Length (void) Returns the length of the list. Count (void) Same as Count (). ===============================================================================*/ #endif // rStack_H
[ "jwnicholas99@gmail.com" ]
jwnicholas99@gmail.com
10e7deafcca80ee57b51efc6c1dabc28f7c3310b
6934288c026289e5317e2aeb467b0cb685cfc59d
/tpc2/src/VentanillaEntrada.h
bbb173453297756c9743bd4f0b2952821b5da715
[]
no_license
gcocce/tpc
6b491ae579e4bf7be43086a63c43a5bec49ba143
f3ab6a689b810c6d5f2d32f0ee61c1bbc393fee8
refs/heads/master
2020-04-06T03:41:06.363897
2012-12-05T17:16:55
2012-12-05T17:16:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
904
h
#ifndef VENTANILLAENTRADA_H_ #define VENTANILLAENTRADA_H_ #include "Semaforo.h" #include "BufferSincronizado.h" #include "Estacionamiento.h" #include "SignalHandler.h" #include "Message.h" #include "logger.h" #include "ConcPipe.h" #include "MsgF.h" class VentanillaEntrada : public EventHandler { private: bool abierta; int estacionamiento; char numeroVentanilla; Semaforo barrera; BufferSincronizado<message> canalEntrada; BufferSincronizado<message> canalSalida; //BufferSincronizado<MsgFString> canalEAdmin; BufferSincronizado<MsgFST> canalEAdmin; Logger* log; ConcPipe* cpipe; public: VentanillaEntrada(Logger* log, char *path, int est, char numeroVentanilla, ConcPipe* cp); ~VentanillaEntrada(); void crear(); void eliminar(); void abrir(); void cerrar(); void iniciar(); void finalizar(); virtual int handleSignal ( int signum ); }; #endif /* VENTANILLAENTRADA_H_ */
[ "gastoncocce@hotmail.com" ]
gastoncocce@hotmail.com
1574a77a78057e2c32b6bc1f241ad1d8568521d4
43a9f64427158c5bec8e9ce60233ba91b8c55f3e
/samples/DockContainer/src/Classes.cpp
eda206ed74a7a59f4167c3928e14a3f8b41d4919
[]
no_license
CCCCCCCCZ/Win32xx
7e8647b74eaca47ef80cadd76d68dc036dabe709
2ef27b55e05931ebabf931f133387bc046f888dc
refs/heads/master
2020-06-07T13:29:41.006512
2019-06-22T07:33:53
2019-06-22T07:33:53
193,032,614
0
1
null
null
null
null
UTF-8
C++
false
false
5,703
cpp
/////////////////////////////////////////////////// // Classes.cpp - Definitions for the CViewClasses, CContainClasses // and CDockClasses classes #include "stdafx.h" #include "Classes.h" #include "ContainerApp.h" #include "resource.h" /////////////////////////////////////////////// // CViewClasses functions CViewClasses::CViewClasses() { } CViewClasses::~CViewClasses() { if (IsWindow()) DeleteAllItems(); } HTREEITEM CViewClasses::AddItem(HTREEITEM hParent, LPCTSTR text, int image) { TVITEM tvi; ZeroMemory(&tvi, sizeof(TVITEM)); tvi.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE; tvi.iImage = image; tvi.iSelectedImage = image; tvi.pszText = const_cast<LPTSTR>(text); TVINSERTSTRUCT tvis; ZeroMemory(&tvis, sizeof(TVINSERTSTRUCT)); tvis.hParent = hParent; tvis.item = tvi; return InsertItem(tvis); } void CViewClasses::OnAttach() { //set the image lists m_normalImages.Create(16, 15, ILC_COLOR32 | ILC_MASK, 1, 0); CBitmap bm(IDB_CLASSVIEW); m_normalImages.Add( bm, RGB(255, 0, 0) ); SetImageList(m_normalImages, LVSIL_NORMAL); // Adjust style to show lines and [+] button DWORD dwStyle = GetStyle(); dwStyle |= TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT; SetStyle(dwStyle); DeleteAllItems(); // Add some tree-view items HTREEITEM htiRoot = AddItem(NULL, _T("TreeView"), 0); HTREEITEM htiCTreeViewApp = AddItem(htiRoot, _T("CTreeViewApp"), 1); AddItem(htiCTreeViewApp, _T("CTreeViewApp()"), 3); AddItem(htiCTreeViewApp, _T("GetMainFrame()"), 3); AddItem(htiCTreeViewApp, _T("InitInstance()"), 3); HTREEITEM htiMainFrame = AddItem(htiRoot, _T("CMainFrame"), 1); AddItem(htiMainFrame, _T("CMainFrame()"), 3); AddItem(htiMainFrame, _T("OnCommand()"), 4); AddItem(htiMainFrame, _T("OnInitialUpdate()"), 4); AddItem(htiMainFrame, _T("WndProc()"), 4); HTREEITEM htiView = AddItem(htiRoot, _T("CView"), 1); AddItem(htiView, _T("CView()"), 3); AddItem(htiView, _T("OnInitialUpdate()"), 4); AddItem(htiView, _T("WndProc()"), 4); // Expand some tree-view items Expand(htiRoot, TVE_EXPAND); Expand(htiCTreeViewApp, TVE_EXPAND); } void CViewClasses::OnDestroy() { SetImageList(NULL, LVSIL_SMALL); } LRESULT CViewClasses::OnMouseActivate(UINT msg, WPARAM wparam, LPARAM lparam) // Respond to a mouse click on the window { // Set window focus. The docker will now report this as active. SetFocus(); return FinalWindowProc(msg, wparam, lparam); } void CViewClasses::PreCreate(CREATESTRUCT& cs) { cs.style = TVS_NOTOOLTIPS|WS_CHILD; cs.lpszClass = WC_TREEVIEW; } LRESULT CViewClasses::WndProc(UINT msg, WPARAM wparam, LPARAM lparam) { switch (msg) { case WM_MOUSEACTIVATE: return OnMouseActivate(msg, wparam, lparam); } return WndProcDefault(msg, wparam, lparam); } /////////////////////////////////////////////// // CContainClasses functions CContainClasses::CContainClasses() { SetTabText(_T("ClassView")); SetTabIcon(IDI_CLASSVIEW); SetDockCaption (_T("Class View - Docking container")); SetView(m_viewClasses); } void CContainClasses::AddCombo() { int nComboWidth = 120; CToolBar& tb = GetToolBar(); if (tb.CommandToIndex(IDM_FILE_SAVE) < 0) return; // Adjust button width and convert to separator tb.SetButtonStyle(IDM_FILE_SAVE, TBSTYLE_SEP); tb.SetButtonWidth(IDM_FILE_SAVE, nComboWidth); // Determine the size and position of the ComboBox int index = tb.CommandToIndex(IDM_FILE_SAVE); CRect rect = tb.GetItemRect(index); // Create the ComboboxEx window m_comboBoxEx.Create(tb); m_comboBoxEx.SetWindowPos(NULL, rect, SWP_NOACTIVATE); // Adjust the toolbar height to accomodate the ComboBoxEx control CRect rc = m_comboBoxEx.GetWindowRect(); tb.SetButtonSize( rc.Height(), rc.Height() ); // Add the ComboBox's items m_comboBoxEx.AddItems(); } BOOL CContainClasses::OnCommand(WPARAM wparam, LPARAM lparam) { UNREFERENCED_PARAMETER(lparam); // OnCommand responds to menu and and toolbar input UINT id = LOWORD(wparam); switch(id) { case IDM_FILE_NEW: return OnFileNew(); case IDM_HELP_ABOUT: return OnHelpAbout(); } return FALSE; } BOOL CContainClasses::OnFileNew() { TRACE("File New\n"); MessageBox(_T("File New"), _T("Button Pressed"), MB_OK); return TRUE; } BOOL CContainClasses::OnHelpAbout() { // Send a message to the frame requesting the help dialog GetContainerApp().GetMainFrame().SendMessage(WM_HELP); return TRUE; } void CContainClasses::SetupToolBar() { // Set the Bitmap resource for the toolbar SetToolBarImages(RGB(192,192,192), IDW_MAIN, 0, 0); // Set the Resource IDs for the toolbar buttons AddToolBarButton( IDM_FILE_NEW ); AddToolBarButton( IDM_FILE_OPEN, FALSE ); AddToolBarButton( 0 ); // Separator AddToolBarButton( IDM_FILE_SAVE, FALSE ); AddToolBarButton( 0 ); // Separator AddToolBarButton( IDM_EDIT_CUT ); AddToolBarButton( IDM_EDIT_COPY ); AddToolBarButton( IDM_EDIT_PASTE ); AddToolBarButton( 0 ); // Separator AddToolBarButton( IDM_FILE_PRINT, FALSE ); AddToolBarButton( 0 ); // Separator AddToolBarButton( IDM_HELP_ABOUT ); // Add the ComboBarEx control to the toolbar AddCombo(); } ///////////////////////////////////////////////// // Definitions for the CDockClasses class CDockClasses::CDockClasses() { SetView(m_classes); // Set the width of the splitter bar SetBarWidth(8); }
[ "czx_1991@qq.com" ]
czx_1991@qq.com
1716467f2a2282dc1dcaed1835841e3a67a2e3f0
e2d6129f991ec7a8c304aa9c045f486cc8901b7c
/src/pcrepp/test_pcre2pp.cc
ce5b0c58b637c90975be8d3f7216982ad322e235
[ "BSD-2-Clause" ]
permissive
tstack/lnav
f1f8769885d1e639fa969dbc8c304626bfcb7318
c796a662731b5bdb74196af0a4dfd0cbdf96e285
refs/heads/master
2023-09-05T19:04:14.646192
2023-09-05T05:51:07
2023-09-05T05:51:07
306,147
5,812
355
BSD-2-Clause
2023-08-05T19:12:34
2009-09-14T01:02:02
C++
UTF-8
C++
false
false
7,794
cc
/** * Copyright (c) 2022, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest/doctest.h" #include "pcre2pp.hh" TEST_CASE("bad pattern") { auto compile_res = lnav::pcre2pp::code::from(string_fragment::from_const("[abc")); CHECK(compile_res.isErr()); auto ce = compile_res.unwrapErr(); CHECK(ce.ce_offset == 4); } TEST_CASE("named captures") { auto compile_res = lnav::pcre2pp::code::from( string_fragment::from_const("(?<abc>a)(b)(?<def>c)")); CHECK(compile_res.isOk()); const std::vector<std::pair<size_t, string_fragment>> expected_caps = { {1, string_fragment::from_const("abc")}, {3, string_fragment::from_const("def")}, }; int caps_index = 0; auto co = compile_res.unwrap(); for (const auto cap : co.get_named_captures()) { const auto& expected_cap = expected_caps[caps_index]; CHECK(expected_cap.first == cap.get_index()); CHECK(expected_cap.second == cap.get_name()); caps_index += 1; } } TEST_CASE("match") { static const char INPUT[] = "key1=1234;key2=5678;"; auto co = lnav::pcre2pp::code::from_const(R"((?<key>\w+)=(?<value>[^;]+);)"); co.capture_from(string_fragment::from_const(INPUT)) .for_each([](lnav::pcre2pp::match_data& md) { printf("got '%s' %s = %s\n", md[0]->to_string().c_str(), md[1]->to_string().c_str(), md[2]->to_string().c_str()); }); } TEST_CASE("partial") { static const char INPUT[] = "key1=1234"; auto co = lnav::pcre2pp::code::from_const(R"([a-z]+=.*)"); auto matched = co.match_partial(string_fragment::from_const(INPUT)); CHECK(matched == 3); } TEST_CASE("capture_name") { auto co = lnav::pcre2pp::code::from_const("(?<abc>def)(ghi)"); CHECK(co.get_capture_count() == 2); CHECK(string_fragment::from_c_str(co.get_name_for_capture(1)) == "abc"); CHECK(co.get_name_for_capture(2) == nullptr); } TEST_CASE("get_capture_count") { auto co = lnav::pcre2pp::code::from_const("(DEFINE)"); CHECK(co.get_capture_count() == 1); } TEST_CASE("get_captures") { auto co = lnav::pcre2pp::code::from_const(R"((?<abc>\w+)-(def)-)"); CHECK(co.get_capture_count() == 2); const auto& caps = co.get_captures(); CHECK(caps.size() == 2); CHECK(caps[0].to_string() == R"((?<abc>\w+))"); CHECK(caps[1].to_string() == R"((def))"); } TEST_CASE("replace") { static const char INPUT[] = "test 1 2 3"; auto co = lnav::pcre2pp::code::from_const(R"(\w*)"); auto in = string_fragment::from_const(INPUT); auto res = co.replace(in, R"({\0})"); CHECK(res == "{test}{} {1}{} {2}{} {3}{}"); } TEST_CASE("replace-empty") { static const char INPUT[] = ""; auto co = lnav::pcre2pp::code::from_const(R"(\w*)"); auto in = string_fragment::from_const(INPUT); auto res = co.replace(in, R"({\0})"); CHECK(res == "{}"); } TEST_CASE("for_each-all") { static const char INPUT[] = "Hello, World!\n"; auto co = lnav::pcre2pp::code::from_const(R"(.*)"); auto in = string_fragment::from_const(INPUT); co.capture_from(in).for_each([](lnav::pcre2pp::match_data& md) { printf("range %d:%d\n", md[0]->sf_begin, md[0]->sf_end); }); } TEST_CASE("capture_count") { auto co = lnav::pcre2pp::code::from_const(R"(^(\w+)=([^;]+);)"); CHECK(co.get_capture_count() == 2); } TEST_CASE("no-caps") { const static std::string empty_cap_regexes[] = { "foo (?:bar)", "foo [(]", "foo \\Q(bar)\\E", "(?i)", }; for (auto re : empty_cap_regexes) { auto co = lnav::pcre2pp::code::from(re).unwrap(); CHECK(co.get_captures().empty()); } } TEST_CASE("ipmatcher") { auto co = lnav::pcre2pp::code::from_const( R"((?(DEFINE)(?<byte>2[0-4]\d|25[0-5]|1\d\d|[1-9]?\d))\b(?&byte)(\.(?&byte)){3}\b)"); auto inp = string_fragment::from_const("192.168.1.1"); auto find_res = co.find_in(inp).ignore_error(); CHECK(find_res.has_value()); CHECK(find_res->f_all.sf_begin == 0); } TEST_CASE("get_captures-nested") { auto re = lnav::pcre2pp::code::from_const("foo (bar (?:baz)?)"); CHECK(re.get_captures().size() == 1); CHECK(re.get_captures()[0].sf_begin == 4); CHECK(re.get_captures()[0].sf_end == 18); CHECK(re.get_captures()[0].length() == 14); } TEST_CASE("get_captures-basic") { auto re = lnav::pcre2pp::code::from_const("(a)(b)(c)"); assert(re.get_captures().size() == 3); assert(re.get_captures()[0].sf_begin == 0); assert(re.get_captures()[0].sf_end == 3); assert(re.get_captures()[1].sf_begin == 3); assert(re.get_captures()[1].sf_end == 6); assert(re.get_captures()[2].sf_begin == 6); assert(re.get_captures()[2].sf_end == 9); } TEST_CASE("get_captures-escape") { auto re = lnav::pcre2pp::code::from_const("\\(a\\)(b)"); assert(re.get_captures().size() == 1); assert(re.get_captures()[0].sf_begin == 5); assert(re.get_captures()[0].sf_end == 8); } TEST_CASE("get_captures-named") { auto re = lnav::pcre2pp::code::from_const("(?<named>b)"); assert(re.get_captures().size() == 1); assert(re.get_captures()[0].sf_begin == 0); assert(re.get_captures()[0].sf_end == 11); } TEST_CASE("get_captures-namedP") { auto re = lnav::pcre2pp::code::from_const("(?P<named>b)"); assert(re.get_captures().size() == 1); assert(re.get_captures()[0].sf_begin == 0); assert(re.get_captures()[0].sf_end == 12); } TEST_CASE("get_captures-namedq") { auto re = lnav::pcre2pp::code::from_const("(?'named'b)"); CHECK(re.get_captures().size() == 1); CHECK(re.get_captures()[0].sf_begin == 0); CHECK(re.get_captures()[0].sf_end == 11); } TEST_CASE("anchored") { auto re = lnav::pcre2pp::code::from_const( "abc", PCRE2_ANCHORED | PCRE2_ENDANCHORED); const auto sub1 = string_fragment::from_const("abc"); const auto sub2 = string_fragment::from_const("abcd"); const auto sub3 = string_fragment::from_const("0abc"); CHECK(re.find_in(sub1).ignore_error().has_value()); CHECK_FALSE(re.find_in(sub2).ignore_error().has_value()); CHECK_FALSE(re.find_in(sub3).ignore_error().has_value()); }
[ "timothyshanestack@gmail.com" ]
timothyshanestack@gmail.com
70659e403193818370c9763e57277954fec8e5aa
c9ea4b7d00be3092b91bf157026117bf2c7a77d7
/位运算初步/P4310.cpp
0b58d89b62abb458ada97dd206dff6fcb1c9c616
[]
no_license
Jerry-Terrasse/Programming
dc39db2259c028d45c58304e8f29b2116eef4bfd
a59a23259d34a14e38a7d4c8c4d6c2b87a91574c
refs/heads/master
2020-04-12T08:31:48.429416
2019-04-20T00:32:55
2019-04-20T00:32:55
162,387,499
3
0
null
null
null
null
UTF-8
C++
false
false
615
cpp
#include<iostream> #define MAXN 100010 #define MAX 65 using namespace std; int f[MAXN][MAX],a[MAXN],n=0,ans=0; int main() { register int i=0,j=0,k=0; cin>>n; for(i=1;i<=n;++i) { cin>>a[i]; } for(i=1;i<=n;++i) { for(j=0;j<MAX;++j) { if(a[i]>>j&1) { for(k=0;k<MAX;++k) { if(a[i]>>k&1) { f[i][j]=max(f[i][j],f[i-1][k]); } } ++f[i][j]; } else { f[i][j]=f[i-1][j]; } } } for(i=0;i<MAX;++i) { ans=max(ans,f[n][i]); } cout<<ans<<endl; return 0; }
[ "3305049949@qq.com" ]
3305049949@qq.com
767e0b76c17293827c1edb301c5aa6f36672ef1d
65099cadbfbcaa34324864230bbfa7162a36fdad
/ENIGMAsystem/SHELL/Graphics_Systems/Direct3D9/DX9draw.cpp
244ccfb05076b18c7e3384f484e0d5f3e7f20a2b
[]
no_license
Rexhunter99/enigma-dev
cb7cc3e4fa2e5fe2b66bf827d0c8b84a37c71fd2
1b5af2c09284c16dd91905d3847554f26da9c1df
refs/heads/master
2021-01-17T14:15:42.919564
2013-10-20T11:48:43
2013-10-20T11:48:43
13,639,130
1
1
null
null
null
null
UTF-8
C++
false
false
6,270
cpp
/** Copyright (C) 2013 Robert B. Colton *** *** This file is a part of the ENIGMA Development Environment. *** *** ENIGMA 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 3 of the license or any later version. *** *** This application and its source code is distributed AS-IS, 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 code. If not, see <http://www.gnu.org/licenses/> **/ #include <math.h> #include "Direct3D9Headers.h" #include "Graphics_Systems/General/GSstdraw.h" #include "DX9binding.h" #include <stdio.h> #include "Universal_System/roomsystem.h" #define __GETR(x) ((x & 0x0000FF)) #define __GETG(x) ((x & 0x00FF00) >> 8) #define __GETB(x) ((x & 0xFF0000) >> 16) #include <vector> using std::vector; namespace enigma { float circleprecision=24; extern unsigned char currentcolor[4]; } namespace enigma_user { int draw_get_msaa_maxlevel() { } bool draw_get_msaa_supported() { } void draw_set_msaa_enabled(bool enable) { } void draw_enable_alphablend(bool enable) { d3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE, enable); } bool draw_get_alpha_test() { DWORD* enabled; d3ddev->GetRenderState(D3DRS_ALPHATESTENABLE, enabled); return *enabled; } unsigned draw_get_alpha_test_ref_value() { DWORD* val; d3ddev->GetRenderState(D3DRS_ALPHAREF, val); return *val; } void draw_set_alpha_test(bool enable) { d3ddev->SetRenderState(D3DRS_ALPHATESTENABLE, enable); } void draw_set_alpha_test_ref_value(unsigned val) { d3ddev->SetRenderState(D3DRS_ALPHAREF, val); } void draw_set_line_pattern(unsigned short pattern, int scale) { } void draw_point(gs_scalar x, gs_scalar y) { } void draw_point_color(gs_scalar x, gs_scalar y, int col) { } void draw_line(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2) { } void draw_line_width(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float width) { } void draw_line_color(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, int c1, int c2) { } void draw_line_width_color(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float width, int c1, int c2) { } void draw_rectangle(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, bool outline) { } void draw_rectangle_angle(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float angle, bool outline) { } void draw_rectangle_color(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, int c1, int c2, int c3, int c4, bool outline) { } void draw_set_circle_precision(float pr) { enigma::circleprecision = pr<3 ? 3 : pr; } float draw_get_circle_precision() { return enigma::circleprecision; } struct D3DTLVERTEX { float fX; float fY; float fZ; }; void draw_circle(gs_scalar x, gs_scalar y, float rad, bool outline) { double pr = 2 * M_PI / enigma::circleprecision; vector<float> Circle; d3ddev->SetFVF(D3DFVF_XYZ); if(outline) { for (double i = 0; i <= 2*M_PI; i += pr) { double xc1=cos(i)*rad,yc1=sin(i)*rad; //D3DTLVERTEX v; //v.fX = x+xc1; v.fY = y+yc1; v.fZ = 0; //v.fRHW = RHW; //v.Color = color; //v.fU = U; v.fV = V; //Circle.push_back(v); Circle.push_back(x+xc1); Circle.push_back(y+yc1); Circle.push_back(0); } d3ddev->DrawPrimitiveUP(D3DPT_LINESTRIP, enigma::circleprecision, &Circle[0], sizeof(float) * 3); } else { //D3DTLVERTEX v; //v.fX = x; v.fY = y; v.fZ = 0; //v.fRHW = RHW; //v.Color = color; //v.fU = U; v.fV = V; //Circle.push_back(v); Circle.push_back(x); Circle.push_back(y); Circle.push_back(0); for (double i = 0; i <= 2*M_PI; i += pr) { double xc1=cos(i)*rad,yc1=sin(i)*rad; //D3DTLVERTEX v; //v.fX = x+xc1; v.fY = y+yc1; v.fZ = 0; //v.fRHW = RHW; //v.Color = color; //v.fU = U; v.fV = V; //Circle.push_back(v); Circle.push_back(x+xc1); Circle.push_back(y+yc1); Circle.push_back(0); } d3ddev->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, enigma::circleprecision, &Circle[0], sizeof(float) * 3); } } void draw_circle_color(gs_scalar x, gs_scalar y, float rad, int c1, int c2, bool outline) { } void draw_circle_perfect(gs_scalar x, gs_scalar y, float rad, bool outline) { } void draw_circle_color_perfect(gs_scalar x, gs_scalar y, float rad, int c1, int c2, bool outline) { } void draw_ellipse(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, bool outline) { } void draw_ellipse_color(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, int c1, int c2, bool outline) { } void draw_ellipse_perfect(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, bool outline) { } void draw_triangle(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float x3, float y3, bool outline) { } void draw_triangle_color(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float x3, float y3, int col1, int col2, int col3, bool outline) { } void draw_roundrect(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2,float rad, bool outline) { } void draw_roundrect_color(gs_scalar x1, gs_scalar y1, gs_scalar x2, gs_scalar y2, float rad, int col1, int col2, bool outline) { } void draw_arrow(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, gs_scalar arrow_size, gs_scalar line_size, bool outline) { } void draw_button(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, gs_scalar border_width, bool up) { } //Mind that health is 1-100 void draw_healthbar(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float amount, int backcol, int mincol, int maxcol, int dir, bool showback, bool showborder) { } } //#include <endian.h> //TODO: Though serprex, the author of the function below, never included endian.h, // // Doing so is necessary for the function to work at its peak. // // When ENIGMA generates configuration files, one should be included here. namespace enigma_user { int draw_getpixel(int x, int y) { } int draw_mandelbrot(int x, int y, float w, double Zx, double Zy, double Zw, unsigned iter) { } }
[ "robertbcolton@hotmail.com" ]
robertbcolton@hotmail.com