blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author_id
stringlengths
0
158
cfde32c39df32a5d43edac377b68c49d63a50d75
63fe87c14c1271ff66a83b3fc2527e5983bc3f30
/include/test_case.hpp
166f5379f0b8ea7623ffac4a6ffd7952fdb61744
[]
no_license
jjureta/cpp.test
78219210b0ce7b45e37cfaf35638cdabee97e1c2
400138cf0ed3d41de2ae85f3bd0352926476d80b
refs/heads/master
2021-01-17T19:57:43.261967
2016-06-16T11:52:23
2016-06-16T11:52:23
61,250,610
0
0
null
null
null
null
UTF-8
C++
false
false
631
hpp
/* * test_case.hpp * * Created on: 2016-06-15 * Author: j_jur_000 */ #ifndef TEST_CASE_HPP_ #define TEST_CASE_HPP_ #include <string> #include <iostream> class test_case { public: test_case(const std::string& tn) : test_case_name(tn) { std::cout << "Start test case: " << test_case_name << std::endl; } test_case(const char* tn) : test_case_name(std::string(tn)) { std::cout << "Start test case: " << test_case_name << std::endl; } ~test_case() { std::cout << "End test case: " << test_case_name << std::endl << std::endl; } private: const std::string test_case_name; }; #endif /* TEST_CASE_HPP_ */
ca1613982233d026a4c6ad848ff4e254a147446b
91211d13b54a99104740aaa3abea85016005e523
/2021-NFM/Results/TankFilling/No_trim_No_repair/FigaroModelTankFilling_No_trim_No_repair.cpp
01e6bbe104a71239b0894c56e8842c8bab190f05
[]
no_license
moves-rwth/dft-bdmp
3b832110153581a31b0c1ea7e01337bab71836b1
7bbae90c0fa79b2fb62a8e55a01d24e905932344
refs/heads/master
2022-06-15T22:10:31.504812
2022-06-09T15:03:16
2022-06-09T15:03:16
196,187,409
1
1
null
2022-06-09T15:03:17
2019-07-10T10:48:31
C++
UTF-8
C++
false
false
31,058
cpp
#include <iostream> #include "FigaroModelTankFilling_No_trim_No_repair.h" using namespace std; namespace storm{ namespace figaro{ /* ---------- DECLARATION OF OCCURRENCE RULES FIRING FLAGS ------------ */ // storm::figaro::FigaroProgram_"+program_name+"::FigaroProgram_"+program_name+"() // { // for(int i=0; i < numBoolState; i++) // boolState[i]=0; // // } void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::init() { //cout <<">>>>>>>>>>>>>>>>>>>> Initialization of variables <<<<<<<<<<<<<<<<<<<<<<<" << endl; REINITIALISATION_OF_required_OF_CCFV12 = true; boolState[already_S_OF_CCFV12] = false; REINITIALISATION_OF_S_OF_CCFV12 = false; REINITIALISATION_OF_relevant_evt_OF_CCFV12 = false; boolState[failF_OF_CCFV12] = false; REINITIALISATION_OF_required_OF_CCFVSOL12 = true; boolState[already_S_OF_CCFVSOL12] = false; REINITIALISATION_OF_S_OF_CCFVSOL12 = false; REINITIALISATION_OF_relevant_evt_OF_CCFVSOL12 = false; boolState[failF_OF_CCFVSOL12] = false; REINITIALISATION_OF_required_OF_Filling = true; boolState[already_S_OF_Filling] = false; REINITIALISATION_OF_S_OF_Filling = false; REINITIALISATION_OF_relevant_evt_OF_Filling = false; boolState[failF_OF_Filling] = false; REINITIALISATION_OF_required_OF_LSH1 = true; boolState[already_S_OF_LSH1] = false; REINITIALISATION_OF_S_OF_LSH1 = false; REINITIALISATION_OF_relevant_evt_OF_LSH1 = false; boolState[failF_OF_LSH1] = false; REINITIALISATION_OF_required_OF_PSH1 = true; boolState[already_S_OF_PSH1] = false; REINITIALISATION_OF_S_OF_PSH1 = false; REINITIALISATION_OF_relevant_evt_OF_PSH1 = false; boolState[failF_OF_PSH1] = false; REINITIALISATION_OF_required_OF_R = true; boolState[already_S_OF_R] = false; REINITIALISATION_OF_S_OF_R = false; REINITIALISATION_OF_relevant_evt_OF_R = false; REINITIALISATION_OF_required_OF_RL = true; boolState[already_S_OF_RL] = false; REINITIALISATION_OF_S_OF_RL = false; REINITIALISATION_OF_relevant_evt_OF_RL = false; REINITIALISATION_OF_required_OF_RLL = true; boolState[already_S_OF_RLL] = false; REINITIALISATION_OF_S_OF_RLL = false; REINITIALISATION_OF_relevant_evt_OF_RLL = false; REINITIALISATION_OF_required_OF_RLR = true; boolState[already_S_OF_RLR] = false; REINITIALISATION_OF_S_OF_RLR = false; REINITIALISATION_OF_relevant_evt_OF_RLR = false; REINITIALISATION_OF_required_OF_System = true; boolState[already_S_OF_System] = false; REINITIALISATION_OF_S_OF_System = false; REINITIALISATION_OF_relevant_evt_OF_System = false; REINITIALISATION_OF_required_OF_UE_1 = true; boolState[already_S_OF_UE_1] = false; REINITIALISATION_OF_S_OF_UE_1 = false; REINITIALISATION_OF_relevant_evt_OF_UE_1 = false; REINITIALISATION_OF_required_OF_V1 = true; boolState[already_S_OF_V1] = false; REINITIALISATION_OF_S_OF_V1 = false; REINITIALISATION_OF_relevant_evt_OF_V1 = false; boolState[failF_OF_V1] = false; REINITIALISATION_OF_required_OF_V2 = true; boolState[already_S_OF_V2] = false; REINITIALISATION_OF_S_OF_V2 = false; REINITIALISATION_OF_relevant_evt_OF_V2 = false; boolState[failF_OF_V2] = false; REINITIALISATION_OF_required_OF_VSOL1 = true; boolState[already_S_OF_VSOL1] = false; REINITIALISATION_OF_S_OF_VSOL1 = false; REINITIALISATION_OF_relevant_evt_OF_VSOL1 = false; boolState[failF_OF_VSOL1] = false; REINITIALISATION_OF_required_OF_VSOL2 = true; boolState[already_S_OF_VSOL2] = false; REINITIALISATION_OF_S_OF_VSOL2 = false; REINITIALISATION_OF_relevant_evt_OF_VSOL2 = false; boolState[failF_OF_VSOL2] = false; /* ---------- DECLARATION OF OCCURRENCE RULES FIRING FLAGS ------------ */ FIRE_xx10_OF_CCFV12 = false; FIRE_xx10_OF_CCFVSOL12 = false; FIRE_xx10_OF_Filling = false; FIRE_xx10_OF_LSH1 = false; FIRE_xx10_OF_PSH1 = false; FIRE_xx10_OF_V1 = false; FIRE_xx10_OF_V2 = false; FIRE_xx10_OF_VSOL1 = false; FIRE_xx10_OF_VSOL2 = false; } void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::saveCurrentState() { // cout <<">>>>>>>>>>>>>>>>>>>> Saving current state <<<<<<<<<<<<<<<<<<<<<<<" << endl; backupBoolState = boolState ; backupFloatState = floatState ; backupIntState = intState ; backupEnumState = enumState ; } int storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::compareStates() { // cout <<">>>>>>>>>>>>>>>>>>>> Comparing state with previous one (return number of differences) <<<<<<<<<<<<<<<<<<<<<<<" << endl; return (backupBoolState != boolState) + (backupFloatState != floatState) + (backupIntState != intState) + (backupEnumState != enumState); } void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::printState() { //cout <<"\n==================== Print of the current state : ====================" << endl; //cout << "Attribute : boolState[required_OF_CCFV12] | Value : " << boolState[required_OF_CCFV12] << endl; //cout << "Attribute : boolState[already_S_OF_CCFV12] | Value : " << boolState[already_S_OF_CCFV12] << endl; //cout << "Attribute : boolState[S_OF_CCFV12] | Value : " << boolState[S_OF_CCFV12] << endl; //cout << "Attribute : boolState[relevant_evt_OF_CCFV12] | Value : " << boolState[relevant_evt_OF_CCFV12] << endl; //cout << "Attribute : boolState[failF_OF_CCFV12] | Value : " << boolState[failF_OF_CCFV12] << endl; //cout << "Attribute : boolState[required_OF_CCFVSOL12] | Value : " << boolState[required_OF_CCFVSOL12] << endl; //cout << "Attribute : boolState[already_S_OF_CCFVSOL12] | Value : " << boolState[already_S_OF_CCFVSOL12] << endl; //cout << "Attribute : boolState[S_OF_CCFVSOL12] | Value : " << boolState[S_OF_CCFVSOL12] << endl; //cout << "Attribute : boolState[relevant_evt_OF_CCFVSOL12] | Value : " << boolState[relevant_evt_OF_CCFVSOL12] << endl; //cout << "Attribute : boolState[failF_OF_CCFVSOL12] | Value : " << boolState[failF_OF_CCFVSOL12] << endl; //cout << "Attribute : boolState[required_OF_Filling] | Value : " << boolState[required_OF_Filling] << endl; //cout << "Attribute : boolState[already_S_OF_Filling] | Value : " << boolState[already_S_OF_Filling] << endl; //cout << "Attribute : boolState[S_OF_Filling] | Value : " << boolState[S_OF_Filling] << endl; //cout << "Attribute : boolState[relevant_evt_OF_Filling] | Value : " << boolState[relevant_evt_OF_Filling] << endl; //cout << "Attribute : boolState[failF_OF_Filling] | Value : " << boolState[failF_OF_Filling] << endl; //cout << "Attribute : boolState[required_OF_LSH1] | Value : " << boolState[required_OF_LSH1] << endl; //cout << "Attribute : boolState[already_S_OF_LSH1] | Value : " << boolState[already_S_OF_LSH1] << endl; //cout << "Attribute : boolState[S_OF_LSH1] | Value : " << boolState[S_OF_LSH1] << endl; //cout << "Attribute : boolState[relevant_evt_OF_LSH1] | Value : " << boolState[relevant_evt_OF_LSH1] << endl; //cout << "Attribute : boolState[failF_OF_LSH1] | Value : " << boolState[failF_OF_LSH1] << endl; //cout << "Attribute : boolState[required_OF_PSH1] | Value : " << boolState[required_OF_PSH1] << endl; //cout << "Attribute : boolState[already_S_OF_PSH1] | Value : " << boolState[already_S_OF_PSH1] << endl; //cout << "Attribute : boolState[S_OF_PSH1] | Value : " << boolState[S_OF_PSH1] << endl; //cout << "Attribute : boolState[relevant_evt_OF_PSH1] | Value : " << boolState[relevant_evt_OF_PSH1] << endl; //cout << "Attribute : boolState[failF_OF_PSH1] | Value : " << boolState[failF_OF_PSH1] << endl; //cout << "Attribute : boolState[required_OF_R] | Value : " << boolState[required_OF_R] << endl; //cout << "Attribute : boolState[already_S_OF_R] | Value : " << boolState[already_S_OF_R] << endl; //cout << "Attribute : boolState[S_OF_R] | Value : " << boolState[S_OF_R] << endl; //cout << "Attribute : boolState[relevant_evt_OF_R] | Value : " << boolState[relevant_evt_OF_R] << endl; //cout << "Attribute : boolState[required_OF_RL] | Value : " << boolState[required_OF_RL] << endl; //cout << "Attribute : boolState[already_S_OF_RL] | Value : " << boolState[already_S_OF_RL] << endl; //cout << "Attribute : boolState[S_OF_RL] | Value : " << boolState[S_OF_RL] << endl; //cout << "Attribute : boolState[relevant_evt_OF_RL] | Value : " << boolState[relevant_evt_OF_RL] << endl; //cout << "Attribute : boolState[required_OF_RLL] | Value : " << boolState[required_OF_RLL] << endl; //cout << "Attribute : boolState[already_S_OF_RLL] | Value : " << boolState[already_S_OF_RLL] << endl; //cout << "Attribute : boolState[S_OF_RLL] | Value : " << boolState[S_OF_RLL] << endl; //cout << "Attribute : boolState[relevant_evt_OF_RLL] | Value : " << boolState[relevant_evt_OF_RLL] << endl; //cout << "Attribute : boolState[required_OF_RLR] | Value : " << boolState[required_OF_RLR] << endl; //cout << "Attribute : boolState[already_S_OF_RLR] | Value : " << boolState[already_S_OF_RLR] << endl; //cout << "Attribute : boolState[S_OF_RLR] | Value : " << boolState[S_OF_RLR] << endl; //cout << "Attribute : boolState[relevant_evt_OF_RLR] | Value : " << boolState[relevant_evt_OF_RLR] << endl; //cout << "Attribute : boolState[required_OF_System] | Value : " << boolState[required_OF_System] << endl; //cout << "Attribute : boolState[already_S_OF_System] | Value : " << boolState[already_S_OF_System] << endl; //cout << "Attribute : boolState[S_OF_System] | Value : " << boolState[S_OF_System] << endl; //cout << "Attribute : boolState[relevant_evt_OF_System] | Value : " << boolState[relevant_evt_OF_System] << endl; //cout << "Attribute : boolState[required_OF_UE_1] | Value : " << boolState[required_OF_UE_1] << endl; //cout << "Attribute : boolState[already_S_OF_UE_1] | Value : " << boolState[already_S_OF_UE_1] << endl; //cout << "Attribute : boolState[S_OF_UE_1] | Value : " << boolState[S_OF_UE_1] << endl; //cout << "Attribute : boolState[relevant_evt_OF_UE_1] | Value : " << boolState[relevant_evt_OF_UE_1] << endl; //cout << "Attribute : boolState[required_OF_V1] | Value : " << boolState[required_OF_V1] << endl; //cout << "Attribute : boolState[already_S_OF_V1] | Value : " << boolState[already_S_OF_V1] << endl; //cout << "Attribute : boolState[S_OF_V1] | Value : " << boolState[S_OF_V1] << endl; //cout << "Attribute : boolState[relevant_evt_OF_V1] | Value : " << boolState[relevant_evt_OF_V1] << endl; //cout << "Attribute : boolState[failF_OF_V1] | Value : " << boolState[failF_OF_V1] << endl; //cout << "Attribute : boolState[required_OF_V2] | Value : " << boolState[required_OF_V2] << endl; //cout << "Attribute : boolState[already_S_OF_V2] | Value : " << boolState[already_S_OF_V2] << endl; //cout << "Attribute : boolState[S_OF_V2] | Value : " << boolState[S_OF_V2] << endl; //cout << "Attribute : boolState[relevant_evt_OF_V2] | Value : " << boolState[relevant_evt_OF_V2] << endl; //cout << "Attribute : boolState[failF_OF_V2] | Value : " << boolState[failF_OF_V2] << endl; //cout << "Attribute : boolState[required_OF_VSOL1] | Value : " << boolState[required_OF_VSOL1] << endl; //cout << "Attribute : boolState[already_S_OF_VSOL1] | Value : " << boolState[already_S_OF_VSOL1] << endl; //cout << "Attribute : boolState[S_OF_VSOL1] | Value : " << boolState[S_OF_VSOL1] << endl; //cout << "Attribute : boolState[relevant_evt_OF_VSOL1] | Value : " << boolState[relevant_evt_OF_VSOL1] << endl; //cout << "Attribute : boolState[failF_OF_VSOL1] | Value : " << boolState[failF_OF_VSOL1] << endl; //cout << "Attribute : boolState[required_OF_VSOL2] | Value : " << boolState[required_OF_VSOL2] << endl; //cout << "Attribute : boolState[already_S_OF_VSOL2] | Value : " << boolState[already_S_OF_VSOL2] << endl; //cout << "Attribute : boolState[S_OF_VSOL2] | Value : " << boolState[S_OF_VSOL2] << endl; //cout << "Attribute : boolState[relevant_evt_OF_VSOL2] | Value : " << boolState[relevant_evt_OF_VSOL2] << endl; //cout << "Attribute : boolState[failF_OF_VSOL2] | Value : " << boolState[failF_OF_VSOL2] << endl; } bool storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::figaromodelhasinstransitions() { return false; } void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::doReinitialisations() { boolState[required_OF_CCFV12] = REINITIALISATION_OF_required_OF_CCFV12; boolState[S_OF_CCFV12] = REINITIALISATION_OF_S_OF_CCFV12; boolState[relevant_evt_OF_CCFV12] = REINITIALISATION_OF_relevant_evt_OF_CCFV12; boolState[required_OF_CCFVSOL12] = REINITIALISATION_OF_required_OF_CCFVSOL12; boolState[S_OF_CCFVSOL12] = REINITIALISATION_OF_S_OF_CCFVSOL12; boolState[relevant_evt_OF_CCFVSOL12] = REINITIALISATION_OF_relevant_evt_OF_CCFVSOL12; boolState[required_OF_Filling] = REINITIALISATION_OF_required_OF_Filling; boolState[S_OF_Filling] = REINITIALISATION_OF_S_OF_Filling; boolState[relevant_evt_OF_Filling] = REINITIALISATION_OF_relevant_evt_OF_Filling; boolState[required_OF_LSH1] = REINITIALISATION_OF_required_OF_LSH1; boolState[S_OF_LSH1] = REINITIALISATION_OF_S_OF_LSH1; boolState[relevant_evt_OF_LSH1] = REINITIALISATION_OF_relevant_evt_OF_LSH1; boolState[required_OF_PSH1] = REINITIALISATION_OF_required_OF_PSH1; boolState[S_OF_PSH1] = REINITIALISATION_OF_S_OF_PSH1; boolState[relevant_evt_OF_PSH1] = REINITIALISATION_OF_relevant_evt_OF_PSH1; boolState[required_OF_R] = REINITIALISATION_OF_required_OF_R; boolState[S_OF_R] = REINITIALISATION_OF_S_OF_R; boolState[relevant_evt_OF_R] = REINITIALISATION_OF_relevant_evt_OF_R; boolState[required_OF_RL] = REINITIALISATION_OF_required_OF_RL; boolState[S_OF_RL] = REINITIALISATION_OF_S_OF_RL; boolState[relevant_evt_OF_RL] = REINITIALISATION_OF_relevant_evt_OF_RL; boolState[required_OF_RLL] = REINITIALISATION_OF_required_OF_RLL; boolState[S_OF_RLL] = REINITIALISATION_OF_S_OF_RLL; boolState[relevant_evt_OF_RLL] = REINITIALISATION_OF_relevant_evt_OF_RLL; boolState[required_OF_RLR] = REINITIALISATION_OF_required_OF_RLR; boolState[S_OF_RLR] = REINITIALISATION_OF_S_OF_RLR; boolState[relevant_evt_OF_RLR] = REINITIALISATION_OF_relevant_evt_OF_RLR; boolState[required_OF_System] = REINITIALISATION_OF_required_OF_System; boolState[S_OF_System] = REINITIALISATION_OF_S_OF_System; boolState[relevant_evt_OF_System] = REINITIALISATION_OF_relevant_evt_OF_System; boolState[required_OF_UE_1] = REINITIALISATION_OF_required_OF_UE_1; boolState[S_OF_UE_1] = REINITIALISATION_OF_S_OF_UE_1; boolState[relevant_evt_OF_UE_1] = REINITIALISATION_OF_relevant_evt_OF_UE_1; boolState[required_OF_V1] = REINITIALISATION_OF_required_OF_V1; boolState[S_OF_V1] = REINITIALISATION_OF_S_OF_V1; boolState[relevant_evt_OF_V1] = REINITIALISATION_OF_relevant_evt_OF_V1; boolState[required_OF_V2] = REINITIALISATION_OF_required_OF_V2; boolState[S_OF_V2] = REINITIALISATION_OF_S_OF_V2; boolState[relevant_evt_OF_V2] = REINITIALISATION_OF_relevant_evt_OF_V2; boolState[required_OF_VSOL1] = REINITIALISATION_OF_required_OF_VSOL1; boolState[S_OF_VSOL1] = REINITIALISATION_OF_S_OF_VSOL1; boolState[relevant_evt_OF_VSOL1] = REINITIALISATION_OF_relevant_evt_OF_VSOL1; boolState[required_OF_VSOL2] = REINITIALISATION_OF_required_OF_VSOL2; boolState[S_OF_VSOL2] = REINITIALISATION_OF_S_OF_VSOL2; boolState[relevant_evt_OF_VSOL2] = REINITIALISATION_OF_relevant_evt_OF_VSOL2; } void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::fireOccurrence(int numFire) { //cout <<">>>>>>>>>>>>>>>>>>>> Fire of occurrence #" << numFire << " <<<<<<<<<<<<<<<<<<<<<<<" << endl; if (numFire == 0) { FIRE_xx10_OF_CCFV12 = true; } if (numFire == 1) { FIRE_xx10_OF_CCFVSOL12 = true; } if (numFire == 2) { FIRE_xx10_OF_Filling = true; } if (numFire == 3) { FIRE_xx10_OF_LSH1 = true; } if (numFire == 4) { FIRE_xx10_OF_PSH1 = true; } if (numFire == 5) { FIRE_xx10_OF_V1 = true; } if (numFire == 6) { FIRE_xx10_OF_V2 = true; } if (numFire == 7) { FIRE_xx10_OF_VSOL1 = true; } if (numFire == 8) { FIRE_xx10_OF_VSOL2 = true; } /* ---------- DECLARATION OF OCCURRENCE RULES------------ */ // Occurrence xx10_OF_CCFV12 if ((boolState[failF_OF_CCFV12] == false) && boolState[required_OF_CCFV12]) { if (FIRE_xx10_OF_CCFV12) { boolState[failF_OF_CCFV12] = true; FIRE_xx10_OF_CCFV12 = false; } } // Occurrence xx10_OF_CCFVSOL12 if ((boolState[failF_OF_CCFVSOL12] == false) && boolState[required_OF_CCFVSOL12]) { if (FIRE_xx10_OF_CCFVSOL12) { boolState[failF_OF_CCFVSOL12] = true; FIRE_xx10_OF_CCFVSOL12 = false; } } // Occurrence xx10_OF_Filling if ((boolState[failF_OF_Filling] == false) && boolState[required_OF_Filling]) { if (FIRE_xx10_OF_Filling) { boolState[failF_OF_Filling] = true; FIRE_xx10_OF_Filling = false; } } // Occurrence xx10_OF_LSH1 if ((boolState[failF_OF_LSH1] == false) && boolState[required_OF_LSH1]) { if (FIRE_xx10_OF_LSH1) { boolState[failF_OF_LSH1] = true; FIRE_xx10_OF_LSH1 = false; } } // Occurrence xx10_OF_PSH1 if ((boolState[failF_OF_PSH1] == false) && boolState[required_OF_PSH1]) { if (FIRE_xx10_OF_PSH1) { boolState[failF_OF_PSH1] = true; FIRE_xx10_OF_PSH1 = false; } } // Occurrence xx10_OF_V1 if ((boolState[failF_OF_V1] == false) && boolState[required_OF_V1]) { if (FIRE_xx10_OF_V1) { boolState[failF_OF_V1] = true; FIRE_xx10_OF_V1 = false; } } // Occurrence xx10_OF_V2 if ((boolState[failF_OF_V2] == false) && boolState[required_OF_V2]) { if (FIRE_xx10_OF_V2) { boolState[failF_OF_V2] = true; FIRE_xx10_OF_V2 = false; } } // Occurrence xx10_OF_VSOL1 if ((boolState[failF_OF_VSOL1] == false) && boolState[required_OF_VSOL1]) { if (FIRE_xx10_OF_VSOL1) { boolState[failF_OF_VSOL1] = true; FIRE_xx10_OF_VSOL1 = false; } } // Occurrence xx10_OF_VSOL2 if ((boolState[failF_OF_VSOL2] == false) && boolState[required_OF_VSOL2]) { if (FIRE_xx10_OF_VSOL2) { boolState[failF_OF_VSOL2] = true; FIRE_xx10_OF_VSOL2 = false; } } } std::vector<std::tuple<int, double, std::string, int>> storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::showFireableOccurrences() { std::vector<std::tuple<int, double, std::string, int>> list = {}; //cout <<"\n==================== List of fireable occurrences : ====================" << endl; if (list.size() > 0) { ins_transition_found = true; return list; } else { ins_transition_found = false; } if ((boolState[failF_OF_CCFV12] == false) && boolState[required_OF_CCFV12]) { //cout << "0 : xx10_OF_CCFV12 : FAULT failF LABEL \"failure in operation CCFV12\" DIST EXP (0.0001) INDUCING boolState[failF_OF_CCFV12] = TRUE" << endl; list.push_back(make_tuple(0, 0.0001, "EXP", 0)); } if ((boolState[failF_OF_CCFVSOL12] == false) && boolState[required_OF_CCFVSOL12]) { //cout << "1 : xx10_OF_CCFVSOL12 : FAULT failF LABEL \"failure in operation CCFVSOL12\" DIST EXP (0.0001) INDUCING boolState[failF_OF_CCFVSOL12] = TRUE" << endl; list.push_back(make_tuple(1, 0.0001, "EXP", 0)); } if ((boolState[failF_OF_Filling] == false) && boolState[required_OF_Filling]) { //cout << "2 : xx10_OF_Filling : FAULT failF LABEL \"failure in operation Filling\" DIST EXP (0.0001) INDUCING boolState[failF_OF_Filling] = TRUE" << endl; list.push_back(make_tuple(2, 0.0001, "EXP", 0)); } if ((boolState[failF_OF_LSH1] == false) && boolState[required_OF_LSH1]) { //cout << "3 : xx10_OF_LSH1 : FAULT failF LABEL \"failure in operation LSH1\" DIST EXP (0.0001) INDUCING boolState[failF_OF_LSH1] = TRUE" << endl; list.push_back(make_tuple(3, 0.0001, "EXP", 0)); } if ((boolState[failF_OF_PSH1] == false) && boolState[required_OF_PSH1]) { //cout << "4 : xx10_OF_PSH1 : FAULT failF LABEL \"failure in operation PSH1\" DIST EXP (0.0001) INDUCING boolState[failF_OF_PSH1] = TRUE" << endl; list.push_back(make_tuple(4, 0.0001, "EXP", 0)); } if ((boolState[failF_OF_V1] == false) && boolState[required_OF_V1]) { //cout << "5 : xx10_OF_V1 : FAULT failF LABEL \"failure in operation V1\" DIST EXP (0.0001) INDUCING boolState[failF_OF_V1] = TRUE" << endl; list.push_back(make_tuple(5, 0.0001, "EXP", 0)); } if ((boolState[failF_OF_V2] == false) && boolState[required_OF_V2]) { //cout << "6 : xx10_OF_V2 : FAULT failF LABEL \"failure in operation V2\" DIST EXP (0.0001) INDUCING boolState[failF_OF_V2] = TRUE" << endl; list.push_back(make_tuple(6, 0.0001, "EXP", 0)); } if ((boolState[failF_OF_VSOL1] == false) && boolState[required_OF_VSOL1]) { //cout << "7 : xx10_OF_VSOL1 : FAULT failF LABEL \"failure in operation VSOL1\" DIST EXP (0.0001) INDUCING boolState[failF_OF_VSOL1] = TRUE" << endl; list.push_back(make_tuple(7, 0.0001, "EXP", 0)); } if ((boolState[failF_OF_VSOL2] == false) && boolState[required_OF_VSOL2]) { //cout << "8 : xx10_OF_VSOL2 : FAULT failF LABEL \"failure in operation VSOL2\" DIST EXP (0.0001) INDUCING boolState[failF_OF_VSOL2] = TRUE" << endl; list.push_back(make_tuple(8, 0.0001, "EXP", 0)); } return list; } void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::runOnceInteractionStep_initialization() { if (boolState[failF_OF_CCFV12] == true ) { boolState[S_OF_CCFV12] = true; } if (boolState[failF_OF_CCFVSOL12] == true ) { boolState[S_OF_CCFVSOL12] = true; } if (boolState[failF_OF_Filling] == true ) { boolState[S_OF_Filling] = true; } if (boolState[failF_OF_LSH1] == true ) { boolState[S_OF_LSH1] = true; } if (boolState[failF_OF_PSH1] == true ) { boolState[S_OF_PSH1] = true; } if (boolState[failF_OF_V1] == true ) { boolState[S_OF_V1] = true; } if (boolState[failF_OF_V2] == true ) { boolState[S_OF_V2] = true; } if (boolState[failF_OF_VSOL1] == true ) { boolState[S_OF_VSOL1] = true; } if (boolState[failF_OF_VSOL2] == true ) { boolState[S_OF_VSOL2] = true; } } void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::runOnceInteractionStep_propagate_effect_S() { if ((boolState[S_OF_CCFV12] || boolState[S_OF_CCFVSOL12]) || boolState[S_OF_RL] ) { boolState[S_OF_R] = true; } if (boolState[S_OF_RLL] && boolState[S_OF_RLR] ) { boolState[S_OF_RL] = true; } if ((boolState[S_OF_LSH1] || boolState[S_OF_V1]) || boolState[S_OF_VSOL1] ) { boolState[S_OF_RLL] = true; } if ((boolState[S_OF_PSH1] || boolState[S_OF_V2]) || boolState[S_OF_VSOL2] ) { boolState[S_OF_RLR] = true; } if (boolState[S_OF_Filling] && boolState[S_OF_R] ) { boolState[S_OF_System] = true; } if (boolState[S_OF_System] ) { boolState[S_OF_UE_1] = true; } } void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::runOnceInteractionStep_propagate_effect_required() { if ( !boolState[required_OF_R] ) { boolState[required_OF_CCFV12] = false; } if (boolState[relevant_evt_OF_R] && ( !boolState[S_OF_R]) ) { boolState[relevant_evt_OF_CCFV12] = true; } if ( !boolState[required_OF_R] ) { boolState[required_OF_CCFVSOL12] = false; } if (boolState[relevant_evt_OF_R] && ( !boolState[S_OF_R]) ) { boolState[relevant_evt_OF_CCFVSOL12] = true; } if ( !boolState[required_OF_System] ) { boolState[required_OF_Filling] = false; } if (boolState[relevant_evt_OF_System] && ( !boolState[S_OF_System]) ) { boolState[relevant_evt_OF_Filling] = true; } if ( !boolState[required_OF_RLL] ) { boolState[required_OF_LSH1] = false; } if (boolState[relevant_evt_OF_RLL] && ( !boolState[S_OF_RLL]) ) { boolState[relevant_evt_OF_LSH1] = true; } if ( !boolState[required_OF_RLR] ) { boolState[required_OF_PSH1] = false; } if (boolState[relevant_evt_OF_RLR] && ( !boolState[S_OF_RLR]) ) { boolState[relevant_evt_OF_PSH1] = true; } if ( !boolState[required_OF_System] ) { boolState[required_OF_R] = false; } if (boolState[relevant_evt_OF_System] && ( !boolState[S_OF_System]) ) { boolState[relevant_evt_OF_R] = true; } if ( !boolState[required_OF_R] ) { boolState[required_OF_RL] = false; } if (boolState[relevant_evt_OF_R] && ( !boolState[S_OF_R]) ) { boolState[relevant_evt_OF_RL] = true; } if ( !boolState[required_OF_RL] ) { boolState[required_OF_RLL] = false; } if (boolState[relevant_evt_OF_RL] && ( !boolState[S_OF_RL]) ) { boolState[relevant_evt_OF_RLL] = true; } if ( !boolState[required_OF_RL] ) { boolState[required_OF_RLR] = false; } if (boolState[relevant_evt_OF_RL] && ( !boolState[S_OF_RL]) ) { boolState[relevant_evt_OF_RLR] = true; } if ( !boolState[required_OF_UE_1] ) { boolState[required_OF_System] = false; } if (boolState[relevant_evt_OF_UE_1] && ( !boolState[S_OF_UE_1]) ) { boolState[relevant_evt_OF_System] = true; } boolState[relevant_evt_OF_UE_1] = true ; if ( !boolState[required_OF_RLL] ) { boolState[required_OF_V1] = false; } if (boolState[relevant_evt_OF_RLL] && ( !boolState[S_OF_RLL]) ) { boolState[relevant_evt_OF_V1] = true; } if ( !boolState[required_OF_RLR] ) { boolState[required_OF_V2] = false; } if (boolState[relevant_evt_OF_RLR] && ( !boolState[S_OF_RLR]) ) { boolState[relevant_evt_OF_V2] = true; } if ( !boolState[required_OF_RLL] ) { boolState[required_OF_VSOL1] = false; } if (boolState[relevant_evt_OF_RLL] && ( !boolState[S_OF_RLL]) ) { boolState[relevant_evt_OF_VSOL1] = true; } if ( !boolState[required_OF_RLR] ) { boolState[required_OF_VSOL2] = false; } if (boolState[relevant_evt_OF_RLR] && ( !boolState[S_OF_RLR]) ) { boolState[relevant_evt_OF_VSOL2] = true; } } void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::runOnceInteractionStep_propagate_leaves() { boolState[already_S_OF_CCFV12] = boolState[S_OF_CCFV12] ; boolState[already_S_OF_CCFVSOL12] = boolState[S_OF_CCFVSOL12] ; boolState[already_S_OF_Filling] = boolState[S_OF_Filling] ; boolState[already_S_OF_LSH1] = boolState[S_OF_LSH1] ; boolState[already_S_OF_PSH1] = boolState[S_OF_PSH1] ; boolState[already_S_OF_R] = boolState[S_OF_R] ; boolState[already_S_OF_RL] = boolState[S_OF_RL] ; boolState[already_S_OF_RLL] = boolState[S_OF_RLL] ; boolState[already_S_OF_RLR] = boolState[S_OF_RLR] ; boolState[already_S_OF_System] = boolState[S_OF_System] ; boolState[already_S_OF_UE_1] = boolState[S_OF_UE_1] ; boolState[already_S_OF_V1] = boolState[S_OF_V1] ; boolState[already_S_OF_V2] = boolState[S_OF_V2] ; boolState[already_S_OF_VSOL1] = boolState[S_OF_VSOL1] ; boolState[already_S_OF_VSOL2] = boolState[S_OF_VSOL2] ; } void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::runInteractions() { int counter = 0; int comparator = 1; doReinitialisations(); int max_interactions_loop = 200; counter = 0; comparator = 1; do { //cout << counter << endl; saveCurrentState(); runOnceInteractionStep_initialization(); comparator = compareStates(); counter++; } while (comparator > 0 && counter < max_interactions_loop); if (comparator <= 0) { //cout << "==> Stabilisation of interactions at loop #" << counter << " for runInteractionStep_initialization() ." << endl; } else { //cout << "==> Maximum of interactions loop reached : #" << counter <<" for runOnceInteractionStep_initialization()." << endl; } counter = 0; comparator = 1; do { //cout << counter << endl; saveCurrentState(); runOnceInteractionStep_propagate_effect_S(); comparator = compareStates(); counter++; } while (comparator > 0 && counter < max_interactions_loop); if (comparator <= 0) { //cout << "==> Stabilisation of interactions at loop #" << counter << " for runInteractionStep_propagate_effect_S() ." << endl; } else { //cout << "==> Maximum of interactions loop reached : #" << counter <<" for runOnceInteractionStep_propagate_effect_S()." << endl; } counter = 0; comparator = 1; do { //cout << counter << endl; saveCurrentState(); runOnceInteractionStep_propagate_effect_required(); comparator = compareStates(); counter++; } while (comparator > 0 && counter < max_interactions_loop); if (comparator <= 0) { //cout << "==> Stabilisation of interactions at loop #" << counter << " for runInteractionStep_propagate_effect_required() ." << endl; } else { //cout << "==> Maximum of interactions loop reached : #" << counter <<" for runOnceInteractionStep_propagate_effect_required()." << endl; } counter = 0; comparator = 1; do { //cout << counter << endl; saveCurrentState(); runOnceInteractionStep_propagate_leaves(); comparator = compareStates(); counter++; } while (comparator > 0 && counter < max_interactions_loop); if (comparator <= 0) { //cout << "==> Stabilisation of interactions at loop #" << counter << " for runInteractionStep_propagate_leaves() ." << endl; } else { //cout << "==> Maximum of interactions loop reached : #" << counter <<" for runOnceInteractionStep_propagate_leaves()." << endl; } // ------------------- Handling of FailureState element -------------------------------- boolFailureState[exp0] = ( boolState[S_OF_UE_1] ); //cout << endl; }void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::printstatetuple(){ std::cout<<"\n State information: ("; for (int i=0; i<boolFailureState.size(); i++) { std::cout<<boolFailureState.at(i); } std::cout<<")"; } int_fast64_t storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::stateSize() const{ return numBoolState; } void storm::figaro::FigaroProgram_TankFilling_No_trim_No_repair::fireinsttransitiongroup(std::string user_input_ins) { std::vector<int> list_user_inputs = {}; int user_input = -2; stringstream ss(user_input_ins); for (int i; ss >> i;) { list_user_inputs.push_back(i); if (ss.peek() == ',') ss.ignore(); } for (size_t i = 0; i < list_user_inputs.size(); i++) { //cout << list_user_inputs[i] << endl; user_input = list_user_inputs[i]; if (user_input == -1) { break; } fireOccurrence(user_input); } } } }
ac8ad1e065f7df0a7a62b05a2651c7f0a2d6264d
2127dbabfaa4eec4e3ef7b6451ce40def60fc0c0
/04/uva512.cpp
4df02ab234b72d9b82eeddda7c529280ab6eddfd
[ "MIT" ]
permissive
ericxie/aoapc
c836ce68e45aed0ccbe0d7d18962913c71e815f6
10092cebbc5b47364680ffecb5269d94349330e8
refs/heads/master
2021-08-04T06:27:34.383221
2021-07-18T09:05:42
2021-07-18T09:05:42
207,291,878
10
0
null
null
null
null
UTF-8
C++
false
false
1,573
cpp
#include <cstdio> int ops[11111][55]; void solve(int x, int y, int n){ int i,j,m,cx=x,cy=y; for(i=0;i<n;i++){ m = ops[i][1]; switch(ops[i][0]){ case 0: for(j=0;j<m;j++){ if(ops[i][2+j]<cy) y--; else if(ops[i][2+j] == cy){ puts("GONE"); return; } } break; case 1: for(j=0;j<m;j++){ if(ops[i][2+j]<cx) x--; else if(ops[i][2+j] == cx){ puts("GONE"); return; } } break; case 2: for(j=0;j<m;j++){ if(ops[i][2+j]<=cy) y++; } break; case 3: for(j=0;j<m;j++){ if(ops[i][2+j]<=cx) x++; } break; case 4: if(ops[i][2] == cx && ops[i][3] == cy) x = ops[i][4], y = ops[i][5]; else if(ops[i][4] == cx && ops[i][5] == cy) x = ops[i][2], y = ops[i][3]; break; } cx = x , cy = y; } printf("moved to (%d,%d)\n",cx,cy); } int main(){ int n,m,i,j,R,C,x,y,T=0; char buf[111]; while(scanf("%d %d",&R,&C),R!=0){ if(T) putchar('\n'); scanf("%d",&n); for(i=0;i<n;i++){ scanf("%s",buf); switch(buf[0]+buf[1]){ case 'D'+'C': ops[i][0] = 0; break; case 'D'+'R': ops[i][0] = 1; break; case 'I'+'C': ops[i][0] = 2; break; case 'I'+'R': ops[i][0] = 3; break; case 'E'+'X': ops[i][0] = 4; break; } if(ops[i][0]!=4) scanf("%d",&ops[i][1]); else ops[i][1] = 4; for(j=0;j<ops[i][1];j++) scanf("%d",&ops[i][2+j]); } printf("Spreadsheet #%d\n",++T); scanf("%d",&m); for(i=0;i<m;i++){ scanf("%d %d",&x,&y); printf("Cell data in (%d,%d) ",x,y); solve(x,y,n); } } return 0; }
f77c01a61aa5b08e21c6111ebd2c6845fa9422d8
5fc19aa0f7940c7d96dbf4feb994c3d9839a8332
/src/render.cpp
25295f9d8f2d72008026b527ef594271d09bce37
[]
no_license
AIV5/proj-game
64e2b75e3539614039d7f75ec501df5e8855bbdf
3edd4cb1521edec33ece2eecc1b384ce54ad6dd7
refs/heads/master
2023-03-27T01:00:55.554832
2021-03-31T12:57:04
2021-03-31T12:57:04
351,522,098
0
0
null
null
null
null
UTF-8
C++
false
false
1,664
cpp
#include <glm/glm.hpp> #include <iostream> #include "render.h" #include "figure.h" #include "shaderManager.h" glm::dvec2 hr = {.5 * PGS_START_WINDOW_WIDTH, .5 * PGS_START_WINDOW_HEIGHT}; GLFWwindow* window; GLuint VAO, prog; void renderLoad () { if (!glfwInit()) exit(-1); window = glfwCreateWindow(PGS_START_WINDOW_WIDTH, PGS_START_WINDOW_HEIGHT, "Projective Game", NULL, NULL); if (!window) { glfwTerminate(); exit(-1); } glfwMakeContextCurrent(window); if (!gladLoadGL()) { std::cout << "Can't load glad\n"; exit(-1); } std::cout << "OpenGL " << GLVersion.major << "." << GLVersion.minor << '\n'; glfwSetWindowSizeCallback(window, changeSize); prog = loadProgram(); glUseProgram(prog); sendResolution(); float point[] = {1,1, 1,-1, -1,-1, -1,1}; GLuint pointsVBO; glGenBuffers(1, &pointsVBO); glBindBuffer(GL_ARRAY_BUFFER, pointsVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(point), point, GL_STATIC_DRAW); glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, pointsVBO); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); } void renderLoop () { glDrawArrays(GL_QUADS, 0, 4); glfwSwapBuffers(window); glfwPollEvents(); } void sendResolution () { GLuint hr_loc = glGetUniformLocation(prog, "hr"); glUniform2f(hr_loc, (float)hr.x, (float)hr.y); } void changeSize (GLFWwindow* _, int w, int h) { hr = .5 * glm::dvec2(w, h); glViewport(0, 0, w, h); sendResolution(); } bool exitCondition () { return glfwWindowShouldClose(window); }
92f4faefd0b9bf388e362c6d8f2d3aa40d83f985
7f1f772271560776681334f00d7eacb35094386e
/tp4/TP4_EJ1.cpp
ffe8e21a4d4146a636399ab3e7052206bf877767
[]
no_license
AgustinPeralta18/PRACTICA_C-
2d1403a9f6922131b8caccfb0c63d24259287a6e
c3330a6574dd341112787ee6307e38951c36dbdf
refs/heads/main
2023-07-13T00:42:50.955022
2021-08-26T01:00:18
2021-08-26T01:00:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,833
cpp
/*1.Realizar una calculadora que realice suma, resta, multiplicación y división. Cada cálculo se debe realizar en funciones pasando los números por valor. /*/ #include <iostream> #include <stdlib.h> #include <cmath> #include <time.h> using namespace std; //Una variable de tipo "double" puede almacenar valores decimales. double sumar (double, double); double restar (double, double); double multiplicar (double, double); double dividir (double, double); int main() { float primerValor, segundoValor; int opcionAElegir; cout<<"****************CALCULADORA EL CHAPON****************"<<endl; cout<<"INGRESE PRIMER VALOR"<<endl; cin>>primerValor; cout<<"INGRESE SEGUNDO VALOR"<<endl; cin>>segundoValor; cout<<"***********ELIJA LA OPERACION QUE QUIERA HACER***********"<<endl; cout<<"SUMAR [1]"<<endl; cout<<"RESTAR [2]"<<endl; cout<<"MULTIPLICAR [3]"<<endl; cout<<"DIVIDIR [4]"<<endl; cin>>opcionAElegir; switch (opcionAElegir){ case 1: cout<<"EL RESULTADO ES: " << sumar(primerValor, segundoValor)<<endl; break; case 2: cout<<"EL RESULTADO ES: " << restar(primerValor, segundoValor)<<endl; break; case 3: cout<<"EL RESULTADO ES: "<< multiplicar(primerValor, segundoValor)<<endl; break; case 4: cout<<"EL RESULTADDO ES: "<< dividir(primerValor, segundoValor)<<endl; break; default: cout<<"INGRESO UN NUMERO INCORRECTO EN LAS OPCIONES QUE NO PERTENECE AL LISTADO"<<endl; break; } return 0; } double sumar (double x, double y){ return x + y; } double restar (double x, double y){ return x - y; } double multiplicar (double x, double y){ return x * y; } double dividir (double x, double y){ return x / y; }
25ce20c42b773d4cb1f41739291c1fddea7e8f9e
3eb180a2400c7b1829664a39375f69cc24d1f0b8
/deps/v8/src/mips/code-stubs-mips.cc
89981fdb193f3abaa76be880be78c463b7b0f2f2
[]
no_license
skifcorp/amigo
86b3ca3190f9951178ce3be641f1e6b05c7dec8f
e1c417286b0bd0077e97f6dd856ad5bca489987b
refs/heads/master
2021-01-10T03:22:20.551290
2016-02-15T06:27:40
2016-02-15T06:28:06
51,735,393
0
0
null
null
null
null
UTF-8
C++
false
false
239,887
cc
// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #if defined(V8_TARGET_ARCH_MIPS) #include "bootstrapper.h" #include "code-stubs.h" #include "codegen.h" #include "regexp-macro-assembler.h" namespace v8 { namespace internal { #define __ ACCESS_MASM(masm) static void EmitIdenticalObjectComparison(MacroAssembler* masm, Label* slow, Condition cc, bool never_nan_nan); static void EmitSmiNonsmiComparison(MacroAssembler* masm, Register lhs, Register rhs, Label* rhs_not_nan, Label* slow, bool strict); static void EmitTwoNonNanDoubleComparison(MacroAssembler* masm, Condition cc); static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm, Register lhs, Register rhs); // Check if the operand is a heap number. static void EmitCheckForHeapNumber(MacroAssembler* masm, Register operand, Register scratch1, Register scratch2, Label* not_a_heap_number) { __ lw(scratch1, FieldMemOperand(operand, HeapObject::kMapOffset)); __ LoadRoot(scratch2, Heap::kHeapNumberMapRootIndex); __ Branch(not_a_heap_number, ne, scratch1, Operand(scratch2)); } void ToNumberStub::Generate(MacroAssembler* masm) { // The ToNumber stub takes one argument in a0. Label check_heap_number, call_builtin; __ JumpIfNotSmi(a0, &check_heap_number); __ mov(v0, a0); __ Ret(); __ bind(&check_heap_number); EmitCheckForHeapNumber(masm, a0, a1, t0, &call_builtin); __ mov(v0, a0); __ Ret(); __ bind(&call_builtin); __ push(a0); __ InvokeBuiltin(Builtins::TO_NUMBER, JUMP_FUNCTION); } void FastNewClosureStub::Generate(MacroAssembler* masm) { // Create a new closure from the given function info in new // space. Set the context to the current context in cp. Label gc; // Pop the function info from the stack. __ pop(a3); // Attempt to allocate new JSFunction in new space. __ AllocateInNewSpace(JSFunction::kSize, v0, a1, a2, &gc, TAG_OBJECT); int map_index = strict_mode_ == kStrictMode ? Context::STRICT_MODE_FUNCTION_MAP_INDEX : Context::FUNCTION_MAP_INDEX; // Compute the function map in the current global context and set that // as the map of the allocated object. __ lw(a2, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_INDEX))); __ lw(a2, FieldMemOperand(a2, GlobalObject::kGlobalContextOffset)); __ lw(a2, MemOperand(a2, Context::SlotOffset(map_index))); __ sw(a2, FieldMemOperand(v0, HeapObject::kMapOffset)); // Initialize the rest of the function. We don't have to update the // write barrier because the allocated object is in new space. __ LoadRoot(a1, Heap::kEmptyFixedArrayRootIndex); __ LoadRoot(a2, Heap::kTheHoleValueRootIndex); __ LoadRoot(t0, Heap::kUndefinedValueRootIndex); __ sw(a1, FieldMemOperand(v0, JSObject::kPropertiesOffset)); __ sw(a1, FieldMemOperand(v0, JSObject::kElementsOffset)); __ sw(a2, FieldMemOperand(v0, JSFunction::kPrototypeOrInitialMapOffset)); __ sw(a3, FieldMemOperand(v0, JSFunction::kSharedFunctionInfoOffset)); __ sw(cp, FieldMemOperand(v0, JSFunction::kContextOffset)); __ sw(a1, FieldMemOperand(v0, JSFunction::kLiteralsOffset)); __ sw(t0, FieldMemOperand(v0, JSFunction::kNextFunctionLinkOffset)); // Initialize the code pointer in the function to be the one // found in the shared function info object. __ lw(a3, FieldMemOperand(a3, SharedFunctionInfo::kCodeOffset)); __ Addu(a3, a3, Operand(Code::kHeaderSize - kHeapObjectTag)); __ sw(a3, FieldMemOperand(v0, JSFunction::kCodeEntryOffset)); // Return result. The argument function info has been popped already. __ Ret(); // Create a new closure through the slower runtime call. __ bind(&gc); __ LoadRoot(t0, Heap::kFalseValueRootIndex); __ Push(cp, a3, t0); __ TailCallRuntime(Runtime::kNewClosure, 3, 1); } void FastNewContextStub::Generate(MacroAssembler* masm) { // Try to allocate the context in new space. Label gc; int length = slots_ + Context::MIN_CONTEXT_SLOTS; // Attempt to allocate the context in new space. __ AllocateInNewSpace(FixedArray::SizeFor(length), v0, a1, a2, &gc, TAG_OBJECT); // Load the function from the stack. __ lw(a3, MemOperand(sp, 0)); // Setup the object header. __ LoadRoot(a2, Heap::kContextMapRootIndex); __ sw(a2, FieldMemOperand(v0, HeapObject::kMapOffset)); __ li(a2, Operand(Smi::FromInt(length))); __ sw(a2, FieldMemOperand(v0, FixedArray::kLengthOffset)); // Setup the fixed slots. __ li(a1, Operand(Smi::FromInt(0))); __ sw(a3, MemOperand(v0, Context::SlotOffset(Context::CLOSURE_INDEX))); __ sw(v0, MemOperand(v0, Context::SlotOffset(Context::FCONTEXT_INDEX))); __ sw(a1, MemOperand(v0, Context::SlotOffset(Context::PREVIOUS_INDEX))); __ sw(a1, MemOperand(v0, Context::SlotOffset(Context::EXTENSION_INDEX))); // Copy the global object from the surrounding context. __ lw(a1, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_INDEX))); __ sw(a1, MemOperand(v0, Context::SlotOffset(Context::GLOBAL_INDEX))); // Initialize the rest of the slots to undefined. __ LoadRoot(a1, Heap::kUndefinedValueRootIndex); for (int i = Context::MIN_CONTEXT_SLOTS; i < length; i++) { __ sw(a1, MemOperand(v0, Context::SlotOffset(i))); } // Remove the on-stack argument and return. __ mov(cp, v0); __ Pop(); __ Ret(); // Need to collect. Call into runtime system. __ bind(&gc); __ TailCallRuntime(Runtime::kNewContext, 1, 1); } void FastCloneShallowArrayStub::Generate(MacroAssembler* masm) { // Stack layout on entry: // [sp]: constant elements. // [sp + kPointerSize]: literal index. // [sp + (2 * kPointerSize)]: literals array. // All sizes here are multiples of kPointerSize. int elements_size = (length_ > 0) ? FixedArray::SizeFor(length_) : 0; int size = JSArray::kSize + elements_size; // Load boilerplate object into r3 and check if we need to create a // boilerplate. Label slow_case; __ lw(a3, MemOperand(sp, 2 * kPointerSize)); __ lw(a0, MemOperand(sp, 1 * kPointerSize)); __ Addu(a3, a3, Operand(FixedArray::kHeaderSize - kHeapObjectTag)); __ sll(t0, a0, kPointerSizeLog2 - kSmiTagSize); __ Addu(t0, a3, t0); __ lw(a3, MemOperand(t0)); __ LoadRoot(t1, Heap::kUndefinedValueRootIndex); __ Branch(&slow_case, eq, a3, Operand(t1)); if (FLAG_debug_code) { const char* message; Heap::RootListIndex expected_map_index; if (mode_ == CLONE_ELEMENTS) { message = "Expected (writable) fixed array"; expected_map_index = Heap::kFixedArrayMapRootIndex; } else { ASSERT(mode_ == COPY_ON_WRITE_ELEMENTS); message = "Expected copy-on-write fixed array"; expected_map_index = Heap::kFixedCOWArrayMapRootIndex; } __ push(a3); __ lw(a3, FieldMemOperand(a3, JSArray::kElementsOffset)); __ lw(a3, FieldMemOperand(a3, HeapObject::kMapOffset)); __ LoadRoot(at, expected_map_index); __ Assert(eq, message, a3, Operand(at)); __ pop(a3); } // Allocate both the JS array and the elements array in one big // allocation. This avoids multiple limit checks. // Return new object in v0. __ AllocateInNewSpace(size, v0, a1, a2, &slow_case, TAG_OBJECT); // Copy the JS array part. for (int i = 0; i < JSArray::kSize; i += kPointerSize) { if ((i != JSArray::kElementsOffset) || (length_ == 0)) { __ lw(a1, FieldMemOperand(a3, i)); __ sw(a1, FieldMemOperand(v0, i)); } } if (length_ > 0) { // Get hold of the elements array of the boilerplate and setup the // elements pointer in the resulting object. __ lw(a3, FieldMemOperand(a3, JSArray::kElementsOffset)); __ Addu(a2, v0, Operand(JSArray::kSize)); __ sw(a2, FieldMemOperand(v0, JSArray::kElementsOffset)); // Copy the elements array. __ CopyFields(a2, a3, a1.bit(), elements_size / kPointerSize); } // Return and remove the on-stack parameters. __ Addu(sp, sp, Operand(3 * kPointerSize)); __ Ret(); __ bind(&slow_case); __ TailCallRuntime(Runtime::kCreateArrayLiteralShallow, 3, 1); } // Takes a Smi and converts to an IEEE 64 bit floating point value in two // registers. The format is 1 sign bit, 11 exponent bits (biased 1023) and // 52 fraction bits (20 in the first word, 32 in the second). Zeros is a // scratch register. Destroys the source register. No GC occurs during this // stub so you don't have to set up the frame. class ConvertToDoubleStub : public CodeStub { public: ConvertToDoubleStub(Register result_reg_1, Register result_reg_2, Register source_reg, Register scratch_reg) : result1_(result_reg_1), result2_(result_reg_2), source_(source_reg), zeros_(scratch_reg) { } private: Register result1_; Register result2_; Register source_; Register zeros_; // Minor key encoding in 16 bits. class ModeBits: public BitField<OverwriteMode, 0, 2> {}; class OpBits: public BitField<Token::Value, 2, 14> {}; Major MajorKey() { return ConvertToDouble; } int MinorKey() { // Encode the parameters in a unique 16 bit value. return result1_.code() + (result2_.code() << 4) + (source_.code() << 8) + (zeros_.code() << 12); } void Generate(MacroAssembler* masm); const char* GetName() { return "ConvertToDoubleStub"; } #ifdef DEBUG void Print() { PrintF("ConvertToDoubleStub\n"); } #endif }; void ConvertToDoubleStub::Generate(MacroAssembler* masm) { #ifndef BIG_ENDIAN_FLOATING_POINT Register exponent = result1_; Register mantissa = result2_; #else Register exponent = result2_; Register mantissa = result1_; #endif Label not_special; // Convert from Smi to integer. __ sra(source_, source_, kSmiTagSize); // Move sign bit from source to destination. This works because the sign bit // in the exponent word of the double has the same position and polarity as // the 2's complement sign bit in a Smi. STATIC_ASSERT(HeapNumber::kSignMask == 0x80000000u); __ And(exponent, source_, Operand(HeapNumber::kSignMask)); // Subtract from 0 if source was negative. __ subu(at, zero_reg, source_); __ movn(source_, at, exponent); // We have -1, 0 or 1, which we treat specially. Register source_ contains // absolute value: it is either equal to 1 (special case of -1 and 1), // greater than 1 (not a special case) or less than 1 (special case of 0). __ Branch(&not_special, gt, source_, Operand(1)); // For 1 or -1 we need to or in the 0 exponent (biased to 1023). static const uint32_t exponent_word_for_1 = HeapNumber::kExponentBias << HeapNumber::kExponentShift; // Safe to use 'at' as dest reg here. __ Or(at, exponent, Operand(exponent_word_for_1)); __ movn(exponent, at, source_); // Write exp when source not 0. // 1, 0 and -1 all have 0 for the second word. __ mov(mantissa, zero_reg); __ Ret(); __ bind(&not_special); // Count leading zeros. // Gets the wrong answer for 0, but we already checked for that case above. __ clz(zeros_, source_); // Compute exponent and or it into the exponent register. // We use mantissa as a scratch register here. __ li(mantissa, Operand(31 + HeapNumber::kExponentBias)); __ subu(mantissa, mantissa, zeros_); __ sll(mantissa, mantissa, HeapNumber::kExponentShift); __ Or(exponent, exponent, mantissa); // Shift up the source chopping the top bit off. __ Addu(zeros_, zeros_, Operand(1)); // This wouldn't work for 1.0 or -1.0 as the shift would be 32 which means 0. __ sllv(source_, source_, zeros_); // Compute lower part of fraction (last 12 bits). __ sll(mantissa, source_, HeapNumber::kMantissaBitsInTopWord); // And the top (top 20 bits). __ srl(source_, source_, 32 - HeapNumber::kMantissaBitsInTopWord); __ or_(exponent, exponent, source_); __ Ret(); } void FloatingPointHelper::LoadSmis(MacroAssembler* masm, FloatingPointHelper::Destination destination, Register scratch1, Register scratch2) { if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); __ sra(scratch1, a0, kSmiTagSize); __ mtc1(scratch1, f14); __ cvt_d_w(f14, f14); __ sra(scratch1, a1, kSmiTagSize); __ mtc1(scratch1, f12); __ cvt_d_w(f12, f12); if (destination == kCoreRegisters) { __ mfc1(a2, f14); __ mfc1(a3, f15); __ mfc1(a0, f12); __ mfc1(a1, f13); } } else { ASSERT(destination == kCoreRegisters); // Write Smi from a0 to a3 and a2 in double format. __ mov(scratch1, a0); ConvertToDoubleStub stub1(a3, a2, scratch1, scratch2); __ push(ra); __ Call(stub1.GetCode(), RelocInfo::CODE_TARGET); // Write Smi from a1 to a1 and a0 in double format. __ mov(scratch1, a1); ConvertToDoubleStub stub2(a1, a0, scratch1, scratch2); __ Call(stub2.GetCode(), RelocInfo::CODE_TARGET); __ pop(ra); } } void FloatingPointHelper::LoadOperands( MacroAssembler* masm, FloatingPointHelper::Destination destination, Register heap_number_map, Register scratch1, Register scratch2, Label* slow) { // Load right operand (a0) to f12 or a2/a3. LoadNumber(masm, destination, a0, f14, a2, a3, heap_number_map, scratch1, scratch2, slow); // Load left operand (a1) to f14 or a0/a1. LoadNumber(masm, destination, a1, f12, a0, a1, heap_number_map, scratch1, scratch2, slow); } void FloatingPointHelper::LoadNumber(MacroAssembler* masm, Destination destination, Register object, FPURegister dst, Register dst1, Register dst2, Register heap_number_map, Register scratch1, Register scratch2, Label* not_number) { if (FLAG_debug_code) { __ AbortIfNotRootValue(heap_number_map, Heap::kHeapNumberMapRootIndex, "HeapNumberMap register clobbered."); } Label is_smi, done; __ JumpIfSmi(object, &is_smi); __ JumpIfNotHeapNumber(object, heap_number_map, scratch1, not_number); // Handle loading a double from a heap number. if (CpuFeatures::IsSupported(FPU) && destination == kFPURegisters) { CpuFeatures::Scope scope(FPU); // Load the double from tagged HeapNumber to double register. // ARM uses a workaround here because of the unaligned HeapNumber // kValueOffset. On MIPS this workaround is built into ldc1 so there's no // point in generating even more instructions. __ ldc1(dst, FieldMemOperand(object, HeapNumber::kValueOffset)); } else { ASSERT(destination == kCoreRegisters); // Load the double from heap number to dst1 and dst2 in double format. __ lw(dst1, FieldMemOperand(object, HeapNumber::kValueOffset)); __ lw(dst2, FieldMemOperand(object, HeapNumber::kValueOffset + kPointerSize)); } __ Branch(&done); // Handle loading a double from a smi. __ bind(&is_smi); if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); // Convert smi to double using FPU instructions. __ SmiUntag(scratch1, object); __ mtc1(scratch1, dst); __ cvt_d_w(dst, dst); if (destination == kCoreRegisters) { // Load the converted smi to dst1 and dst2 in double format. __ mfc1(dst1, dst); __ mfc1(dst2, FPURegister::from_code(dst.code() + 1)); } } else { ASSERT(destination == kCoreRegisters); // Write smi to dst1 and dst2 double format. __ mov(scratch1, object); ConvertToDoubleStub stub(dst2, dst1, scratch1, scratch2); __ push(ra); __ Call(stub.GetCode(), RelocInfo::CODE_TARGET); __ pop(ra); } __ bind(&done); } void FloatingPointHelper::ConvertNumberToInt32(MacroAssembler* masm, Register object, Register dst, Register heap_number_map, Register scratch1, Register scratch2, Register scratch3, FPURegister double_scratch, Label* not_number) { if (FLAG_debug_code) { __ AbortIfNotRootValue(heap_number_map, Heap::kHeapNumberMapRootIndex, "HeapNumberMap register clobbered."); } Label is_smi; Label done; Label not_in_int32_range; __ JumpIfSmi(object, &is_smi); __ lw(scratch1, FieldMemOperand(object, HeapNumber::kMapOffset)); __ Branch(not_number, ne, scratch1, Operand(heap_number_map)); __ ConvertToInt32(object, dst, scratch1, scratch2, double_scratch, &not_in_int32_range); __ jmp(&done); __ bind(&not_in_int32_range); __ lw(scratch1, FieldMemOperand(object, HeapNumber::kExponentOffset)); __ lw(scratch2, FieldMemOperand(object, HeapNumber::kMantissaOffset)); __ EmitOutOfInt32RangeTruncate(dst, scratch1, scratch2, scratch3); __ jmp(&done); __ bind(&is_smi); __ SmiUntag(dst, object); __ bind(&done); } void FloatingPointHelper::ConvertIntToDouble(MacroAssembler* masm, Register int_scratch, Destination destination, FPURegister double_dst, Register dst1, Register dst2, Register scratch2, FPURegister single_scratch) { ASSERT(!int_scratch.is(scratch2)); Label done; if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); __ mtc1(int_scratch, single_scratch); __ cvt_d_w(double_dst, single_scratch); if (destination == kCoreRegisters) { __ mfc1(dst1, double_dst); __ mfc1(dst2, FPURegister::from_code(double_dst.code() + 1)); } } else { Label fewer_than_20_useful_bits; // Expected output: // | dst2 | dst1 | // | s | exp | mantissa | // Check for zero. __ mov(dst2, int_scratch); __ mov(dst1, int_scratch); __ Branch(&done, eq, int_scratch, Operand(zero_reg)); // Preload the sign of the value. __ And(dst2, int_scratch, Operand(HeapNumber::kSignMask)); // Get the absolute value of the object (as an unsigned integer). Label skip_sub; __ Branch(&skip_sub, ge, dst2, Operand(zero_reg)); __ Subu(int_scratch, zero_reg, int_scratch); __ bind(&skip_sub); // Get mantisssa[51:20]. // Get the position of the first set bit. __ clz(dst1, int_scratch); __ li(scratch2, 31); __ Subu(dst1, scratch2, dst1); // Set the exponent. __ Addu(scratch2, dst1, Operand(HeapNumber::kExponentBias)); __ Ins(dst2, scratch2, HeapNumber::kExponentShift, HeapNumber::kExponentBits); // Clear the first non null bit. __ li(scratch2, Operand(1)); __ sllv(scratch2, scratch2, dst1); __ li(at, -1); __ Xor(scratch2, scratch2, at); __ And(int_scratch, int_scratch, scratch2); // Get the number of bits to set in the lower part of the mantissa. __ Subu(scratch2, dst1, Operand(HeapNumber::kMantissaBitsInTopWord)); __ Branch(&fewer_than_20_useful_bits, lt, scratch2, Operand(zero_reg)); // Set the higher 20 bits of the mantissa. __ srlv(at, int_scratch, scratch2); __ or_(dst2, dst2, at); __ li(at, 32); __ subu(scratch2, at, scratch2); __ sllv(dst1, int_scratch, scratch2); __ Branch(&done); __ bind(&fewer_than_20_useful_bits); __ li(at, HeapNumber::kMantissaBitsInTopWord); __ subu(scratch2, at, dst1); __ sllv(scratch2, int_scratch, scratch2); __ Or(dst2, dst2, scratch2); // Set dst1 to 0. __ mov(dst1, zero_reg); } __ bind(&done); } void FloatingPointHelper::LoadNumberAsInt32Double(MacroAssembler* masm, Register object, Destination destination, FPURegister double_dst, Register dst1, Register dst2, Register heap_number_map, Register scratch1, Register scratch2, FPURegister single_scratch, Label* not_int32) { ASSERT(!scratch1.is(object) && !scratch2.is(object)); ASSERT(!scratch1.is(scratch2)); ASSERT(!heap_number_map.is(object) && !heap_number_map.is(scratch1) && !heap_number_map.is(scratch2)); Label done, obj_is_not_smi; __ JumpIfNotSmi(object, &obj_is_not_smi); __ SmiUntag(scratch1, object); ConvertIntToDouble(masm, scratch1, destination, double_dst, dst1, dst2, scratch2, single_scratch); __ Branch(&done); __ bind(&obj_is_not_smi); if (FLAG_debug_code) { __ AbortIfNotRootValue(heap_number_map, Heap::kHeapNumberMapRootIndex, "HeapNumberMap register clobbered."); } __ JumpIfNotHeapNumber(object, heap_number_map, scratch1, not_int32); // Load the number. if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); // Load the double value. __ ldc1(double_dst, FieldMemOperand(object, HeapNumber::kValueOffset)); // NOTE: ARM uses a MacroAssembler function here (EmitVFPTruncate). // On MIPS a lot of things cannot be implemented the same way so right // now it makes a lot more sense to just do things manually. // Save FCSR. __ cfc1(scratch1, FCSR); // Disable FPU exceptions. __ ctc1(zero_reg, FCSR); __ trunc_w_d(single_scratch, double_dst); // Retrieve FCSR. __ cfc1(scratch2, FCSR); // Restore FCSR. __ ctc1(scratch1, FCSR); // Check for inexact conversion. __ srl(scratch2, scratch2, kFCSRFlagShift); __ And(scratch2, scratch2, (kFCSRFlagMask | kFCSRInexactFlagBit)); // Jump to not_int32 if the operation did not succeed. __ Branch(not_int32, ne, scratch2, Operand(zero_reg)); if (destination == kCoreRegisters) { __ mfc1(dst1, double_dst); __ mfc1(dst2, FPURegister::from_code(double_dst.code() + 1)); } } else { ASSERT(!scratch1.is(object) && !scratch2.is(object)); // Load the double value in the destination registers. __ lw(dst2, FieldMemOperand(object, HeapNumber::kExponentOffset)); __ lw(dst1, FieldMemOperand(object, HeapNumber::kMantissaOffset)); // Check for 0 and -0. __ And(scratch1, dst1, Operand(~HeapNumber::kSignMask)); __ Or(scratch1, scratch1, Operand(dst2)); __ Branch(&done, eq, scratch1, Operand(zero_reg)); // Check that the value can be exactly represented by a 32-bit integer. // Jump to not_int32 if that's not the case. DoubleIs32BitInteger(masm, dst1, dst2, scratch1, scratch2, not_int32); // dst1 and dst2 were trashed. Reload the double value. __ lw(dst2, FieldMemOperand(object, HeapNumber::kExponentOffset)); __ lw(dst1, FieldMemOperand(object, HeapNumber::kMantissaOffset)); } __ bind(&done); } void FloatingPointHelper::LoadNumberAsInt32(MacroAssembler* masm, Register object, Register dst, Register heap_number_map, Register scratch1, Register scratch2, Register scratch3, FPURegister double_scratch, Label* not_int32) { ASSERT(!dst.is(object)); ASSERT(!scratch1.is(object) && !scratch2.is(object) && !scratch3.is(object)); ASSERT(!scratch1.is(scratch2) && !scratch1.is(scratch3) && !scratch2.is(scratch3)); Label done; // Untag the object into the destination register. __ SmiUntag(dst, object); // Just return if the object is a smi. __ JumpIfSmi(object, &done); if (FLAG_debug_code) { __ AbortIfNotRootValue(heap_number_map, Heap::kHeapNumberMapRootIndex, "HeapNumberMap register clobbered."); } __ JumpIfNotHeapNumber(object, heap_number_map, scratch1, not_int32); // Object is a heap number. // Convert the floating point value to a 32-bit integer. if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); // Load the double value. __ ldc1(double_scratch, FieldMemOperand(object, HeapNumber::kValueOffset)); // NOTE: ARM uses a MacroAssembler function here (EmitVFPTruncate). // On MIPS a lot of things cannot be implemented the same way so right // now it makes a lot more sense to just do things manually. // Save FCSR. __ cfc1(scratch1, FCSR); // Disable FPU exceptions. __ ctc1(zero_reg, FCSR); __ trunc_w_d(double_scratch, double_scratch); // Retrieve FCSR. __ cfc1(scratch2, FCSR); // Restore FCSR. __ ctc1(scratch1, FCSR); // Check for inexact conversion. __ srl(scratch2, scratch2, kFCSRFlagShift); __ And(scratch2, scratch2, (kFCSRFlagMask | kFCSRInexactFlagBit)); // Jump to not_int32 if the operation did not succeed. __ Branch(not_int32, ne, scratch2, Operand(zero_reg)); // Get the result in the destination register. __ mfc1(dst, double_scratch); } else { // Load the double value in the destination registers. __ lw(scratch2, FieldMemOperand(object, HeapNumber::kExponentOffset)); __ lw(scratch1, FieldMemOperand(object, HeapNumber::kMantissaOffset)); // Check for 0 and -0. __ And(dst, scratch1, Operand(~HeapNumber::kSignMask)); __ Or(dst, scratch2, Operand(dst)); __ Branch(&done, eq, dst, Operand(zero_reg)); DoubleIs32BitInteger(masm, scratch1, scratch2, dst, scratch3, not_int32); // Registers state after DoubleIs32BitInteger. // dst: mantissa[51:20]. // scratch2: 1 // Shift back the higher bits of the mantissa. __ srlv(dst, dst, scratch3); // Set the implicit first bit. __ li(at, 32); __ subu(scratch3, at, scratch3); __ sllv(scratch2, scratch2, scratch3); __ Or(dst, dst, scratch2); // Set the sign. __ lw(scratch1, FieldMemOperand(object, HeapNumber::kExponentOffset)); __ And(scratch1, scratch1, Operand(HeapNumber::kSignMask)); Label skip_sub; __ Branch(&skip_sub, ge, scratch1, Operand(zero_reg)); __ Subu(dst, zero_reg, dst); __ bind(&skip_sub); } __ bind(&done); } void FloatingPointHelper::DoubleIs32BitInteger(MacroAssembler* masm, Register src1, Register src2, Register dst, Register scratch, Label* not_int32) { // Get exponent alone in scratch. __ Ext(scratch, src1, HeapNumber::kExponentShift, HeapNumber::kExponentBits); // Substract the bias from the exponent. __ Subu(scratch, scratch, Operand(HeapNumber::kExponentBias)); // src1: higher (exponent) part of the double value. // src2: lower (mantissa) part of the double value. // scratch: unbiased exponent. // Fast cases. Check for obvious non 32-bit integer values. // Negative exponent cannot yield 32-bit integers. __ Branch(not_int32, lt, scratch, Operand(zero_reg)); // Exponent greater than 31 cannot yield 32-bit integers. // Also, a positive value with an exponent equal to 31 is outside of the // signed 32-bit integer range. // Another way to put it is that if (exponent - signbit) > 30 then the // number cannot be represented as an int32. Register tmp = dst; __ srl(at, src1, 31); __ subu(tmp, scratch, at); __ Branch(not_int32, gt, tmp, Operand(30)); // - Bits [21:0] in the mantissa are not null. __ And(tmp, src2, 0x3fffff); __ Branch(not_int32, ne, tmp, Operand(zero_reg)); // Otherwise the exponent needs to be big enough to shift left all the // non zero bits left. So we need the (30 - exponent) last bits of the // 31 higher bits of the mantissa to be null. // Because bits [21:0] are null, we can check instead that the // (32 - exponent) last bits of the 32 higher bits of the mantisssa are null. // Get the 32 higher bits of the mantissa in dst. __ Ext(dst, src2, HeapNumber::kMantissaBitsInTopWord, 32 - HeapNumber::kMantissaBitsInTopWord); __ sll(at, src1, HeapNumber::kNonMantissaBitsInTopWord); __ or_(dst, dst, at); // Create the mask and test the lower bits (of the higher bits). __ li(at, 32); __ subu(scratch, at, scratch); __ li(src2, 1); __ sllv(src1, src2, scratch); __ Subu(src1, src1, Operand(1)); __ And(src1, dst, src1); __ Branch(not_int32, ne, src1, Operand(zero_reg)); } void FloatingPointHelper::CallCCodeForDoubleOperation( MacroAssembler* masm, Token::Value op, Register heap_number_result, Register scratch) { // Using core registers: // a0: Left value (least significant part of mantissa). // a1: Left value (sign, exponent, top of mantissa). // a2: Right value (least significant part of mantissa). // a3: Right value (sign, exponent, top of mantissa). // Assert that heap_number_result is saved. // We currently always use s0 to pass it. ASSERT(heap_number_result.is(s0)); // Push the current return address before the C call. __ push(ra); __ PrepareCallCFunction(4, scratch); // Two doubles are 4 arguments. if (!IsMipsSoftFloatABI) { CpuFeatures::Scope scope(FPU); // We are not using MIPS FPU instructions, and parameters for the runtime // function call are prepaired in a0-a3 registers, but function we are // calling is compiled with hard-float flag and expecting hard float ABI // (parameters in f12/f14 registers). We need to copy parameters from // a0-a3 registers to f12/f14 register pairs. __ mtc1(a0, f12); __ mtc1(a1, f13); __ mtc1(a2, f14); __ mtc1(a3, f15); } // Call C routine that may not cause GC or other trouble. __ CallCFunction(ExternalReference::double_fp_operation(op, masm->isolate()), 4); // Store answer in the overwritable heap number. if (!IsMipsSoftFloatABI) { CpuFeatures::Scope scope(FPU); // Double returned in register f0. __ sdc1(f0, FieldMemOperand(heap_number_result, HeapNumber::kValueOffset)); } else { // Double returned in registers v0 and v1. __ sw(v1, FieldMemOperand(heap_number_result, HeapNumber::kExponentOffset)); __ sw(v0, FieldMemOperand(heap_number_result, HeapNumber::kMantissaOffset)); } // Place heap_number_result in v0 and return to the pushed return address. __ mov(v0, heap_number_result); __ pop(ra); __ Ret(); } // See comment for class, this does NOT work for int32's that are in Smi range. void WriteInt32ToHeapNumberStub::Generate(MacroAssembler* masm) { Label max_negative_int; // the_int_ has the answer which is a signed int32 but not a Smi. // We test for the special value that has a different exponent. STATIC_ASSERT(HeapNumber::kSignMask == 0x80000000u); // Test sign, and save for later conditionals. __ And(sign_, the_int_, Operand(0x80000000u)); __ Branch(&max_negative_int, eq, the_int_, Operand(0x80000000u)); // Set up the correct exponent in scratch_. All non-Smi int32s have the same. // A non-Smi integer is 1.xxx * 2^30 so the exponent is 30 (biased). uint32_t non_smi_exponent = (HeapNumber::kExponentBias + 30) << HeapNumber::kExponentShift; __ li(scratch_, Operand(non_smi_exponent)); // Set the sign bit in scratch_ if the value was negative. __ or_(scratch_, scratch_, sign_); // Subtract from 0 if the value was negative. __ subu(at, zero_reg, the_int_); __ movn(the_int_, at, sign_); // We should be masking the implict first digit of the mantissa away here, // but it just ends up combining harmlessly with the last digit of the // exponent that happens to be 1. The sign bit is 0 so we shift 10 to get // the most significant 1 to hit the last bit of the 12 bit sign and exponent. ASSERT(((1 << HeapNumber::kExponentShift) & non_smi_exponent) != 0); const int shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 2; __ srl(at, the_int_, shift_distance); __ or_(scratch_, scratch_, at); __ sw(scratch_, FieldMemOperand(the_heap_number_, HeapNumber::kExponentOffset)); __ sll(scratch_, the_int_, 32 - shift_distance); __ sw(scratch_, FieldMemOperand(the_heap_number_, HeapNumber::kMantissaOffset)); __ Ret(); __ bind(&max_negative_int); // The max negative int32 is stored as a positive number in the mantissa of // a double because it uses a sign bit instead of using two's complement. // The actual mantissa bits stored are all 0 because the implicit most // significant 1 bit is not stored. non_smi_exponent += 1 << HeapNumber::kExponentShift; __ li(scratch_, Operand(HeapNumber::kSignMask | non_smi_exponent)); __ sw(scratch_, FieldMemOperand(the_heap_number_, HeapNumber::kExponentOffset)); __ mov(scratch_, zero_reg); __ sw(scratch_, FieldMemOperand(the_heap_number_, HeapNumber::kMantissaOffset)); __ Ret(); } // Handle the case where the lhs and rhs are the same object. // Equality is almost reflexive (everything but NaN), so this is a test // for "identity and not NaN". static void EmitIdenticalObjectComparison(MacroAssembler* masm, Label* slow, Condition cc, bool never_nan_nan) { Label not_identical; Label heap_number, return_equal; Register exp_mask_reg = t5; __ Branch(&not_identical, ne, a0, Operand(a1)); // The two objects are identical. If we know that one of them isn't NaN then // we now know they test equal. if (cc != eq || !never_nan_nan) { __ li(exp_mask_reg, Operand(HeapNumber::kExponentMask)); // Test for NaN. Sadly, we can't just compare to factory->nan_value(), // so we do the second best thing - test it ourselves. // They are both equal and they are not both Smis so both of them are not // Smis. If it's not a heap number, then return equal. if (cc == less || cc == greater) { __ GetObjectType(a0, t4, t4); __ Branch(slow, greater, t4, Operand(FIRST_JS_OBJECT_TYPE)); } else { __ GetObjectType(a0, t4, t4); __ Branch(&heap_number, eq, t4, Operand(HEAP_NUMBER_TYPE)); // Comparing JS objects with <=, >= is complicated. if (cc != eq) { __ Branch(slow, greater, t4, Operand(FIRST_JS_OBJECT_TYPE)); // Normally here we fall through to return_equal, but undefined is // special: (undefined == undefined) == true, but // (undefined <= undefined) == false! See ECMAScript 11.8.5. if (cc == less_equal || cc == greater_equal) { __ Branch(&return_equal, ne, t4, Operand(ODDBALL_TYPE)); __ LoadRoot(t2, Heap::kUndefinedValueRootIndex); __ Branch(&return_equal, ne, a0, Operand(t2)); if (cc == le) { // undefined <= undefined should fail. __ li(v0, Operand(GREATER)); } else { // undefined >= undefined should fail. __ li(v0, Operand(LESS)); } __ Ret(); } } } } __ bind(&return_equal); if (cc == less) { __ li(v0, Operand(GREATER)); // Things aren't less than themselves. } else if (cc == greater) { __ li(v0, Operand(LESS)); // Things aren't greater than themselves. } else { __ mov(v0, zero_reg); // Things are <=, >=, ==, === themselves. } __ Ret(); if (cc != eq || !never_nan_nan) { // For less and greater we don't have to check for NaN since the result of // x < x is false regardless. For the others here is some code to check // for NaN. if (cc != lt && cc != gt) { __ bind(&heap_number); // It is a heap number, so return non-equal if it's NaN and equal if it's // not NaN. // The representation of NaN values has all exponent bits (52..62) set, // and not all mantissa bits (0..51) clear. // Read top bits of double representation (second word of value). __ lw(t2, FieldMemOperand(a0, HeapNumber::kExponentOffset)); // Test that exponent bits are all set. __ And(t3, t2, Operand(exp_mask_reg)); // If all bits not set (ne cond), then not a NaN, objects are equal. __ Branch(&return_equal, ne, t3, Operand(exp_mask_reg)); // Shift out flag and all exponent bits, retaining only mantissa. __ sll(t2, t2, HeapNumber::kNonMantissaBitsInTopWord); // Or with all low-bits of mantissa. __ lw(t3, FieldMemOperand(a0, HeapNumber::kMantissaOffset)); __ Or(v0, t3, Operand(t2)); // For equal we already have the right value in v0: Return zero (equal) // if all bits in mantissa are zero (it's an Infinity) and non-zero if // not (it's a NaN). For <= and >= we need to load v0 with the failing // value if it's a NaN. if (cc != eq) { // All-zero means Infinity means equal. __ Ret(eq, v0, Operand(zero_reg)); if (cc == le) { __ li(v0, Operand(GREATER)); // NaN <= NaN should fail. } else { __ li(v0, Operand(LESS)); // NaN >= NaN should fail. } } __ Ret(); } // No fall through here. } __ bind(&not_identical); } static void EmitSmiNonsmiComparison(MacroAssembler* masm, Register lhs, Register rhs, Label* both_loaded_as_doubles, Label* slow, bool strict) { ASSERT((lhs.is(a0) && rhs.is(a1)) || (lhs.is(a1) && rhs.is(a0))); Label lhs_is_smi; __ And(t0, lhs, Operand(kSmiTagMask)); __ Branch(&lhs_is_smi, eq, t0, Operand(zero_reg)); // Rhs is a Smi. // Check whether the non-smi is a heap number. __ GetObjectType(lhs, t4, t4); if (strict) { // If lhs was not a number and rhs was a Smi then strict equality cannot // succeed. Return non-equal (lhs is already not zero). __ mov(v0, lhs); __ Ret(ne, t4, Operand(HEAP_NUMBER_TYPE)); } else { // Smi compared non-strictly with a non-Smi non-heap-number. Call // the runtime. __ Branch(slow, ne, t4, Operand(HEAP_NUMBER_TYPE)); } // Rhs is a smi, lhs is a number. // Convert smi rhs to double. if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); __ sra(at, rhs, kSmiTagSize); __ mtc1(at, f14); __ cvt_d_w(f14, f14); __ ldc1(f12, FieldMemOperand(lhs, HeapNumber::kValueOffset)); } else { // Load lhs to a double in a2, a3. __ lw(a3, FieldMemOperand(lhs, HeapNumber::kValueOffset + 4)); __ lw(a2, FieldMemOperand(lhs, HeapNumber::kValueOffset)); // Write Smi from rhs to a1 and a0 in double format. t5 is scratch. __ mov(t6, rhs); ConvertToDoubleStub stub1(a1, a0, t6, t5); __ push(ra); __ Call(stub1.GetCode(), RelocInfo::CODE_TARGET); __ pop(ra); } // We now have both loaded as doubles. __ jmp(both_loaded_as_doubles); __ bind(&lhs_is_smi); // Lhs is a Smi. Check whether the non-smi is a heap number. __ GetObjectType(rhs, t4, t4); if (strict) { // If lhs was not a number and rhs was a Smi then strict equality cannot // succeed. Return non-equal. __ li(v0, Operand(1)); __ Ret(ne, t4, Operand(HEAP_NUMBER_TYPE)); } else { // Smi compared non-strictly with a non-Smi non-heap-number. Call // the runtime. __ Branch(slow, ne, t4, Operand(HEAP_NUMBER_TYPE)); } // Lhs is a smi, rhs is a number. // Convert smi lhs to double. if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); __ sra(at, lhs, kSmiTagSize); __ mtc1(at, f12); __ cvt_d_w(f12, f12); __ ldc1(f14, FieldMemOperand(rhs, HeapNumber::kValueOffset)); } else { // Convert lhs to a double format. t5 is scratch. __ mov(t6, lhs); ConvertToDoubleStub stub2(a3, a2, t6, t5); __ push(ra); __ Call(stub2.GetCode(), RelocInfo::CODE_TARGET); __ pop(ra); // Load rhs to a double in a1, a0. if (rhs.is(a0)) { __ lw(a1, FieldMemOperand(rhs, HeapNumber::kValueOffset + 4)); __ lw(a0, FieldMemOperand(rhs, HeapNumber::kValueOffset)); } else { __ lw(a0, FieldMemOperand(rhs, HeapNumber::kValueOffset)); __ lw(a1, FieldMemOperand(rhs, HeapNumber::kValueOffset + 4)); } } // Fall through to both_loaded_as_doubles. } void EmitNanCheck(MacroAssembler* masm, Condition cc) { bool exp_first = (HeapNumber::kExponentOffset == HeapNumber::kValueOffset); if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); // Lhs and rhs are already loaded to f12 and f14 register pairs. __ mfc1(t0, f14); // f14 has LS 32 bits of rhs. __ mfc1(t1, f15); // f15 has MS 32 bits of rhs. __ mfc1(t2, f12); // f12 has LS 32 bits of lhs. __ mfc1(t3, f13); // f13 has MS 32 bits of lhs. } else { // Lhs and rhs are already loaded to GP registers. __ mov(t0, a0); // a0 has LS 32 bits of rhs. __ mov(t1, a1); // a1 has MS 32 bits of rhs. __ mov(t2, a2); // a2 has LS 32 bits of lhs. __ mov(t3, a3); // a3 has MS 32 bits of lhs. } Register rhs_exponent = exp_first ? t0 : t1; Register lhs_exponent = exp_first ? t2 : t3; Register rhs_mantissa = exp_first ? t1 : t0; Register lhs_mantissa = exp_first ? t3 : t2; Label one_is_nan, neither_is_nan; Label lhs_not_nan_exp_mask_is_loaded; Register exp_mask_reg = t4; __ li(exp_mask_reg, HeapNumber::kExponentMask); __ and_(t5, lhs_exponent, exp_mask_reg); __ Branch(&lhs_not_nan_exp_mask_is_loaded, ne, t5, Operand(exp_mask_reg)); __ sll(t5, lhs_exponent, HeapNumber::kNonMantissaBitsInTopWord); __ Branch(&one_is_nan, ne, t5, Operand(zero_reg)); __ Branch(&one_is_nan, ne, lhs_mantissa, Operand(zero_reg)); __ li(exp_mask_reg, HeapNumber::kExponentMask); __ bind(&lhs_not_nan_exp_mask_is_loaded); __ and_(t5, rhs_exponent, exp_mask_reg); __ Branch(&neither_is_nan, ne, t5, Operand(exp_mask_reg)); __ sll(t5, rhs_exponent, HeapNumber::kNonMantissaBitsInTopWord); __ Branch(&one_is_nan, ne, t5, Operand(zero_reg)); __ Branch(&neither_is_nan, eq, rhs_mantissa, Operand(zero_reg)); __ bind(&one_is_nan); // NaN comparisons always fail. // Load whatever we need in v0 to make the comparison fail. if (cc == lt || cc == le) { __ li(v0, Operand(GREATER)); } else { __ li(v0, Operand(LESS)); } __ Ret(); // Return. __ bind(&neither_is_nan); } static void EmitTwoNonNanDoubleComparison(MacroAssembler* masm, Condition cc) { // f12 and f14 have the two doubles. Neither is a NaN. // Call a native function to do a comparison between two non-NaNs. // Call C routine that may not cause GC or other trouble. // We use a call_was and return manually because we need arguments slots to // be freed. Label return_result_not_equal, return_result_equal; if (cc == eq) { // Doubles are not equal unless they have the same bit pattern. // Exception: 0 and -0. bool exp_first = (HeapNumber::kExponentOffset == HeapNumber::kValueOffset); if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); // Lhs and rhs are already loaded to f12 and f14 register pairs. __ mfc1(t0, f14); // f14 has LS 32 bits of rhs. __ mfc1(t1, f15); // f15 has MS 32 bits of rhs. __ mfc1(t2, f12); // f12 has LS 32 bits of lhs. __ mfc1(t3, f13); // f13 has MS 32 bits of lhs. } else { // Lhs and rhs are already loaded to GP registers. __ mov(t0, a0); // a0 has LS 32 bits of rhs. __ mov(t1, a1); // a1 has MS 32 bits of rhs. __ mov(t2, a2); // a2 has LS 32 bits of lhs. __ mov(t3, a3); // a3 has MS 32 bits of lhs. } Register rhs_exponent = exp_first ? t0 : t1; Register lhs_exponent = exp_first ? t2 : t3; Register rhs_mantissa = exp_first ? t1 : t0; Register lhs_mantissa = exp_first ? t3 : t2; __ xor_(v0, rhs_mantissa, lhs_mantissa); __ Branch(&return_result_not_equal, ne, v0, Operand(zero_reg)); __ subu(v0, rhs_exponent, lhs_exponent); __ Branch(&return_result_equal, eq, v0, Operand(zero_reg)); // 0, -0 case. __ sll(rhs_exponent, rhs_exponent, kSmiTagSize); __ sll(lhs_exponent, lhs_exponent, kSmiTagSize); __ or_(t4, rhs_exponent, lhs_exponent); __ or_(t4, t4, rhs_mantissa); __ Branch(&return_result_not_equal, ne, t4, Operand(zero_reg)); __ bind(&return_result_equal); __ li(v0, Operand(EQUAL)); __ Ret(); } __ bind(&return_result_not_equal); if (!CpuFeatures::IsSupported(FPU)) { __ push(ra); __ PrepareCallCFunction(4, t4); // Two doubles count as 4 arguments. if (!IsMipsSoftFloatABI) { // We are not using MIPS FPU instructions, and parameters for the runtime // function call are prepaired in a0-a3 registers, but function we are // calling is compiled with hard-float flag and expecting hard float ABI // (parameters in f12/f14 registers). We need to copy parameters from // a0-a3 registers to f12/f14 register pairs. __ mtc1(a0, f12); __ mtc1(a1, f13); __ mtc1(a2, f14); __ mtc1(a3, f15); } __ CallCFunction(ExternalReference::compare_doubles(masm->isolate()), 4); __ pop(ra); // Because this function returns int, result is in v0. __ Ret(); } else { CpuFeatures::Scope scope(FPU); Label equal, less_than; __ c(EQ, D, f12, f14); __ bc1t(&equal); __ nop(); __ c(OLT, D, f12, f14); __ bc1t(&less_than); __ nop(); // Not equal, not less, not NaN, must be greater. __ li(v0, Operand(GREATER)); __ Ret(); __ bind(&equal); __ li(v0, Operand(EQUAL)); __ Ret(); __ bind(&less_than); __ li(v0, Operand(LESS)); __ Ret(); } } static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm, Register lhs, Register rhs) { // If either operand is a JSObject or an oddball value, then they are // not equal since their pointers are different. // There is no test for undetectability in strict equality. STATIC_ASSERT(LAST_TYPE == JS_FUNCTION_TYPE); Label first_non_object; // Get the type of the first operand into a2 and compare it with // FIRST_JS_OBJECT_TYPE. __ GetObjectType(lhs, a2, a2); __ Branch(&first_non_object, less, a2, Operand(FIRST_JS_OBJECT_TYPE)); // Return non-zero. Label return_not_equal; __ bind(&return_not_equal); __ li(v0, Operand(1)); __ Ret(); __ bind(&first_non_object); // Check for oddballs: true, false, null, undefined. __ Branch(&return_not_equal, eq, a2, Operand(ODDBALL_TYPE)); __ GetObjectType(rhs, a3, a3); __ Branch(&return_not_equal, greater, a3, Operand(FIRST_JS_OBJECT_TYPE)); // Check for oddballs: true, false, null, undefined. __ Branch(&return_not_equal, eq, a3, Operand(ODDBALL_TYPE)); // Now that we have the types we might as well check for symbol-symbol. // Ensure that no non-strings have the symbol bit set. STATIC_ASSERT(LAST_TYPE < kNotStringTag + kIsSymbolMask); STATIC_ASSERT(kSymbolTag != 0); __ And(t2, a2, Operand(a3)); __ And(t0, t2, Operand(kIsSymbolMask)); __ Branch(&return_not_equal, ne, t0, Operand(zero_reg)); } static void EmitCheckForTwoHeapNumbers(MacroAssembler* masm, Register lhs, Register rhs, Label* both_loaded_as_doubles, Label* not_heap_numbers, Label* slow) { __ GetObjectType(lhs, a3, a2); __ Branch(not_heap_numbers, ne, a2, Operand(HEAP_NUMBER_TYPE)); __ lw(a2, FieldMemOperand(rhs, HeapObject::kMapOffset)); // If first was a heap number & second wasn't, go to slow case. __ Branch(slow, ne, a3, Operand(a2)); // Both are heap numbers. Load them up then jump to the code we have // for that. if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); __ ldc1(f12, FieldMemOperand(lhs, HeapNumber::kValueOffset)); __ ldc1(f14, FieldMemOperand(rhs, HeapNumber::kValueOffset)); } else { __ lw(a2, FieldMemOperand(lhs, HeapNumber::kValueOffset)); __ lw(a3, FieldMemOperand(lhs, HeapNumber::kValueOffset + 4)); if (rhs.is(a0)) { __ lw(a1, FieldMemOperand(rhs, HeapNumber::kValueOffset + 4)); __ lw(a0, FieldMemOperand(rhs, HeapNumber::kValueOffset)); } else { __ lw(a0, FieldMemOperand(rhs, HeapNumber::kValueOffset)); __ lw(a1, FieldMemOperand(rhs, HeapNumber::kValueOffset + 4)); } } __ jmp(both_loaded_as_doubles); } // Fast negative check for symbol-to-symbol equality. static void EmitCheckForSymbolsOrObjects(MacroAssembler* masm, Register lhs, Register rhs, Label* possible_strings, Label* not_both_strings) { ASSERT((lhs.is(a0) && rhs.is(a1)) || (lhs.is(a1) && rhs.is(a0))); // a2 is object type of lhs. // Ensure that no non-strings have the symbol bit set. Label object_test; STATIC_ASSERT(kSymbolTag != 0); __ And(at, a2, Operand(kIsNotStringMask)); __ Branch(&object_test, ne, at, Operand(zero_reg)); __ And(at, a2, Operand(kIsSymbolMask)); __ Branch(possible_strings, eq, at, Operand(zero_reg)); __ GetObjectType(rhs, a3, a3); __ Branch(not_both_strings, ge, a3, Operand(FIRST_NONSTRING_TYPE)); __ And(at, a3, Operand(kIsSymbolMask)); __ Branch(possible_strings, eq, at, Operand(zero_reg)); // Both are symbols. We already checked they weren't the same pointer // so they are not equal. __ li(v0, Operand(1)); // Non-zero indicates not equal. __ Ret(); __ bind(&object_test); __ Branch(not_both_strings, lt, a2, Operand(FIRST_JS_OBJECT_TYPE)); __ GetObjectType(rhs, a2, a3); __ Branch(not_both_strings, lt, a3, Operand(FIRST_JS_OBJECT_TYPE)); // If both objects are undetectable, they are equal. Otherwise, they // are not equal, since they are different objects and an object is not // equal to undefined. __ lw(a3, FieldMemOperand(lhs, HeapObject::kMapOffset)); __ lbu(a2, FieldMemOperand(a2, Map::kBitFieldOffset)); __ lbu(a3, FieldMemOperand(a3, Map::kBitFieldOffset)); __ and_(a0, a2, a3); __ And(a0, a0, Operand(1 << Map::kIsUndetectable)); __ Xor(v0, a0, Operand(1 << Map::kIsUndetectable)); __ Ret(); } void NumberToStringStub::GenerateLookupNumberStringCache(MacroAssembler* masm, Register object, Register result, Register scratch1, Register scratch2, Register scratch3, bool object_is_smi, Label* not_found) { // Use of registers. Register result is used as a temporary. Register number_string_cache = result; Register mask = scratch3; // Load the number string cache. __ LoadRoot(number_string_cache, Heap::kNumberStringCacheRootIndex); // Make the hash mask from the length of the number string cache. It // contains two elements (number and string) for each cache entry. __ lw(mask, FieldMemOperand(number_string_cache, FixedArray::kLengthOffset)); // Divide length by two (length is a smi). __ sra(mask, mask, kSmiTagSize + 1); __ Addu(mask, mask, -1); // Make mask. // Calculate the entry in the number string cache. The hash value in the // number string cache for smis is just the smi value, and the hash for // doubles is the xor of the upper and lower words. See // Heap::GetNumberStringCache. Isolate* isolate = masm->isolate(); Label is_smi; Label load_result_from_cache; if (!object_is_smi) { __ JumpIfSmi(object, &is_smi); if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); __ CheckMap(object, scratch1, Heap::kHeapNumberMapRootIndex, not_found, true); STATIC_ASSERT(8 == kDoubleSize); __ Addu(scratch1, object, Operand(HeapNumber::kValueOffset - kHeapObjectTag)); __ lw(scratch2, MemOperand(scratch1, kPointerSize)); __ lw(scratch1, MemOperand(scratch1, 0)); __ Xor(scratch1, scratch1, Operand(scratch2)); __ And(scratch1, scratch1, Operand(mask)); // Calculate address of entry in string cache: each entry consists // of two pointer sized fields. __ sll(scratch1, scratch1, kPointerSizeLog2 + 1); __ Addu(scratch1, number_string_cache, scratch1); Register probe = mask; __ lw(probe, FieldMemOperand(scratch1, FixedArray::kHeaderSize)); __ JumpIfSmi(probe, not_found); __ ldc1(f12, FieldMemOperand(object, HeapNumber::kValueOffset)); __ ldc1(f14, FieldMemOperand(probe, HeapNumber::kValueOffset)); __ c(EQ, D, f12, f14); __ bc1t(&load_result_from_cache); __ nop(); // bc1t() requires explicit fill of branch delay slot. __ Branch(not_found); } else { // Note that there is no cache check for non-FPU case, even though // it seems there could be. May be a tiny opimization for non-FPU // cores. __ Branch(not_found); } } __ bind(&is_smi); Register scratch = scratch1; __ sra(scratch, object, 1); // Shift away the tag. __ And(scratch, mask, Operand(scratch)); // Calculate address of entry in string cache: each entry consists // of two pointer sized fields. __ sll(scratch, scratch, kPointerSizeLog2 + 1); __ Addu(scratch, number_string_cache, scratch); // Check if the entry is the smi we are looking for. Register probe = mask; __ lw(probe, FieldMemOperand(scratch, FixedArray::kHeaderSize)); __ Branch(not_found, ne, object, Operand(probe)); // Get the result from the cache. __ bind(&load_result_from_cache); __ lw(result, FieldMemOperand(scratch, FixedArray::kHeaderSize + kPointerSize)); __ IncrementCounter(isolate->counters()->number_to_string_native(), 1, scratch1, scratch2); } void NumberToStringStub::Generate(MacroAssembler* masm) { Label runtime; __ lw(a1, MemOperand(sp, 0)); // Generate code to lookup number in the number string cache. GenerateLookupNumberStringCache(masm, a1, v0, a2, a3, t0, false, &runtime); __ Addu(sp, sp, Operand(1 * kPointerSize)); __ Ret(); __ bind(&runtime); // Handle number to string in the runtime system if not found in the cache. __ TailCallRuntime(Runtime::kNumberToString, 1, 1); } // On entry lhs_ (lhs) and rhs_ (rhs) are the things to be compared. // On exit, v0 is 0, positive, or negative (smi) to indicate the result // of the comparison. void CompareStub::Generate(MacroAssembler* masm) { Label slow; // Call builtin. Label not_smis, both_loaded_as_doubles; if (include_smi_compare_) { Label not_two_smis, smi_done; __ Or(a2, a1, a0); __ JumpIfNotSmi(a2, &not_two_smis); __ sra(a1, a1, 1); __ sra(a0, a0, 1); __ Subu(v0, a1, a0); __ Ret(); __ bind(&not_two_smis); } else if (FLAG_debug_code) { __ Or(a2, a1, a0); __ And(a2, a2, kSmiTagMask); __ Assert(ne, "CompareStub: unexpected smi operands.", a2, Operand(zero_reg)); } // NOTICE! This code is only reached after a smi-fast-case check, so // it is certain that at least one operand isn't a smi. // Handle the case where the objects are identical. Either returns the answer // or goes to slow. Only falls through if the objects were not identical. EmitIdenticalObjectComparison(masm, &slow, cc_, never_nan_nan_); // If either is a Smi (we know that not both are), then they can only // be strictly equal if the other is a HeapNumber. STATIC_ASSERT(kSmiTag == 0); ASSERT_EQ(0, Smi::FromInt(0)); __ And(t2, lhs_, Operand(rhs_)); __ JumpIfNotSmi(t2, &not_smis, t0); // One operand is a smi. EmitSmiNonsmiComparison generates code that can: // 1) Return the answer. // 2) Go to slow. // 3) Fall through to both_loaded_as_doubles. // 4) Jump to rhs_not_nan. // In cases 3 and 4 we have found out we were dealing with a number-number // comparison and the numbers have been loaded into f12 and f14 as doubles, // or in GP registers (a0, a1, a2, a3) depending on the presence of the FPU. EmitSmiNonsmiComparison(masm, lhs_, rhs_, &both_loaded_as_doubles, &slow, strict_); __ bind(&both_loaded_as_doubles); // f12, f14 are the double representations of the left hand side // and the right hand side if we have FPU. Otherwise a2, a3 represent // left hand side and a0, a1 represent right hand side. Isolate* isolate = masm->isolate(); if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); Label nan; __ li(t0, Operand(LESS)); __ li(t1, Operand(GREATER)); __ li(t2, Operand(EQUAL)); // Check if either rhs or lhs is NaN. __ c(UN, D, f12, f14); __ bc1t(&nan); __ nop(); // Check if LESS condition is satisfied. If true, move conditionally // result to v0. __ c(OLT, D, f12, f14); __ movt(v0, t0); // Use previous check to store conditionally to v0 oposite condition // (GREATER). If rhs is equal to lhs, this will be corrected in next // check. __ movf(v0, t1); // Check if EQUAL condition is satisfied. If true, move conditionally // result to v0. __ c(EQ, D, f12, f14); __ movt(v0, t2); __ Ret(); __ bind(&nan); // NaN comparisons always fail. // Load whatever we need in v0 to make the comparison fail. if (cc_ == lt || cc_ == le) { __ li(v0, Operand(GREATER)); } else { __ li(v0, Operand(LESS)); } __ Ret(); } else { // Checks for NaN in the doubles we have loaded. Can return the answer or // fall through if neither is a NaN. Also binds rhs_not_nan. EmitNanCheck(masm, cc_); // Compares two doubles that are not NaNs. Returns the answer. // Never falls through. EmitTwoNonNanDoubleComparison(masm, cc_); } __ bind(&not_smis); // At this point we know we are dealing with two different objects, // and neither of them is a Smi. The objects are in lhs_ and rhs_. if (strict_) { // This returns non-equal for some object types, or falls through if it // was not lucky. EmitStrictTwoHeapObjectCompare(masm, lhs_, rhs_); } Label check_for_symbols; Label flat_string_check; // Check for heap-number-heap-number comparison. Can jump to slow case, // or load both doubles and jump to the code that handles // that case. If the inputs are not doubles then jumps to check_for_symbols. // In this case a2 will contain the type of lhs_. EmitCheckForTwoHeapNumbers(masm, lhs_, rhs_, &both_loaded_as_doubles, &check_for_symbols, &flat_string_check); __ bind(&check_for_symbols); if (cc_ == eq && !strict_) { // Returns an answer for two symbols or two detectable objects. // Otherwise jumps to string case or not both strings case. // Assumes that a2 is the type of lhs_ on entry. EmitCheckForSymbolsOrObjects(masm, lhs_, rhs_, &flat_string_check, &slow); } // Check for both being sequential ASCII strings, and inline if that is the // case. __ bind(&flat_string_check); __ JumpIfNonSmisNotBothSequentialAsciiStrings(lhs_, rhs_, a2, a3, &slow); __ IncrementCounter(isolate->counters()->string_compare_native(), 1, a2, a3); if (cc_ == eq) { StringCompareStub::GenerateFlatAsciiStringEquals(masm, lhs_, rhs_, a2, a3, t0); } else { StringCompareStub::GenerateCompareFlatAsciiStrings(masm, lhs_, rhs_, a2, a3, t0, t1); } // Never falls through to here. __ bind(&slow); // Prepare for call to builtin. Push object pointers, a0 (lhs) first, // a1 (rhs) second. __ Push(lhs_, rhs_); // Figure out which native to call and setup the arguments. Builtins::JavaScript native; if (cc_ == eq) { native = strict_ ? Builtins::STRICT_EQUALS : Builtins::EQUALS; } else { native = Builtins::COMPARE; int ncr; // NaN compare result. if (cc_ == lt || cc_ == le) { ncr = GREATER; } else { ASSERT(cc_ == gt || cc_ == ge); // Remaining cases. ncr = LESS; } __ li(a0, Operand(Smi::FromInt(ncr))); __ push(a0); } // Call the native; it returns -1 (less), 0 (equal), or 1 (greater) // tagged as a small integer. __ InvokeBuiltin(native, JUMP_FUNCTION); } // This stub does not handle the inlined cases (Smis, Booleans, undefined). // The stub returns zero for false, and a non-zero value for true. void ToBooleanStub::Generate(MacroAssembler* masm) { // This stub uses FPU instructions. ASSERT(CpuFeatures::IsEnabled(FPU)); Label false_result; Label not_heap_number; Register scratch0 = t5.is(tos_) ? t3 : t5; __ LoadRoot(scratch0, Heap::kNullValueRootIndex); __ Branch(&false_result, eq, tos_, Operand(scratch0)); // HeapNumber => false if +0, -0, or NaN. __ lw(scratch0, FieldMemOperand(tos_, HeapObject::kMapOffset)); __ LoadRoot(at, Heap::kHeapNumberMapRootIndex); __ Branch(&not_heap_number, ne, scratch0, Operand(at)); __ Subu(at, tos_, Operand(kHeapObjectTag)); __ ldc1(f12, MemOperand(at, HeapNumber::kValueOffset)); __ fcmp(f12, 0.0, UEQ); // "tos_" is a register, and contains a non zero value by default. // Hence we only need to overwrite "tos_" with zero to return false for // FP_ZERO or FP_NAN cases. Otherwise, by default it returns true. __ movt(tos_, zero_reg); __ Ret(); __ bind(&not_heap_number); // Check if the value is 'null'. // 'null' => false. __ LoadRoot(at, Heap::kNullValueRootIndex); __ Branch(&false_result, eq, tos_, Operand(at)); // It can be an undetectable object. // Undetectable => false. __ lw(at, FieldMemOperand(tos_, HeapObject::kMapOffset)); __ lbu(scratch0, FieldMemOperand(at, Map::kBitFieldOffset)); __ And(scratch0, scratch0, Operand(1 << Map::kIsUndetectable)); __ Branch(&false_result, eq, scratch0, Operand(1 << Map::kIsUndetectable)); // JavaScript object => true. __ lw(scratch0, FieldMemOperand(tos_, HeapObject::kMapOffset)); __ lbu(scratch0, FieldMemOperand(scratch0, Map::kInstanceTypeOffset)); // "tos_" is a register and contains a non-zero value. // Hence we implicitly return true if the greater than // condition is satisfied. __ Ret(gt, scratch0, Operand(FIRST_JS_OBJECT_TYPE)); // Check for string. __ lw(scratch0, FieldMemOperand(tos_, HeapObject::kMapOffset)); __ lbu(scratch0, FieldMemOperand(scratch0, Map::kInstanceTypeOffset)); // "tos_" is a register and contains a non-zero value. // Hence we implicitly return true if the greater than // condition is satisfied. __ Ret(gt, scratch0, Operand(FIRST_NONSTRING_TYPE)); // String value => false iff empty, i.e., length is zero. __ lw(tos_, FieldMemOperand(tos_, String::kLengthOffset)); // If length is zero, "tos_" contains zero ==> false. // If length is not zero, "tos_" contains a non-zero value ==> true. __ Ret(); // Return 0 in "tos_" for false. __ bind(&false_result); __ mov(tos_, zero_reg); __ Ret(); } Handle<Code> GetTypeRecordingUnaryOpStub(int key, TRUnaryOpIC::TypeInfo type_info) { TypeRecordingUnaryOpStub stub(key, type_info); return stub.GetCode(); } const char* TypeRecordingUnaryOpStub::GetName() { if (name_ != NULL) return name_; const int kMaxNameLength = 100; name_ = Isolate::Current()->bootstrapper()->AllocateAutoDeletedArray( kMaxNameLength); if (name_ == NULL) return "OOM"; const char* op_name = Token::Name(op_); const char* overwrite_name = NULL; // Make g++ happy. switch (mode_) { case UNARY_NO_OVERWRITE: overwrite_name = "Alloc"; break; case UNARY_OVERWRITE: overwrite_name = "Overwrite"; break; } OS::SNPrintF(Vector<char>(name_, kMaxNameLength), "TypeRecordingUnaryOpStub_%s_%s_%s", op_name, overwrite_name, TRUnaryOpIC::GetName(operand_type_)); return name_; } // TODO(svenpanne): Use virtual functions instead of switch. void TypeRecordingUnaryOpStub::Generate(MacroAssembler* masm) { switch (operand_type_) { case TRUnaryOpIC::UNINITIALIZED: GenerateTypeTransition(masm); break; case TRUnaryOpIC::SMI: GenerateSmiStub(masm); break; case TRUnaryOpIC::HEAP_NUMBER: GenerateHeapNumberStub(masm); break; case TRUnaryOpIC::GENERIC: GenerateGenericStub(masm); break; } } void TypeRecordingUnaryOpStub::GenerateTypeTransition(MacroAssembler* masm) { // Argument is in a0 and v0 at this point, so we can overwrite a0. // Push this stub's key. Although the operation and the type info are // encoded into the key, the encoding is opaque, so push them too. __ li(a2, Operand(Smi::FromInt(MinorKey()))); __ li(a1, Operand(Smi::FromInt(op_))); __ li(a0, Operand(Smi::FromInt(operand_type_))); __ Push(v0, a2, a1, a0); __ TailCallExternalReference( ExternalReference(IC_Utility(IC::kTypeRecordingUnaryOp_Patch), masm->isolate()), 4, 1); } // TODO(svenpanne): Use virtual functions instead of switch. void TypeRecordingUnaryOpStub::GenerateSmiStub(MacroAssembler* masm) { switch (op_) { case Token::SUB: GenerateSmiStubSub(masm); break; case Token::BIT_NOT: GenerateSmiStubBitNot(masm); break; default: UNREACHABLE(); } } void TypeRecordingUnaryOpStub::GenerateSmiStubSub(MacroAssembler* masm) { Label non_smi, slow; GenerateSmiCodeSub(masm, &non_smi, &slow); __ bind(&non_smi); __ bind(&slow); GenerateTypeTransition(masm); } void TypeRecordingUnaryOpStub::GenerateSmiStubBitNot(MacroAssembler* masm) { Label non_smi; GenerateSmiCodeBitNot(masm, &non_smi); __ bind(&non_smi); GenerateTypeTransition(masm); } void TypeRecordingUnaryOpStub::GenerateSmiCodeSub(MacroAssembler* masm, Label* non_smi, Label* slow) { __ JumpIfNotSmi(a0, non_smi); // The result of negating zero or the smallest negative smi is not a smi. __ And(t0, a0, ~0x80000000); __ Branch(slow, eq, t0, Operand(zero_reg)); // Return '0 - value'. __ Subu(v0, zero_reg, a0); __ Ret(); } void TypeRecordingUnaryOpStub::GenerateSmiCodeBitNot(MacroAssembler* masm, Label* non_smi) { __ JumpIfNotSmi(a0, non_smi); // Flip bits and revert inverted smi-tag. __ Neg(v0, a0); __ And(v0, v0, ~kSmiTagMask); __ Ret(); } // TODO(svenpanne): Use virtual functions instead of switch. void TypeRecordingUnaryOpStub::GenerateHeapNumberStub(MacroAssembler* masm) { switch (op_) { case Token::SUB: GenerateHeapNumberStubSub(masm); break; case Token::BIT_NOT: GenerateHeapNumberStubBitNot(masm); break; default: UNREACHABLE(); } } void TypeRecordingUnaryOpStub::GenerateHeapNumberStubSub(MacroAssembler* masm) { Label non_smi, slow; GenerateSmiCodeSub(masm, &non_smi, &slow); __ bind(&non_smi); GenerateHeapNumberCodeSub(masm, &slow); __ bind(&slow); GenerateTypeTransition(masm); } void TypeRecordingUnaryOpStub::GenerateHeapNumberStubBitNot( MacroAssembler* masm) { Label non_smi, slow; GenerateSmiCodeBitNot(masm, &non_smi); __ bind(&non_smi); GenerateHeapNumberCodeBitNot(masm, &slow); __ bind(&slow); GenerateTypeTransition(masm); } void TypeRecordingUnaryOpStub::GenerateHeapNumberCodeSub(MacroAssembler* masm, Label* slow) { EmitCheckForHeapNumber(masm, a0, a1, t2, slow); // a0 is a heap number. Get a new heap number in a1. if (mode_ == UNARY_OVERWRITE) { __ lw(a2, FieldMemOperand(a0, HeapNumber::kExponentOffset)); __ Xor(a2, a2, Operand(HeapNumber::kSignMask)); // Flip sign. __ sw(a2, FieldMemOperand(a0, HeapNumber::kExponentOffset)); } else { Label slow_allocate_heapnumber, heapnumber_allocated; __ AllocateHeapNumber(a1, a2, a3, t2, &slow_allocate_heapnumber); __ jmp(&heapnumber_allocated); __ bind(&slow_allocate_heapnumber); __ EnterInternalFrame(); __ push(a0); __ CallRuntime(Runtime::kNumberAlloc, 0); __ mov(a1, v0); __ pop(a0); __ LeaveInternalFrame(); __ bind(&heapnumber_allocated); __ lw(a3, FieldMemOperand(a0, HeapNumber::kMantissaOffset)); __ lw(a2, FieldMemOperand(a0, HeapNumber::kExponentOffset)); __ sw(a3, FieldMemOperand(a1, HeapNumber::kMantissaOffset)); __ Xor(a2, a2, Operand(HeapNumber::kSignMask)); // Flip sign. __ sw(a2, FieldMemOperand(a1, HeapNumber::kExponentOffset)); __ mov(v0, a1); } __ Ret(); } void TypeRecordingUnaryOpStub::GenerateHeapNumberCodeBitNot( MacroAssembler* masm, Label* slow) { EmitCheckForHeapNumber(masm, a0, a1, t2, slow); // Convert the heap number in a0 to an untagged integer in a1. __ ConvertToInt32(a0, a1, a2, a3, f0, slow); // Do the bitwise operation and check if the result fits in a smi. Label try_float; __ Neg(a1, a1); __ Addu(a2, a1, Operand(0x40000000)); __ Branch(&try_float, lt, a2, Operand(zero_reg)); // Tag the result as a smi and we're done. __ SmiTag(v0, a1); __ Ret(); // Try to store the result in a heap number. __ bind(&try_float); if (mode_ == UNARY_NO_OVERWRITE) { Label slow_allocate_heapnumber, heapnumber_allocated; __ AllocateHeapNumber(v0, a2, a3, t2, &slow_allocate_heapnumber); __ jmp(&heapnumber_allocated); __ bind(&slow_allocate_heapnumber); __ EnterInternalFrame(); __ push(a1); __ CallRuntime(Runtime::kNumberAlloc, 0); __ pop(a1); __ LeaveInternalFrame(); __ bind(&heapnumber_allocated); } if (CpuFeatures::IsSupported(FPU)) { // Convert the int32 in a1 to the heap number in v0. a2 is corrupted. CpuFeatures::Scope scope(FPU); __ mtc1(a1, f0); __ cvt_d_w(f0, f0); __ sdc1(f0, FieldMemOperand(v0, HeapNumber::kValueOffset)); __ Ret(); } else { // WriteInt32ToHeapNumberStub does not trigger GC, so we do not // have to set up a frame. WriteInt32ToHeapNumberStub stub(a1, v0, a2, a3); __ Jump(stub.GetCode(), RelocInfo::CODE_TARGET); } } // TODO(svenpanne): Use virtual functions instead of switch. void TypeRecordingUnaryOpStub::GenerateGenericStub(MacroAssembler* masm) { switch (op_) { case Token::SUB: GenerateGenericStubSub(masm); break; case Token::BIT_NOT: GenerateGenericStubBitNot(masm); break; default: UNREACHABLE(); } } void TypeRecordingUnaryOpStub::GenerateGenericStubSub(MacroAssembler* masm) { Label non_smi, slow; GenerateSmiCodeSub(masm, &non_smi, &slow); __ bind(&non_smi); GenerateHeapNumberCodeSub(masm, &slow); __ bind(&slow); GenerateGenericCodeFallback(masm); } void TypeRecordingUnaryOpStub::GenerateGenericStubBitNot(MacroAssembler* masm) { Label non_smi, slow; GenerateSmiCodeBitNot(masm, &non_smi); __ bind(&non_smi); GenerateHeapNumberCodeBitNot(masm, &slow); __ bind(&slow); GenerateGenericCodeFallback(masm); } void TypeRecordingUnaryOpStub::GenerateGenericCodeFallback( MacroAssembler* masm) { // Handle the slow case by jumping to the JavaScript builtin. __ push(a0); switch (op_) { case Token::SUB: __ InvokeBuiltin(Builtins::UNARY_MINUS, JUMP_FUNCTION); break; case Token::BIT_NOT: __ InvokeBuiltin(Builtins::BIT_NOT, JUMP_FUNCTION); break; default: UNREACHABLE(); } } Handle<Code> GetTypeRecordingBinaryOpStub(int key, TRBinaryOpIC::TypeInfo type_info, TRBinaryOpIC::TypeInfo result_type_info) { TypeRecordingBinaryOpStub stub(key, type_info, result_type_info); return stub.GetCode(); } void TypeRecordingBinaryOpStub::GenerateTypeTransition(MacroAssembler* masm) { Label get_result; __ Push(a1, a0); __ li(a2, Operand(Smi::FromInt(MinorKey()))); __ li(a1, Operand(Smi::FromInt(op_))); __ li(a0, Operand(Smi::FromInt(operands_type_))); __ Push(a2, a1, a0); __ TailCallExternalReference( ExternalReference(IC_Utility(IC::kTypeRecordingBinaryOp_Patch), masm->isolate()), 5, 1); } void TypeRecordingBinaryOpStub::GenerateTypeTransitionWithSavedArgs( MacroAssembler* masm) { UNIMPLEMENTED(); } void TypeRecordingBinaryOpStub::Generate(MacroAssembler* masm) { switch (operands_type_) { case TRBinaryOpIC::UNINITIALIZED: GenerateTypeTransition(masm); break; case TRBinaryOpIC::SMI: GenerateSmiStub(masm); break; case TRBinaryOpIC::INT32: GenerateInt32Stub(masm); break; case TRBinaryOpIC::HEAP_NUMBER: GenerateHeapNumberStub(masm); break; case TRBinaryOpIC::ODDBALL: GenerateOddballStub(masm); break; case TRBinaryOpIC::BOTH_STRING: GenerateBothStringStub(masm); break; case TRBinaryOpIC::STRING: GenerateStringStub(masm); break; case TRBinaryOpIC::GENERIC: GenerateGeneric(masm); break; default: UNREACHABLE(); } } const char* TypeRecordingBinaryOpStub::GetName() { if (name_ != NULL) return name_; const int kMaxNameLength = 100; name_ = Isolate::Current()->bootstrapper()->AllocateAutoDeletedArray( kMaxNameLength); if (name_ == NULL) return "OOM"; const char* op_name = Token::Name(op_); const char* overwrite_name; switch (mode_) { case NO_OVERWRITE: overwrite_name = "Alloc"; break; case OVERWRITE_RIGHT: overwrite_name = "OverwriteRight"; break; case OVERWRITE_LEFT: overwrite_name = "OverwriteLeft"; break; default: overwrite_name = "UnknownOverwrite"; break; } OS::SNPrintF(Vector<char>(name_, kMaxNameLength), "TypeRecordingBinaryOpStub_%s_%s_%s", op_name, overwrite_name, TRBinaryOpIC::GetName(operands_type_)); return name_; } void TypeRecordingBinaryOpStub::GenerateSmiSmiOperation( MacroAssembler* masm) { Register left = a1; Register right = a0; Register scratch1 = t0; Register scratch2 = t1; ASSERT(right.is(a0)); STATIC_ASSERT(kSmiTag == 0); Label not_smi_result; switch (op_) { case Token::ADD: __ AdduAndCheckForOverflow(v0, left, right, scratch1); __ RetOnNoOverflow(scratch1); // No need to revert anything - right and left are intact. break; case Token::SUB: __ SubuAndCheckForOverflow(v0, left, right, scratch1); __ RetOnNoOverflow(scratch1); // No need to revert anything - right and left are intact. break; case Token::MUL: { // Remove tag from one of the operands. This way the multiplication result // will be a smi if it fits the smi range. __ SmiUntag(scratch1, right); // Do multiplication. // lo = lower 32 bits of scratch1 * left. // hi = higher 32 bits of scratch1 * left. __ Mult(left, scratch1); // Check for overflowing the smi range - no overflow if higher 33 bits of // the result are identical. __ mflo(scratch1); __ mfhi(scratch2); __ sra(scratch1, scratch1, 31); __ Branch(&not_smi_result, ne, scratch1, Operand(scratch2)); // Go slow on zero result to handle -0. __ mflo(v0); __ Ret(ne, v0, Operand(zero_reg)); // We need -0 if we were multiplying a negative number with 0 to get 0. // We know one of them was zero. __ Addu(scratch2, right, left); Label skip; // ARM uses the 'pl' condition, which is 'ge'. // Negating it results in 'lt'. __ Branch(&skip, lt, scratch2, Operand(zero_reg)); ASSERT(Smi::FromInt(0) == 0); __ mov(v0, zero_reg); __ Ret(); // Return smi 0 if the non-zero one was positive. __ bind(&skip); // We fall through here if we multiplied a negative number with 0, because // that would mean we should produce -0. } break; case Token::DIV: { Label done; __ SmiUntag(scratch2, right); __ SmiUntag(scratch1, left); __ Div(scratch1, scratch2); // A minor optimization: div may be calculated asynchronously, so we check // for division by zero before getting the result. __ Branch(&not_smi_result, eq, scratch2, Operand(zero_reg)); // If the result is 0, we need to make sure the dividsor (right) is // positive, otherwise it is a -0 case. // Quotient is in 'lo', remainder is in 'hi'. // Check for no remainder first. __ mfhi(scratch1); __ Branch(&not_smi_result, ne, scratch1, Operand(zero_reg)); __ mflo(scratch1); __ Branch(&done, ne, scratch1, Operand(zero_reg)); __ Branch(&not_smi_result, lt, scratch2, Operand(zero_reg)); __ bind(&done); // Check that the signed result fits in a Smi. __ Addu(scratch2, scratch1, Operand(0x40000000)); __ Branch(&not_smi_result, lt, scratch2, Operand(zero_reg)); __ SmiTag(v0, scratch1); __ Ret(); } break; case Token::MOD: { Label done; __ SmiUntag(scratch2, right); __ SmiUntag(scratch1, left); __ Div(scratch1, scratch2); // A minor optimization: div may be calculated asynchronously, so we check // for division by 0 before calling mfhi. // Check for zero on the right hand side. __ Branch(&not_smi_result, eq, scratch2, Operand(zero_reg)); // If the result is 0, we need to make sure the dividend (left) is // positive (or 0), otherwise it is a -0 case. // Remainder is in 'hi'. __ mfhi(scratch2); __ Branch(&done, ne, scratch2, Operand(zero_reg)); __ Branch(&not_smi_result, lt, scratch1, Operand(zero_reg)); __ bind(&done); // Check that the signed result fits in a Smi. __ Addu(scratch1, scratch2, Operand(0x40000000)); __ Branch(&not_smi_result, lt, scratch1, Operand(zero_reg)); __ SmiTag(v0, scratch2); __ Ret(); } break; case Token::BIT_OR: __ Or(v0, left, Operand(right)); __ Ret(); break; case Token::BIT_AND: __ And(v0, left, Operand(right)); __ Ret(); break; case Token::BIT_XOR: __ Xor(v0, left, Operand(right)); __ Ret(); break; case Token::SAR: // Remove tags from right operand. __ GetLeastBitsFromSmi(scratch1, right, 5); __ srav(scratch1, left, scratch1); // Smi tag result. __ And(v0, scratch1, Operand(~kSmiTagMask)); __ Ret(); break; case Token::SHR: // Remove tags from operands. We can't do this on a 31 bit number // because then the 0s get shifted into bit 30 instead of bit 31. __ SmiUntag(scratch1, left); __ GetLeastBitsFromSmi(scratch2, right, 5); __ srlv(v0, scratch1, scratch2); // Unsigned shift is not allowed to produce a negative number, so // check the sign bit and the sign bit after Smi tagging. __ And(scratch1, v0, Operand(0xc0000000)); __ Branch(&not_smi_result, ne, scratch1, Operand(zero_reg)); // Smi tag result. __ SmiTag(v0); __ Ret(); break; case Token::SHL: // Remove tags from operands. __ SmiUntag(scratch1, left); __ GetLeastBitsFromSmi(scratch2, right, 5); __ sllv(scratch1, scratch1, scratch2); // Check that the signed result fits in a Smi. __ Addu(scratch2, scratch1, Operand(0x40000000)); __ Branch(&not_smi_result, lt, scratch2, Operand(zero_reg)); __ SmiTag(v0, scratch1); __ Ret(); break; default: UNREACHABLE(); } __ bind(&not_smi_result); } void TypeRecordingBinaryOpStub::GenerateFPOperation(MacroAssembler* masm, bool smi_operands, Label* not_numbers, Label* gc_required) { Register left = a1; Register right = a0; Register scratch1 = t3; Register scratch2 = t5; Register scratch3 = t0; ASSERT(smi_operands || (not_numbers != NULL)); if (smi_operands && FLAG_debug_code) { __ AbortIfNotSmi(left); __ AbortIfNotSmi(right); } Register heap_number_map = t2; __ LoadRoot(heap_number_map, Heap::kHeapNumberMapRootIndex); switch (op_) { case Token::ADD: case Token::SUB: case Token::MUL: case Token::DIV: case Token::MOD: { // Load left and right operands into f12 and f14 or a0/a1 and a2/a3 // depending on whether FPU is available or not. FloatingPointHelper::Destination destination = CpuFeatures::IsSupported(FPU) && op_ != Token::MOD ? FloatingPointHelper::kFPURegisters : FloatingPointHelper::kCoreRegisters; // Allocate new heap number for result. Register result = s0; GenerateHeapResultAllocation( masm, result, heap_number_map, scratch1, scratch2, gc_required); // Load the operands. if (smi_operands) { FloatingPointHelper::LoadSmis(masm, destination, scratch1, scratch2); } else { FloatingPointHelper::LoadOperands(masm, destination, heap_number_map, scratch1, scratch2, not_numbers); } // Calculate the result. if (destination == FloatingPointHelper::kFPURegisters) { // Using FPU registers: // f12: Left value. // f14: Right value. CpuFeatures::Scope scope(FPU); switch (op_) { case Token::ADD: __ add_d(f10, f12, f14); break; case Token::SUB: __ sub_d(f10, f12, f14); break; case Token::MUL: __ mul_d(f10, f12, f14); break; case Token::DIV: __ div_d(f10, f12, f14); break; default: UNREACHABLE(); } // ARM uses a workaround here because of the unaligned HeapNumber // kValueOffset. On MIPS this workaround is built into sdc1 so // there's no point in generating even more instructions. __ sdc1(f10, FieldMemOperand(result, HeapNumber::kValueOffset)); __ mov(v0, result); __ Ret(); } else { // Call the C function to handle the double operation. FloatingPointHelper::CallCCodeForDoubleOperation(masm, op_, result, scratch1); if (FLAG_debug_code) { __ stop("Unreachable code."); } } break; } case Token::BIT_OR: case Token::BIT_XOR: case Token::BIT_AND: case Token::SAR: case Token::SHR: case Token::SHL: { if (smi_operands) { __ SmiUntag(a3, left); __ SmiUntag(a2, right); } else { // Convert operands to 32-bit integers. Right in a2 and left in a3. FloatingPointHelper::ConvertNumberToInt32(masm, left, a3, heap_number_map, scratch1, scratch2, scratch3, f0, not_numbers); FloatingPointHelper::ConvertNumberToInt32(masm, right, a2, heap_number_map, scratch1, scratch2, scratch3, f0, not_numbers); } Label result_not_a_smi; switch (op_) { case Token::BIT_OR: __ Or(a2, a3, Operand(a2)); break; case Token::BIT_XOR: __ Xor(a2, a3, Operand(a2)); break; case Token::BIT_AND: __ And(a2, a3, Operand(a2)); break; case Token::SAR: // Use only the 5 least significant bits of the shift count. __ GetLeastBitsFromInt32(a2, a2, 5); __ srav(a2, a3, a2); break; case Token::SHR: // Use only the 5 least significant bits of the shift count. __ GetLeastBitsFromInt32(a2, a2, 5); __ srlv(a2, a3, a2); // SHR is special because it is required to produce a positive answer. // The code below for writing into heap numbers isn't capable of // writing the register as an unsigned int so we go to slow case if we // hit this case. if (CpuFeatures::IsSupported(FPU)) { __ Branch(&result_not_a_smi, lt, a2, Operand(zero_reg)); } else { __ Branch(not_numbers, lt, a2, Operand(zero_reg)); } break; case Token::SHL: // Use only the 5 least significant bits of the shift count. __ GetLeastBitsFromInt32(a2, a2, 5); __ sllv(a2, a3, a2); break; default: UNREACHABLE(); } // Check that the *signed* result fits in a smi. __ Addu(a3, a2, Operand(0x40000000)); __ Branch(&result_not_a_smi, lt, a3, Operand(zero_reg)); __ SmiTag(v0, a2); __ Ret(); // Allocate new heap number for result. __ bind(&result_not_a_smi); Register result = t1; if (smi_operands) { __ AllocateHeapNumber( result, scratch1, scratch2, heap_number_map, gc_required); } else { GenerateHeapResultAllocation( masm, result, heap_number_map, scratch1, scratch2, gc_required); } // a2: Answer as signed int32. // t1: Heap number to write answer into. // Nothing can go wrong now, so move the heap number to v0, which is the // result. __ mov(v0, t1); if (CpuFeatures::IsSupported(FPU)) { // Convert the int32 in a2 to the heap number in a0. As // mentioned above SHR needs to always produce a positive result. CpuFeatures::Scope scope(FPU); __ mtc1(a2, f0); if (op_ == Token::SHR) { __ Cvt_d_uw(f0, f0); } else { __ cvt_d_w(f0, f0); } // ARM uses a workaround here because of the unaligned HeapNumber // kValueOffset. On MIPS this workaround is built into sdc1 so // there's no point in generating even more instructions. __ sdc1(f0, FieldMemOperand(v0, HeapNumber::kValueOffset)); __ Ret(); } else { // Tail call that writes the int32 in a2 to the heap number in v0, using // a3 and a0 as scratch. v0 is preserved and returned. WriteInt32ToHeapNumberStub stub(a2, v0, a3, a0); __ TailCallStub(&stub); } break; } default: UNREACHABLE(); } } // Generate the smi code. If the operation on smis are successful this return is // generated. If the result is not a smi and heap number allocation is not // requested the code falls through. If number allocation is requested but a // heap number cannot be allocated the code jumps to the lable gc_required. void TypeRecordingBinaryOpStub::GenerateSmiCode(MacroAssembler* masm, Label* use_runtime, Label* gc_required, SmiCodeGenerateHeapNumberResults allow_heapnumber_results) { Label not_smis; Register left = a1; Register right = a0; Register scratch1 = t3; Register scratch2 = t5; // Perform combined smi check on both operands. __ Or(scratch1, left, Operand(right)); STATIC_ASSERT(kSmiTag == 0); __ JumpIfNotSmi(scratch1, &not_smis); // If the smi-smi operation results in a smi return is generated. GenerateSmiSmiOperation(masm); // If heap number results are possible generate the result in an allocated // heap number. if (allow_heapnumber_results == ALLOW_HEAPNUMBER_RESULTS) { GenerateFPOperation(masm, true, use_runtime, gc_required); } __ bind(&not_smis); } void TypeRecordingBinaryOpStub::GenerateSmiStub(MacroAssembler* masm) { Label not_smis, call_runtime; if (result_type_ == TRBinaryOpIC::UNINITIALIZED || result_type_ == TRBinaryOpIC::SMI) { // Only allow smi results. GenerateSmiCode(masm, &call_runtime, NULL, NO_HEAPNUMBER_RESULTS); } else { // Allow heap number result and don't make a transition if a heap number // cannot be allocated. GenerateSmiCode(masm, &call_runtime, &call_runtime, ALLOW_HEAPNUMBER_RESULTS); } // Code falls through if the result is not returned as either a smi or heap // number. GenerateTypeTransition(masm); __ bind(&call_runtime); GenerateCallRuntime(masm); } void TypeRecordingBinaryOpStub::GenerateStringStub(MacroAssembler* masm) { ASSERT(operands_type_ == TRBinaryOpIC::STRING); // Try to add arguments as strings, otherwise, transition to the generic // TRBinaryOpIC type. GenerateAddStrings(masm); GenerateTypeTransition(masm); } void TypeRecordingBinaryOpStub::GenerateBothStringStub(MacroAssembler* masm) { Label call_runtime; ASSERT(operands_type_ == TRBinaryOpIC::BOTH_STRING); ASSERT(op_ == Token::ADD); // If both arguments are strings, call the string add stub. // Otherwise, do a transition. // Registers containing left and right operands respectively. Register left = a1; Register right = a0; // Test if left operand is a string. __ JumpIfSmi(left, &call_runtime); __ GetObjectType(left, a2, a2); __ Branch(&call_runtime, ge, a2, Operand(FIRST_NONSTRING_TYPE)); // Test if right operand is a string. __ JumpIfSmi(right, &call_runtime); __ GetObjectType(right, a2, a2); __ Branch(&call_runtime, ge, a2, Operand(FIRST_NONSTRING_TYPE)); StringAddStub string_add_stub(NO_STRING_CHECK_IN_STUB); GenerateRegisterArgsPush(masm); __ TailCallStub(&string_add_stub); __ bind(&call_runtime); GenerateTypeTransition(masm); } void TypeRecordingBinaryOpStub::GenerateInt32Stub(MacroAssembler* masm) { ASSERT(operands_type_ == TRBinaryOpIC::INT32); Register left = a1; Register right = a0; Register scratch1 = t3; Register scratch2 = t5; FPURegister double_scratch = f0; FPURegister single_scratch = f6; Register heap_number_result = no_reg; Register heap_number_map = t2; __ LoadRoot(heap_number_map, Heap::kHeapNumberMapRootIndex); Label call_runtime; // Labels for type transition, used for wrong input or output types. // Both label are currently actually bound to the same position. We use two // different label to differentiate the cause leading to type transition. Label transition; // Smi-smi fast case. Label skip; __ Or(scratch1, left, right); __ JumpIfNotSmi(scratch1, &skip); GenerateSmiSmiOperation(masm); // Fall through if the result is not a smi. __ bind(&skip); switch (op_) { case Token::ADD: case Token::SUB: case Token::MUL: case Token::DIV: case Token::MOD: { // Load both operands and check that they are 32-bit integer. // Jump to type transition if they are not. The registers a0 and a1 (right // and left) are preserved for the runtime call. FloatingPointHelper::Destination destination = CpuFeatures::IsSupported(FPU) && op_ != Token::MOD ? FloatingPointHelper::kFPURegisters : FloatingPointHelper::kCoreRegisters; FloatingPointHelper::LoadNumberAsInt32Double(masm, right, destination, f14, a2, a3, heap_number_map, scratch1, scratch2, f2, &transition); FloatingPointHelper::LoadNumberAsInt32Double(masm, left, destination, f12, t0, t1, heap_number_map, scratch1, scratch2, f2, &transition); if (destination == FloatingPointHelper::kFPURegisters) { CpuFeatures::Scope scope(FPU); Label return_heap_number; switch (op_) { case Token::ADD: __ add_d(f10, f12, f14); break; case Token::SUB: __ sub_d(f10, f12, f14); break; case Token::MUL: __ mul_d(f10, f12, f14); break; case Token::DIV: __ div_d(f10, f12, f14); break; default: UNREACHABLE(); } if (op_ != Token::DIV) { // These operations produce an integer result. // Try to return a smi if we can. // Otherwise return a heap number if allowed, or jump to type // transition. // NOTE: ARM uses a MacroAssembler function here (EmitVFPTruncate). // On MIPS a lot of things cannot be implemented the same way so right // now it makes a lot more sense to just do things manually. // Save FCSR. __ cfc1(scratch1, FCSR); // Disable FPU exceptions. __ ctc1(zero_reg, FCSR); __ trunc_w_d(single_scratch, f10); // Retrieve FCSR. __ cfc1(scratch2, FCSR); // Restore FCSR. __ ctc1(scratch1, FCSR); // Check for inexact conversion. __ srl(scratch2, scratch2, kFCSRFlagShift); __ And(scratch2, scratch2, kFCSRFlagMask); if (result_type_ <= TRBinaryOpIC::INT32) { // If scratch2 != 0, result does not fit in a 32-bit integer. __ Branch(&transition, ne, scratch2, Operand(zero_reg)); } // Check if the result fits in a smi. __ mfc1(scratch1, single_scratch); __ Addu(scratch2, scratch1, Operand(0x40000000)); // If not try to return a heap number. __ Branch(&return_heap_number, lt, scratch2, Operand(zero_reg)); // Check for minus zero. Return heap number for minus zero. Label not_zero; __ Branch(&not_zero, ne, scratch1, Operand(zero_reg)); __ mfc1(scratch2, f11); __ And(scratch2, scratch2, HeapNumber::kSignMask); __ Branch(&return_heap_number, ne, scratch2, Operand(zero_reg)); __ bind(&not_zero); // Tag the result and return. __ SmiTag(v0, scratch1); __ Ret(); } else { // DIV just falls through to allocating a heap number. } if (result_type_ >= (op_ == Token::DIV) ? TRBinaryOpIC::HEAP_NUMBER : TRBinaryOpIC::INT32) { __ bind(&return_heap_number); // We are using FPU registers so s0 is available. heap_number_result = s0; GenerateHeapResultAllocation(masm, heap_number_result, heap_number_map, scratch1, scratch2, &call_runtime); __ mov(v0, heap_number_result); __ sdc1(f10, FieldMemOperand(v0, HeapNumber::kValueOffset)); __ Ret(); } // A DIV operation expecting an integer result falls through // to type transition. } else { // We preserved a0 and a1 to be able to call runtime. // Save the left value on the stack. __ Push(t1, t0); Label pop_and_call_runtime; // Allocate a heap number to store the result. heap_number_result = s0; GenerateHeapResultAllocation(masm, heap_number_result, heap_number_map, scratch1, scratch2, &pop_and_call_runtime); // Load the left value from the value saved on the stack. __ Pop(a1, a0); // Call the C function to handle the double operation. FloatingPointHelper::CallCCodeForDoubleOperation( masm, op_, heap_number_result, scratch1); if (FLAG_debug_code) { __ stop("Unreachable code."); } __ bind(&pop_and_call_runtime); __ Drop(2); __ Branch(&call_runtime); } break; } case Token::BIT_OR: case Token::BIT_XOR: case Token::BIT_AND: case Token::SAR: case Token::SHR: case Token::SHL: { Label return_heap_number; Register scratch3 = t1; // Convert operands to 32-bit integers. Right in a2 and left in a3. The // registers a0 and a1 (right and left) are preserved for the runtime // call. FloatingPointHelper::LoadNumberAsInt32(masm, left, a3, heap_number_map, scratch1, scratch2, scratch3, f0, &transition); FloatingPointHelper::LoadNumberAsInt32(masm, right, a2, heap_number_map, scratch1, scratch2, scratch3, f0, &transition); // The ECMA-262 standard specifies that, for shift operations, only the // 5 least significant bits of the shift value should be used. switch (op_) { case Token::BIT_OR: __ Or(a2, a3, Operand(a2)); break; case Token::BIT_XOR: __ Xor(a2, a3, Operand(a2)); break; case Token::BIT_AND: __ And(a2, a3, Operand(a2)); break; case Token::SAR: __ And(a2, a2, Operand(0x1f)); __ srav(a2, a3, a2); break; case Token::SHR: __ And(a2, a2, Operand(0x1f)); __ srlv(a2, a3, a2); // SHR is special because it is required to produce a positive answer. // We only get a negative result if the shift value (a2) is 0. // This result cannot be respresented as a signed 32-bit integer, try // to return a heap number if we can. // The non FPU code does not support this special case, so jump to // runtime if we don't support it. if (CpuFeatures::IsSupported(FPU)) { __ Branch((result_type_ <= TRBinaryOpIC::INT32) ? &transition : &return_heap_number, lt, a2, Operand(zero_reg)); } else { __ Branch((result_type_ <= TRBinaryOpIC::INT32) ? &transition : &call_runtime, lt, a2, Operand(zero_reg)); } break; case Token::SHL: __ And(a2, a2, Operand(0x1f)); __ sllv(a2, a3, a2); break; default: UNREACHABLE(); } // Check if the result fits in a smi. __ Addu(scratch1, a2, Operand(0x40000000)); // If not try to return a heap number. (We know the result is an int32.) __ Branch(&return_heap_number, lt, scratch1, Operand(zero_reg)); // Tag the result and return. __ SmiTag(v0, a2); __ Ret(); __ bind(&return_heap_number); heap_number_result = t1; GenerateHeapResultAllocation(masm, heap_number_result, heap_number_map, scratch1, scratch2, &call_runtime); if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); if (op_ != Token::SHR) { // Convert the result to a floating point value. __ mtc1(a2, double_scratch); __ cvt_d_w(double_scratch, double_scratch); } else { // The result must be interpreted as an unsigned 32-bit integer. __ mtc1(a2, double_scratch); __ Cvt_d_uw(double_scratch, double_scratch); } // Store the result. __ mov(v0, heap_number_result); __ sdc1(double_scratch, FieldMemOperand(v0, HeapNumber::kValueOffset)); __ Ret(); } else { // Tail call that writes the int32 in a2 to the heap number in v0, using // a3 and a1 as scratch. v0 is preserved and returned. __ mov(a0, t1); WriteInt32ToHeapNumberStub stub(a2, v0, a3, a1); __ TailCallStub(&stub); } break; } default: UNREACHABLE(); } if (transition.is_linked()) { __ bind(&transition); GenerateTypeTransition(masm); } __ bind(&call_runtime); GenerateCallRuntime(masm); } void TypeRecordingBinaryOpStub::GenerateOddballStub(MacroAssembler* masm) { Label call_runtime; if (op_ == Token::ADD) { // Handle string addition here, because it is the only operation // that does not do a ToNumber conversion on the operands. GenerateAddStrings(masm); } // Convert oddball arguments to numbers. Label check, done; __ LoadRoot(t0, Heap::kUndefinedValueRootIndex); __ Branch(&check, ne, a1, Operand(t0)); if (Token::IsBitOp(op_)) { __ li(a1, Operand(Smi::FromInt(0))); } else { __ LoadRoot(a1, Heap::kNanValueRootIndex); } __ jmp(&done); __ bind(&check); __ LoadRoot(t0, Heap::kUndefinedValueRootIndex); __ Branch(&done, ne, a0, Operand(t0)); if (Token::IsBitOp(op_)) { __ li(a0, Operand(Smi::FromInt(0))); } else { __ LoadRoot(a0, Heap::kNanValueRootIndex); } __ bind(&done); GenerateHeapNumberStub(masm); } void TypeRecordingBinaryOpStub::GenerateHeapNumberStub(MacroAssembler* masm) { Label call_runtime; GenerateFPOperation(masm, false, &call_runtime, &call_runtime); __ bind(&call_runtime); GenerateCallRuntime(masm); } void TypeRecordingBinaryOpStub::GenerateGeneric(MacroAssembler* masm) { Label call_runtime, call_string_add_or_runtime; GenerateSmiCode(masm, &call_runtime, &call_runtime, ALLOW_HEAPNUMBER_RESULTS); GenerateFPOperation(masm, false, &call_string_add_or_runtime, &call_runtime); __ bind(&call_string_add_or_runtime); if (op_ == Token::ADD) { GenerateAddStrings(masm); } __ bind(&call_runtime); GenerateCallRuntime(masm); } void TypeRecordingBinaryOpStub::GenerateAddStrings(MacroAssembler* masm) { ASSERT(op_ == Token::ADD); Label left_not_string, call_runtime; Register left = a1; Register right = a0; // Check if left argument is a string. __ JumpIfSmi(left, &left_not_string); __ GetObjectType(left, a2, a2); __ Branch(&left_not_string, ge, a2, Operand(FIRST_NONSTRING_TYPE)); StringAddStub string_add_left_stub(NO_STRING_CHECK_LEFT_IN_STUB); GenerateRegisterArgsPush(masm); __ TailCallStub(&string_add_left_stub); // Left operand is not a string, test right. __ bind(&left_not_string); __ JumpIfSmi(right, &call_runtime); __ GetObjectType(right, a2, a2); __ Branch(&call_runtime, ge, a2, Operand(FIRST_NONSTRING_TYPE)); StringAddStub string_add_right_stub(NO_STRING_CHECK_RIGHT_IN_STUB); GenerateRegisterArgsPush(masm); __ TailCallStub(&string_add_right_stub); // At least one argument is not a string. __ bind(&call_runtime); } void TypeRecordingBinaryOpStub::GenerateCallRuntime(MacroAssembler* masm) { GenerateRegisterArgsPush(masm); switch (op_) { case Token::ADD: __ InvokeBuiltin(Builtins::ADD, JUMP_FUNCTION); break; case Token::SUB: __ InvokeBuiltin(Builtins::SUB, JUMP_FUNCTION); break; case Token::MUL: __ InvokeBuiltin(Builtins::MUL, JUMP_FUNCTION); break; case Token::DIV: __ InvokeBuiltin(Builtins::DIV, JUMP_FUNCTION); break; case Token::MOD: __ InvokeBuiltin(Builtins::MOD, JUMP_FUNCTION); break; case Token::BIT_OR: __ InvokeBuiltin(Builtins::BIT_OR, JUMP_FUNCTION); break; case Token::BIT_AND: __ InvokeBuiltin(Builtins::BIT_AND, JUMP_FUNCTION); break; case Token::BIT_XOR: __ InvokeBuiltin(Builtins::BIT_XOR, JUMP_FUNCTION); break; case Token::SAR: __ InvokeBuiltin(Builtins::SAR, JUMP_FUNCTION); break; case Token::SHR: __ InvokeBuiltin(Builtins::SHR, JUMP_FUNCTION); break; case Token::SHL: __ InvokeBuiltin(Builtins::SHL, JUMP_FUNCTION); break; default: UNREACHABLE(); } } void TypeRecordingBinaryOpStub::GenerateHeapResultAllocation( MacroAssembler* masm, Register result, Register heap_number_map, Register scratch1, Register scratch2, Label* gc_required) { // Code below will scratch result if allocation fails. To keep both arguments // intact for the runtime call result cannot be one of these. ASSERT(!result.is(a0) && !result.is(a1)); if (mode_ == OVERWRITE_LEFT || mode_ == OVERWRITE_RIGHT) { Label skip_allocation, allocated; Register overwritable_operand = mode_ == OVERWRITE_LEFT ? a1 : a0; // If the overwritable operand is already an object, we skip the // allocation of a heap number. __ JumpIfNotSmi(overwritable_operand, &skip_allocation); // Allocate a heap number for the result. __ AllocateHeapNumber( result, scratch1, scratch2, heap_number_map, gc_required); __ Branch(&allocated); __ bind(&skip_allocation); // Use object holding the overwritable operand for result. __ mov(result, overwritable_operand); __ bind(&allocated); } else { ASSERT(mode_ == NO_OVERWRITE); __ AllocateHeapNumber( result, scratch1, scratch2, heap_number_map, gc_required); } } void TypeRecordingBinaryOpStub::GenerateRegisterArgsPush(MacroAssembler* masm) { __ Push(a1, a0); } void TranscendentalCacheStub::Generate(MacroAssembler* masm) { // Untagged case: double input in f4, double result goes // into f4. // Tagged case: tagged input on top of stack and in a0, // tagged result (heap number) goes into v0. Label input_not_smi; Label loaded; Label calculate; Label invalid_cache; const Register scratch0 = t5; const Register scratch1 = t3; const Register cache_entry = a0; const bool tagged = (argument_type_ == TAGGED); if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); if (tagged) { // Argument is a number and is on stack and in a0. // Load argument and check if it is a smi. __ JumpIfNotSmi(a0, &input_not_smi); // Input is a smi. Convert to double and load the low and high words // of the double into a2, a3. __ sra(t0, a0, kSmiTagSize); __ mtc1(t0, f4); __ cvt_d_w(f4, f4); __ mfc1(a2, f4); __ mfc1(a3, f5); __ Branch(&loaded); __ bind(&input_not_smi); // Check if input is a HeapNumber. __ CheckMap(a0, a1, Heap::kHeapNumberMapRootIndex, &calculate, true); // Input is a HeapNumber. Store the // low and high words into a2, a3. __ lw(a2, FieldMemOperand(a0, HeapNumber::kValueOffset)); __ lw(a3, FieldMemOperand(a0, HeapNumber::kValueOffset + 4)); } else { // Input is untagged double in f4. Output goes to f4. __ mfc1(a2, f4); __ mfc1(a3, f5); } __ bind(&loaded); // a2 = low 32 bits of double value. // a3 = high 32 bits of double value. // Compute hash (the shifts are arithmetic): // h = (low ^ high); h ^= h >> 16; h ^= h >> 8; h = h & (cacheSize - 1); __ Xor(a1, a2, a3); __ sra(t0, a1, 16); __ Xor(a1, a1, t0); __ sra(t0, a1, 8); __ Xor(a1, a1, t0); ASSERT(IsPowerOf2(TranscendentalCache::SubCache::kCacheSize)); __ And(a1, a1, Operand(TranscendentalCache::SubCache::kCacheSize - 1)); // a2 = low 32 bits of double value. // a3 = high 32 bits of double value. // a1 = TranscendentalCache::hash(double value). __ li(cache_entry, Operand( ExternalReference::transcendental_cache_array_address( masm->isolate()))); // a0 points to cache array. __ lw(cache_entry, MemOperand(cache_entry, type_ * sizeof( Isolate::Current()->transcendental_cache()->caches_[0]))); // a0 points to the cache for the type type_. // If NULL, the cache hasn't been initialized yet, so go through runtime. __ Branch(&invalid_cache, eq, cache_entry, Operand(zero_reg)); #ifdef DEBUG // Check that the layout of cache elements match expectations. { TranscendentalCache::SubCache::Element test_elem[2]; char* elem_start = reinterpret_cast<char*>(&test_elem[0]); char* elem2_start = reinterpret_cast<char*>(&test_elem[1]); char* elem_in0 = reinterpret_cast<char*>(&(test_elem[0].in[0])); char* elem_in1 = reinterpret_cast<char*>(&(test_elem[0].in[1])); char* elem_out = reinterpret_cast<char*>(&(test_elem[0].output)); CHECK_EQ(12, elem2_start - elem_start); // Two uint_32's and a pointer. CHECK_EQ(0, elem_in0 - elem_start); CHECK_EQ(kIntSize, elem_in1 - elem_start); CHECK_EQ(2 * kIntSize, elem_out - elem_start); } #endif // Find the address of the a1'st entry in the cache, i.e., &a0[a1*12]. __ sll(t0, a1, 1); __ Addu(a1, a1, t0); __ sll(t0, a1, 2); __ Addu(cache_entry, cache_entry, t0); // Check if cache matches: Double value is stored in uint32_t[2] array. __ lw(t0, MemOperand(cache_entry, 0)); __ lw(t1, MemOperand(cache_entry, 4)); __ lw(t2, MemOperand(cache_entry, 8)); __ Addu(cache_entry, cache_entry, 12); __ Branch(&calculate, ne, a2, Operand(t0)); __ Branch(&calculate, ne, a3, Operand(t1)); // Cache hit. Load result, cleanup and return. if (tagged) { // Pop input value from stack and load result into v0. __ Drop(1); __ mov(v0, t2); } else { // Load result into f4. __ ldc1(f4, FieldMemOperand(t2, HeapNumber::kValueOffset)); } __ Ret(); } // if (CpuFeatures::IsSupported(FPU)) __ bind(&calculate); if (tagged) { __ bind(&invalid_cache); __ TailCallExternalReference(ExternalReference(RuntimeFunction(), masm->isolate()), 1, 1); } else { if (!CpuFeatures::IsSupported(FPU)) UNREACHABLE(); CpuFeatures::Scope scope(FPU); Label no_update; Label skip_cache; const Register heap_number_map = t2; // Call C function to calculate the result and update the cache. // Register a0 holds precalculated cache entry address; preserve // it on the stack and pop it into register cache_entry after the // call. __ push(cache_entry); GenerateCallCFunction(masm, scratch0); __ GetCFunctionDoubleResult(f4); // Try to update the cache. If we cannot allocate a // heap number, we return the result without updating. __ pop(cache_entry); __ LoadRoot(t1, Heap::kHeapNumberMapRootIndex); __ AllocateHeapNumber(t2, scratch0, scratch1, t1, &no_update); __ sdc1(f4, FieldMemOperand(t2, HeapNumber::kValueOffset)); __ sw(a2, MemOperand(cache_entry, 0 * kPointerSize)); __ sw(a3, MemOperand(cache_entry, 1 * kPointerSize)); __ sw(t2, MemOperand(cache_entry, 2 * kPointerSize)); __ mov(v0, cache_entry); __ Ret(); __ bind(&invalid_cache); // The cache is invalid. Call runtime which will recreate the // cache. __ LoadRoot(t1, Heap::kHeapNumberMapRootIndex); __ AllocateHeapNumber(a0, scratch0, scratch1, t1, &skip_cache); __ sdc1(f4, FieldMemOperand(a0, HeapNumber::kValueOffset)); __ EnterInternalFrame(); __ push(a0); __ CallRuntime(RuntimeFunction(), 1); __ LeaveInternalFrame(); __ ldc1(f4, FieldMemOperand(v0, HeapNumber::kValueOffset)); __ Ret(); __ bind(&skip_cache); // Call C function to calculate the result and answer directly // without updating the cache. GenerateCallCFunction(masm, scratch0); __ GetCFunctionDoubleResult(f4); __ bind(&no_update); // We return the value in f4 without adding it to the cache, but // we cause a scavenging GC so that future allocations will succeed. __ EnterInternalFrame(); // Allocate an aligned object larger than a HeapNumber. ASSERT(4 * kPointerSize >= HeapNumber::kSize); __ li(scratch0, Operand(4 * kPointerSize)); __ push(scratch0); __ CallRuntimeSaveDoubles(Runtime::kAllocateInNewSpace); __ LeaveInternalFrame(); __ Ret(); } } void TranscendentalCacheStub::GenerateCallCFunction(MacroAssembler* masm, Register scratch) { __ push(ra); __ PrepareCallCFunction(2, scratch); __ mfc1(v0, f4); __ mfc1(v1, f5); switch (type_) { case TranscendentalCache::SIN: __ CallCFunction( ExternalReference::math_sin_double_function(masm->isolate()), 2); break; case TranscendentalCache::COS: __ CallCFunction( ExternalReference::math_cos_double_function(masm->isolate()), 2); break; case TranscendentalCache::LOG: __ CallCFunction( ExternalReference::math_log_double_function(masm->isolate()), 2); break; default: UNIMPLEMENTED(); break; } __ pop(ra); } Runtime::FunctionId TranscendentalCacheStub::RuntimeFunction() { switch (type_) { // Add more cases when necessary. case TranscendentalCache::SIN: return Runtime::kMath_sin; case TranscendentalCache::COS: return Runtime::kMath_cos; case TranscendentalCache::LOG: return Runtime::kMath_log; default: UNIMPLEMENTED(); return Runtime::kAbort; } } void StackCheckStub::Generate(MacroAssembler* masm) { __ TailCallRuntime(Runtime::kStackGuard, 0, 1); } void MathPowStub::Generate(MacroAssembler* masm) { Label call_runtime; if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); Label base_not_smi; Label exponent_not_smi; Label convert_exponent; const Register base = a0; const Register exponent = a2; const Register heapnumbermap = t1; const Register heapnumber = s0; // Callee-saved register. const Register scratch = t2; const Register scratch2 = t3; // Alocate FP values in the ABI-parameter-passing regs. const DoubleRegister double_base = f12; const DoubleRegister double_exponent = f14; const DoubleRegister double_result = f0; const DoubleRegister double_scratch = f2; __ LoadRoot(heapnumbermap, Heap::kHeapNumberMapRootIndex); __ lw(base, MemOperand(sp, 1 * kPointerSize)); __ lw(exponent, MemOperand(sp, 0 * kPointerSize)); // Convert base to double value and store it in f0. __ JumpIfNotSmi(base, &base_not_smi); // Base is a Smi. Untag and convert it. __ SmiUntag(base); __ mtc1(base, double_scratch); __ cvt_d_w(double_base, double_scratch); __ Branch(&convert_exponent); __ bind(&base_not_smi); __ lw(scratch, FieldMemOperand(base, JSObject::kMapOffset)); __ Branch(&call_runtime, ne, scratch, Operand(heapnumbermap)); // Base is a heapnumber. Load it into double register. __ ldc1(double_base, FieldMemOperand(base, HeapNumber::kValueOffset)); __ bind(&convert_exponent); __ JumpIfNotSmi(exponent, &exponent_not_smi); __ SmiUntag(exponent); // The base is in a double register and the exponent is // an untagged smi. Allocate a heap number and call a // C function for integer exponents. The register containing // the heap number is callee-saved. __ AllocateHeapNumber(heapnumber, scratch, scratch2, heapnumbermap, &call_runtime); __ push(ra); __ PrepareCallCFunction(3, scratch); // ABI (o32) for func(double d, int x): d in f12, x in a2. ASSERT(double_base.is(f12)); ASSERT(exponent.is(a2)); if (IsMipsSoftFloatABI) { // Simulator case, supports FPU, but with soft-float passing. __ mfc1(a0, double_base); __ mfc1(a1, FPURegister::from_code(double_base.code() + 1)); } __ CallCFunction( ExternalReference::power_double_int_function(masm->isolate()), 3); __ pop(ra); __ GetCFunctionDoubleResult(double_result); __ sdc1(double_result, FieldMemOperand(heapnumber, HeapNumber::kValueOffset)); __ mov(v0, heapnumber); __ DropAndRet(2 * kPointerSize); __ bind(&exponent_not_smi); __ lw(scratch, FieldMemOperand(exponent, JSObject::kMapOffset)); __ Branch(&call_runtime, ne, scratch, Operand(heapnumbermap)); // Exponent is a heapnumber. Load it into double register. __ ldc1(double_exponent, FieldMemOperand(exponent, HeapNumber::kValueOffset)); // The base and the exponent are in double registers. // Allocate a heap number and call a C function for // double exponents. The register containing // the heap number is callee-saved. __ AllocateHeapNumber(heapnumber, scratch, scratch2, heapnumbermap, &call_runtime); __ push(ra); __ PrepareCallCFunction(4, scratch); // ABI (o32) for func(double a, double b): a in f12, b in f14. ASSERT(double_base.is(f12)); ASSERT(double_exponent.is(f14)); if (IsMipsSoftFloatABI) { __ mfc1(a0, double_base); __ mfc1(a1, FPURegister::from_code(double_base.code() + 1)); __ mfc1(a2, double_exponent); __ mfc1(a3, FPURegister::from_code(double_exponent.code() + 1)); } __ CallCFunction( ExternalReference::power_double_double_function(masm->isolate()), 4); __ pop(ra); __ GetCFunctionDoubleResult(double_result); __ sdc1(double_result, FieldMemOperand(heapnumber, HeapNumber::kValueOffset)); __ mov(v0, heapnumber); __ DropAndRet(2 * kPointerSize); } __ bind(&call_runtime); __ TailCallRuntime(Runtime::kMath_pow_cfunction, 2, 1); } bool CEntryStub::NeedsImmovableCode() { return true; } void CEntryStub::GenerateThrowTOS(MacroAssembler* masm) { __ Throw(v0); } void CEntryStub::GenerateThrowUncatchable(MacroAssembler* masm, UncatchableExceptionType type) { __ ThrowUncatchable(type, v0); } void CEntryStub::GenerateCore(MacroAssembler* masm, Label* throw_normal_exception, Label* throw_termination_exception, Label* throw_out_of_memory_exception, bool do_gc, bool always_allocate) { // v0: result parameter for PerformGC, if any // s0: number of arguments including receiver (C callee-saved) // s1: pointer to the first argument (C callee-saved) // s2: pointer to builtin function (C callee-saved) if (do_gc) { // Move result passed in v0 into a0 to call PerformGC. __ mov(a0, v0); __ PrepareCallCFunction(1, a1); __ CallCFunction( ExternalReference::perform_gc_function(masm->isolate()), 1); } ExternalReference scope_depth = ExternalReference::heap_always_allocate_scope_depth(masm->isolate()); if (always_allocate) { __ li(a0, Operand(scope_depth)); __ lw(a1, MemOperand(a0)); __ Addu(a1, a1, Operand(1)); __ sw(a1, MemOperand(a0)); } // Prepare arguments for C routine: a0 = argc, a1 = argv __ mov(a0, s0); __ mov(a1, s1); // We are calling compiled C/C++ code. a0 and a1 hold our two arguments. We // also need to reserve the 4 argument slots on the stack. __ AssertStackIsAligned(); __ li(a2, Operand(ExternalReference::isolate_address())); // From arm version of this function: // TODO(1242173): To let the GC traverse the return address of the exit // frames, we need to know where the return address is. Right now, // we push it on the stack to be able to find it again, but we never // restore from it in case of changes, which makes it impossible to // support moving the C entry code stub. This should be fixed, but currently // this is OK because the CEntryStub gets generated so early in the V8 boot // sequence that it is not moving ever. { Assembler::BlockTrampolinePoolScope block_trampoline_pool(masm); // This branch-and-link sequence is needed to find the current PC on mips, // saved to the ra register. // Use masm-> here instead of the double-underscore macro since extra // coverage code can interfere with the proper calculation of ra. Label find_ra; masm->bal(&find_ra); // bal exposes branch delay slot. masm->nop(); // Branch delay slot nop. masm->bind(&find_ra); // Adjust the value in ra to point to the correct return location, 2nd // instruction past the real call into C code (the jalr(t9)), and push it. // This is the return address of the exit frame. const int kNumInstructionsToJump = 6; masm->Addu(ra, ra, kNumInstructionsToJump * kPointerSize); masm->sw(ra, MemOperand(sp)); // This spot was reserved in EnterExitFrame. masm->Subu(sp, sp, StandardFrameConstants::kCArgsSlotsSize); // Stack is still aligned. // Call the C routine. masm->mov(t9, s2); // Function pointer to t9 to conform to ABI for PIC. masm->jalr(t9); masm->nop(); // Branch delay slot nop. // Make sure the stored 'ra' points to this position. ASSERT_EQ(kNumInstructionsToJump, masm->InstructionsGeneratedSince(&find_ra)); } // Restore stack (remove arg slots). __ Addu(sp, sp, StandardFrameConstants::kCArgsSlotsSize); if (always_allocate) { // It's okay to clobber a2 and a3 here. v0 & v1 contain result. __ li(a2, Operand(scope_depth)); __ lw(a3, MemOperand(a2)); __ Subu(a3, a3, Operand(1)); __ sw(a3, MemOperand(a2)); } // Check for failure result. Label failure_returned; STATIC_ASSERT(((kFailureTag + 1) & kFailureTagMask) == 0); __ addiu(a2, v0, 1); __ andi(t0, a2, kFailureTagMask); __ Branch(&failure_returned, eq, t0, Operand(zero_reg)); // Exit C frame and return. // v0:v1: result // sp: stack pointer // fp: frame pointer __ LeaveExitFrame(save_doubles_, s0); __ Ret(); // Check if we should retry or throw exception. Label retry; __ bind(&failure_returned); STATIC_ASSERT(Failure::RETRY_AFTER_GC == 0); __ andi(t0, v0, ((1 << kFailureTypeTagSize) - 1) << kFailureTagSize); __ Branch(&retry, eq, t0, Operand(zero_reg)); // Special handling of out of memory exceptions. Failure* out_of_memory = Failure::OutOfMemoryException(); __ Branch(throw_out_of_memory_exception, eq, v0, Operand(reinterpret_cast<int32_t>(out_of_memory))); // Retrieve the pending exception and clear the variable. __ li(t0, Operand(ExternalReference::the_hole_value_location(masm->isolate()))); __ lw(a3, MemOperand(t0)); __ li(t0, Operand(ExternalReference(Isolate::k_pending_exception_address, masm->isolate()))); __ lw(v0, MemOperand(t0)); __ sw(a3, MemOperand(t0)); // Special handling of termination exceptions which are uncatchable // by javascript code. __ Branch(throw_termination_exception, eq, v0, Operand(masm->isolate()->factory()->termination_exception())); // Handle normal exception. __ jmp(throw_normal_exception); __ bind(&retry); // Last failure (v0) will be moved to (a0) for parameter when retrying. } void CEntryStub::Generate(MacroAssembler* masm) { // Called from JavaScript; parameters are on stack as if calling JS function // a0: number of arguments including receiver // a1: pointer to builtin function // fp: frame pointer (restored after C call) // sp: stack pointer (restored as callee's sp after C call) // cp: current context (C callee-saved) // NOTE: Invocations of builtins may return failure objects // instead of a proper result. The builtin entry handles // this by performing a garbage collection and retrying the // builtin once. // Compute the argv pointer in a callee-saved register. __ sll(s1, a0, kPointerSizeLog2); __ Addu(s1, sp, s1); __ Subu(s1, s1, Operand(kPointerSize)); // Enter the exit frame that transitions from JavaScript to C++. __ EnterExitFrame(save_doubles_); // Setup argc and the builtin function in callee-saved registers. __ mov(s0, a0); __ mov(s2, a1); // s0: number of arguments (C callee-saved) // s1: pointer to first argument (C callee-saved) // s2: pointer to builtin function (C callee-saved) Label throw_normal_exception; Label throw_termination_exception; Label throw_out_of_memory_exception; // Call into the runtime system. GenerateCore(masm, &throw_normal_exception, &throw_termination_exception, &throw_out_of_memory_exception, false, false); // Do space-specific GC and retry runtime call. GenerateCore(masm, &throw_normal_exception, &throw_termination_exception, &throw_out_of_memory_exception, true, false); // Do full GC and retry runtime call one final time. Failure* failure = Failure::InternalError(); __ li(v0, Operand(reinterpret_cast<int32_t>(failure))); GenerateCore(masm, &throw_normal_exception, &throw_termination_exception, &throw_out_of_memory_exception, true, true); __ bind(&throw_out_of_memory_exception); GenerateThrowUncatchable(masm, OUT_OF_MEMORY); __ bind(&throw_termination_exception); GenerateThrowUncatchable(masm, TERMINATION); __ bind(&throw_normal_exception); GenerateThrowTOS(masm); } void JSEntryStub::GenerateBody(MacroAssembler* masm, bool is_construct) { Label invoke, exit; // Registers: // a0: entry address // a1: function // a2: reveiver // a3: argc // // Stack: // 4 args slots // args // Save callee saved registers on the stack. __ MultiPush((kCalleeSaved | ra.bit()) & ~sp.bit()); // Load argv in s0 register. __ lw(s0, MemOperand(sp, kNumCalleeSaved * kPointerSize + StandardFrameConstants::kCArgsSlotsSize)); // We build an EntryFrame. __ li(t3, Operand(-1)); // Push a bad frame pointer to fail if it is used. int marker = is_construct ? StackFrame::ENTRY_CONSTRUCT : StackFrame::ENTRY; __ li(t2, Operand(Smi::FromInt(marker))); __ li(t1, Operand(Smi::FromInt(marker))); __ li(t0, Operand(ExternalReference(Isolate::k_c_entry_fp_address, masm->isolate()))); __ lw(t0, MemOperand(t0)); __ Push(t3, t2, t1, t0); // Setup frame pointer for the frame to be pushed. __ addiu(fp, sp, -EntryFrameConstants::kCallerFPOffset); // Registers: // a0: entry_address // a1: function // a2: reveiver_pointer // a3: argc // s0: argv // // Stack: // caller fp | // function slot | entry frame // context slot | // bad fp (0xff...f) | // callee saved registers + ra // 4 args slots // args #ifdef ENABLE_LOGGING_AND_PROFILING // If this is the outermost JS call, set js_entry_sp value. ExternalReference js_entry_sp(Isolate::k_js_entry_sp_address, masm->isolate()); __ li(t1, Operand(ExternalReference(js_entry_sp))); __ lw(t2, MemOperand(t1)); { Label skip; __ Branch(&skip, ne, t2, Operand(zero_reg)); __ sw(fp, MemOperand(t1)); __ bind(&skip); } #endif // Call a faked try-block that does the invoke. __ bal(&invoke); // bal exposes branch delay slot. __ nop(); // Branch delay slot nop. // Caught exception: Store result (exception) in the pending // exception field in the JSEnv and return a failure sentinel. // Coming in here the fp will be invalid because the PushTryHandler below // sets it to 0 to signal the existence of the JSEntry frame. __ li(t0, Operand(ExternalReference(Isolate::k_pending_exception_address, masm->isolate()))); __ sw(v0, MemOperand(t0)); // We come back from 'invoke'. result is in v0. __ li(v0, Operand(reinterpret_cast<int32_t>(Failure::Exception()))); __ b(&exit); // b exposes branch delay slot. __ nop(); // Branch delay slot nop. // Invoke: Link this frame into the handler chain. __ bind(&invoke); __ PushTryHandler(IN_JS_ENTRY, JS_ENTRY_HANDLER); // If an exception not caught by another handler occurs, this handler // returns control to the code after the bal(&invoke) above, which // restores all kCalleeSaved registers (including cp and fp) to their // saved values before returning a failure to C. // Clear any pending exceptions. __ li(t0, Operand(ExternalReference::the_hole_value_location(masm->isolate()))); __ lw(t1, MemOperand(t0)); __ li(t0, Operand(ExternalReference(Isolate::k_pending_exception_address, masm->isolate()))); __ sw(t1, MemOperand(t0)); // Invoke the function by calling through JS entry trampoline builtin. // Notice that we cannot store a reference to the trampoline code directly in // this stub, because runtime stubs are not traversed when doing GC. // Registers: // a0: entry_address // a1: function // a2: reveiver_pointer // a3: argc // s0: argv // // Stack: // handler frame // entry frame // callee saved registers + ra // 4 args slots // args if (is_construct) { ExternalReference construct_entry(Builtins::kJSConstructEntryTrampoline, masm->isolate()); __ li(t0, Operand(construct_entry)); } else { ExternalReference entry(Builtins::kJSEntryTrampoline, masm->isolate()); __ li(t0, Operand(entry)); } __ lw(t9, MemOperand(t0)); // Deref address. // Call JSEntryTrampoline. __ addiu(t9, t9, Code::kHeaderSize - kHeapObjectTag); __ Call(t9); // Unlink this frame from the handler chain. When reading the // address of the next handler, there is no need to use the address // displacement since the current stack pointer (sp) points directly // to the stack handler. __ lw(t1, MemOperand(sp, StackHandlerConstants::kNextOffset)); __ li(t0, Operand(ExternalReference(Isolate::k_handler_address, masm->isolate()))); __ sw(t1, MemOperand(t0)); // This restores sp to its position before PushTryHandler. __ addiu(sp, sp, StackHandlerConstants::kSize); #ifdef ENABLE_LOGGING_AND_PROFILING // If current FP value is the same as js_entry_sp value, it means that // the current function is the outermost. __ li(t1, Operand(ExternalReference(js_entry_sp))); __ lw(t2, MemOperand(t1)); { Label skip; __ Branch(&skip, ne, fp, Operand(t2)); __ sw(zero_reg, MemOperand(t1)); __ bind(&skip); } #endif __ bind(&exit); // v0 holds result. // Restore the top frame descriptors from the stack. __ pop(t1); __ li(t0, Operand(ExternalReference(Isolate::k_c_entry_fp_address, masm->isolate()))); __ sw(t1, MemOperand(t0)); // Reset the stack to the callee saved registers. __ addiu(sp, sp, -EntryFrameConstants::kCallerFPOffset); // Restore callee saved registers from the stack. __ MultiPop((kCalleeSaved | ra.bit()) & ~sp.bit()); // Return. __ Jump(ra); } // Uses registers a0 to t0. Expected input is // object in a0 (or at sp+1*kPointerSize) and function in // a1 (or at sp), depending on whether or not // args_in_registers() is true. void InstanceofStub::Generate(MacroAssembler* masm) { // Fixed register usage throughout the stub: const Register object = a0; // Object (lhs). const Register map = a3; // Map of the object. const Register function = a1; // Function (rhs). const Register prototype = t0; // Prototype of the function. const Register scratch = a2; Label slow, loop, is_instance, is_not_instance, not_js_object; if (!HasArgsInRegisters()) { __ lw(object, MemOperand(sp, 1 * kPointerSize)); __ lw(function, MemOperand(sp, 0)); } // Check that the left hand is a JS object and load map. __ JumpIfSmi(object, &not_js_object); __ IsObjectJSObjectType(object, map, scratch, &not_js_object); // Look up the function and the map in the instanceof cache. Label miss; __ LoadRoot(t1, Heap::kInstanceofCacheFunctionRootIndex); __ Branch(&miss, ne, function, Operand(t1)); __ LoadRoot(t1, Heap::kInstanceofCacheMapRootIndex); __ Branch(&miss, ne, map, Operand(t1)); __ LoadRoot(v0, Heap::kInstanceofCacheAnswerRootIndex); __ DropAndRet(HasArgsInRegisters() ? 0 : 2); __ bind(&miss); __ TryGetFunctionPrototype(function, prototype, scratch, &slow); // Check that the function prototype is a JS object. __ JumpIfSmi(prototype, &slow); __ IsObjectJSObjectType(prototype, scratch, scratch, &slow); __ StoreRoot(function, Heap::kInstanceofCacheFunctionRootIndex); __ StoreRoot(map, Heap::kInstanceofCacheMapRootIndex); // Register mapping: a3 is object map and t0 is function prototype. // Get prototype of object into a2. __ lw(scratch, FieldMemOperand(map, Map::kPrototypeOffset)); // Loop through the prototype chain looking for the function prototype. __ bind(&loop); __ Branch(&is_instance, eq, scratch, Operand(prototype)); __ LoadRoot(t1, Heap::kNullValueRootIndex); __ Branch(&is_not_instance, eq, scratch, Operand(t1)); __ lw(scratch, FieldMemOperand(scratch, HeapObject::kMapOffset)); __ lw(scratch, FieldMemOperand(scratch, Map::kPrototypeOffset)); __ Branch(&loop); __ bind(&is_instance); ASSERT(Smi::FromInt(0) == 0); __ mov(v0, zero_reg); __ StoreRoot(v0, Heap::kInstanceofCacheAnswerRootIndex); __ DropAndRet(HasArgsInRegisters() ? 0 : 2); __ bind(&is_not_instance); __ li(v0, Operand(Smi::FromInt(1))); __ StoreRoot(v0, Heap::kInstanceofCacheAnswerRootIndex); __ DropAndRet(HasArgsInRegisters() ? 0 : 2); Label object_not_null, object_not_null_or_smi; __ bind(&not_js_object); // Before null, smi and string value checks, check that the rhs is a function // as for a non-function rhs an exception needs to be thrown. __ JumpIfSmi(function, &slow); __ GetObjectType(function, map, scratch); __ Branch(&slow, ne, scratch, Operand(JS_FUNCTION_TYPE)); // Null is not instance of anything. __ Branch(&object_not_null, ne, scratch, Operand(masm->isolate()->factory()->null_value())); __ li(v0, Operand(Smi::FromInt(1))); __ DropAndRet(HasArgsInRegisters() ? 0 : 2); __ bind(&object_not_null); // Smi values are not instances of anything. __ JumpIfNotSmi(object, &object_not_null_or_smi); __ li(v0, Operand(Smi::FromInt(1))); __ DropAndRet(HasArgsInRegisters() ? 0 : 2); __ bind(&object_not_null_or_smi); // String values are not instances of anything. __ IsObjectJSStringType(object, scratch, &slow); __ li(v0, Operand(Smi::FromInt(1))); __ DropAndRet(HasArgsInRegisters() ? 0 : 2); // Slow-case. Tail call builtin. __ bind(&slow); if (HasArgsInRegisters()) { __ Push(a0, a1); } __ InvokeBuiltin(Builtins::INSTANCE_OF, JUMP_FUNCTION); } void ArgumentsAccessStub::GenerateReadElement(MacroAssembler* masm) { // The displacement is the offset of the last parameter (if any) // relative to the frame pointer. static const int kDisplacement = StandardFrameConstants::kCallerSPOffset - kPointerSize; // Check that the key is a smiGenerateReadElement. Label slow; __ JumpIfNotSmi(a1, &slow); // Check if the calling frame is an arguments adaptor frame. Label adaptor; __ lw(a2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset)); __ lw(a3, MemOperand(a2, StandardFrameConstants::kContextOffset)); __ Branch(&adaptor, eq, a3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR))); // Check index (a1) against formal parameters count limit passed in // through register a0. Use unsigned comparison to get negative // check for free. __ Branch(&slow, hs, a1, Operand(a0)); // Read the argument from the stack and return it. __ subu(a3, a0, a1); __ sll(t3, a3, kPointerSizeLog2 - kSmiTagSize); __ Addu(a3, fp, Operand(t3)); __ lw(v0, MemOperand(a3, kDisplacement)); __ Ret(); // Arguments adaptor case: Check index (a1) against actual arguments // limit found in the arguments adaptor frame. Use unsigned // comparison to get negative check for free. __ bind(&adaptor); __ lw(a0, MemOperand(a2, ArgumentsAdaptorFrameConstants::kLengthOffset)); __ Branch(&slow, Ugreater_equal, a1, Operand(a0)); // Read the argument from the adaptor frame and return it. __ subu(a3, a0, a1); __ sll(t3, a3, kPointerSizeLog2 - kSmiTagSize); __ Addu(a3, a2, Operand(t3)); __ lw(v0, MemOperand(a3, kDisplacement)); __ Ret(); // Slow-case: Handle non-smi or out-of-bounds access to arguments // by calling the runtime system. __ bind(&slow); __ push(a1); __ TailCallRuntime(Runtime::kGetArgumentsProperty, 1, 1); } void ArgumentsAccessStub::GenerateNewObject(MacroAssembler* masm) { // sp[0] : number of parameters // sp[4] : receiver displacement // sp[8] : function // Check if the calling frame is an arguments adaptor frame. Label adaptor_frame, try_allocate, runtime; __ lw(a2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset)); __ lw(a3, MemOperand(a2, StandardFrameConstants::kContextOffset)); __ Branch(&adaptor_frame, eq, a3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR))); // Get the length from the frame. __ lw(a1, MemOperand(sp, 0)); __ Branch(&try_allocate); // Patch the arguments.length and the parameters pointer. __ bind(&adaptor_frame); __ lw(a1, MemOperand(a2, ArgumentsAdaptorFrameConstants::kLengthOffset)); __ sw(a1, MemOperand(sp, 0)); __ sll(at, a1, kPointerSizeLog2 - kSmiTagSize); __ Addu(a3, a2, Operand(at)); __ Addu(a3, a3, Operand(StandardFrameConstants::kCallerSPOffset)); __ sw(a3, MemOperand(sp, 1 * kPointerSize)); // Try the new space allocation. Start out with computing the size // of the arguments object and the elements array in words. Label add_arguments_object; __ bind(&try_allocate); __ Branch(&add_arguments_object, eq, a1, Operand(zero_reg)); __ srl(a1, a1, kSmiTagSize); __ Addu(a1, a1, Operand(FixedArray::kHeaderSize / kPointerSize)); __ bind(&add_arguments_object); __ Addu(a1, a1, Operand(GetArgumentsObjectSize() / kPointerSize)); // Do the allocation of both objects in one go. __ AllocateInNewSpace( a1, v0, a2, a3, &runtime, static_cast<AllocationFlags>(TAG_OBJECT | SIZE_IN_WORDS)); // Get the arguments boilerplate from the current (global) context. __ lw(t0, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_INDEX))); __ lw(t0, FieldMemOperand(t0, GlobalObject::kGlobalContextOffset)); __ lw(t0, MemOperand(t0, Context::SlotOffset(GetArgumentsBoilerplateIndex()))); // Copy the JS object part. __ CopyFields(v0, t0, a3.bit(), JSObject::kHeaderSize / kPointerSize); if (type_ == NEW_NON_STRICT) { // Setup the callee in-object property. STATIC_ASSERT(Heap::kArgumentsCalleeIndex == 1); __ lw(a3, MemOperand(sp, 2 * kPointerSize)); const int kCalleeOffset = JSObject::kHeaderSize + Heap::kArgumentsCalleeIndex * kPointerSize; __ sw(a3, FieldMemOperand(v0, kCalleeOffset)); } // Get the length (smi tagged) and set that as an in-object property too. STATIC_ASSERT(Heap::kArgumentsLengthIndex == 0); __ lw(a1, MemOperand(sp, 0 * kPointerSize)); __ sw(a1, FieldMemOperand(v0, JSObject::kHeaderSize + Heap::kArgumentsLengthIndex * kPointerSize)); Label done; __ Branch(&done, eq, a1, Operand(zero_reg)); // Get the parameters pointer from the stack. __ lw(a2, MemOperand(sp, 1 * kPointerSize)); // Setup the elements pointer in the allocated arguments object and // initialize the header in the elements fixed array. __ Addu(t0, v0, Operand(GetArgumentsObjectSize())); __ sw(t0, FieldMemOperand(v0, JSObject::kElementsOffset)); __ LoadRoot(a3, Heap::kFixedArrayMapRootIndex); __ sw(a3, FieldMemOperand(t0, FixedArray::kMapOffset)); __ sw(a1, FieldMemOperand(t0, FixedArray::kLengthOffset)); __ srl(a1, a1, kSmiTagSize); // Untag the length for the loop. // Copy the fixed array slots. Label loop; // Setup t0 to point to the first array slot. __ Addu(t0, t0, Operand(FixedArray::kHeaderSize - kHeapObjectTag)); __ bind(&loop); // Pre-decrement a2 with kPointerSize on each iteration. // Pre-decrement in order to skip receiver. __ Addu(a2, a2, Operand(-kPointerSize)); __ lw(a3, MemOperand(a2)); // Post-increment t0 with kPointerSize on each iteration. __ sw(a3, MemOperand(t0)); __ Addu(t0, t0, Operand(kPointerSize)); __ Subu(a1, a1, Operand(1)); __ Branch(&loop, ne, a1, Operand(zero_reg)); // Return and remove the on-stack parameters. __ bind(&done); __ Addu(sp, sp, Operand(3 * kPointerSize)); __ Ret(); // Do the runtime call to allocate the arguments object. __ bind(&runtime); __ TailCallRuntime(Runtime::kNewArgumentsFast, 3, 1); } void RegExpExecStub::Generate(MacroAssembler* masm) { // Just jump directly to runtime if native RegExp is not selected at compile // time or if regexp entry in generated code is turned off runtime switch or // at compilation. #ifdef V8_INTERPRETED_REGEXP __ TailCallRuntime(Runtime::kRegExpExec, 4, 1); #else // V8_INTERPRETED_REGEXP if (!FLAG_regexp_entry_native) { __ TailCallRuntime(Runtime::kRegExpExec, 4, 1); return; } // Stack frame on entry. // sp[0]: last_match_info (expected JSArray) // sp[4]: previous index // sp[8]: subject string // sp[12]: JSRegExp object static const int kLastMatchInfoOffset = 0 * kPointerSize; static const int kPreviousIndexOffset = 1 * kPointerSize; static const int kSubjectOffset = 2 * kPointerSize; static const int kJSRegExpOffset = 3 * kPointerSize; Label runtime, invoke_regexp; // Allocation of registers for this function. These are in callee save // registers and will be preserved by the call to the native RegExp code, as // this code is called using the normal C calling convention. When calling // directly from generated code the native RegExp code will not do a GC and // therefore the content of these registers are safe to use after the call. // MIPS - using s0..s2, since we are not using CEntry Stub. Register subject = s0; Register regexp_data = s1; Register last_match_info_elements = s2; // Ensure that a RegExp stack is allocated. ExternalReference address_of_regexp_stack_memory_address = ExternalReference::address_of_regexp_stack_memory_address( masm->isolate()); ExternalReference address_of_regexp_stack_memory_size = ExternalReference::address_of_regexp_stack_memory_size(masm->isolate()); __ li(a0, Operand(address_of_regexp_stack_memory_size)); __ lw(a0, MemOperand(a0, 0)); __ Branch(&runtime, eq, a0, Operand(zero_reg)); // Check that the first argument is a JSRegExp object. __ lw(a0, MemOperand(sp, kJSRegExpOffset)); STATIC_ASSERT(kSmiTag == 0); __ JumpIfSmi(a0, &runtime); __ GetObjectType(a0, a1, a1); __ Branch(&runtime, ne, a1, Operand(JS_REGEXP_TYPE)); // Check that the RegExp has been compiled (data contains a fixed array). __ lw(regexp_data, FieldMemOperand(a0, JSRegExp::kDataOffset)); if (FLAG_debug_code) { __ And(t0, regexp_data, Operand(kSmiTagMask)); __ Check(nz, "Unexpected type for RegExp data, FixedArray expected", t0, Operand(zero_reg)); __ GetObjectType(regexp_data, a0, a0); __ Check(eq, "Unexpected type for RegExp data, FixedArray expected", a0, Operand(FIXED_ARRAY_TYPE)); } // regexp_data: RegExp data (FixedArray) // Check the type of the RegExp. Only continue if type is JSRegExp::IRREGEXP. __ lw(a0, FieldMemOperand(regexp_data, JSRegExp::kDataTagOffset)); __ Branch(&runtime, ne, a0, Operand(Smi::FromInt(JSRegExp::IRREGEXP))); // regexp_data: RegExp data (FixedArray) // Check that the number of captures fit in the static offsets vector buffer. __ lw(a2, FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset)); // Calculate number of capture registers (number_of_captures + 1) * 2. This // uses the asumption that smis are 2 * their untagged value. STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1); __ Addu(a2, a2, Operand(2)); // a2 was a smi. // Check that the static offsets vector buffer is large enough. __ Branch(&runtime, hi, a2, Operand(OffsetsVector::kStaticOffsetsVectorSize)); // a2: Number of capture registers // regexp_data: RegExp data (FixedArray) // Check that the second argument is a string. __ lw(subject, MemOperand(sp, kSubjectOffset)); __ JumpIfSmi(subject, &runtime); __ GetObjectType(subject, a0, a0); __ And(a0, a0, Operand(kIsNotStringMask)); STATIC_ASSERT(kStringTag == 0); __ Branch(&runtime, ne, a0, Operand(zero_reg)); // Get the length of the string to r3. __ lw(a3, FieldMemOperand(subject, String::kLengthOffset)); // a2: Number of capture registers // a3: Length of subject string as a smi // subject: Subject string // regexp_data: RegExp data (FixedArray) // Check that the third argument is a positive smi less than the subject // string length. A negative value will be greater (unsigned comparison). __ lw(a0, MemOperand(sp, kPreviousIndexOffset)); __ And(at, a0, Operand(kSmiTagMask)); __ Branch(&runtime, ne, at, Operand(zero_reg)); __ Branch(&runtime, ls, a3, Operand(a0)); // a2: Number of capture registers // subject: Subject string // regexp_data: RegExp data (FixedArray) // Check that the fourth object is a JSArray object. __ lw(a0, MemOperand(sp, kLastMatchInfoOffset)); __ JumpIfSmi(a0, &runtime); __ GetObjectType(a0, a1, a1); __ Branch(&runtime, ne, a1, Operand(JS_ARRAY_TYPE)); // Check that the JSArray is in fast case. __ lw(last_match_info_elements, FieldMemOperand(a0, JSArray::kElementsOffset)); __ lw(a0, FieldMemOperand(last_match_info_elements, HeapObject::kMapOffset)); __ Branch(&runtime, ne, a0, Operand( masm->isolate()->factory()->fixed_array_map())); // Check that the last match info has space for the capture registers and the // additional information. __ lw(a0, FieldMemOperand(last_match_info_elements, FixedArray::kLengthOffset)); __ Addu(a2, a2, Operand(RegExpImpl::kLastMatchOverhead)); __ sra(at, a0, kSmiTagSize); // Untag length for comparison. __ Branch(&runtime, gt, a2, Operand(at)); // subject: Subject string // regexp_data: RegExp data (FixedArray) // Check the representation and encoding of the subject string. Label seq_string; __ lw(a0, FieldMemOperand(subject, HeapObject::kMapOffset)); __ lbu(a0, FieldMemOperand(a0, Map::kInstanceTypeOffset)); // First check for flat string. __ And(at, a0, Operand(kIsNotStringMask | kStringRepresentationMask)); STATIC_ASSERT((kStringTag | kSeqStringTag) == 0); __ Branch(&seq_string, eq, at, Operand(zero_reg)); // subject: Subject string // a0: instance type if Subject string // regexp_data: RegExp data (FixedArray) // Check for flat cons string. // A flat cons string is a cons string where the second part is the empty // string. In that case the subject string is just the first part of the cons // string. Also in this case the first part of the cons string is known to be // a sequential string or an external string. STATIC_ASSERT(kExternalStringTag != 0); STATIC_ASSERT((kConsStringTag & kExternalStringTag) == 0); __ And(at, a0, Operand(kIsNotStringMask | kExternalStringTag)); __ Branch(&runtime, ne, at, Operand(zero_reg)); __ lw(a0, FieldMemOperand(subject, ConsString::kSecondOffset)); __ LoadRoot(a1, Heap::kEmptyStringRootIndex); __ Branch(&runtime, ne, a0, Operand(a1)); __ lw(subject, FieldMemOperand(subject, ConsString::kFirstOffset)); __ lw(a0, FieldMemOperand(subject, HeapObject::kMapOffset)); __ lbu(a0, FieldMemOperand(a0, Map::kInstanceTypeOffset)); // Is first part a flat string? STATIC_ASSERT(kSeqStringTag == 0); __ And(at, a0, Operand(kStringRepresentationMask)); __ Branch(&runtime, ne, at, Operand(zero_reg)); __ bind(&seq_string); // subject: Subject string // regexp_data: RegExp data (FixedArray) // a0: Instance type of subject string STATIC_ASSERT(kStringEncodingMask == 4); STATIC_ASSERT(kAsciiStringTag == 4); STATIC_ASSERT(kTwoByteStringTag == 0); // Find the code object based on the assumptions above. __ And(a0, a0, Operand(kStringEncodingMask)); // Non-zero for ascii. __ lw(t9, FieldMemOperand(regexp_data, JSRegExp::kDataAsciiCodeOffset)); __ sra(a3, a0, 2); // a3 is 1 for ascii, 0 for UC16 (usyed below). __ lw(t0, FieldMemOperand(regexp_data, JSRegExp::kDataUC16CodeOffset)); __ movz(t9, t0, a0); // If UC16 (a0 is 0), replace t9 w/kDataUC16CodeOffset. // Check that the irregexp code has been generated for the actual string // encoding. If it has, the field contains a code object otherwise it // contains the hole. __ GetObjectType(t9, a0, a0); __ Branch(&runtime, ne, a0, Operand(CODE_TYPE)); // a3: encoding of subject string (1 if ASCII, 0 if two_byte); // t9: code // subject: Subject string // regexp_data: RegExp data (FixedArray) // Load used arguments before starting to push arguments for call to native // RegExp code to avoid handling changing stack height. __ lw(a1, MemOperand(sp, kPreviousIndexOffset)); __ sra(a1, a1, kSmiTagSize); // Untag the Smi. // a1: previous index // a3: encoding of subject string (1 if ASCII, 0 if two_byte); // t9: code // subject: Subject string // regexp_data: RegExp data (FixedArray) // All checks done. Now push arguments for native regexp code. __ IncrementCounter(masm->isolate()->counters()->regexp_entry_native(), 1, a0, a2); // Isolates: note we add an additional parameter here (isolate pointer). static const int kRegExpExecuteArguments = 8; static const int kParameterRegisters = 4; __ EnterExitFrame(false, kRegExpExecuteArguments - kParameterRegisters); // Stack pointer now points to cell where return address is to be written. // Arguments are before that on the stack or in registers, meaning we // treat the return address as argument 5. Thus every argument after that // needs to be shifted back by 1. Since DirectCEntryStub will handle // allocating space for the c argument slots, we don't need to calculate // that into the argument positions on the stack. This is how the stack will // look (sp meaning the value of sp at this moment): // [sp + 4] - Argument 8 // [sp + 3] - Argument 7 // [sp + 2] - Argument 6 // [sp + 1] - Argument 5 // [sp + 0] - saved ra // Argument 8: Pass current isolate address. // CFunctionArgumentOperand handles MIPS stack argument slots. __ li(a0, Operand(ExternalReference::isolate_address())); __ sw(a0, MemOperand(sp, 4 * kPointerSize)); // Argument 7: Indicate that this is a direct call from JavaScript. __ li(a0, Operand(1)); __ sw(a0, MemOperand(sp, 3 * kPointerSize)); // Argument 6: Start (high end) of backtracking stack memory area. __ li(a0, Operand(address_of_regexp_stack_memory_address)); __ lw(a0, MemOperand(a0, 0)); __ li(a2, Operand(address_of_regexp_stack_memory_size)); __ lw(a2, MemOperand(a2, 0)); __ addu(a0, a0, a2); __ sw(a0, MemOperand(sp, 2 * kPointerSize)); // Argument 5: static offsets vector buffer. __ li(a0, Operand( ExternalReference::address_of_static_offsets_vector(masm->isolate()))); __ sw(a0, MemOperand(sp, 1 * kPointerSize)); // For arguments 4 and 3 get string length, calculate start of string data // and calculate the shift of the index (0 for ASCII and 1 for two byte). __ lw(a0, FieldMemOperand(subject, String::kLengthOffset)); __ sra(a0, a0, kSmiTagSize); STATIC_ASSERT(SeqAsciiString::kHeaderSize == SeqTwoByteString::kHeaderSize); __ Addu(t0, subject, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag)); __ Xor(a3, a3, Operand(1)); // 1 for 2-byte str, 0 for 1-byte. // Argument 4 (a3): End of string data // Argument 3 (a2): Start of string data __ sllv(t1, a1, a3); __ addu(a2, t0, t1); __ sllv(t1, a0, a3); __ addu(a3, t0, t1); // Argument 2 (a1): Previous index. // Already there // Argument 1 (a0): Subject string. __ mov(a0, subject); // Locate the code entry and call it. __ Addu(t9, t9, Operand(Code::kHeaderSize - kHeapObjectTag)); DirectCEntryStub stub; stub.GenerateCall(masm, t9); __ LeaveExitFrame(false, no_reg); // v0: result // subject: subject string (callee saved) // regexp_data: RegExp data (callee saved) // last_match_info_elements: Last match info elements (callee saved) // Check the result. Label success; __ Branch(&success, eq, v0, Operand(NativeRegExpMacroAssembler::SUCCESS)); Label failure; __ Branch(&failure, eq, v0, Operand(NativeRegExpMacroAssembler::FAILURE)); // If not exception it can only be retry. Handle that in the runtime system. __ Branch(&runtime, ne, v0, Operand(NativeRegExpMacroAssembler::EXCEPTION)); // Result must now be exception. If there is no pending exception already a // stack overflow (on the backtrack stack) was detected in RegExp code but // haven't created the exception yet. Handle that in the runtime system. // TODO(592): Rerunning the RegExp to get the stack overflow exception. __ li(a1, Operand( ExternalReference::the_hole_value_location(masm->isolate()))); __ lw(a1, MemOperand(a1, 0)); __ li(a2, Operand(ExternalReference(Isolate::k_pending_exception_address, masm->isolate()))); __ lw(v0, MemOperand(a2, 0)); __ Branch(&runtime, eq, v0, Operand(a1)); __ sw(a1, MemOperand(a2, 0)); // Clear pending exception. // Check if the exception is a termination. If so, throw as uncatchable. __ LoadRoot(a0, Heap::kTerminationExceptionRootIndex); Label termination_exception; __ Branch(&termination_exception, eq, v0, Operand(a0)); __ Throw(a0); // Expects thrown value in v0. __ bind(&termination_exception); __ ThrowUncatchable(TERMINATION, v0); // Expects thrown value in v0. __ bind(&failure); // For failure and exception return null. __ li(v0, Operand(masm->isolate()->factory()->null_value())); __ Addu(sp, sp, Operand(4 * kPointerSize)); __ Ret(); // Process the result from the native regexp code. __ bind(&success); __ lw(a1, FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset)); // Calculate number of capture registers (number_of_captures + 1) * 2. STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1); __ Addu(a1, a1, Operand(2)); // a1 was a smi. // a1: number of capture registers // subject: subject string // Store the capture count. __ sll(a2, a1, kSmiTagSize + kSmiShiftSize); // To smi. __ sw(a2, FieldMemOperand(last_match_info_elements, RegExpImpl::kLastCaptureCountOffset)); // Store last subject and last input. __ mov(a3, last_match_info_elements); // Moved up to reduce latency. __ sw(subject, FieldMemOperand(last_match_info_elements, RegExpImpl::kLastSubjectOffset)); __ RecordWrite(a3, Operand(RegExpImpl::kLastSubjectOffset), a2, t0); __ sw(subject, FieldMemOperand(last_match_info_elements, RegExpImpl::kLastInputOffset)); __ mov(a3, last_match_info_elements); __ RecordWrite(a3, Operand(RegExpImpl::kLastInputOffset), a2, t0); // Get the static offsets vector filled by the native regexp code. ExternalReference address_of_static_offsets_vector = ExternalReference::address_of_static_offsets_vector(masm->isolate()); __ li(a2, Operand(address_of_static_offsets_vector)); // a1: number of capture registers // a2: offsets vector Label next_capture, done; // Capture register counter starts from number of capture registers and // counts down until wrapping after zero. __ Addu(a0, last_match_info_elements, Operand(RegExpImpl::kFirstCaptureOffset - kHeapObjectTag)); __ bind(&next_capture); __ Subu(a1, a1, Operand(1)); __ Branch(&done, lt, a1, Operand(zero_reg)); // Read the value from the static offsets vector buffer. __ lw(a3, MemOperand(a2, 0)); __ addiu(a2, a2, kPointerSize); // Store the smi value in the last match info. __ sll(a3, a3, kSmiTagSize); // Convert to Smi. __ sw(a3, MemOperand(a0, 0)); __ Branch(&next_capture, USE_DELAY_SLOT); __ addiu(a0, a0, kPointerSize); // In branch delay slot. __ bind(&done); // Return last match info. __ lw(v0, MemOperand(sp, kLastMatchInfoOffset)); __ Addu(sp, sp, Operand(4 * kPointerSize)); __ Ret(); // Do the runtime call to execute the regexp. __ bind(&runtime); __ TailCallRuntime(Runtime::kRegExpExec, 4, 1); #endif // V8_INTERPRETED_REGEXP } void RegExpConstructResultStub::Generate(MacroAssembler* masm) { const int kMaxInlineLength = 100; Label slowcase; Label done; __ lw(a1, MemOperand(sp, kPointerSize * 2)); STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiTagSize == 1); __ JumpIfNotSmi(a1, &slowcase); __ Branch(&slowcase, hi, a1, Operand(Smi::FromInt(kMaxInlineLength))); // Smi-tagging is equivalent to multiplying by 2. // Allocate RegExpResult followed by FixedArray with size in ebx. // JSArray: [Map][empty properties][Elements][Length-smi][index][input] // Elements: [Map][Length][..elements..] // Size of JSArray with two in-object properties and the header of a // FixedArray. int objects_size = (JSRegExpResult::kSize + FixedArray::kHeaderSize) / kPointerSize; __ srl(t1, a1, kSmiTagSize + kSmiShiftSize); __ Addu(a2, t1, Operand(objects_size)); __ AllocateInNewSpace( a2, // In: Size, in words. v0, // Out: Start of allocation (tagged). a3, // Scratch register. t0, // Scratch register. &slowcase, static_cast<AllocationFlags>(TAG_OBJECT | SIZE_IN_WORDS)); // v0: Start of allocated area, object-tagged. // a1: Number of elements in array, as smi. // t1: Number of elements, untagged. // Set JSArray map to global.regexp_result_map(). // Set empty properties FixedArray. // Set elements to point to FixedArray allocated right after the JSArray. // Interleave operations for better latency. __ lw(a2, ContextOperand(cp, Context::GLOBAL_INDEX)); __ Addu(a3, v0, Operand(JSRegExpResult::kSize)); __ li(t0, Operand(masm->isolate()->factory()->empty_fixed_array())); __ lw(a2, FieldMemOperand(a2, GlobalObject::kGlobalContextOffset)); __ sw(a3, FieldMemOperand(v0, JSObject::kElementsOffset)); __ lw(a2, ContextOperand(a2, Context::REGEXP_RESULT_MAP_INDEX)); __ sw(t0, FieldMemOperand(v0, JSObject::kPropertiesOffset)); __ sw(a2, FieldMemOperand(v0, HeapObject::kMapOffset)); // Set input, index and length fields from arguments. __ lw(a1, MemOperand(sp, kPointerSize * 0)); __ sw(a1, FieldMemOperand(v0, JSRegExpResult::kInputOffset)); __ lw(a1, MemOperand(sp, kPointerSize * 1)); __ sw(a1, FieldMemOperand(v0, JSRegExpResult::kIndexOffset)); __ lw(a1, MemOperand(sp, kPointerSize * 2)); __ sw(a1, FieldMemOperand(v0, JSArray::kLengthOffset)); // Fill out the elements FixedArray. // v0: JSArray, tagged. // a3: FixedArray, tagged. // t1: Number of elements in array, untagged. // Set map. __ li(a2, Operand(masm->isolate()->factory()->fixed_array_map())); __ sw(a2, FieldMemOperand(a3, HeapObject::kMapOffset)); // Set FixedArray length. __ sll(t2, t1, kSmiTagSize); __ sw(t2, FieldMemOperand(a3, FixedArray::kLengthOffset)); // Fill contents of fixed-array with the-hole. __ li(a2, Operand(masm->isolate()->factory()->the_hole_value())); __ Addu(a3, a3, Operand(FixedArray::kHeaderSize - kHeapObjectTag)); // Fill fixed array elements with hole. // v0: JSArray, tagged. // a2: the hole. // a3: Start of elements in FixedArray. // t1: Number of elements to fill. Label loop; __ sll(t1, t1, kPointerSizeLog2); // Convert num elements to num bytes. __ addu(t1, t1, a3); // Point past last element to store. __ bind(&loop); __ Branch(&done, ge, a3, Operand(t1)); // Break when a3 past end of elem. __ sw(a2, MemOperand(a3)); __ Branch(&loop, USE_DELAY_SLOT); __ addiu(a3, a3, kPointerSize); // In branch delay slot. __ bind(&done); __ Addu(sp, sp, Operand(3 * kPointerSize)); __ Ret(); __ bind(&slowcase); __ TailCallRuntime(Runtime::kRegExpConstructResult, 3, 1); } void CallFunctionStub::Generate(MacroAssembler* masm) { Label slow; // If the receiver might be a value (string, number or boolean) check // for this and box it if it is. if (ReceiverMightBeValue()) { // Get the receiver from the stack. // function, receiver [, arguments] Label receiver_is_value, receiver_is_js_object; __ lw(a1, MemOperand(sp, argc_ * kPointerSize)); // Check if receiver is a smi (which is a number value). __ JumpIfSmi(a1, &receiver_is_value); // Check if the receiver is a valid JS object. __ GetObjectType(a1, a2, a2); __ Branch(&receiver_is_js_object, ge, a2, Operand(FIRST_JS_OBJECT_TYPE)); // Call the runtime to box the value. __ bind(&receiver_is_value); // We need natives to execute this. __ EnterInternalFrame(); __ push(a1); __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION); __ LeaveInternalFrame(); __ sw(v0, MemOperand(sp, argc_ * kPointerSize)); __ bind(&receiver_is_js_object); } // Get the function to call from the stack. // function, receiver [, arguments] __ lw(a1, MemOperand(sp, (argc_ + 1) * kPointerSize)); // Check that the function is really a JavaScript function. // a1: pushed function (to be verified) __ JumpIfSmi(a1, &slow); // Get the map of the function object. __ GetObjectType(a1, a2, a2); __ Branch(&slow, ne, a2, Operand(JS_FUNCTION_TYPE)); // Fast-case: Invoke the function now. // a1: pushed function ParameterCount actual(argc_); __ InvokeFunction(a1, actual, JUMP_FUNCTION); // Slow-case: Non-function called. __ bind(&slow); // CALL_NON_FUNCTION expects the non-function callee as receiver (instead // of the original receiver from the call site). __ sw(a1, MemOperand(sp, argc_ * kPointerSize)); __ li(a0, Operand(argc_)); // Setup the number of arguments. __ mov(a2, zero_reg); __ GetBuiltinEntry(a3, Builtins::CALL_NON_FUNCTION); __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(), RelocInfo::CODE_TARGET); } // Unfortunately you have to run without snapshots to see most of these // names in the profile since most compare stubs end up in the snapshot. const char* CompareStub::GetName() { ASSERT((lhs_.is(a0) && rhs_.is(a1)) || (lhs_.is(a1) && rhs_.is(a0))); if (name_ != NULL) return name_; const int kMaxNameLength = 100; name_ = Isolate::Current()->bootstrapper()->AllocateAutoDeletedArray( kMaxNameLength); if (name_ == NULL) return "OOM"; const char* cc_name; switch (cc_) { case lt: cc_name = "LT"; break; case gt: cc_name = "GT"; break; case le: cc_name = "LE"; break; case ge: cc_name = "GE"; break; case eq: cc_name = "EQ"; break; case ne: cc_name = "NE"; break; default: cc_name = "UnknownCondition"; break; } const char* lhs_name = lhs_.is(a0) ? "_a0" : "_a1"; const char* rhs_name = rhs_.is(a0) ? "_a0" : "_a1"; const char* strict_name = ""; if (strict_ && (cc_ == eq || cc_ == ne)) { strict_name = "_STRICT"; } const char* never_nan_nan_name = ""; if (never_nan_nan_ && (cc_ == eq || cc_ == ne)) { never_nan_nan_name = "_NO_NAN"; } const char* include_number_compare_name = ""; if (!include_number_compare_) { include_number_compare_name = "_NO_NUMBER"; } const char* include_smi_compare_name = ""; if (!include_smi_compare_) { include_smi_compare_name = "_NO_SMI"; } OS::SNPrintF(Vector<char>(name_, kMaxNameLength), "CompareStub_%s%s%s%s%s%s", cc_name, lhs_name, rhs_name, strict_name, never_nan_nan_name, include_number_compare_name, include_smi_compare_name); return name_; } int CompareStub::MinorKey() { // Encode the two parameters in a unique 16 bit value. ASSERT(static_cast<unsigned>(cc_) < (1 << 14)); ASSERT((lhs_.is(a0) && rhs_.is(a1)) || (lhs_.is(a1) && rhs_.is(a0))); return ConditionField::encode(static_cast<unsigned>(cc_)) | RegisterField::encode(lhs_.is(a0)) | StrictField::encode(strict_) | NeverNanNanField::encode(cc_ == eq ? never_nan_nan_ : false) | IncludeSmiCompareField::encode(include_smi_compare_); } // StringCharCodeAtGenerator. void StringCharCodeAtGenerator::GenerateFast(MacroAssembler* masm) { Label flat_string; Label ascii_string; Label got_char_code; ASSERT(!t0.is(scratch_)); ASSERT(!t0.is(index_)); ASSERT(!t0.is(result_)); ASSERT(!t0.is(object_)); // If the receiver is a smi trigger the non-string case. __ JumpIfSmi(object_, receiver_not_string_); // Fetch the instance type of the receiver into result register. __ lw(result_, FieldMemOperand(object_, HeapObject::kMapOffset)); __ lbu(result_, FieldMemOperand(result_, Map::kInstanceTypeOffset)); // If the receiver is not a string trigger the non-string case. __ And(t0, result_, Operand(kIsNotStringMask)); __ Branch(receiver_not_string_, ne, t0, Operand(zero_reg)); // If the index is non-smi trigger the non-smi case. __ JumpIfNotSmi(index_, &index_not_smi_); // Put smi-tagged index into scratch register. __ mov(scratch_, index_); __ bind(&got_smi_index_); // Check for index out of range. __ lw(t0, FieldMemOperand(object_, String::kLengthOffset)); __ Branch(index_out_of_range_, ls, t0, Operand(scratch_)); // We need special handling for non-flat strings. STATIC_ASSERT(kSeqStringTag == 0); __ And(t0, result_, Operand(kStringRepresentationMask)); __ Branch(&flat_string, eq, t0, Operand(zero_reg)); // Handle non-flat strings. __ And(t0, result_, Operand(kIsConsStringMask)); __ Branch(&call_runtime_, eq, t0, Operand(zero_reg)); // ConsString. // Check whether the right hand side is the empty string (i.e. if // this is really a flat string in a cons string). If that is not // the case we would rather go to the runtime system now to flatten // the string. __ lw(result_, FieldMemOperand(object_, ConsString::kSecondOffset)); __ LoadRoot(t0, Heap::kEmptyStringRootIndex); __ Branch(&call_runtime_, ne, result_, Operand(t0)); // Get the first of the two strings and load its instance type. __ lw(object_, FieldMemOperand(object_, ConsString::kFirstOffset)); __ lw(result_, FieldMemOperand(object_, HeapObject::kMapOffset)); __ lbu(result_, FieldMemOperand(result_, Map::kInstanceTypeOffset)); // If the first cons component is also non-flat, then go to runtime. STATIC_ASSERT(kSeqStringTag == 0); __ And(t0, result_, Operand(kStringRepresentationMask)); __ Branch(&call_runtime_, ne, t0, Operand(zero_reg)); // Check for 1-byte or 2-byte string. __ bind(&flat_string); STATIC_ASSERT(kAsciiStringTag != 0); __ And(t0, result_, Operand(kStringEncodingMask)); __ Branch(&ascii_string, ne, t0, Operand(zero_reg)); // 2-byte string. // Load the 2-byte character code into the result register. We can // add without shifting since the smi tag size is the log2 of the // number of bytes in a two-byte character. STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1 && kSmiShiftSize == 0); __ Addu(scratch_, object_, Operand(scratch_)); __ lhu(result_, FieldMemOperand(scratch_, SeqTwoByteString::kHeaderSize)); __ Branch(&got_char_code); // ASCII string. // Load the byte into the result register. __ bind(&ascii_string); __ srl(t0, scratch_, kSmiTagSize); __ Addu(scratch_, object_, t0); __ lbu(result_, FieldMemOperand(scratch_, SeqAsciiString::kHeaderSize)); __ bind(&got_char_code); __ sll(result_, result_, kSmiTagSize); __ bind(&exit_); } void StringCharCodeAtGenerator::GenerateSlow( MacroAssembler* masm, const RuntimeCallHelper& call_helper) { __ Abort("Unexpected fallthrough to CharCodeAt slow case"); // Index is not a smi. __ bind(&index_not_smi_); // If index is a heap number, try converting it to an integer. __ CheckMap(index_, scratch_, Heap::kHeapNumberMapRootIndex, index_not_number_, true); call_helper.BeforeCall(masm); // Consumed by runtime conversion function: __ Push(object_, index_, index_); if (index_flags_ == STRING_INDEX_IS_NUMBER) { __ CallRuntime(Runtime::kNumberToIntegerMapMinusZero, 1); } else { ASSERT(index_flags_ == STRING_INDEX_IS_ARRAY_INDEX); // NumberToSmi discards numbers that are not exact integers. __ CallRuntime(Runtime::kNumberToSmi, 1); } // Save the conversion result before the pop instructions below // have a chance to overwrite it. __ Move(scratch_, v0); __ pop(index_); __ pop(object_); // Reload the instance type. __ lw(result_, FieldMemOperand(object_, HeapObject::kMapOffset)); __ lbu(result_, FieldMemOperand(result_, Map::kInstanceTypeOffset)); call_helper.AfterCall(masm); // If index is still not a smi, it must be out of range. __ JumpIfNotSmi(scratch_, index_out_of_range_); // Otherwise, return to the fast path. __ Branch(&got_smi_index_); // Call runtime. We get here when the receiver is a string and the // index is a number, but the code of getting the actual character // is too complex (e.g., when the string needs to be flattened). __ bind(&call_runtime_); call_helper.BeforeCall(masm); __ Push(object_, index_); __ CallRuntime(Runtime::kStringCharCodeAt, 2); __ Move(result_, v0); call_helper.AfterCall(masm); __ jmp(&exit_); __ Abort("Unexpected fallthrough from CharCodeAt slow case"); } // ------------------------------------------------------------------------- // StringCharFromCodeGenerator void StringCharFromCodeGenerator::GenerateFast(MacroAssembler* masm) { // Fast case of Heap::LookupSingleCharacterStringFromCode. ASSERT(!t0.is(result_)); ASSERT(!t0.is(code_)); STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiShiftSize == 0); ASSERT(IsPowerOf2(String::kMaxAsciiCharCode + 1)); __ And(t0, code_, Operand(kSmiTagMask | ((~String::kMaxAsciiCharCode) << kSmiTagSize))); __ Branch(&slow_case_, ne, t0, Operand(zero_reg)); __ LoadRoot(result_, Heap::kSingleCharacterStringCacheRootIndex); // At this point code register contains smi tagged ASCII char code. STATIC_ASSERT(kSmiTag == 0); __ sll(t0, code_, kPointerSizeLog2 - kSmiTagSize); __ Addu(result_, result_, t0); __ lw(result_, FieldMemOperand(result_, FixedArray::kHeaderSize)); __ LoadRoot(t0, Heap::kUndefinedValueRootIndex); __ Branch(&slow_case_, eq, result_, Operand(t0)); __ bind(&exit_); } void StringCharFromCodeGenerator::GenerateSlow( MacroAssembler* masm, const RuntimeCallHelper& call_helper) { __ Abort("Unexpected fallthrough to CharFromCode slow case"); __ bind(&slow_case_); call_helper.BeforeCall(masm); __ push(code_); __ CallRuntime(Runtime::kCharFromCode, 1); __ Move(result_, v0); call_helper.AfterCall(masm); __ Branch(&exit_); __ Abort("Unexpected fallthrough from CharFromCode slow case"); } // ------------------------------------------------------------------------- // StringCharAtGenerator void StringCharAtGenerator::GenerateFast(MacroAssembler* masm) { char_code_at_generator_.GenerateFast(masm); char_from_code_generator_.GenerateFast(masm); } void StringCharAtGenerator::GenerateSlow( MacroAssembler* masm, const RuntimeCallHelper& call_helper) { char_code_at_generator_.GenerateSlow(masm, call_helper); char_from_code_generator_.GenerateSlow(masm, call_helper); } class StringHelper : public AllStatic { public: // Generate code for copying characters using a simple loop. This should only // be used in places where the number of characters is small and the // additional setup and checking in GenerateCopyCharactersLong adds too much // overhead. Copying of overlapping regions is not supported. // Dest register ends at the position after the last character written. static void GenerateCopyCharacters(MacroAssembler* masm, Register dest, Register src, Register count, Register scratch, bool ascii); // Generate code for copying a large number of characters. This function // is allowed to spend extra time setting up conditions to make copying // faster. Copying of overlapping regions is not supported. // Dest register ends at the position after the last character written. static void GenerateCopyCharactersLong(MacroAssembler* masm, Register dest, Register src, Register count, Register scratch1, Register scratch2, Register scratch3, Register scratch4, Register scratch5, int flags); // Probe the symbol table for a two character string. If the string is // not found by probing a jump to the label not_found is performed. This jump // does not guarantee that the string is not in the symbol table. If the // string is found the code falls through with the string in register r0. // Contents of both c1 and c2 registers are modified. At the exit c1 is // guaranteed to contain halfword with low and high bytes equal to // initial contents of c1 and c2 respectively. static void GenerateTwoCharacterSymbolTableProbe(MacroAssembler* masm, Register c1, Register c2, Register scratch1, Register scratch2, Register scratch3, Register scratch4, Register scratch5, Label* not_found); // Generate string hash. static void GenerateHashInit(MacroAssembler* masm, Register hash, Register character); static void GenerateHashAddCharacter(MacroAssembler* masm, Register hash, Register character); static void GenerateHashGetHash(MacroAssembler* masm, Register hash); private: DISALLOW_IMPLICIT_CONSTRUCTORS(StringHelper); }; void StringHelper::GenerateCopyCharacters(MacroAssembler* masm, Register dest, Register src, Register count, Register scratch, bool ascii) { Label loop; Label done; // This loop just copies one character at a time, as it is only used for // very short strings. if (!ascii) { __ addu(count, count, count); } __ Branch(&done, eq, count, Operand(zero_reg)); __ addu(count, dest, count); // Count now points to the last dest byte. __ bind(&loop); __ lbu(scratch, MemOperand(src)); __ addiu(src, src, 1); __ sb(scratch, MemOperand(dest)); __ addiu(dest, dest, 1); __ Branch(&loop, lt, dest, Operand(count)); __ bind(&done); } enum CopyCharactersFlags { COPY_ASCII = 1, DEST_ALWAYS_ALIGNED = 2 }; void StringHelper::GenerateCopyCharactersLong(MacroAssembler* masm, Register dest, Register src, Register count, Register scratch1, Register scratch2, Register scratch3, Register scratch4, Register scratch5, int flags) { bool ascii = (flags & COPY_ASCII) != 0; bool dest_always_aligned = (flags & DEST_ALWAYS_ALIGNED) != 0; if (dest_always_aligned && FLAG_debug_code) { // Check that destination is actually word aligned if the flag says // that it is. __ And(scratch4, dest, Operand(kPointerAlignmentMask)); __ Check(eq, "Destination of copy not aligned.", scratch4, Operand(zero_reg)); } const int kReadAlignment = 4; const int kReadAlignmentMask = kReadAlignment - 1; // Ensure that reading an entire aligned word containing the last character // of a string will not read outside the allocated area (because we pad up // to kObjectAlignment). STATIC_ASSERT(kObjectAlignment >= kReadAlignment); // Assumes word reads and writes are little endian. // Nothing to do for zero characters. Label done; if (!ascii) { __ addu(count, count, count); } __ Branch(&done, eq, count, Operand(zero_reg)); Label byte_loop; // Must copy at least eight bytes, otherwise just do it one byte at a time. __ Subu(scratch1, count, Operand(8)); __ Addu(count, dest, Operand(count)); Register limit = count; // Read until src equals this. __ Branch(&byte_loop, lt, scratch1, Operand(zero_reg)); if (!dest_always_aligned) { // Align dest by byte copying. Copies between zero and three bytes. __ And(scratch4, dest, Operand(kReadAlignmentMask)); Label dest_aligned; __ Branch(&dest_aligned, eq, scratch4, Operand(zero_reg)); Label aligned_loop; __ bind(&aligned_loop); __ lbu(scratch1, MemOperand(src)); __ addiu(src, src, 1); __ sb(scratch1, MemOperand(dest)); __ addiu(dest, dest, 1); __ addiu(scratch4, scratch4, 1); __ Branch(&aligned_loop, le, scratch4, Operand(kReadAlignmentMask)); __ bind(&dest_aligned); } Label simple_loop; __ And(scratch4, src, Operand(kReadAlignmentMask)); __ Branch(&simple_loop, eq, scratch4, Operand(zero_reg)); // Loop for src/dst that are not aligned the same way. // This loop uses lwl and lwr instructions. These instructions // depend on the endianness, and the implementation assumes little-endian. { Label loop; __ bind(&loop); __ lwr(scratch1, MemOperand(src)); __ Addu(src, src, Operand(kReadAlignment)); __ lwl(scratch1, MemOperand(src, -1)); __ sw(scratch1, MemOperand(dest)); __ Addu(dest, dest, Operand(kReadAlignment)); __ Subu(scratch2, limit, dest); __ Branch(&loop, ge, scratch2, Operand(kReadAlignment)); } __ Branch(&byte_loop); // Simple loop. // Copy words from src to dest, until less than four bytes left. // Both src and dest are word aligned. __ bind(&simple_loop); { Label loop; __ bind(&loop); __ lw(scratch1, MemOperand(src)); __ Addu(src, src, Operand(kReadAlignment)); __ sw(scratch1, MemOperand(dest)); __ Addu(dest, dest, Operand(kReadAlignment)); __ Subu(scratch2, limit, dest); __ Branch(&loop, ge, scratch2, Operand(kReadAlignment)); } // Copy bytes from src to dest until dest hits limit. __ bind(&byte_loop); // Test if dest has already reached the limit. __ Branch(&done, ge, dest, Operand(limit)); __ lbu(scratch1, MemOperand(src)); __ addiu(src, src, 1); __ sb(scratch1, MemOperand(dest)); __ addiu(dest, dest, 1); __ Branch(&byte_loop); __ bind(&done); } void StringHelper::GenerateTwoCharacterSymbolTableProbe(MacroAssembler* masm, Register c1, Register c2, Register scratch1, Register scratch2, Register scratch3, Register scratch4, Register scratch5, Label* not_found) { // Register scratch3 is the general scratch register in this function. Register scratch = scratch3; // Make sure that both characters are not digits as such strings has a // different hash algorithm. Don't try to look for these in the symbol table. Label not_array_index; __ Subu(scratch, c1, Operand(static_cast<int>('0'))); __ Branch(&not_array_index, Ugreater, scratch, Operand(static_cast<int>('9' - '0'))); __ Subu(scratch, c2, Operand(static_cast<int>('0'))); // If check failed combine both characters into single halfword. // This is required by the contract of the method: code at the // not_found branch expects this combination in c1 register. Label tmp; __ sll(scratch1, c2, kBitsPerByte); __ Branch(&tmp, Ugreater, scratch, Operand(static_cast<int>('9' - '0'))); __ Or(c1, c1, scratch1); __ bind(&tmp); __ Branch(not_found, Uless_equal, scratch, Operand(static_cast<int>('9' - '0'))); __ bind(&not_array_index); // Calculate the two character string hash. Register hash = scratch1; StringHelper::GenerateHashInit(masm, hash, c1); StringHelper::GenerateHashAddCharacter(masm, hash, c2); StringHelper::GenerateHashGetHash(masm, hash); // Collect the two characters in a register. Register chars = c1; __ sll(scratch, c2, kBitsPerByte); __ Or(chars, chars, scratch); // chars: two character string, char 1 in byte 0 and char 2 in byte 1. // hash: hash of two character string. // Load symbol table. // Load address of first element of the symbol table. Register symbol_table = c2; __ LoadRoot(symbol_table, Heap::kSymbolTableRootIndex); Register undefined = scratch4; __ LoadRoot(undefined, Heap::kUndefinedValueRootIndex); // Calculate capacity mask from the symbol table capacity. Register mask = scratch2; __ lw(mask, FieldMemOperand(symbol_table, SymbolTable::kCapacityOffset)); __ sra(mask, mask, 1); __ Addu(mask, mask, -1); // Calculate untagged address of the first element of the symbol table. Register first_symbol_table_element = symbol_table; __ Addu(first_symbol_table_element, symbol_table, Operand(SymbolTable::kElementsStartOffset - kHeapObjectTag)); // Registers. // chars: two character string, char 1 in byte 0 and char 2 in byte 1. // hash: hash of two character string // mask: capacity mask // first_symbol_table_element: address of the first element of // the symbol table // undefined: the undefined object // scratch: - // Perform a number of probes in the symbol table. static const int kProbes = 4; Label found_in_symbol_table; Label next_probe[kProbes]; Register candidate = scratch5; // Scratch register contains candidate. for (int i = 0; i < kProbes; i++) { // Calculate entry in symbol table. if (i > 0) { __ Addu(candidate, hash, Operand(SymbolTable::GetProbeOffset(i))); } else { __ mov(candidate, hash); } __ And(candidate, candidate, Operand(mask)); // Load the entry from the symble table. STATIC_ASSERT(SymbolTable::kEntrySize == 1); __ sll(scratch, candidate, kPointerSizeLog2); __ Addu(scratch, scratch, first_symbol_table_element); __ lw(candidate, MemOperand(scratch)); // If entry is undefined no string with this hash can be found. Label is_string; __ GetObjectType(candidate, scratch, scratch); __ Branch(&is_string, ne, scratch, Operand(ODDBALL_TYPE)); __ Branch(not_found, eq, undefined, Operand(candidate)); // Must be null (deleted entry). if (FLAG_debug_code) { __ LoadRoot(scratch, Heap::kNullValueRootIndex); __ Assert(eq, "oddball in symbol table is not undefined or null", scratch, Operand(candidate)); } __ jmp(&next_probe[i]); __ bind(&is_string); // Check that the candidate is a non-external ASCII string. The instance // type is still in the scratch register from the CompareObjectType // operation. __ JumpIfInstanceTypeIsNotSequentialAscii(scratch, scratch, &next_probe[i]); // If length is not 2 the string is not a candidate. __ lw(scratch, FieldMemOperand(candidate, String::kLengthOffset)); __ Branch(&next_probe[i], ne, scratch, Operand(Smi::FromInt(2))); // Check if the two characters match. // Assumes that word load is little endian. __ lhu(scratch, FieldMemOperand(candidate, SeqAsciiString::kHeaderSize)); __ Branch(&found_in_symbol_table, eq, chars, Operand(scratch)); __ bind(&next_probe[i]); } // No matching 2 character string found by probing. __ jmp(not_found); // Scratch register contains result when we fall through to here. Register result = candidate; __ bind(&found_in_symbol_table); __ mov(v0, result); } void StringHelper::GenerateHashInit(MacroAssembler* masm, Register hash, Register character) { // hash = character + (character << 10); __ sll(hash, character, 10); __ addu(hash, hash, character); // hash ^= hash >> 6; __ sra(at, hash, 6); __ xor_(hash, hash, at); } void StringHelper::GenerateHashAddCharacter(MacroAssembler* masm, Register hash, Register character) { // hash += character; __ addu(hash, hash, character); // hash += hash << 10; __ sll(at, hash, 10); __ addu(hash, hash, at); // hash ^= hash >> 6; __ sra(at, hash, 6); __ xor_(hash, hash, at); } void StringHelper::GenerateHashGetHash(MacroAssembler* masm, Register hash) { // hash += hash << 3; __ sll(at, hash, 3); __ addu(hash, hash, at); // hash ^= hash >> 11; __ sra(at, hash, 11); __ xor_(hash, hash, at); // hash += hash << 15; __ sll(at, hash, 15); __ addu(hash, hash, at); // if (hash == 0) hash = 27; __ ori(at, zero_reg, 27); __ movz(hash, at, hash); } void SubStringStub::Generate(MacroAssembler* masm) { Label sub_string_runtime; // Stack frame on entry. // ra: return address // sp[0]: to // sp[4]: from // sp[8]: string // This stub is called from the native-call %_SubString(...), so // nothing can be assumed about the arguments. It is tested that: // "string" is a sequential string, // both "from" and "to" are smis, and // 0 <= from <= to <= string.length. // If any of these assumptions fail, we call the runtime system. static const int kToOffset = 0 * kPointerSize; static const int kFromOffset = 1 * kPointerSize; static const int kStringOffset = 2 * kPointerSize; Register to = t2; Register from = t3; // Check bounds and smi-ness. __ lw(to, MemOperand(sp, kToOffset)); __ lw(from, MemOperand(sp, kFromOffset)); STATIC_ASSERT(kFromOffset == kToOffset + 4); STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1); __ JumpIfNotSmi(from, &sub_string_runtime); __ JumpIfNotSmi(to, &sub_string_runtime); __ sra(a3, from, kSmiTagSize); // Remove smi tag. __ sra(t5, to, kSmiTagSize); // Remove smi tag. // a3: from index (untagged smi) // t5: to index (untagged smi) __ Branch(&sub_string_runtime, lt, a3, Operand(zero_reg)); // From < 0. __ subu(a2, t5, a3); __ Branch(&sub_string_runtime, gt, a3, Operand(t5)); // Fail if from > to. // Special handling of sub-strings of length 1 and 2. One character strings // are handled in the runtime system (looked up in the single character // cache). Two character strings are looked for in the symbol cache. __ Branch(&sub_string_runtime, lt, a2, Operand(2)); // Both to and from are smis. // a2: result string length // a3: from index (untagged smi) // t2: (a.k.a. to): to (smi) // t3: (a.k.a. from): from offset (smi) // t5: to index (untagged smi) // Make sure first argument is a sequential (or flat) string. __ lw(t1, MemOperand(sp, kStringOffset)); __ Branch(&sub_string_runtime, eq, t1, Operand(kSmiTagMask)); __ lw(a1, FieldMemOperand(t1, HeapObject::kMapOffset)); __ lbu(a1, FieldMemOperand(a1, Map::kInstanceTypeOffset)); __ And(t4, a1, Operand(kIsNotStringMask)); __ Branch(&sub_string_runtime, ne, t4, Operand(zero_reg)); // a1: instance type // a2: result string length // a3: from index (untagged smi) // t1: string // t2: (a.k.a. to): to (smi) // t3: (a.k.a. from): from offset (smi) // t5: to index (untagged smi) Label seq_string; __ And(t0, a1, Operand(kStringRepresentationMask)); STATIC_ASSERT(kSeqStringTag < kConsStringTag); STATIC_ASSERT(kConsStringTag < kExternalStringTag); // External strings go to runtime. __ Branch(&sub_string_runtime, gt, t0, Operand(kConsStringTag)); // Sequential strings are handled directly. __ Branch(&seq_string, lt, t0, Operand(kConsStringTag)); // Cons string. Try to recurse (once) on the first substring. // (This adds a little more generality than necessary to handle flattened // cons strings, but not much). __ lw(t1, FieldMemOperand(t1, ConsString::kFirstOffset)); __ lw(t0, FieldMemOperand(t1, HeapObject::kMapOffset)); __ lbu(a1, FieldMemOperand(t0, Map::kInstanceTypeOffset)); STATIC_ASSERT(kSeqStringTag == 0); // Cons and External strings go to runtime. __ Branch(&sub_string_runtime, ne, a1, Operand(kStringRepresentationMask)); // Definitly a sequential string. __ bind(&seq_string); // a1: instance type // a2: result string length // a3: from index (untagged smi) // t1: string // t2: (a.k.a. to): to (smi) // t3: (a.k.a. from): from offset (smi) // t5: to index (untagged smi) __ lw(t0, FieldMemOperand(t1, String::kLengthOffset)); __ Branch(&sub_string_runtime, lt, t0, Operand(to)); // Fail if to > length. to = no_reg; // a1: instance type // a2: result string length // a3: from index (untagged smi) // t1: string // t3: (a.k.a. from): from offset (smi) // t5: to index (untagged smi) // Check for flat ASCII string. Label non_ascii_flat; STATIC_ASSERT(kTwoByteStringTag == 0); __ And(t4, a1, Operand(kStringEncodingMask)); __ Branch(&non_ascii_flat, eq, t4, Operand(zero_reg)); Label result_longer_than_two; __ Branch(&result_longer_than_two, gt, a2, Operand(2)); // Sub string of length 2 requested. // Get the two characters forming the sub string. __ Addu(t1, t1, Operand(a3)); __ lbu(a3, FieldMemOperand(t1, SeqAsciiString::kHeaderSize)); __ lbu(t0, FieldMemOperand(t1, SeqAsciiString::kHeaderSize + 1)); // Try to lookup two character string in symbol table. Label make_two_character_string; StringHelper::GenerateTwoCharacterSymbolTableProbe( masm, a3, t0, a1, t1, t2, t3, t4, &make_two_character_string); Counters* counters = masm->isolate()->counters(); __ IncrementCounter(counters->sub_string_native(), 1, a3, t0); __ Addu(sp, sp, Operand(3 * kPointerSize)); __ Ret(); // a2: result string length. // a3: two characters combined into halfword in little endian byte order. __ bind(&make_two_character_string); __ AllocateAsciiString(v0, a2, t0, t1, t4, &sub_string_runtime); __ sh(a3, FieldMemOperand(v0, SeqAsciiString::kHeaderSize)); __ IncrementCounter(counters->sub_string_native(), 1, a3, t0); __ Addu(sp, sp, Operand(3 * kPointerSize)); __ Ret(); __ bind(&result_longer_than_two); // Allocate the result. __ AllocateAsciiString(v0, a2, t4, t0, a1, &sub_string_runtime); // v0: result string. // a2: result string length. // a3: from index (untagged smi) // t1: string. // t3: (a.k.a. from): from offset (smi) // Locate first character of result. __ Addu(a1, v0, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag)); // Locate 'from' character of string. __ Addu(t1, t1, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag)); __ Addu(t1, t1, Operand(a3)); // v0: result string. // a1: first character of result string. // a2: result string length. // t1: first character of sub string to copy. STATIC_ASSERT((SeqAsciiString::kHeaderSize & kObjectAlignmentMask) == 0); StringHelper::GenerateCopyCharactersLong( masm, a1, t1, a2, a3, t0, t2, t3, t4, COPY_ASCII | DEST_ALWAYS_ALIGNED); __ IncrementCounter(counters->sub_string_native(), 1, a3, t0); __ Addu(sp, sp, Operand(3 * kPointerSize)); __ Ret(); __ bind(&non_ascii_flat); // a2: result string length. // t1: string. // t3: (a.k.a. from): from offset (smi) // Check for flat two byte string. // Allocate the result. __ AllocateTwoByteString(v0, a2, a1, a3, t0, &sub_string_runtime); // v0: result string. // a2: result string length. // t1: string. // Locate first character of result. __ Addu(a1, v0, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag)); // Locate 'from' character of string. __ Addu(t1, t1, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag)); // As "from" is a smi it is 2 times the value which matches the size of a two // byte character. __ Addu(t1, t1, Operand(from)); from = no_reg; // v0: result string. // a1: first character of result. // a2: result length. // t1: first character of string to copy. STATIC_ASSERT((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0); StringHelper::GenerateCopyCharactersLong( masm, a1, t1, a2, a3, t0, t2, t3, t4, DEST_ALWAYS_ALIGNED); __ IncrementCounter(counters->sub_string_native(), 1, a3, t0); __ Addu(sp, sp, Operand(3 * kPointerSize)); __ Ret(); // Just jump to runtime to create the sub string. __ bind(&sub_string_runtime); __ TailCallRuntime(Runtime::kSubString, 3, 1); } void StringCompareStub::GenerateFlatAsciiStringEquals(MacroAssembler* masm, Register left, Register right, Register scratch1, Register scratch2, Register scratch3) { Register length = scratch1; // Compare lengths. Label strings_not_equal, check_zero_length; __ lw(length, FieldMemOperand(left, String::kLengthOffset)); __ lw(scratch2, FieldMemOperand(right, String::kLengthOffset)); __ Branch(&check_zero_length, eq, length, Operand(scratch2)); __ bind(&strings_not_equal); __ li(v0, Operand(Smi::FromInt(NOT_EQUAL))); __ Ret(); // Check if the length is zero. Label compare_chars; __ bind(&check_zero_length); STATIC_ASSERT(kSmiTag == 0); __ Branch(&compare_chars, ne, length, Operand(zero_reg)); __ li(v0, Operand(Smi::FromInt(EQUAL))); __ Ret(); // Compare characters. __ bind(&compare_chars); GenerateAsciiCharsCompareLoop(masm, left, right, length, scratch2, scratch3, v0, &strings_not_equal); // Characters are equal. __ li(v0, Operand(Smi::FromInt(EQUAL))); __ Ret(); } void StringCompareStub::GenerateCompareFlatAsciiStrings(MacroAssembler* masm, Register left, Register right, Register scratch1, Register scratch2, Register scratch3, Register scratch4) { Label result_not_equal, compare_lengths; // Find minimum length and length difference. __ lw(scratch1, FieldMemOperand(left, String::kLengthOffset)); __ lw(scratch2, FieldMemOperand(right, String::kLengthOffset)); __ Subu(scratch3, scratch1, Operand(scratch2)); Register length_delta = scratch3; __ slt(scratch4, scratch2, scratch1); __ movn(scratch1, scratch2, scratch4); Register min_length = scratch1; STATIC_ASSERT(kSmiTag == 0); __ Branch(&compare_lengths, eq, min_length, Operand(zero_reg)); // Compare loop. GenerateAsciiCharsCompareLoop(masm, left, right, min_length, scratch2, scratch4, v0, &result_not_equal); // Compare lengths - strings up to min-length are equal. __ bind(&compare_lengths); ASSERT(Smi::FromInt(EQUAL) == static_cast<Smi*>(0)); // Use length_delta as result if it's zero. __ mov(scratch2, length_delta); __ mov(scratch4, zero_reg); __ mov(v0, zero_reg); __ bind(&result_not_equal); // Conditionally update the result based either on length_delta or // the last comparion performed in the loop above. Label ret; __ Branch(&ret, eq, scratch2, Operand(scratch4)); __ li(v0, Operand(Smi::FromInt(GREATER))); __ Branch(&ret, gt, scratch2, Operand(scratch4)); __ li(v0, Operand(Smi::FromInt(LESS))); __ bind(&ret); __ Ret(); } void StringCompareStub::GenerateAsciiCharsCompareLoop( MacroAssembler* masm, Register left, Register right, Register length, Register scratch1, Register scratch2, Register scratch3, Label* chars_not_equal) { // Change index to run from -length to -1 by adding length to string // start. This means that loop ends when index reaches zero, which // doesn't need an additional compare. __ SmiUntag(length); __ Addu(scratch1, length, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag)); __ Addu(left, left, Operand(scratch1)); __ Addu(right, right, Operand(scratch1)); __ Subu(length, zero_reg, length); Register index = length; // index = -length; // Compare loop. Label loop; __ bind(&loop); __ Addu(scratch3, left, index); __ lbu(scratch1, MemOperand(scratch3)); __ Addu(scratch3, right, index); __ lbu(scratch2, MemOperand(scratch3)); __ Branch(chars_not_equal, ne, scratch1, Operand(scratch2)); __ Addu(index, index, 1); __ Branch(&loop, ne, index, Operand(zero_reg)); } void StringCompareStub::Generate(MacroAssembler* masm) { Label runtime; Counters* counters = masm->isolate()->counters(); // Stack frame on entry. // sp[0]: right string // sp[4]: left string __ lw(a1, MemOperand(sp, 1 * kPointerSize)); // Left. __ lw(a0, MemOperand(sp, 0 * kPointerSize)); // Right. Label not_same; __ Branch(&not_same, ne, a0, Operand(a1)); STATIC_ASSERT(EQUAL == 0); STATIC_ASSERT(kSmiTag == 0); __ li(v0, Operand(Smi::FromInt(EQUAL))); __ IncrementCounter(counters->string_compare_native(), 1, a1, a2); __ Addu(sp, sp, Operand(2 * kPointerSize)); __ Ret(); __ bind(&not_same); // Check that both objects are sequential ASCII strings. __ JumpIfNotBothSequentialAsciiStrings(a1, a0, a2, a3, &runtime); // Compare flat ASCII strings natively. Remove arguments from stack first. __ IncrementCounter(counters->string_compare_native(), 1, a2, a3); __ Addu(sp, sp, Operand(2 * kPointerSize)); GenerateCompareFlatAsciiStrings(masm, a1, a0, a2, a3, t0, t1); __ bind(&runtime); __ TailCallRuntime(Runtime::kStringCompare, 2, 1); } void StringAddStub::Generate(MacroAssembler* masm) { Label string_add_runtime, call_builtin; Builtins::JavaScript builtin_id = Builtins::ADD; Counters* counters = masm->isolate()->counters(); // Stack on entry: // sp[0]: second argument (right). // sp[4]: first argument (left). // Load the two arguments. __ lw(a0, MemOperand(sp, 1 * kPointerSize)); // First argument. __ lw(a1, MemOperand(sp, 0 * kPointerSize)); // Second argument. // Make sure that both arguments are strings if not known in advance. if (flags_ == NO_STRING_ADD_FLAGS) { __ JumpIfEitherSmi(a0, a1, &string_add_runtime); // Load instance types. __ lw(t0, FieldMemOperand(a0, HeapObject::kMapOffset)); __ lw(t1, FieldMemOperand(a1, HeapObject::kMapOffset)); __ lbu(t0, FieldMemOperand(t0, Map::kInstanceTypeOffset)); __ lbu(t1, FieldMemOperand(t1, Map::kInstanceTypeOffset)); STATIC_ASSERT(kStringTag == 0); // If either is not a string, go to runtime. __ Or(t4, t0, Operand(t1)); __ And(t4, t4, Operand(kIsNotStringMask)); __ Branch(&string_add_runtime, ne, t4, Operand(zero_reg)); } else { // Here at least one of the arguments is definitely a string. // We convert the one that is not known to be a string. if ((flags_ & NO_STRING_CHECK_LEFT_IN_STUB) == 0) { ASSERT((flags_ & NO_STRING_CHECK_RIGHT_IN_STUB) != 0); GenerateConvertArgument( masm, 1 * kPointerSize, a0, a2, a3, t0, t1, &call_builtin); builtin_id = Builtins::STRING_ADD_RIGHT; } else if ((flags_ & NO_STRING_CHECK_RIGHT_IN_STUB) == 0) { ASSERT((flags_ & NO_STRING_CHECK_LEFT_IN_STUB) != 0); GenerateConvertArgument( masm, 0 * kPointerSize, a1, a2, a3, t0, t1, &call_builtin); builtin_id = Builtins::STRING_ADD_LEFT; } } // Both arguments are strings. // a0: first string // a1: second string // t0: first string instance type (if flags_ == NO_STRING_ADD_FLAGS) // t1: second string instance type (if flags_ == NO_STRING_ADD_FLAGS) { Label strings_not_empty; // Check if either of the strings are empty. In that case return the other. // These tests use zero-length check on string-length whch is an Smi. // Assert that Smi::FromInt(0) is really 0. STATIC_ASSERT(kSmiTag == 0); ASSERT(Smi::FromInt(0) == 0); __ lw(a2, FieldMemOperand(a0, String::kLengthOffset)); __ lw(a3, FieldMemOperand(a1, String::kLengthOffset)); __ mov(v0, a0); // Assume we'll return first string (from a0). __ movz(v0, a1, a2); // If first is empty, return second (from a1). __ slt(t4, zero_reg, a2); // if (a2 > 0) t4 = 1. __ slt(t5, zero_reg, a3); // if (a3 > 0) t5 = 1. __ and_(t4, t4, t5); // Branch if both strings were non-empty. __ Branch(&strings_not_empty, ne, t4, Operand(zero_reg)); __ IncrementCounter(counters->string_add_native(), 1, a2, a3); __ Addu(sp, sp, Operand(2 * kPointerSize)); __ Ret(); __ bind(&strings_not_empty); } // Untag both string-lengths. __ sra(a2, a2, kSmiTagSize); __ sra(a3, a3, kSmiTagSize); // Both strings are non-empty. // a0: first string // a1: second string // a2: length of first string // a3: length of second string // t0: first string instance type (if flags_ == NO_STRING_ADD_FLAGS) // t1: second string instance type (if flags_ == NO_STRING_ADD_FLAGS) // Look at the length of the result of adding the two strings. Label string_add_flat_result, longer_than_two; // Adding two lengths can't overflow. STATIC_ASSERT(String::kMaxLength < String::kMaxLength * 2); __ Addu(t2, a2, Operand(a3)); // Use the symbol table when adding two one character strings, as it // helps later optimizations to return a symbol here. __ Branch(&longer_than_two, ne, t2, Operand(2)); // Check that both strings are non-external ASCII strings. if (flags_ != NO_STRING_ADD_FLAGS) { __ lw(t0, FieldMemOperand(a0, HeapObject::kMapOffset)); __ lw(t1, FieldMemOperand(a1, HeapObject::kMapOffset)); __ lbu(t0, FieldMemOperand(t0, Map::kInstanceTypeOffset)); __ lbu(t1, FieldMemOperand(t1, Map::kInstanceTypeOffset)); } __ JumpIfBothInstanceTypesAreNotSequentialAscii(t0, t1, t2, t3, &string_add_runtime); // Get the two characters forming the sub string. __ lbu(a2, FieldMemOperand(a0, SeqAsciiString::kHeaderSize)); __ lbu(a3, FieldMemOperand(a1, SeqAsciiString::kHeaderSize)); // Try to lookup two character string in symbol table. If it is not found // just allocate a new one. Label make_two_character_string; StringHelper::GenerateTwoCharacterSymbolTableProbe( masm, a2, a3, t2, t3, t0, t1, t4, &make_two_character_string); __ IncrementCounter(counters->string_add_native(), 1, a2, a3); __ Addu(sp, sp, Operand(2 * kPointerSize)); __ Ret(); __ bind(&make_two_character_string); // Resulting string has length 2 and first chars of two strings // are combined into single halfword in a2 register. // So we can fill resulting string without two loops by a single // halfword store instruction (which assumes that processor is // in a little endian mode). __ li(t2, Operand(2)); __ AllocateAsciiString(v0, t2, t0, t1, t4, &string_add_runtime); __ sh(a2, FieldMemOperand(v0, SeqAsciiString::kHeaderSize)); __ IncrementCounter(counters->string_add_native(), 1, a2, a3); __ Addu(sp, sp, Operand(2 * kPointerSize)); __ Ret(); __ bind(&longer_than_two); // Check if resulting string will be flat. __ Branch(&string_add_flat_result, lt, t2, Operand(String::kMinNonFlatLength)); // Handle exceptionally long strings in the runtime system. STATIC_ASSERT((String::kMaxLength & 0x80000000) == 0); ASSERT(IsPowerOf2(String::kMaxLength + 1)); // kMaxLength + 1 is representable as shifted literal, kMaxLength is not. __ Branch(&string_add_runtime, hs, t2, Operand(String::kMaxLength + 1)); // If result is not supposed to be flat, allocate a cons string object. // If both strings are ASCII the result is an ASCII cons string. if (flags_ != NO_STRING_ADD_FLAGS) { __ lw(t0, FieldMemOperand(a0, HeapObject::kMapOffset)); __ lw(t1, FieldMemOperand(a1, HeapObject::kMapOffset)); __ lbu(t0, FieldMemOperand(t0, Map::kInstanceTypeOffset)); __ lbu(t1, FieldMemOperand(t1, Map::kInstanceTypeOffset)); } Label non_ascii, allocated, ascii_data; STATIC_ASSERT(kTwoByteStringTag == 0); // Branch to non_ascii if either string-encoding field is zero (non-ascii). __ And(t4, t0, Operand(t1)); __ And(t4, t4, Operand(kStringEncodingMask)); __ Branch(&non_ascii, eq, t4, Operand(zero_reg)); // Allocate an ASCII cons string. __ bind(&ascii_data); __ AllocateAsciiConsString(t3, t2, t0, t1, &string_add_runtime); __ bind(&allocated); // Fill the fields of the cons string. __ sw(a0, FieldMemOperand(t3, ConsString::kFirstOffset)); __ sw(a1, FieldMemOperand(t3, ConsString::kSecondOffset)); __ mov(v0, t3); __ IncrementCounter(counters->string_add_native(), 1, a2, a3); __ Addu(sp, sp, Operand(2 * kPointerSize)); __ Ret(); __ bind(&non_ascii); // At least one of the strings is two-byte. Check whether it happens // to contain only ASCII characters. // t0: first instance type. // t1: second instance type. // Branch to if _both_ instances have kAsciiDataHintMask set. __ And(at, t0, Operand(kAsciiDataHintMask)); __ and_(at, at, t1); __ Branch(&ascii_data, ne, at, Operand(zero_reg)); __ xor_(t0, t0, t1); STATIC_ASSERT(kAsciiStringTag != 0 && kAsciiDataHintTag != 0); __ And(t0, t0, Operand(kAsciiStringTag | kAsciiDataHintTag)); __ Branch(&ascii_data, eq, t0, Operand(kAsciiStringTag | kAsciiDataHintTag)); // Allocate a two byte cons string. __ AllocateTwoByteConsString(t3, t2, t0, t1, &string_add_runtime); __ Branch(&allocated); // Handle creating a flat result. First check that both strings are // sequential and that they have the same encoding. // a0: first string // a1: second string // a2: length of first string // a3: length of second string // t0: first string instance type (if flags_ == NO_STRING_ADD_FLAGS) // t1: second string instance type (if flags_ == NO_STRING_ADD_FLAGS) // t2: sum of lengths. __ bind(&string_add_flat_result); if (flags_ != NO_STRING_ADD_FLAGS) { __ lw(t0, FieldMemOperand(a0, HeapObject::kMapOffset)); __ lw(t1, FieldMemOperand(a1, HeapObject::kMapOffset)); __ lbu(t0, FieldMemOperand(t0, Map::kInstanceTypeOffset)); __ lbu(t1, FieldMemOperand(t1, Map::kInstanceTypeOffset)); } // Check that both strings are sequential, meaning that we // branch to runtime if either string tag is non-zero. STATIC_ASSERT(kSeqStringTag == 0); __ Or(t4, t0, Operand(t1)); __ And(t4, t4, Operand(kStringRepresentationMask)); __ Branch(&string_add_runtime, ne, t4, Operand(zero_reg)); // Now check if both strings have the same encoding (ASCII/Two-byte). // a0: first string // a1: second string // a2: length of first string // a3: length of second string // t0: first string instance type // t1: second string instance type // t2: sum of lengths. Label non_ascii_string_add_flat_result; ASSERT(IsPowerOf2(kStringEncodingMask)); // Just one bit to test. __ xor_(t3, t1, t0); __ And(t3, t3, Operand(kStringEncodingMask)); __ Branch(&string_add_runtime, ne, t3, Operand(zero_reg)); // And see if it's ASCII (0) or two-byte (1). __ And(t3, t0, Operand(kStringEncodingMask)); __ Branch(&non_ascii_string_add_flat_result, eq, t3, Operand(zero_reg)); // Both strings are sequential ASCII strings. We also know that they are // short (since the sum of the lengths is less than kMinNonFlatLength). // t2: length of resulting flat string __ AllocateAsciiString(t3, t2, t0, t1, t4, &string_add_runtime); // Locate first character of result. __ Addu(t2, t3, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag)); // Locate first character of first argument. __ Addu(a0, a0, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag)); // a0: first character of first string. // a1: second string. // a2: length of first string. // a3: length of second string. // t2: first character of result. // t3: result string. StringHelper::GenerateCopyCharacters(masm, t2, a0, a2, t0, true); // Load second argument and locate first character. __ Addu(a1, a1, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag)); // a1: first character of second string. // a3: length of second string. // t2: next character of result. // t3: result string. StringHelper::GenerateCopyCharacters(masm, t2, a1, a3, t0, true); __ mov(v0, t3); __ IncrementCounter(counters->string_add_native(), 1, a2, a3); __ Addu(sp, sp, Operand(2 * kPointerSize)); __ Ret(); __ bind(&non_ascii_string_add_flat_result); // Both strings are sequential two byte strings. // a0: first string. // a1: second string. // a2: length of first string. // a3: length of second string. // t2: sum of length of strings. __ AllocateTwoByteString(t3, t2, t0, t1, t4, &string_add_runtime); // a0: first string. // a1: second string. // a2: length of first string. // a3: length of second string. // t3: result string. // Locate first character of result. __ Addu(t2, t3, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag)); // Locate first character of first argument. __ Addu(a0, a0, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag)); // a0: first character of first string. // a1: second string. // a2: length of first string. // a3: length of second string. // t2: first character of result. // t3: result string. StringHelper::GenerateCopyCharacters(masm, t2, a0, a2, t0, false); // Locate first character of second argument. __ Addu(a1, a1, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag)); // a1: first character of second string. // a3: length of second string. // t2: next character of result (after copy of first string). // t3: result string. StringHelper::GenerateCopyCharacters(masm, t2, a1, a3, t0, false); __ mov(v0, t3); __ IncrementCounter(counters->string_add_native(), 1, a2, a3); __ Addu(sp, sp, Operand(2 * kPointerSize)); __ Ret(); // Just jump to runtime to add the two strings. __ bind(&string_add_runtime); __ TailCallRuntime(Runtime::kStringAdd, 2, 1); if (call_builtin.is_linked()) { __ bind(&call_builtin); __ InvokeBuiltin(builtin_id, JUMP_FUNCTION); } } void StringAddStub::GenerateConvertArgument(MacroAssembler* masm, int stack_offset, Register arg, Register scratch1, Register scratch2, Register scratch3, Register scratch4, Label* slow) { // First check if the argument is already a string. Label not_string, done; __ JumpIfSmi(arg, &not_string); __ GetObjectType(arg, scratch1, scratch1); __ Branch(&done, lt, scratch1, Operand(FIRST_NONSTRING_TYPE)); // Check the number to string cache. Label not_cached; __ bind(&not_string); // Puts the cached result into scratch1. NumberToStringStub::GenerateLookupNumberStringCache(masm, arg, scratch1, scratch2, scratch3, scratch4, false, &not_cached); __ mov(arg, scratch1); __ sw(arg, MemOperand(sp, stack_offset)); __ jmp(&done); // Check if the argument is a safe string wrapper. __ bind(&not_cached); __ JumpIfSmi(arg, slow); __ GetObjectType(arg, scratch1, scratch2); // map -> scratch1. __ Branch(slow, ne, scratch2, Operand(JS_VALUE_TYPE)); __ lbu(scratch2, FieldMemOperand(scratch1, Map::kBitField2Offset)); __ li(scratch4, 1 << Map::kStringWrapperSafeForDefaultValueOf); __ And(scratch2, scratch2, scratch4); __ Branch(slow, ne, scratch2, Operand(scratch4)); __ lw(arg, FieldMemOperand(arg, JSValue::kValueOffset)); __ sw(arg, MemOperand(sp, stack_offset)); __ bind(&done); } void ICCompareStub::GenerateSmis(MacroAssembler* masm) { ASSERT(state_ == CompareIC::SMIS); Label miss; __ Or(a2, a1, a0); __ JumpIfNotSmi(a2, &miss); if (GetCondition() == eq) { // For equality we do not care about the sign of the result. __ Subu(v0, a0, a1); } else { // Untag before subtracting to avoid handling overflow. __ SmiUntag(a1); __ SmiUntag(a0); __ Subu(v0, a1, a0); } __ Ret(); __ bind(&miss); GenerateMiss(masm); } void ICCompareStub::GenerateHeapNumbers(MacroAssembler* masm) { ASSERT(state_ == CompareIC::HEAP_NUMBERS); Label generic_stub; Label unordered; Label miss; __ And(a2, a1, Operand(a0)); __ JumpIfSmi(a2, &generic_stub); __ GetObjectType(a0, a2, a2); __ Branch(&miss, ne, a2, Operand(HEAP_NUMBER_TYPE)); __ GetObjectType(a1, a2, a2); __ Branch(&miss, ne, a2, Operand(HEAP_NUMBER_TYPE)); // Inlining the double comparison and falling back to the general compare // stub if NaN is involved or FPU is unsupported. if (CpuFeatures::IsSupported(FPU)) { CpuFeatures::Scope scope(FPU); // Load left and right operand. __ Subu(a2, a1, Operand(kHeapObjectTag)); __ ldc1(f0, MemOperand(a2, HeapNumber::kValueOffset)); __ Subu(a2, a0, Operand(kHeapObjectTag)); __ ldc1(f2, MemOperand(a2, HeapNumber::kValueOffset)); Label fpu_eq, fpu_lt, fpu_gt; // Compare operands (test if unordered). __ c(UN, D, f0, f2); // Don't base result on status bits when a NaN is involved. __ bc1t(&unordered); __ nop(); // Test if equal. __ c(EQ, D, f0, f2); __ bc1t(&fpu_eq); __ nop(); // Test if unordered or less (unordered case is already handled). __ c(ULT, D, f0, f2); __ bc1t(&fpu_lt); __ nop(); // Otherwise it's greater. __ bc1f(&fpu_gt); __ nop(); // Return a result of -1, 0, or 1. __ bind(&fpu_eq); __ li(v0, Operand(EQUAL)); __ Ret(); __ bind(&fpu_lt); __ li(v0, Operand(LESS)); __ Ret(); __ bind(&fpu_gt); __ li(v0, Operand(GREATER)); __ Ret(); __ bind(&unordered); } CompareStub stub(GetCondition(), strict(), NO_COMPARE_FLAGS, a1, a0); __ bind(&generic_stub); __ Jump(stub.GetCode(), RelocInfo::CODE_TARGET); __ bind(&miss); GenerateMiss(masm); } void ICCompareStub::GenerateSymbols(MacroAssembler* masm) { ASSERT(state_ == CompareIC::SYMBOLS); Label miss; // Registers containing left and right operands respectively. Register left = a1; Register right = a0; Register tmp1 = a2; Register tmp2 = a3; // Check that both operands are heap objects. __ JumpIfEitherSmi(left, right, &miss); // Check that both operands are symbols. __ lw(tmp1, FieldMemOperand(left, HeapObject::kMapOffset)); __ lw(tmp2, FieldMemOperand(right, HeapObject::kMapOffset)); __ lbu(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset)); __ lbu(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset)); STATIC_ASSERT(kSymbolTag != 0); __ And(tmp1, tmp1, Operand(tmp2)); __ And(tmp1, tmp1, kIsSymbolMask); __ Branch(&miss, eq, tmp1, Operand(zero_reg)); // Make sure a0 is non-zero. At this point input operands are // guaranteed to be non-zero. ASSERT(right.is(a0)); STATIC_ASSERT(EQUAL == 0); STATIC_ASSERT(kSmiTag == 0); __ mov(v0, right); // Symbols are compared by identity. __ Ret(ne, left, Operand(right)); __ li(v0, Operand(Smi::FromInt(EQUAL))); __ Ret(); __ bind(&miss); GenerateMiss(masm); } void ICCompareStub::GenerateStrings(MacroAssembler* masm) { ASSERT(state_ == CompareIC::STRINGS); Label miss; // Registers containing left and right operands respectively. Register left = a1; Register right = a0; Register tmp1 = a2; Register tmp2 = a3; Register tmp3 = t0; Register tmp4 = t1; Register tmp5 = t2; // Check that both operands are heap objects. __ JumpIfEitherSmi(left, right, &miss); // Check that both operands are strings. This leaves the instance // types loaded in tmp1 and tmp2. __ lw(tmp1, FieldMemOperand(left, HeapObject::kMapOffset)); __ lw(tmp2, FieldMemOperand(right, HeapObject::kMapOffset)); __ lbu(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset)); __ lbu(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset)); STATIC_ASSERT(kNotStringTag != 0); __ Or(tmp3, tmp1, tmp2); __ And(tmp5, tmp3, Operand(kIsNotStringMask)); __ Branch(&miss, ne, tmp5, Operand(zero_reg)); // Fast check for identical strings. Label left_ne_right; STATIC_ASSERT(EQUAL == 0); STATIC_ASSERT(kSmiTag == 0); __ Branch(&left_ne_right, ne, left, Operand(right), USE_DELAY_SLOT); __ mov(v0, zero_reg); // In the delay slot. __ Ret(); __ bind(&left_ne_right); // Handle not identical strings. // Check that both strings are symbols. If they are, we're done // because we already know they are not identical. ASSERT(GetCondition() == eq); STATIC_ASSERT(kSymbolTag != 0); __ And(tmp3, tmp1, Operand(tmp2)); __ And(tmp5, tmp3, Operand(kIsSymbolMask)); Label is_symbol; __ Branch(&is_symbol, eq, tmp5, Operand(zero_reg), USE_DELAY_SLOT); __ mov(v0, a0); // In the delay slot. // Make sure a0 is non-zero. At this point input operands are // guaranteed to be non-zero. ASSERT(right.is(a0)); __ Ret(); __ bind(&is_symbol); // Check that both strings are sequential ASCII. Label runtime; __ JumpIfBothInstanceTypesAreNotSequentialAscii(tmp1, tmp2, tmp3, tmp4, &runtime); // Compare flat ASCII strings. Returns when done. StringCompareStub::GenerateFlatAsciiStringEquals( masm, left, right, tmp1, tmp2, tmp3); // Handle more complex cases in runtime. __ bind(&runtime); __ Push(left, right); __ TailCallRuntime(Runtime::kStringEquals, 2, 1); __ bind(&miss); GenerateMiss(masm); } void ICCompareStub::GenerateObjects(MacroAssembler* masm) { ASSERT(state_ == CompareIC::OBJECTS); Label miss; __ And(a2, a1, Operand(a0)); __ JumpIfSmi(a2, &miss); __ GetObjectType(a0, a2, a2); __ Branch(&miss, ne, a2, Operand(JS_OBJECT_TYPE)); __ GetObjectType(a1, a2, a2); __ Branch(&miss, ne, a2, Operand(JS_OBJECT_TYPE)); ASSERT(GetCondition() == eq); __ Subu(v0, a0, Operand(a1)); __ Ret(); __ bind(&miss); GenerateMiss(masm); } void ICCompareStub::GenerateMiss(MacroAssembler* masm) { __ Push(a1, a0); __ push(ra); // Call the runtime system in a fresh internal frame. ExternalReference miss = ExternalReference(IC_Utility(IC::kCompareIC_Miss), masm->isolate()); __ EnterInternalFrame(); __ Push(a1, a0); __ li(t0, Operand(Smi::FromInt(op_))); __ push(t0); __ CallExternalReference(miss, 3); __ LeaveInternalFrame(); // Compute the entry point of the rewritten stub. __ Addu(a2, v0, Operand(Code::kHeaderSize - kHeapObjectTag)); // Restore registers. __ pop(ra); __ pop(a0); __ pop(a1); __ Jump(a2); } void DirectCEntryStub::Generate(MacroAssembler* masm) { // No need to pop or drop anything, LeaveExitFrame will restore the old // stack, thus dropping the allocated space for the return value. // The saved ra is after the reserved stack space for the 4 args. __ lw(t9, MemOperand(sp, kCArgsSlotsSize)); if (FLAG_debug_code && EnableSlowAsserts()) { // In case of an error the return address may point to a memory area // filled with kZapValue by the GC. // Dereference the address and check for this. __ lw(t0, MemOperand(t9)); __ Assert(ne, "Received invalid return address.", t0, Operand(reinterpret_cast<uint32_t>(kZapValue))); } __ Jump(t9); } void DirectCEntryStub::GenerateCall(MacroAssembler* masm, ExternalReference function) { __ li(t9, Operand(function)); this->GenerateCall(masm, t9); } void DirectCEntryStub::GenerateCall(MacroAssembler* masm, Register target) { __ Move(t9, target); __ AssertStackIsAligned(); // Allocate space for arg slots. __ Subu(sp, sp, kCArgsSlotsSize); // Block the trampoline pool through the whole function to make sure the // number of generated instructions is constant. Assembler::BlockTrampolinePoolScope block_trampoline_pool(masm); // We need to get the current 'pc' value, which is not available on MIPS. Label find_ra; masm->bal(&find_ra); // ra = pc + 8. masm->nop(); // Branch delay slot nop. masm->bind(&find_ra); const int kNumInstructionsToJump = 6; masm->addiu(ra, ra, kNumInstructionsToJump * kPointerSize); // Push return address (accessible to GC through exit frame pc). // This spot for ra was reserved in EnterExitFrame. masm->sw(ra, MemOperand(sp, kCArgsSlotsSize)); masm->li(ra, Operand(reinterpret_cast<intptr_t>(GetCode().location()), RelocInfo::CODE_TARGET), true); // Call the function. masm->Jump(t9); // Make sure the stored 'ra' points to this position. ASSERT_EQ(kNumInstructionsToJump, masm->InstructionsGeneratedSince(&find_ra)); } MaybeObject* StringDictionaryLookupStub::GenerateNegativeLookup( MacroAssembler* masm, Label* miss, Label* done, Register receiver, Register properties, String* name, Register scratch0) { // If names of slots in range from 1 to kProbes - 1 for the hash value are // not equal to the name and kProbes-th slot is not used (its name is the // undefined value), it guarantees the hash table doesn't contain the // property. It's true even if some slots represent deleted properties // (their names are the null value). for (int i = 0; i < kInlinedProbes; i++) { // scratch0 points to properties hash. // Compute the masked index: (hash + i + i * i) & mask. Register index = scratch0; // Capacity is smi 2^n. __ lw(index, FieldMemOperand(properties, kCapacityOffset)); __ Subu(index, index, Operand(1)); __ And(index, index, Operand( Smi::FromInt(name->Hash() + StringDictionary::GetProbeOffset(i)))); // Scale the index by multiplying by the entry size. ASSERT(StringDictionary::kEntrySize == 3); // index *= 3. __ mov(at, index); __ sll(index, index, 1); __ Addu(index, index, at); Register entity_name = scratch0; // Having undefined at this place means the name is not contained. ASSERT_EQ(kSmiTagSize, 1); Register tmp = properties; __ sll(scratch0, index, 1); __ Addu(tmp, properties, scratch0); __ lw(entity_name, FieldMemOperand(tmp, kElementsStartOffset)); ASSERT(!tmp.is(entity_name)); __ LoadRoot(tmp, Heap::kUndefinedValueRootIndex); __ Branch(done, eq, entity_name, Operand(tmp)); if (i != kInlinedProbes - 1) { // Stop if found the property. __ Branch(miss, eq, entity_name, Operand(Handle<String>(name))); // Check if the entry name is not a symbol. __ lw(entity_name, FieldMemOperand(entity_name, HeapObject::kMapOffset)); __ lbu(entity_name, FieldMemOperand(entity_name, Map::kInstanceTypeOffset)); __ And(scratch0, entity_name, Operand(kIsSymbolMask)); __ Branch(miss, eq, scratch0, Operand(zero_reg)); // Restore the properties. __ lw(properties, FieldMemOperand(receiver, JSObject::kPropertiesOffset)); } } const int spill_mask = (ra.bit() | t2.bit() | t1.bit() | t0.bit() | a3.bit() | a2.bit() | a1.bit() | a0.bit()); __ MultiPush(spill_mask); __ lw(a0, FieldMemOperand(receiver, JSObject::kPropertiesOffset)); __ li(a1, Operand(Handle<String>(name))); StringDictionaryLookupStub stub(NEGATIVE_LOOKUP); MaybeObject* result = masm->TryCallStub(&stub); if (result->IsFailure()) return result; __ MultiPop(spill_mask); __ Branch(done, eq, v0, Operand(zero_reg)); __ Branch(miss, ne, v0, Operand(zero_reg)); return result; } // Probe the string dictionary in the |elements| register. Jump to the // |done| label if a property with the given name is found. Jump to // the |miss| label otherwise. // If lookup was successful |scratch2| will be equal to elements + 4 * index. void StringDictionaryLookupStub::GeneratePositiveLookup(MacroAssembler* masm, Label* miss, Label* done, Register elements, Register name, Register scratch1, Register scratch2) { // Assert that name contains a string. if (FLAG_debug_code) __ AbortIfNotString(name); // Compute the capacity mask. __ lw(scratch1, FieldMemOperand(elements, kCapacityOffset)); __ sra(scratch1, scratch1, kSmiTagSize); // convert smi to int __ Subu(scratch1, scratch1, Operand(1)); // Generate an unrolled loop that performs a few probes before // giving up. Measurements done on Gmail indicate that 2 probes // cover ~93% of loads from dictionaries. for (int i = 0; i < kInlinedProbes; i++) { // Compute the masked index: (hash + i + i * i) & mask. __ lw(scratch2, FieldMemOperand(name, String::kHashFieldOffset)); if (i > 0) { // Add the probe offset (i + i * i) left shifted to avoid right shifting // the hash in a separate instruction. The value hash + i + i * i is right // shifted in the following and instruction. ASSERT(StringDictionary::GetProbeOffset(i) < 1 << (32 - String::kHashFieldOffset)); __ Addu(scratch2, scratch2, Operand( StringDictionary::GetProbeOffset(i) << String::kHashShift)); } __ srl(scratch2, scratch2, String::kHashShift); __ And(scratch2, scratch1, scratch2); // Scale the index by multiplying by the element size. ASSERT(StringDictionary::kEntrySize == 3); // scratch2 = scratch2 * 3. __ mov(at, scratch2); __ sll(scratch2, scratch2, 1); __ Addu(scratch2, scratch2, at); // Check if the key is identical to the name. __ sll(at, scratch2, 2); __ Addu(scratch2, elements, at); __ lw(at, FieldMemOperand(scratch2, kElementsStartOffset)); __ Branch(done, eq, name, Operand(at)); } const int spill_mask = (ra.bit() | t2.bit() | t1.bit() | t0.bit() | a3.bit() | a2.bit() | a1.bit() | a0.bit()) & ~(scratch1.bit() | scratch2.bit()); __ MultiPush(spill_mask); __ Move(a0, elements); __ Move(a1, name); StringDictionaryLookupStub stub(POSITIVE_LOOKUP); __ CallStub(&stub); __ mov(scratch2, a2); __ MultiPop(spill_mask); __ Branch(done, ne, v0, Operand(zero_reg)); __ Branch(miss, eq, v0, Operand(zero_reg)); } void StringDictionaryLookupStub::Generate(MacroAssembler* masm) { // Registers: // result: StringDictionary to probe // a1: key // : StringDictionary to probe. // index_: will hold an index of entry if lookup is successful. // might alias with result_. // Returns: // result_ is zero if lookup failed, non zero otherwise. Register result = v0; Register dictionary = a0; Register key = a1; Register index = a2; Register mask = a3; Register hash = t0; Register undefined = t1; Register entry_key = t2; Label in_dictionary, maybe_in_dictionary, not_in_dictionary; __ lw(mask, FieldMemOperand(dictionary, kCapacityOffset)); __ sra(mask, mask, kSmiTagSize); __ Subu(mask, mask, Operand(1)); __ lw(hash, FieldMemOperand(key, String::kHashFieldOffset)); __ LoadRoot(undefined, Heap::kUndefinedValueRootIndex); for (int i = kInlinedProbes; i < kTotalProbes; i++) { // Compute the masked index: (hash + i + i * i) & mask. // Capacity is smi 2^n. if (i > 0) { // Add the probe offset (i + i * i) left shifted to avoid right shifting // the hash in a separate instruction. The value hash + i + i * i is right // shifted in the following and instruction. ASSERT(StringDictionary::GetProbeOffset(i) < 1 << (32 - String::kHashFieldOffset)); __ Addu(index, hash, Operand( StringDictionary::GetProbeOffset(i) << String::kHashShift)); } else { __ mov(index, hash); } __ srl(index, index, String::kHashShift); __ And(index, mask, index); // Scale the index by multiplying by the entry size. ASSERT(StringDictionary::kEntrySize == 3); // index *= 3. __ mov(at, index); __ sll(index, index, 1); __ Addu(index, index, at); ASSERT_EQ(kSmiTagSize, 1); __ sll(index, index, 2); __ Addu(index, index, dictionary); __ lw(entry_key, FieldMemOperand(index, kElementsStartOffset)); // Having undefined at this place means the name is not contained. __ Branch(&not_in_dictionary, eq, entry_key, Operand(undefined)); // Stop if found the property. __ Branch(&in_dictionary, eq, entry_key, Operand(key)); if (i != kTotalProbes - 1 && mode_ == NEGATIVE_LOOKUP) { // Check if the entry name is not a symbol. __ lw(entry_key, FieldMemOperand(entry_key, HeapObject::kMapOffset)); __ lbu(entry_key, FieldMemOperand(entry_key, Map::kInstanceTypeOffset)); __ And(result, entry_key, Operand(kIsSymbolMask)); __ Branch(&maybe_in_dictionary, eq, result, Operand(zero_reg)); } } __ bind(&maybe_in_dictionary); // If we are doing negative lookup then probing failure should be // treated as a lookup success. For positive lookup probing failure // should be treated as lookup failure. if (mode_ == POSITIVE_LOOKUP) { __ mov(result, zero_reg); __ Ret(); } __ bind(&in_dictionary); __ li(result, 1); __ Ret(); __ bind(&not_in_dictionary); __ mov(result, zero_reg); __ Ret(); } #undef __ } } // namespace v8::internal #endif // V8_TARGET_ARCH_MIPS
dc00c06ff9cd380c666dac33e3593ec673e54a82
0deb187582752608ac6ca27f43936200cf016001
/ProcessNode.h
1bbde79ae71169a0bee716b8873958d499cf169a
[]
no_license
cainiao2hao/cmonitor
c8880eea0b716480380ed9f29f3b9e6c3ec3dbbe
d90d867d7a00f26f0052aedec6a4278462378805
refs/heads/master
2016-09-05T11:55:15.202929
2013-06-20T03:32:20
2013-06-20T03:32:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
659
h
#pragma once #include <stdio.h> #include <cstring> #include <iostream> #include <unistd.h> #include <pwd.h> #include<sys/time.h> #include<sys/resource.h> #include <map> #include "grab-packet.h" #include <dirent.h> using namespace std; #define SYS 0 #define PRO 1 extern int TOTALMEM; class ProcessNode { public: char path[20], UserName[20], ProName[20], state; int pid, uid, mem, pr, totalmem; int cputime[2][5], pos, cpup; int in[5], out[5], p, intotal, outtotal; double memp, in_speed, out_speed; ProcessNode(char* s); ProcessNode(); void freshspeed(); void get_info_by_linkname(char * linkname); void fresh(); };
b35b32127d2a85c17ce8aa48c7de451eff316eea
2203f9e82de6157d337aae1fdffcbb11def70a62
/testdata/samplecdp/config/catering/submissions/wrong_answer/bad2.cpp
7aa0c9e70d3926e633e9ae09b32b31d2dc60b103
[]
no_license
Kamo98/DIPLOM_NEW
c55b59ccd0610d4d2867619ca40c9fed0957a786
4434a43acedc44fc7b041214f66204a4936ffe6b
refs/heads/master
2023-04-27T18:22:32.869058
2020-05-21T13:21:30
2020-05-21T13:21:30
265,855,486
0
0
null
2021-05-12T00:29:54
2020-05-21T13:27:35
Java
UTF-8
C++
false
false
1,282
cpp
#include<iostream> using namespace std; const int MAXN = 100; const int MAXK = 100; long table[MAXN+1][MAXN+1][MAXK+1]; // table[i][k][k] = optimal cost for first i events // with one set a event j using k sets of equipment long cost[MAXN+1][MAXN+1]; int main() { int n, nSets; cin >> n >> nSets; if (nSets > n) nSets = n; for(int i=0; i<n; i++) { for(int j=i+1; j<=n; j++) { cin >> cost[i][j]; } } table[1][1][1] = cost[0][1]; for(int i=2; i<=n; i++) { table[i][i][1] = table[i-1][i-1][1] + cost[i-1][i]; } for(int i=2; i<=n; i++) { for(int j=1; j<i; j++) table[i][j][1] = table[n][n][1]+1; } for(int k=2; k<=nSets; k++) { for(int i=2; i<=n; i++) { for(int j=1; j<i; j++) { int ans = table[i-1][j][k-1]; table[i][i][k] = ans; for(int l=1; l<j; l++) { if (table[i][l][k] + cost[l][j] < ans) ans = table[i][l][k] + cost[l][k]; } if (table[i-1][j][k-1] + cost[0][i] < ans) ans = table[i-1][j][k-1] + cost[0][i]; table[i][j][k] = ans; if (ans < table[i][i][k]) table[i][i][k] = ans; } } } cout << table[n][n][nSets] << endl; for(int i=1; i<=n; i++) for(int j=1; j<=i; j++) for(int k=1; k<=nSets; k++) cout << "i,j,k=" << i << ',' << j << ',' << k << ": " << table[i][j][k] << endl; }
9ce4fc49f60536c2a77b14e7a2ba3bd572f4eebc
bbcaaebddba6c2c422c75e7fa6614e75db033d1c
/Qt/Examples/Qt-5.9/multimediawidgets/camera/videosettings.h
416761d06f64083e569056102f509c600f575481
[]
no_license
heatherThida/CS10
178862a55adb35bb1ba22004d401010a93046e9b
b05d1c30359943470cbbd348d58d2bd4b5148fae
refs/heads/master
2020-12-03T04:01:23.896399
2017-07-26T19:12:38
2017-07-26T19:12:38
95,803,381
1
1
null
null
null
null
UTF-8
C++
false
false
3,003
h
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef VIDEOSETTINGS_H #define VIDEOSETTINGS_H #include <QDialog> #include <QAudioEncoderSettings> #include <QVideoEncoderSettings> QT_BEGIN_NAMESPACE class QComboBox; class QMediaRecorder; namespace Ui { class VideoSettingsUi; } QT_END_NAMESPACE class VideoSettings : public QDialog { Q_OBJECT public: VideoSettings(QMediaRecorder *mediaRecorder, QWidget *parent = 0); ~VideoSettings(); QAudioEncoderSettings audioSettings() const; void setAudioSettings(const QAudioEncoderSettings&); QVideoEncoderSettings videoSettings() const; void setVideoSettings(const QVideoEncoderSettings&); QString format() const; void setFormat(const QString &format); protected: void changeEvent(QEvent *e) override; private: QVariant boxValue(const QComboBox*) const; void selectComboBoxItem(QComboBox *box, const QVariant &value); Ui::VideoSettingsUi *ui; QMediaRecorder *mediaRecorder; }; #endif // VIDEOSETTINGS_H
8623d4da501f0c21e9bed544ccaf0ef47e7e7aaa
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-cloudsearch/source/model/DeleteExpressionRequest.cpp
13106a38db60363a77f77a18f9010476fa6847eb
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
1,477
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/cloudsearch/model/DeleteExpressionRequest.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> using namespace Aws::CloudSearch::Model; using namespace Aws::Utils; DeleteExpressionRequest::DeleteExpressionRequest() : m_domainNameHasBeenSet(false), m_expressionNameHasBeenSet(false) { } Aws::String DeleteExpressionRequest::SerializePayload() const { Aws::StringStream ss; ss << "Action=DeleteExpression&"; if(m_domainNameHasBeenSet) { ss << "DomainName=" << StringUtils::URLEncode(m_domainName.c_str()) << "&"; } if(m_expressionNameHasBeenSet) { ss << "ExpressionName=" << StringUtils::URLEncode(m_expressionName.c_str()) << "&"; } ss << "Version=2013-01-01"; return ss.str(); } void DeleteExpressionRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const { uri.SetQueryString(SerializePayload()); }
77d9b790211f89ea93a21bb6249feb8ec78dc73c
ad5f0634b87cfec512664edc1cd57202ab97544d
/logger.cc
3f43421bc64676dcf0132c1ce4cd24431978cb81
[]
no_license
WarEric/tinylog
1cd830da17cad4b6614ab6f5257699c9fe0bd74e
ad0152680997f63adb235635c13db306edb056ce
refs/heads/master
2020-04-05T04:17:04.801830
2019-01-05T02:26:00
2019-01-05T02:26:00
156,545,046
0
0
null
null
null
null
UTF-8
C++
false
false
8,634
cc
/** * by [email protected] 2018-10-21 **/ #include <iostream> #include <stdlib.h> #include <cstring> #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include "logger.h" namespace tinylog{ Logger::Logger():clilevel(INFO) { fd = -1; opencli = 1; if(pthread_mutex_init(&mutex, NULL) != 0) { std::cerr << "logger pthread_mutex_init fail" << std::endl; } } Logger::Logger(std::string file, LEVEL lev):fdlevel(lev) { opencli = 0; if((fd = open(file.c_str(), O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0){ std::cerr << "create logfile " << file << " fail." << std::endl; fd = -1; } if(pthread_mutex_init(&mutex, NULL) != 0) { std::cerr << "logger pthread_mutex_init fail" << std::endl; } } Logger::Logger(int openflag, LEVEL lev):clilevel(lev) { fd = -1; opencli = openflag; if(pthread_mutex_init(&mutex, NULL) != 0) { std::cerr << "logger pthread_mutex_init fail" << std::endl; } } Logger::Logger(std::string file, LEVEL filelev, int openflag, LEVEL clilev):fdlevel(filelev), clilevel(clilev) { opencli = openflag; if((fd = open(file.c_str(), O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0){ std::cerr << "create logfile " << file << " fail." << std::endl; fd = -1; } if(pthread_mutex_init(&mutex, NULL) != 0) { std::cerr << "logger pthread_mutex_init fail" << std::endl; } } Logger::~Logger() { if(fd > 0) close(fd); pthread_mutex_destroy(&mutex); if(opencli) write(STDOUT_FILENO, "\033[0m", strlen("\033[0m")); } void Logger::trace(std::string msg) { pthread_mutex_lock(&mutex); //block all sinal sigset_t newmask, oldmask; sigfillset(&newmask); if(sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) { std::string str("logger sigprocmask SIG_BLOCK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } if(fd > 0) { if(fdlevel <= TRACE) write_log(TRACE, fd, msg); } if(opencli != 0) { if(clilevel <= TRACE) write_screen(TRACE, STDOUT_FILENO, msg); } //resume old singal if(sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) { std::string str("logger sigprocmask SIG_SETMASK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } pthread_mutex_unlock(&mutex); } void Logger::debug(std::string msg) { pthread_mutex_lock(&mutex); //block all sinal sigset_t newmask, oldmask; sigfillset(&newmask); if(sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) { std::string str("logger sigprocmask SIG_BLOCK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } if(fd > 0) { if(fdlevel <= DEBUG) write_log(DEBUG, fd, msg); } if(opencli != 0) { if(clilevel <= DEBUG) write_screen(DEBUG, STDOUT_FILENO, msg); } //resume old singal if(sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) { std::string str("logger sigprocmask SIG_SETMASK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } pthread_mutex_unlock(&mutex); } void Logger::info(std::string msg) { pthread_mutex_lock(&mutex); //block all sinal sigset_t newmask, oldmask; sigfillset(&newmask); if(sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) { std::string str("logger sigprocmask SIG_BLOCK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } if(fd > 0) { if(fdlevel <= INFO) write_log(INFO, fd, msg); } if(opencli != 0) { if(clilevel <= INFO) write_screen(INFO, STDOUT_FILENO, msg); } //resume old singal if(sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) { std::string str("logger sigprocmask SIG_SETMASK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } pthread_mutex_unlock(&mutex); } void Logger::warn(std::string msg) { pthread_mutex_lock(&mutex); //block all sinal sigset_t newmask, oldmask; sigfillset(&newmask); if(sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) { std::string str("logger sigprocmask SIG_BLOCK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } if(fd > 0) { if(fdlevel <= WARN) write_log(WARN, fd, msg); } if(opencli != 0) { if(clilevel <= WARN) write_screen(WARN, STDOUT_FILENO, msg); } //resume old singal if(sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) { std::string str("logger sigprocmask SIG_SETMASK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } pthread_mutex_unlock(&mutex); } void Logger::error(std::string msg) { pthread_mutex_lock(&mutex); //block all sinal sigset_t newmask, oldmask; sigfillset(&newmask); if(sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) { std::string str("logger sigprocmask SIG_BLOCK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } if(fd > 0) { if(fdlevel <= ERROR) write_log(ERROR, fd, msg); } if(opencli != 0) { if(clilevel <= ERROR) write_screen(ERROR, STDOUT_FILENO, msg); } //resume old singal if(sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) { std::string str("logger sigprocmask SIG_SETMASK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } pthread_mutex_unlock(&mutex); } void Logger::fatal(std::string msg) { pthread_mutex_lock(&mutex); //block all sinal sigset_t newmask, oldmask; sigfillset(&newmask); if(sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) { std::string str("logger sigprocmask SIG_BLOCK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } if(fd > 0) { if(fdlevel <= FATAL) write_log(FATAL, fd, msg); } if(opencli != 0) { if(clilevel <= FATAL) write_screen(FATAL, STDOUT_FILENO, msg); } //resume old singal if(sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) { std::string str("logger sigprocmask SIG_SETMASK error"); if(fd > 0) write_log(FATAL, fd, str); if(opencli) write_screen(FATAL, STDOUT_FILENO, str); exit(EXIT_FAILURE); } pthread_mutex_unlock(&mutex); } int Logger::write_log(LEVEL level, int fd, std::string msg) { switch(level){ case TRACE: msg.insert(0, " TRACE: "); break; case DEBUG: msg.insert(0, " DEBUG: "); break; case INFO: msg.insert(0, " INFO: "); break; case WARN: msg.insert(0, " WARN: "); break; case ERROR: msg.insert(0, " ERROR: "); break; case FATAL: msg.insert(0, " FATAL: "); break; default: break; } msg.insert(0, logtime()); msg.append("\n"); int n = write(fd, msg.c_str(), msg.size()); return n; } int Logger::write_screen(LEVEL level, int fd, std::string msg) { switch(level){ case TRACE: msg.insert(0, " TRACE: "); msg.insert(0, logtime()); msg.insert(0, "\033[36m"); //deepgreen break; case DEBUG: msg.insert(0, " DEBUG: "); msg.insert(0, logtime()); msg.insert(0, "\033[32m"); //green break; case INFO: msg.insert(0, " INFO: "); msg.insert(0, logtime()); msg.insert(0, "\033[34m"); //blue break; case WARN: msg.insert(0, " WARN: "); msg.insert(0, logtime()); msg.insert(0, "\033[35m"); //purple break; case ERROR: msg.insert(0, " ERROR: "); msg.insert(0, logtime()); msg.insert(0, "\033[33m"); //yellow break; case FATAL: msg.insert(0, " FATAL: "); msg.insert(0, logtime()); msg.insert(0, "\033[31m"); //red break; default: break; } msg.append("\033[0m\n"); int n = write(fd, msg.c_str(), msg.size()); return n; } /** * I got the time code from internet, though it isn't efficient. **/ std::string Logger::logtime() { struct timeval tv; char timeArray[40]; gettimeofday(&tv, NULL); memset(timeArray, 0, sizeof(timeArray)); strftime(timeArray, sizeof(timeArray) - 1, "%F %T", localtime(&tv.tv_sec)); std::string usecond(std::to_string(tv.tv_usec) + "(us) "); // blank is essential format usecond = usecond.substr(0, 6+4); std::stringstream ss; ss << std::string(timeArray) << "." << usecond; return ss.str(); } }
55b73631cb31b77a3d28fe32c14665298a2c51bd
bcf138c82fcba9acc7d7ce4d3a92618b06ebe7c7
/rdr2/0x159EF5B6EDCE00E8.cpp
c00896df97a49e32b9f22b789d4ace1640e0001c
[]
no_license
DeepWolf413/additional-native-data
aded47e042f0feb30057e753910e0884c44121a0
e015b2500b52065252ffbe3c53865fe3cdd3e06c
refs/heads/main
2023-07-10T00:19:54.416083
2021-08-12T16:00:12
2021-08-12T16:00:12
395,340,507
1
0
null
null
null
null
UTF-8
C++
false
false
724
cpp
// beat_outlaw_transport.ysc @ L13071 void func_335() { if (ENTITY::DOES_ENTITY_EXIST(iLocal_818)) { if (!func_50(iLocal_819, 16777216)) { if (AITRANSPORT::_0x159EF5B6EDCE00E8(uLocal_801[6], iLocal_818)) { if (ENTITY::HAS_ANIM_EVENT_FIRED(uLocal_801[6], 1403772282)) { func_24(&iLocal_819, 16777216); func_81(uLocal_801[6], 0); if (AITRANSPORT::_0x159EF5B6EDCE00E8(uLocal_801[6], iLocal_818)) { AITRANSPORT::_0x8886D83A430537FD(uLocal_801[6], 0); } } } } else if (AITRANSPORT::_0x159EF5B6EDCE00E8(uLocal_801[6], iLocal_818)) { AITRANSPORT::_0x8886D83A430537FD(uLocal_801[6], 0); } } }
13127c03476a26d115c3716239057cf5c0293d20
bf925ff377f37a33d20b357c1c8b1a7882cd4baf
/DNSRelay/DNSRelay.cpp
9e52e91577498f26ad85a6afd2de71eea7f52ad4
[]
no_license
PowerCui/DNSRelay
5811c474a7c51c71ffcf9fabfd1fbcab077a6b51
02dcff0ca94c60a9f21c297191d6e3f878a35d3e
refs/heads/main
2023-05-10T09:51:28.613578
2021-06-02T10:12:09
2021-06-02T10:12:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,161
cpp
#include <iostream> #include <WS2tcpip.h> #include "DNSRelay.h" #include "cache.h" #define _WINSOCK_DEPRECATED_NO_WARNINGS int main(int argc, char **argv) { if (parseArgu(argc, argv)) { init(); fd_set fdread; while (true) { FD_ZERO(&fdread); FD_SET(clientSock, &fdread); FD_SET(servSock, &fdread); TIMEVAL tv; //设置超时等待时间 tv.tv_sec = 0; tv.tv_usec = 500; int ret = select(0, &fdread, NULL, NULL, &tv); if (ret == SOCKET_ERROR) { printf("ERROR:select %d\n", WSAGetLastError()); } if (ret > 0) { if (FD_ISSET(clientSock, &fdread)) { clientReceive(); // printf("*"); } if (FD_ISSET(servSock, &fdread)); { serverReceive(); } } } /*int nonBlock = 1; ioctlsocket(clientSock, FIONBIO, (u_long FAR *)&nonBlock); ioctlsocket(servSock, FIONBIO, (u_long FAR *)&nonBlock); while (1) { clientReceive(); serverReceive(); }*/ } else { printf("argument error\n"); printf("set debugLevel\t\t\t-d/-D(more 'd' for higher level)\n" "set log file name\t\t-l/-L <log file name>\n" "set domain file\t\t\t-f/-F <domain list file>\n" "set host address\t\t-h/-F <address in decimalism>"); } closesocket(clientSock); closesocket(servSock); WSACleanup(); return 0; } bool init() { cacheTrie->tree; WSAStartup(MAKEWORD(2, 2), &wsaData); clientSock = socket(AF_INET, SOCK_DGRAM, 0); servSock = socket(AF_INET, SOCK_DGRAM, 0); if (clientSock == INVALID_SOCKET || servSock == INVALID_SOCKET) { printf("ERROR:socket open failed!\n"); return false; } memset(&clientSockAddr, 0, sizeof(clientSockAddr)); clientSockAddr.sin_family = AF_INET; clientSockAddr.sin_addr.s_addr = INADDR_ANY; clientSockAddr.sin_port = htons(53); memset(&servSockAddr, 0, sizeof(servSockAddr)); servSockAddr.sin_family = AF_INET; servSockAddr.sin_addr.s_addr = inet_addr(sAddress); servSockAddr.sin_port = htons(53); int on = 1; setsockopt(clientSock, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)); if (bind(clientSock, (SOCKADDR *)&clientSockAddr, addrLen) < 0) { printf("ERROR:Could not bind:%s\n", strerror(errno)); } switch (dLevel) { case mid: case high: char tmp[20] = {0}; inet_ntop(AF_INET, &sAddress, tmp, INET_ADDRSTRLEN); printf("DNS server :%s\n", sAddress); printf("Listening on port:53\n"); break; } for (int i = 0; i < ID_TABLE_SIZE; i++) { idTable[i].cliId = 0; idTable[i].exprieTime = 0; memset(&(idTable[i].cliAddr), 0, sizeof(struct sockaddr_in)); } logName = fopen(logFile, "a+"); //printf("%s", domainList); domain = fopen(domainList, "a+"); if (domain == NULL) { printf("ERROR:Domain list open failed\n"); exit(0); } /* pair<string, string> tmp; char buf[128]; char ip1[20]; while (!feof(domain)) { fscanf(domain, "%s", ip1); fscanf(domain, "%s", buf); unsigned len = strlen(buf); for (int i = 0; i < len; i++) { if (buf[i] >= 'A' && buf[i] <= 'Z') { buf[i] += 32; } } tmp.first = buf; tmp.second = ip1; list.push_back(tmp); }*/ cacheTrie = (struct Trie *)malloc(sizeof(struct Trie)); memset(cacheTrie->tree, 0, MAX_ROW * MAX_COL); tableTrie = (struct Trie *)malloc(sizeof(struct Trie)); memset(tableTrie->tree, 0, MAX_ROW * MAX_COL); cacheTrie->totalNode = 0; tableTrie->totalNode = 0; cacheSize = 0; char domainName[MAX_STR] = { 0 }; char ipAddr[MAX_STR] = { 0 }; unsigned char ip[4]; while (!feof(domain)) { fscanf(domain, "%s", ipAddr); fscanf(domain, "%s", domainName); tranIp(ip, ipAddr); insertNode(tableTrie, domainName, ip); } head = (struct Node *)malloc(sizeof(struct Node)); head->next = NULL; tail = head; for (int i = 0; i < ID_TABLE_SIZE; i++) { idTable[i].cliId = 0; idTable[i].exprieTime = 0; memset(&(idTable[i].cliAddr), 0, sizeof(struct sockaddr_in)); } return true; } int search(Packet *pkt) { struct source *s; struct question *q; int ret = -1; pkt->pktHead->QR = 1; pkt->pktHead->RA = 1; pkt->pktHead->rcode = 0; pkt->pktHead->ancount = 0; pkt->pktHead->nscount = 0; pkt->pktHead->arcount = 0; q = pkt->pktQuestion; printCache(); while (q) { s = (struct source *)malloc(sizeof(struct source)); memset(s, 0, sizeof(struct source)); s->name = strdup(q->qName); s->type = q->qType; s->Class = q->qClass; s->TTL = 3600; if (q->qType == 1) { s->rData = (char *)malloc(4 * sizeof(char)); s->rdLength = 4; if (findInCache((unsigned char *)s->rData, q->qName)) { switch (dLevel) { case mid: printf("Find in Cache\n"); break; case high: printf("Find in Cache %s\n", q->qName); } ret = 0; } else if (findInTable((unsigned char *)s->rData, q->qName)) { switch (dLevel) { case mid: printf("Find in Table\n"); break; case high: printf("Find in Table %s\n", q->qName); } ret = 0; } else { switch (dLevel) { case mid : case high: printf("Can't find in local\n"); } ret = -1; } if (s->rData[0] == 0 && s->rData[1] == 0 && s->rData[2] == 0 && s->rData[3] == 0) { switch (dLevel) { case mid: printf("Blocked\n"); break; case high: printf("Blocked %s", q->qName); } pkt->pktHead->rcode = 3; } if (ret == 0) { pkt->pktHead->ancount++; s->next = pkt->pktAnswer; pkt->pktAnswer = s; } else { free(s->name); free(s->rData); free(s); } } q = q->next; } return ret; } bool parseArgu(int argc, char **argv) { int dNum = 0; int32_t tmp; int i = 1; while (i <= argc - 1) { switch (argv[i][1]) { case 'd': case 'D': for (int j = 1; argv[i][j]; j++) { if (argv[i][j] == 'd' || argv[i][j] == 'D') { dNum++; } else { return false; } } std::cout << dNum; if (dNum > 3) { return false; } else { dLevel = (debugLevel)(dNum - 1); std::cout << dLevel; } i++; break; case 'l': case 'L': memcpy(logFile, argv[i+1], strlen(argv[i+1])); i += 2; break; case 'h': case 'H': if ((tmp = inet_addr(argv[i + 1])) > 0) { //std::cout << sizeof(uint32_t) << std::endl; //std::cout << std::hex << tmp << std::endl; memcpy(sAddress, argv[i + 1], strlen(argv[i + 1]) + 1); } else { return false; } i += 2; break; case 'f': case 'F': memcpy(domainList, argv[i+1], strlen(argv[i+1])); i += 2; break; } } return true; } void clientReceive() { //printf("C\n"); int pktLen = 0; unsigned char buff[BUFFER_SIZE]; Packet pkt; memset(&pkt, 0, sizeof(pkt)); pktLen = recvfrom(clientSock, (char*)buff, sizeof(buff), 0, (struct sockaddr *)&clientSockAddr, &addrLen); if (pktLen < 0) { printf("ERROR:receive packet from client error\n"); return; } else { switch (dLevel) { case low: printf("Receive a packet from client\n"); break; case mid: printf("Receive a packet from client:%s port:%d packet length:%d\n" , inet_ntoa(clientSockAddr.sin_addr) , ntohs(clientSockAddr.sin_port) , pktLen); break; case high: printf("Receive a packet from client:%s port:%d packet length:%d\n" , inet_ntoa(clientSockAddr.sin_addr) , ntohs(clientSockAddr.sin_port) , pktLen); printInHex(buff, pktLen); } } //printf("c\n"); if (!decodePkt(&pkt, (char *)buff, pktLen)) { printf("ERROR: Unpack packet error!\n"); //exit(0); } time_t t; struct tm *lt; time(&t); lt = localtime(&t); fprintf(logName, "Requsest:%d\n%d-%02d-%02d\n%02d:%02d:%02d\nclient %15s : %-5d\n%s\n\n" , requestCnt++, (1900 + lt->tm_year), (1 + lt->tm_mon), lt->tm_mday , lt->tm_hour, lt->tm_min, lt->tm_sec , inet_ntoa(clientSockAddr.sin_addr), ntohs(clientSockAddr.sin_port), pkt.pktQuestion->qName); if (search(&pkt) != -1) { unsigned pktLen; if (!(pktLen = encodePkt(&pkt,(char*)buff))) { printf("ERROR:Encode packet error\n"); } else { switch (dLevel) { case low: printf("Send to client\n"); break; case mid: printf("Send to client:%s port:%d\n" , inet_ntoa(clientSockAddr.sin_addr) , ntohs(clientSockAddr.sin_port)); break; case high: printf("Send to client:%s port:%d\n" , inet_ntoa(clientSockAddr.sin_addr) , ntohs(clientSockAddr.sin_port)); printInHex(buff, pktLen); break; } time(&t); lt = localtime(&t); fprintf(logName, "Response:%d\n%d-%02d-%02d\n%02d:%02d:%02d\nclient %15s : %-5d\n Q:%s A:%s\n\n" , requestCnt++, (1900 + lt->tm_year), (1 + lt->tm_mon), lt->tm_mday , lt->tm_hour, lt->tm_min, lt->tm_sec , inet_ntoa(clientSockAddr.sin_addr), ntohs(clientSockAddr.sin_port), pkt.pktQuestion->qName ,pkt.pktAnswer->rData); sendto(clientSock, (char *)buff, pktLen, 0, (struct sockaddr*)&clientSockAddr, addrLen); } } else { uint16_t i; for (i = 0; i < ID_TABLE_SIZE; i++) { if (idTable[i].exprieTime < time(NULL)) { break; } } if (i == ID_TABLE_SIZE) { printf("ERROR: idTable is full"); exit(0); } uint16_t servId = htons(i); idTable[i].cliAddr = clientSockAddr; idTable[i].cliId = pkt.pktHead->ID; idTable[i].exprieTime = time(NULL) + TIMEOUT; memcpy(buff, &servId, sizeof(uint16_t)); switch (dLevel) { case low: printf("Send to server\n"); break; case mid: printf("Send to server:%s port:%d id:%d len:%d\n" ,servSockAddr.sin_addr,servSockAddr.sin_port,i,pktLen); break; case high: printf("Send to server:%s port:%d id:%d len:%d\n" , inet_ntoa(servSockAddr.sin_addr), ntohs(servSockAddr.sin_port), servId, pktLen); printInHex(buff, pktLen); } time(&t); lt = localtime(&t); fprintf(logName, "Relay:%d\n%d-%02d-%02d\n%02d:%02d:%02d\nserver %15s : %-5d\n Q:%s\n\n" , requestCnt++, (1900 + lt->tm_year), (1 + lt->tm_mon), lt->tm_mday , lt->tm_hour, lt->tm_min, lt->tm_sec , inet_ntoa(servSockAddr.sin_addr), ntohs(servSockAddr.sin_port), pkt.pktQuestion->qName); sendto(servSock, (char*)buff, pktLen, 0, (struct sockaddr*)&servSockAddr, sizeof(servSockAddr)); } freePkt(&pkt); } void serverReceive() { struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; if (setsockopt(servSock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) < 0) { printf("socket option SO_RCVTIMEO not support\n"); return; } int len = 0; char buf[BUFFER_SIZE]; Packet pkt; memset(&pkt, 0, sizeof(struct packet)); len = recvfrom(servSock, buf, sizeof(buf), 0, (struct sockaddr *)&servSockAddr, &addrLen); if (len > 0) printInHex((unsigned char*)buf, len); //printInHex((unsigned char*)buf, len); if (len == EWOULDBLOCK || len == EAGAIN) { printf("server timeout\n"); return; } //printf("s\n"); if (len < 0 || !decodePkt(&pkt, buf, len)) { printf("Error:Receive from server error\n"); return; } switch (dLevel) { case low: printf("Receive from server\n"); break; case mid: printf("Receive from server:%s port:%d id:%d len:%d\n" , inet_ntoa(servSockAddr.sin_addr), ntohs(servSockAddr.sin_port), pkt.pktHead->ID, len); break; case high: printf("Receive from server:%s port:%d id:%d len:%d\n" , inet_ntoa(servSockAddr.sin_addr), ntohs(servSockAddr.sin_port), pkt.pktHead->ID, len); printInHex((unsigned char*)buf, len); } time_t t; struct tm *lt; time(&t); lt = localtime(&t); fprintf(logName, "Receive:%d\n%d-%02d-%02d\n%02d:%02d:%02d\nserver %15s : %-5d\n Q:%s\n\n" , requestCnt++, (1900 + lt->tm_year), (1 + lt->tm_mon), lt->tm_mday , lt->tm_hour, lt->tm_min, lt->tm_sec , inet_ntoa(servSockAddr.sin_addr), ntohs(servSockAddr.sin_port), pkt.pktQuestion->qName); uint16_t nId = pkt.pktHead->ID; uint16_t clientId = htons(idTable[nId].cliId); memcpy(buf, &clientId, sizeof(uint16_t)); struct sockaddr_in ca = idTable[nId].cliAddr; //idTable[nId].exprieTime = 0; time(&t); lt = localtime(&t); fprintf(logName, "Reponse:%d\n%d-%02d-%02d\n%02d:%02d:%02d\nclient %15s : %-5d\n Q:%s\n\n" , requestCnt++, (1900 + lt->tm_year), (1 + lt->tm_mon), lt->tm_mday , lt->tm_hour, lt->tm_min, lt->tm_sec , inet_ntoa(clientSockAddr.sin_addr), ntohs(clientSockAddr.sin_port), pkt.pktQuestion->qName); sendto(clientSock, buf, len, 0, (struct sockaddr *)&ca, sizeof(ca)); if (pkt.pktHead->ancount) { struct source *s = pkt.pktAnswer; while (s) { if (s->type == 1) { char *domainName = s->name; unsigned char *address = (unsigned char *)s->rData; updateCache(address, domainName); printCache(); } s = s->next; } } freePkt(&pkt); } void printInHex(unsigned char *buff, unsigned len) { for (int i = 0; i < len; i++) { printf("%02x ", buff[i]); if (i % 16 == 15) { printf("\n"); } } printf("\n"); } //bool searchInList(Packet *pkt) //{ // Question *q = pkt->pktQuestion; // Source *r = (struct source*)malloc(sizeof(struct source)); // while (q) // { // int i; // for (i = 0; i < list.size(); i++) // { // if (list[i].first == q->qName) // { // if (list[i].second != "0.0.0.0") // { // r->name = strdup(q->qName); // r->type = q->qType; // r->Class = q->qClass; // r->rdLength = 4; // r->TTL = 3600; // r->rData = (char *)malloc(r->rdLength * (sizeof(char))); // unsigned long tmp = inet_addr(list[i].second.c_str()); // memcpy(r->rData, &tmp, 4); // r->next = pkt->pktAnswer; // pkt->pktAnswer = r; // (pkt->pktHead->ancount)++; // } // switch (dLevel) // { // case mid: // printf("Find in local file\n"); // break; // case high: // printf("Find in local file,line:%d domain:%s ip:%s\n" // , i,list[i].first.c_str(),list[i].second.c_str()); // } // return true; // } // } // if (i == list.size()) // { // switch (dLevel) // { // case mid: // printf("Not find in local file\n"); // break; // case high: // printf("Not find in local file domain:%s\n", q->qName); // } // return false; // } // q = q->next; // } // return true; //} bool decodePkt(Packet *pkt, char *buff, unsigned int len) { //printf("*"); pkt->pktHead = (struct header*)malloc(sizeof(struct header)); /*pkt->pktQuestion = (struct question*)malloc(sizeof(struct question)); pkt->pktQuestion->next = NULL;*/ char *rawBuf = buff; getHeader(pkt->pktHead,buff); Header * head = pkt->pktHead; switch (dLevel) { case mid: printf("Header decode\n"); break; case high: printf("Header decode id:%d qr:%d opcode:%d AA:%d TC:%d RD:%d \n\ RA:%d rcode:%d qdcount:%d ancount:%d nscount:%d arcount:%d\n" , head->ID, head->QR, head->opcode, head->AA, head->TC, head->RD ,head->RA,head->rcode,head->qdcount,head->ancount,head->nscount ,head->arcount); } decodeQuestion(pkt, &buff); for (int i = 0; i < pkt->pktHead->ancount; i++) { if (i == 0) { pkt->pktAnswer = (struct source*)malloc(sizeof(struct source)); pkt->pktAnswer->next = NULL; } else { Source *tmp = (struct source*)malloc(sizeof(struct source)); tmp->next = pkt->pktAnswer; pkt->pktAnswer = tmp; } decodeSource(pkt->pktAnswer, &buff, rawBuf); switch (dLevel) { case mid: printf("Decode answer\n"); break; case high: printf("Decode answer name:%s type:%d class:%d ttl:%d rdLength:%d \n" ,pkt->pktAnswer->name,pkt->pktAnswer->type,pkt->pktAnswer->Class,pkt->pktAnswer->TTL ,pkt->pktAnswer->rdLength); } } for (int i = 0; i < pkt->pktHead->nscount; i++) { if (i == 0) { pkt->pktAuthority = (struct source*)malloc(sizeof(struct source)); pkt->pktAuthority->next = NULL; } else { Source *tmp = (struct source*)malloc(sizeof(struct source)); tmp->next = pkt->pktAuthority; pkt->pktAuthority= tmp; } char * tmploc = rawBuf; decodeSource(pkt->pktAuthority, &buff, rawBuf); switch (dLevel) { case mid: printf("Decode authority\n"); break; case high: printf("Decode authority name:%s type:%d class:%d ttl:%d rdLength:%d \n" , pkt->pktAuthority->name, pkt->pktAuthority->type, pkt->pktAuthority->Class, pkt->pktAuthority->TTL , pkt->pktAuthority->rdLength); } } return true; } bool decodeSource(Source *s, char **buf, char *raw) { char *name = decodeDomain(buf,raw ); s->name = name; if (!name) { printf("Error:Decode Source domain name failed\n"); return false; } s->type = get16bit(buf); s->Class = get16bit(buf); s->TTL = get32bit(buf); s->rdLength = get16bit(buf); s->rData = (char *)malloc(sizeof(char)*(s->rdLength + 1)); memcpy(s->rData, *buf , s->rdLength + 1); (*buf) += s->rdLength; } bool decodeQuestion(Packet *pkt, char **buf) { char *rawBuf = *buf; (*buf) += 12; int num = pkt->pktHead->qdcount; for (int i = 0; i < num; i++) { if (i == 0) { pkt->pktQuestion = (struct question*)malloc(sizeof(struct question)); pkt->pktQuestion->next = NULL; } else { Question * newQ; newQ = (struct question*)malloc(sizeof(struct question)); newQ->next = pkt->pktQuestion; pkt->pktQuestion = newQ; } pkt->pktQuestion->qName = decodeDomain(buf, rawBuf); pkt->pktQuestion->qType = get16bit(buf); pkt->pktQuestion->qClass = get16bit(buf); switch (dLevel) { case mid: printf("Decode question %d\n", i); break; case high: printf("Decode question %d qName:%s qType:%d qClass:%d\n", i , pkt->pktQuestion->qName, pkt->pktQuestion->qType, pkt->pktQuestion->qClass); } } return true; } char * decodeDomain(char **buf, char *raw) { if (**buf == '\0') { (*buf)++; return strdup("\0"); } //char *rawBuf = *buf; unsigned char len = 0; uint16_t offset = 0; //(*buf) += loc; char * reVal; char name[254] = {0}; unsigned nameLen = 0; while ((len = (char)**buf)!=0) { if (len >= 0xc0) { (**buf) = (**buf) & (~COMPRESSMUSK); offset = get16bit(buf); *((*buf) - 2) = *((*buf) - 2) | COMPRESSMUSK; char *newLoc = raw + offset; char * tmp = decodeDomain(&newLoc,raw); if (!tmp) { return NULL; } memcpy(name + strlen(name), tmp, strlen(tmp)+1); reVal = (char*)malloc((strlen(name)+1) * sizeof(char)); memcpy(reVal, name, strlen(name)+1); return reVal; } else { (*buf)++; for (int i = 0; i < len; i++,nameLen++) { name[nameLen] = get8bit(buf); } name[nameLen] = '.'; nameLen++; } } name[nameLen - 1] = '\0'; reVal = (char*)malloc((strlen(name)+1) * sizeof(char)); memset(reVal, 0, strlen(name)+1); memcpy(reVal, name, strlen(name)+1); if (get8bit(buf)) { return NULL; } return reVal; } void getHeader(Header *head, char *buff) { head->ID = get16bit(&buff); uint32_t tmp; tmp = get16bit(&buff); head->QR = (tmp & QRMUSK) >> 15; head->opcode = (tmp & OPCODEMUSK) >> 11; head->AA = (tmp & AAMUSK) >> 10; head->TC = (tmp & TCMUSK) >> 9; head->RD = (tmp & RDMUSK) >> 8; head->RA = (tmp & RAMUSK) >> 7; head->rcode = tmp & RCODEMUSK; head->qdcount = get16bit(&buff); head->ancount = get16bit(&buff); head->nscount = get16bit(&buff); head->arcount = get16bit(&buff); } unsigned encodePkt(Packet *pkt, char *buff) { char *rawBuf = buff; //pkt->pktHead = (struct header*)malloc(sizeof(struct header)); setHeader(pkt->pktHead, buff); buff += 12; for (int i = 0; i < pkt->pktHead->qdcount; i++) { /*if (i == 0) { pkt->pktQuestion = (struct question *)malloc(sizeof(struct question)); } else { Question *tmp; tmp = (struct question *)malloc(sizeof(struct question)); tmp->next = pkt->pktQuestion; pkt->pktQuestion = tmp; }*/ encodeQuestion(pkt->pktQuestion, &buff); } for (int i = 0; i < pkt->pktHead->ancount; i++) { encodeSource(pkt->pktAnswer, &buff); } return buff - rawBuf; } void encodeDomain(char *name, char **buf) { int labLen[10]; int labCount = 0; int len = 0; int nameLoc = 0; for (int i = 0; i < strlen(name); i++, len++) { if (name[i] == '.') { labLen[labCount] = len; len = -1; labCount++; } } labLen[labCount] = len; labCount++; for (int i = 0; i < labCount; i++) { set8bit(buf, (uint8_t)labLen[i]); if (i != 0) { nameLoc++; } for (int j = 0; j < labLen[i]; j++) { set8bit(buf, (uint8_t)name[nameLoc]); nameLoc++; } } } unsigned encodeQuestion(Question *q, char **buf) { char **rawBuf = buf; encodeDomain(q->qName, buf); set8bit(buf, 0); set16bit(buf, q->qType); set16bit(buf, q->qClass); return (*buf) - (*rawBuf); } unsigned encodeSource(Source *s, char **buf) { char *rawBuf = *buf; encodeDomain(s->name, buf); set8bit(buf, 0); set16bit(buf, s->type); set16bit(buf, s->Class); set32bit(buf, s->TTL); set16bit(buf, s->rdLength); memcpy(*buf, s->rData, s->rdLength); (*buf) += 4; return (*buf) - rawBuf; } void setHeader(Header *head, char *buf) { set16bit(&buf, head->ID); uint32_t tmp = 0; tmp |= ((head->QR) << 15); tmp |= ((head->opcode) << 11); tmp |= ((head->AA) << 10); tmp |= ((head->TC) << 9); tmp |= ((head->RD) << 8); tmp |= ((head->RA) << 7); tmp |= (head->rcode); set16bit(&buf, (uint16_t)tmp); set16bit(&buf, head->qdcount); set16bit(&buf, head->ancount); set16bit(&buf, head->nscount); set16bit(&buf, head->arcount); } uint8_t get8bit(char **buff) { uint8_t t; memcpy(&t, *buff, 1); (*buff)++; return t; } uint16_t get16bit(char **buff) { uint16_t t; memcpy(&t, *buff, 2); (*buff) += 2; return ntohs(t); } uint32_t get32bit(char **buff) { uint32_t t; memcpy(&t, *buff, 4); (*buff) += 4; return ntohl(t); } void set8bit(char **buf, uint8_t t) { memcpy(*buf, &t, 1); (*buf)++; } void set16bit(char **buf, uint16_t t) { t = htons(t); memcpy(*buf, &t, 2); (*buf) += 2; } void set32bit(char **buf, uint32_t t) { t = htonl(t); memcpy(*buf, &t, 4); (*buf) += 4; } void freePkt(Packet *pkt) { free(pkt->pktHead); Question * q; while (pkt->pktQuestion) { free(pkt->pktQuestion->qName); q = pkt->pktQuestion->next; free(pkt->pktQuestion); pkt->pktQuestion = q; } Source *sAn; while (pkt->pktAnswer) { free(pkt->pktAnswer->name); sAn = pkt->pktAnswer->next; free(pkt->pktAnswer); pkt->pktAnswer = sAn; } Source *sAu; while (pkt->pktAuthority) { free(pkt->pktAuthority->name); sAu = pkt->pktAuthority->next; free(pkt->pktAuthority); pkt->pktAuthority = sAu; } }
d04021c66e7c55e4cf009a97a611945d7b1b0c42
1d7bcd5276db86c939077bf279bcd1486407b427
/Stats/StatsDLL.h
e951996c561f588941c39f76b8ff9375fe8acbc9
[]
no_license
jvansanten/xylo-pulse-counter
3630b39839d75c86f126cdda8ee77af56a4fcd2c
e6acc518440a6e5630d7ee8ecb8670bcc8577d12
refs/heads/master
2021-01-21T10:34:26.746250
2020-03-03T14:30:41
2020-03-03T14:30:41
83,456,564
0
1
null
null
null
null
UTF-8
C++
false
false
8,265
h
// StatsDLL.cpp : FPGA-based Fast Multisource Pulse Registration System // Simple .dll for LabVIEW or C++ program API. // by Sergey Polyakov & Joffrey Peters // This dll provides USB connectivity to the Xylo-EM board, allowing the user to pull single pulse and coincidence statistics, // or time-tagged events from the FPGA. // TTL pulses and toggling is supported on two channels #ifdef STATS_LIBRARY_EXPORTS # define LIBRARY_API __declspec(dllexport) #else # define LIBRARY_API __declspec(dllimport) #endif #include "stdafx.h" #include <iostream> #include <fstream> #include <conio.h> #include <time.h> #include <bitset> #include <stdio.h> #include "C:\Cypress\Cypress Suite USB 3.4.7\CyAPI\inc\CyAPI.h" //NOTE: CyAPI.h requires linking to Setupapi.lib //FPGA commands static unsigned char FPGA_NO_CHANGE = 0; static unsigned char FPGA_CLEAR = 1; static unsigned char FPGA_DISABLE = 2; static unsigned char FPGA_ENABLE = 4; static unsigned char FPGA_GETDATA = 8; //TTL FPGA output commands static unsigned char FPGA_PULSE = 0x10; //16 static unsigned char FPGA_TOGGLE = 0x20; //32 //TTL channels static unsigned char FPGA_TTL_1 = 0x40; //64 static unsigned char FPGA_TTL_2 = 0x80; //128 //Errors static const int ERROR_USB_INITIATED = -1; //Error: USB communication already initiated. static const int ERROR_USB_UNINITIATED = -2; //Error: Trying to close NULL USB connection. static const int ERROR_FPGA_REQUEST_DATA_SIZE = -3; //Error while requesting data size from FPGA static const int ERROR_FPGA_GET_DATA_SIZE = -4; //Error getting size of data from FPGA static const int ERROR_FPGA_GET_BULK_DATA = -5; //Error while getting bulk data from FPGA static const int ERROR_FPGA_DATA_SIZE = -6; //Error: returned data not the 64 bytes expected... static const int ERROR_COUNTS_INITIALIZATION = -7; //Error: insufficiently sized buffer passed to FPGA_Counts() static const int ERROR_FPGA_PULSE = -8; //Error: could not send pulse command to FPGA. static const int ERROR_FPGA_TOGGLE = -9; //Error: could not send toggle command to FPGA. //constants static const int USBFrame = 512; static const int BYTE_SIZE = 8; static const int FPGAdataPointSize = 4; //Time Tag data is 4 bytes per click static const int FPGAStatsDataSize = 64; //64 bytes //KNJN GUID {0EFA2C93-0C7B-454F-9403-D638F6C37E65} static GUID GUID_KNJN_FX2 = {0x0EFA2C93, 0x0C7B, 0x454F, 0x94, 0x03, 0xD6, 0x38, 0xF6, 0xC3, 0x7E, 0x65}; //CYUSB GUID="{AE18AA60-7F6A-11d4-97DD-00010229B959} //Using this one with the CyUSB signed driver! static GUID GUID_CYUSB_FX2 = {0xAE18AA60, 0x7F6A, 0x11d4, 0x97, 0xDD, 0x00, 0x01, 0x02, 0x29, 0xB9, 0x59}; #define BulkOutPipe0 USBDevice->EndPoints[1] #define BulkInPipe1 USBDevice->EndPoints[2] #define BulkOutPipe2 USBDevice->EndPoints[3] #define BulkOutPipe3 USBDevice->EndPoints[4] #define BulkInPipe4 USBDevice->EndPoints[5] #define BulkInPipe5 USBDevice->EndPoints[6] //Name of a function with real time access to received data. //User could write his/her own function and give its name here. Default function is "correlate" //The user function must be declared as //void <function_name> (unsigned char* data, int length, __int64 *stats); //where: //data is an array of recorded events, 4 bytes are used per one event, as defined in documentation //length is the length of the array (divide by 4 to get number of events) //stats is an array of integers, with any user output. The pointer to zeroth element will be passed to LabVEIW. The LavVIEW code assumes a 16-element array. #define REALTIME_FUNCTION correlate /////////////////////////////////////////////////// // Opens and closes the FPGA/USB driver /////////////////////////////////////////////////// //create USB connection with CyUSB driver and return 0; if USB connection already created, return -1. LIBRARY_API int USB_Open(); //return 0 if all is well, or -2 if CyUSB connection is NULL to begin with LIBRARY_API int USB_Close(); /////////////////////////////////////////////////// // Pulls timestamped clicks from FPGA // //bool saveClicks: boolean to specify whether time-tagged events should be saved in a file of fileName //unsigned char fpgaCommand: command to give to FPGA, (FPGA_ENABLE, FPGA_DISABLE, FPGA_CLEAR, FPGA_NO_CHANGE) // Note: one may also include TTL commands with these by simply using bitwise or | to // combine the commands. Using multiple runs will cause these commands to be issued // to the FPGA that many times before returning results to the user. //char* fileName: name of file storing time-tagged events //int* stats: 16 element array of integers used to store the 4-channel coincidence statistics measured by correlate() function //int runs: number of times the USB transfer should occur before returning the *stats array and close file write. // //returns 0 if successful, < 0 otherwise: // ERROR_FPGA_REQUEST_DATA_SIZE is for uninitialized USB devices // ERROR_FPGA_REQUEST_DATA_SIZE is for data request size errors // ERROR_FPGA_GET_BULK_DATA is for data transfer errors // /////////////////////////////////////////////////// LIBRARY_API int FPGA_TimeTag(bool saveClicks, unsigned char fpgaCommand, char* fileName, __int64* stats, int runs); /////////////////////////////////////////////////// // Pulls click statistics from the FPGA // //bool saveData: boolean to specify whether click information should be saved in a file of fileName //unsigned char fpgaCommand: command to give to FPGA, (FPGA_ENABLE, FPGA_DISABLE, FPGA_CLEAR, FPGA_NO_CHANGE) // Note: one may also include TTL commands with these by simply using bitwise or | to // combine the commands. Using multiple runs will cause these commands to be issued // to the FPGA that many times before returning results to the user. //char* fileName: name of file storing time-tagged events //int* stats: 16 element array of integers used to store the 4-channel coincidence statistics taken during this function call (runs FPGA board queries) //unsigned int* data: the data in the raw format sent by the FPGA. The first 6 bytes are dedicated to clock ticks, the next 14 sets of 4 bytes are for // individual clicks, then coincidence clicks in the order defined by the stats structure below. The last two bytes are for four-fold coincidences. // The bytes are ordered least to most significant due to the way the FPGA transfers the data //int* length: length of the data variable passed into the function. The output value of length will be the actual length of the *data array passed out. //int runs: number of times the USB transfer should occur before returning the *stats and *data arrays and close file write. // //returns 0 if successful, <0 otherwise: // ERROR_FPGA_REQUEST_DATA_SIZE is for errors requesting data size, (typically due to disconnected, misprogrammed, or uninitialized USB devices) // ERROR_FPGA_REQUEST_DATA_SIZE is for data request size errors // ERROR_FPGA_GET_BULK_DATA is for data transfer errors // ERROR_COUNTS_INITIALIZATION is for insufficient *length parameter passed given the number of runs // /////////////////////////////////////////////////// LIBRARY_API int FPGA_Counts(bool saveData, unsigned char fpgaCommand, char* fileName, __int64* stats, unsigned __int64* data, int* length, int runs); /******** Output pulse from channel. returns 0 if successful, negative value if error ********/ LIBRARY_API int FPGA_Pulse(unsigned char fpgaCommand); /******** Toggle channel output state. returns new output state, or negative value if error ********/ LIBRARY_API int FPGA_Toggle(unsigned char fpgaCommand); ///////////////////////////////////////////////////// // Default REALTIME_FUNCTION // Simple correlation analysis. Computes statistics. ///////////////////////////////////////////////////// /* stats structure: number of occurences of these events: stats[0] start events stats[1] state 0 stats[2] state 1 stats[3] state 2 stats[4] state 3 stats[5] states 0&1 stats[6] states 0&2 stats[7] states 0&3 stats[8] state 1&2 stats[9] state 1&3 stats[10] state 2&3 stats[11] states 0&1&2 stats[12] states 0&1&3 stats[13] states 0&2&3 stats[14] state 1&2&3 stats[15] states 0&1&2&3 */ void correlate (unsigned char* data, int length, __int64 *stats);
814117ed7179f0bb7540540389e2a3a49b4c8006
e8bd00c6904a163024783cb31403a5ff668750e3
/libs/bcg_opengl/systems/bcg_mesh_system.cpp
af5ff68f263a7ecab4536fa3f806430abced37da
[]
no_license
intrinsicD/basics_lab
165f53d9420de7ab7abd8bde5f3f32b9824f5762
109afca04014275015efc93e0472412d8f3feb13
refs/heads/basics_lab
2023-04-14T04:54:25.658721
2021-04-13T05:52:09
2021-04-13T05:52:09
343,719,615
0
3
null
2021-04-13T05:52:09
2021-03-02T09:37:53
C++
UTF-8
C++
false
false
20,721
cpp
// // Created by alex on 28.10.20. // #include "bcg_mesh_system.h" #include "bcg_viewer_state.h" #include "bcg_entity_info.h" #include "bcg_property_map_eigen.h" #include "geometry/aligned_box/bcg_aligned_box.h" #include "geometry/mesh/bcg_mesh_factory.h" #include "geometry/mesh/bcg_mesh_vertex_normals.h" #include "geometry/mesh/bcg_mesh_face_normals.h" #include "geometry/mesh/bcg_mesh_face_centers.h" #include "geometry/mesh/bcg_mesh_edge_dihedral_angle.h" #include "geometry/mesh/bcg_mesh_boundary.h" #include "geometry/mesh/bcg_mesh_vertex_convex_concave.h" #include "geometry/mesh/bcg_mesh_features.h" #include "geometry/mesh/bcg_mesh_subdivision.h" #include "geometry/mesh/bcg_mesh_connected_components.h" #include "geometry/mesh/bcg_mesh_laplacian.h" #include "geometry/mesh/bcg_mesh_curvature_taubin.h" #include "geometry/mesh/bcg_mesh_simplification.h" #include "geometry/mesh/bcg_mesh_remeshing.h" #include "geometry/mesh/bcg_mesh_statistics.h" #include "geometry/mesh/bcg_mesh_smoothing.h" #include "geometry/graph/bcg_graph_edge_centers.h" #include "renderers/picking_renderer/bcg_events_picking_renderer.h" #include "renderers/mesh_renderer/bcg_events_mesh_renderer.h" namespace bcg { mesh_system::mesh_system(viewer_state *state) : system("mesh_system", state) { state->dispatcher.sink<event::mesh::setup>().connect<&mesh_system::on_setup>(this); state->dispatcher.sink<event::mesh::make_triangle>().connect<&mesh_system::on_make_triangle>(this); state->dispatcher.sink<event::mesh::make_quad>().connect<&mesh_system::on_make_quad>(this); state->dispatcher.sink<event::mesh::make_box>().connect<&mesh_system::on_make_box>(this); state->dispatcher.sink<event::mesh::boundary>().connect<&mesh_system::on_boundary>(this); state->dispatcher.sink<event::mesh::vertex_convex_concave>().connect<&mesh_system::on_vertex_convex_concave>(this); state->dispatcher.sink<event::mesh::features>().connect<&mesh_system::on_features>(this); state->dispatcher.sink<event::mesh::features_clear>().connect<&mesh_system::on_features_clear>(this); state->dispatcher.sink<event::mesh::subdivision::catmull_clark>().connect<&mesh_system::on_subdivision_catmull_clark>( this); state->dispatcher.sink<event::mesh::subdivision::loop>().connect<&mesh_system::on_subdivision_loop>(this); state->dispatcher.sink<event::mesh::subdivision::sqrt3>().connect<&mesh_system::on_subdivision_sqrt3>(this); state->dispatcher.sink<event::mesh::connected_components::detect>().connect<&mesh_system::on_connected_components_detect>( this); state->dispatcher.sink<event::mesh::connected_components::split>().connect<&mesh_system::on_connected_components_split>( this); state->dispatcher.sink<event::mesh::laplacian::build>().connect<&mesh_system::on_build_laplacian>(this); state->dispatcher.sink<event::mesh::curvature::taubin>().connect<&mesh_system::on_curvature_taubin>(this); state->dispatcher.sink<event::mesh::simplification>().connect<&mesh_system::on_simplification>(this); state->dispatcher.sink<event::mesh::remeshing::uniform>().connect<&mesh_system::on_remeshing_uniform>(this); state->dispatcher.sink<event::mesh::remeshing::adaptive>().connect<&mesh_system::on_remeshing_adaptive>(this); state->dispatcher.sink<event::mesh::statistics>().connect<&mesh_system::on_statistics>(this); state->dispatcher.sink<event::mesh::smoothing::explicit_smoothing>().connect<&mesh_system::on_smoothing_explicit>(this); state->dispatcher.sink<event::mesh::smoothing::explicit_smoothing_1D>().connect<&mesh_system::on_smoothing_explicit_1D>(this); state->dispatcher.sink<event::mesh::smoothing::explicit_smoothing_3D>().connect<&mesh_system::on_smoothing_explicit_3D>(this); state->dispatcher.sink<event::mesh::smoothing::implicit_smoothing>().connect<&mesh_system::on_smoothing_implicit>(this); state->dispatcher.sink<event::mesh::smoothing::implicit_smoothing_1D>().connect<&mesh_system::on_smoothing_implicit_1D>(this); state->dispatcher.sink<event::mesh::smoothing::implicit_smoothing_3D>().connect<&mesh_system::on_smoothing_implicit_3D>(this); state->dispatcher.sink<event::mesh::smoothing::taubin_smoothing>().connect<&mesh_system::on_smoothing_taubin>(this); state->dispatcher.sink<event::mesh::vertex_normals::uniform>().connect<&mesh_system::on_vertex_normal_uniform>( this); state->dispatcher.sink<event::mesh::vertex_normals::area>().connect<&mesh_system::on_vertex_normal_area>(this); state->dispatcher.sink<event::mesh::vertex_normals::angle>().connect<&mesh_system::on_vertex_normal_angle>(this); state->dispatcher.sink<event::mesh::vertex_normals::area_angle>().connect<&mesh_system::on_vertex_normal_area_angle>( this); state->dispatcher.sink<event::mesh::face::centers>().connect<&mesh_system::on_face_centers>(this); state->dispatcher.sink<event::mesh::face::normals>().connect<&mesh_system::on_face_normals>(this); state->dispatcher.sink<event::graph::edge::centers>().connect<&mesh_system::on_edge_centers>(this); state->dispatcher.sink<event::mesh::edge::dihedral_angle>().connect<&mesh_system::on_dihedral_angle>(this); } void mesh_system::on_setup(const event::mesh::setup &event) { auto &mesh = state->scene.get<halfedge_mesh>(event.id); state->dispatcher.trigger<event::transform::add>(event.id); aligned_box3 aabb(mesh.positions.vector()); state->scene.emplace<entity_info>(event.id, event.filename, "mesh", aabb.center(), aabb.halfextent().maxCoeff()); Map(mesh.positions) = (MapConst(mesh.positions).rowwise() - aabb.center().transpose()) / aabb.halfextent().maxCoeff(); if(!mesh.vertices.has("v_normal")){ state->dispatcher.trigger<event::mesh::vertex_normals::area_angle>(event.id); } state->dispatcher.trigger<event::mesh::face::centers>(event.id); state->dispatcher.trigger<event::graph::edge::centers>(event.id); state->dispatcher.trigger<event::aligned_box::add>(event.id); state->scene.emplace_or_replace<event::picking_renderer::enqueue>(event.id); state->scene.emplace_or_replace<event::mesh_renderer::enqueue>(event.id); state->picker.entity_id = event.id; std::cout << mesh << "\n"; } //---------------------------------------------------------------------------------------------------------------------- void mesh_system::on_make_triangle(const event::mesh::make_triangle &) { mesh_factory factory; auto mesh = factory.make_triangle(); auto id = state->scene.create(); state->scene.emplace<halfedge_mesh>(id, mesh); state->dispatcher.trigger<event::mesh::setup>(id); } void mesh_system::on_make_quad(const event::mesh::make_quad &) { mesh_factory factory; auto mesh = factory.make_quad(); auto id = state->scene.create(); state->scene.emplace<halfedge_mesh>(id, mesh); state->dispatcher.trigger<event::mesh::setup>(id); } void mesh_system::on_make_box(const event::mesh::make_box &event) { mesh_factory factory; auto mesh = factory.make_box(); auto id = state->scene.create(); state->scene.emplace<halfedge_mesh>(id, mesh); state->dispatcher.trigger<event::mesh::setup>(id); } //---------------------------------------------------------------------------------------------------------------------- void mesh_system::on_boundary(const event::mesh::boundary &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); mesh_boundary(mesh, state->config.parallel_grain_size); } void mesh_system::on_vertex_convex_concave(const event::mesh::vertex_convex_concave &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); vertex_convex_concave(mesh, state->config.parallel_grain_size); } void mesh_system::on_features(const event::mesh::features &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); mesh_features(mesh, event.boundary, event.angle, event.threshold_degrees, state->config.parallel_grain_size); } void mesh_system::on_features_clear(const event::mesh::features_clear &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); mesh_clear_features(mesh); } void mesh_system::on_subdivision_catmull_clark(const event::mesh::subdivision::catmull_clark &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); mesh_subdivision_catmull_clark(mesh, state->config.parallel_grain_size); state->dispatcher.trigger<event::mesh::vertex_normals::area_angle>(event.id); state->dispatcher.trigger<event::spatial_index::update_indices>(event.id); } void mesh_system::on_subdivision_loop(const event::mesh::subdivision::loop &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); mesh_subdivision_loop(mesh, state->config.parallel_grain_size); state->dispatcher.trigger<event::mesh::vertex_normals::area_angle>(event.id); state->dispatcher.trigger<event::spatial_index::update_indices>(event.id); } void mesh_system::on_subdivision_sqrt3(const event::mesh::subdivision::sqrt3 &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); mesh_subdivision_sqrt3(mesh, state->config.parallel_grain_size); state->dispatcher.trigger<event::mesh::vertex_normals::area_angle>(event.id); state->dispatcher.trigger<event::spatial_index::update_indices>(event.id); } void mesh_system::on_connected_components_detect(const event::mesh::connected_components::detect &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); mesh_connected_components_detect(mesh); } void mesh_system::on_connected_components_split(const event::mesh::connected_components::split &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); auto parts = mesh_connected_components_split(mesh); for (const auto part : parts) { auto id = state->scene.create(); state->scene.emplace<halfedge_mesh>(id, part); state->dispatcher.trigger<event::mesh::setup>(id); state->dispatcher.trigger<event::hierarchy::add_child>(event.id, id); state->dispatcher.trigger<event::hierarchy::set_parent>(id, event.id); } } void mesh_system::on_build_laplacian(const event::mesh::laplacian::build &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); auto laplacian = build_laplacian(mesh, event.s_type, event.m_type, state->config.parallel_grain_size, event.edge_scaling_property_name); state->scene.emplace_or_replace<mesh_laplacian>(event.id, laplacian); } void mesh_system::on_curvature_taubin(const event::mesh::curvature::taubin &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); mesh_curvature_taubin(mesh, event.post_smoothing_steps, event.two_ring_neighborhood, state->config.parallel_grain_size); } void mesh_system::on_simplification(const event::mesh::simplification &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); mesh_simplification(mesh, event.n_vertices, event.aspect_ratio, event.edge_length, event.max_valence, event.normal_deviation, event.hausdorff_error); state->dispatcher.trigger<event::mesh::vertex_normals::area_angle>(event.id); state->dispatcher.trigger<event::spatial_index::update_indices>(event.id); } void mesh_system::on_remeshing_uniform(const event::mesh::remeshing::uniform &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); mesh_remeshing_uniform(mesh, event.edge_length, event.iterations, event.use_projection); state->dispatcher.trigger<event::mesh::vertex_normals::area_angle>(event.id); state->dispatcher.trigger<event::spatial_index::update_indices>(event.id); } void mesh_system::on_remeshing_adaptive(const event::mesh::remeshing::adaptive &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); mesh_remeshing_adaptive(mesh, event.min_edge_length, event.max_edge_length, event.approx_error, event.iterations, event.use_projection); state->dispatcher.trigger<event::mesh::vertex_normals::area_angle>(event.id); state->dispatcher.trigger<event::spatial_index::update_indices>(event.id); } void mesh_system::on_statistics(const event::mesh::statistics &event){ if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); auto stats = mesh_statistics(mesh, state->config.parallel_grain_size); state->scene.emplace_or_replace<mesh_stats>(event.id, stats); } void mesh_system::on_smoothing_explicit(const event::mesh::smoothing::explicit_smoothing &event){ if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; if (!state->scene.has<mesh_laplacian>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); auto &laplacian = state->scene.get<mesh_laplacian>(event.id); explicit_smoothing(mesh, laplacian, event.smoothing_steps, event.timestep, state->config.parallel_grain_size); state->dispatcher.trigger<event::mesh::vertex_normals::area_angle>(event.id); } void mesh_system::on_smoothing_implicit(const event::mesh::smoothing::implicit_smoothing &event){ if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); auto &laplacian = state->scene.get<mesh_laplacian>(event.id); implicit_smoothing(mesh, laplacian, event.timestep); state->dispatcher.trigger<event::mesh::vertex_normals::area_angle>(event.id); } void mesh_system::on_smoothing_explicit_1D(const event::mesh::smoothing::explicit_smoothing_1D &event){ if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); auto &laplacian = state->scene.get<mesh_laplacian>(event.id); auto p = event.prop; explicit_smoothing(mesh, laplacian, p, event.smoothing_steps, event.timestep, state->config.parallel_grain_size); } void mesh_system::on_smoothing_implicit_1D(const event::mesh::smoothing::implicit_smoothing_1D &event){ if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); auto &laplacian = state->scene.get<mesh_laplacian>(event.id); auto p = event.prop; implicit_smoothing<bcg_scalar_t , 1>(mesh, laplacian, p, event.timestep); } void mesh_system::on_smoothing_explicit_3D(const event::mesh::smoothing::explicit_smoothing_3D &event){ if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); auto &laplacian = state->scene.get<mesh_laplacian>(event.id); auto p = event.prop; explicit_smoothing(mesh, laplacian, p, event.smoothing_steps, event.timestep, state->config.parallel_grain_size); } void mesh_system::on_smoothing_implicit_3D(const event::mesh::smoothing::implicit_smoothing_3D &event){ if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); auto &laplacian = state->scene.get<mesh_laplacian>(event.id); auto p = event.prop; implicit_smoothing(mesh, laplacian, p, event.timestep); } void mesh_system::on_smoothing_taubin(const event::mesh::smoothing::taubin_smoothing &event){ if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); auto &laplacian = state->scene.get<mesh_laplacian>(event.id); taubin_smoothing(mesh, laplacian, event.lambda, event.mu, event.smoothing_steps); state->dispatcher.trigger<event::mesh::vertex_normals::area_angle>(event.id); } //---------------------------------------------------------------------------------------------------------------------- void mesh_system::on_vertex_normal_uniform(const event::mesh::vertex_normals::uniform &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); vertex_normals(mesh, vertex_normal_uniform, state->config.parallel_grain_size); } void mesh_system::on_vertex_normal_area(const event::mesh::vertex_normals::area &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); vertex_normals(mesh, vertex_normal_area, state->config.parallel_grain_size); } void mesh_system::on_vertex_normal_angle(const event::mesh::vertex_normals::angle &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); vertex_normals(mesh, vertex_normal_angle, state->config.parallel_grain_size); } void mesh_system::on_vertex_normal_area_angle(const event::mesh::vertex_normals::area_angle &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); vertex_normals(mesh, vertex_normal_area_angle, state->config.parallel_grain_size); } //---------------------------------------------------------------------------------------------------------------------- void mesh_system::on_dihedral_angle(const event::mesh::edge::dihedral_angle &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); edge_dihedral_angles(mesh, state->config.parallel_grain_size); } void mesh_system::on_edge_centers(const event::graph::edge::centers &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); edge_centers(mesh, state->config.parallel_grain_size); } //---------------------------------------------------------------------------------------------------------------------- void mesh_system::on_face_centers(const event::mesh::face::centers &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); face_centers(mesh, state->config.parallel_grain_size); } void mesh_system::on_face_normals(const event::mesh::face::normals &event) { if (!state->scene.valid(event.id)) return; if (!state->scene.has<halfedge_mesh>(event.id)) return; auto &mesh = state->scene.get<halfedge_mesh>(event.id); face_normals(mesh, state->config.parallel_grain_size); } //---------------------------------------------------------------------------------------------------------------------- }
35404a8e47e46e792742ebff224791e844cd2b38
3abec2a3286f58162e9ed57f47ae069fc9847c60
/acmicpc/2252.cpp
3a042da7f90384b16f7655b3cce1788cf13260d4
[]
no_license
bongster/algospot
e0adba4142c2a3b0809755100669a142a20d0f4f
e4685d6ab378c65c04b67d53c3c31e20d8813b8f
refs/heads/master
2021-05-24T02:56:52.406705
2019-06-17T00:04:42
2019-06-17T00:04:42
37,861,163
0
0
null
2021-03-25T21:39:30
2015-06-22T14:47:20
C++
UTF-8
C++
false
false
569
cpp
#include <iostream> #include <vector> #include <queue> using namespace std; vector<int> a[32001]; int idn[32001]; int main() { int n,m, x, y; scanf("%d %d", &n, &m); for (int i=0; i<m; i++) { scanf("%d %d", &x, &y); idn[y] +=1; a[x].push_back(y); } queue<int> q; for (int i=1;i<=n;i++) { if (idn[i] == 0) { q.push(i); } } while (!q.empty()) { int x = q.front(); printf("%d ", x); q.pop(); for (int i=0; i< a[x].size(); i++) { int y = a[x][i]; idn[y] -= 1; if (idn[y] == 0) { q.push(y); } } } printf("\n"); return 0; }
99299cecb96ce473290f5aac6236fc4d6b8eb177
fc12dde31f918d342c4efa75e6a37f23cbbfc1f3
/OS_2018_2019/ex3/ShuffleThreadContext.h
e6fa20fe4b07844e1d2bcfc56c097503c955ece7
[]
no_license
DanielMagen/University-exercises
4f9bbef566b14326d4006f0deae3fd3de2ab303a
c8502459edad916079550bc0704a0b7f69c9df1f
refs/heads/master
2022-12-03T04:27:37.802675
2020-08-15T10:15:05
2020-08-15T10:15:05
287,717,481
0
0
null
null
null
null
UTF-8
C++
false
false
1,642
h
// // Created by on 5/5/19. // #ifndef EX3_SHUFFLETHREADCONTEXT_H #define EX3_SHUFFLETHREADCONTEXT_H #include "ThreadContext.h" /** * A special type of thread -The thread that shuffles */ class ShuffleThreadContext : public ThreadContext { private: /** * A pointer to all the existing threads */ std::vector<ThreadContext *> *_contexts; public: /** * A constructor * @param gv- A pointer to the "GlobalVariables" object that all the threads point to * @param id- This thread's id * @param client- A pointer to the "client" object that all threads point to * @param inputVec- The input vector * @param outputVec- The output vector * @param intermediateVectorBeingReduced- The vector for pairs taken from the jobPool * @param contexts- All the threads */ ShuffleThreadContext( GlobalVariables *gv, int id, const MapReduceClient &client, const InputVec &inputVec, OutputVec *outputVec, IntermediateVec *intermediateVectorBeingReduced, std::vector<ThreadContext *> *contexts); /** * @return A pointer ot all the threads */ std::vector<ThreadContext *> *getContexts(); /** * Set the Length Of The Items To Work On * @param setTo- The length to set to */ void setLengthOfItemsToWorkOn(unsigned long setTo); /** * @return The number of all existing threads */ int getNumberOfThreads(); /** * sets the ShuffleFinished flag to True */ void setShuffleFinishedTrue(); }; #endif //EX3_SHUFFLETHREADCONTEXT_H
394ae4896140e56f14fe452027e51cd69f31472e
788da62dce9041878fd098e5347408fbf0679ace
/qcom/proprietary/data/dss_new/src/utils/src/ds_Utils_CritSect.h
358df893725d4df13ead5ca37aff806b72acb5a8
[]
no_license
Snapdragon-Computer-Vision-Engine-Team/msm8974-sources2
e7daa0bf3096e09286fd6e9f3a4e078774e49565
8e8a1d7b8b840a7c93e39634d61614665974acb1
refs/heads/master
2021-12-15T03:28:26.619350
2017-07-25T06:50:38
2017-07-25T06:50:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,198
h
#ifndef DS_UTILS_CRIT_SECT_H #define DS_UTILS_CRIT_SECT_H /*=========================================================================*/ /*! @file ds_Utils_CritSect.h @brief This class provides critical section facility to objects in a platform independent manner. It implements the ds::Utils::ICritSect interface. @see AEEICritSect.h @see ds_Utils_ICritSect.h Copyright (c) 2008-2010 Qualcomm Technologies, Inc. All Rights Reserved. Qualcomm Technologies Confidential and Proprietary */ /*=========================================================================*/ /*=========================================================================== EDIT HISTORY FOR MODULE $Header: //source/qcom/qct/modem/datamodem/interface/utils/rel/11.03/src/ds_Utils_CritSect.h#1 $ $DateTime: 2011/06/17 12:02:33 $ $Author: zhasan $ ===========================================================================*/ /*=========================================================================== INCLUDE FILES FOR MODULE ===========================================================================*/ #include "comdef.h" #include "ps_crit_sect.h" #include "ds_Utils_CSSupport.h" #include "AEEICritSect.h" #include "AEECCritSect.h" #include "ds_Errors_Def.h" #include "AEEStdErr.h" #include "ps_mem_ext.h" #include "ps_mem.h" /*=========================================================================== PUBLIC DATA DECLARATIONS ===========================================================================*/ namespace ds { namespace Utils { /*lint -esym(1510, ICritSect) */ /*lint -esym(1510, IQI) */ class CritSect : public ICritSect { private: ps_crit_sect_type mutex; public: CritSect() throw(); virtual ~CritSect() throw(); DSIQI_IMPL_DEFAULTS(ICritSect) virtual void CDECL Enter() throw(); virtual void CDECL Leave() throw(); virtual int CDECL TryEnter() throw(); /*------------------------------------------------------------------------- CreateInstance method for CritSects -------------------------------------------------------------------------*/ static int CreateInstance (void* env, AEECLSID clsid, void* privset, void** newObj) { (void) privset; (void) env; if (AEECLSID_CCritSect == clsid) { *newObj = (ICritSect *)(new CritSect()); if (NULL == *newObj) { return AEE_ENOMEMORY; } return AEE_SUCCESS; } return AEE_ECLASSNOTSUPPORT; } /*------------------------------------------------------------------------- Overloaded new/delete methods. -------------------------------------------------------------------------*/ /* Overloaded new operator */ void* operator new (unsigned int num_bytes) throw() { (void) num_bytes; return ps_mem_get_buf (PS_MEM_DS_UTILS_CRIT_SECT); } /* Overloaded delete operator */ void operator delete (void* objPtr) throw() { PS_MEM_FREE(objPtr); } }; /* class CritSect */ } /* namespace Utils */ } /* namespace ds */ #endif /* DS_UTILS_CRIT_SECT_H */
8d90847cb1f50ece431b8524a21395ba581dc6c1
52b1a2650d5ee7c52c82a1de8413e6a12f5d675b
/itgclient/client/modules/VS_INFYTSS/src/VS_TSS_Hash.cpp
6863683bc211adcec6b99bc1ec6f5a0c28de1237
[]
no_license
classic130/processing_center_additional
89fc9367ad12649416d972a0af2a8a925fedc9e5
efe745ff6780abc7c83a5f6cf1ac0166926e355d
refs/heads/master
2022-03-05T12:23:47.955954
2019-10-18T10:12:31
2019-10-18T10:12:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,386
cpp
#include <stdio.h> #include <assert.h> #include <windows.h> // TSS specific includes #include "tcpa_defines.h" #include "tcpa_struct.h" #include "tssapi_error.h" #include "tss_values.h" #include "tss_helpers.h" #include <VS_TSS_Context.h> #include <VS_TSS_Key.h> #include <VS_TSS_Hash.h> // XXX From cspglobals.h #define VS_SHA_1 32772 // DLL export functions. extern "C" __declspec(dllexport) VS_TSS_Hash* CreateHashObject(const VS_TSS_Context* i_chContext, const DWORD i_cdwAlgorithmId, DWORD* o_dwError) { return new VS_TSS_Hash(i_chContext, i_cdwAlgorithmId, o_dwError); } // Implementation of VS_TSS_Hash VS_TSS_Hash::VS_TSS_Hash(const VS_TSS_Context* i_cpContext, const DWORD i_cdwAlgorithmId, DWORD* o_dwError) { *o_dwError = S_OK; do { try { if (i_cdwAlgorithmId != VS_SHA_1) { *o_dwError = NTE_BAD_ALGID; break; } // Always create a hash object of HASH_ALG_OTHER type. This way you can sign data of any length. ((VS_TSS_Context*)i_cpContext)->GetContext( (ITCPAContextPtr *) &m_pContextObject); m_pContextObject->CreateObject(TSS_OBJECT_TYPE_HASH, HASH_ALG_OTHER, (IUnknown **)&m_pHashObject); // set SHA1 hash algorithm identifier ITCPAAttribPtr pHashAttrib(m_pHashObject); BYTE pbHashOID[DER_PREFIX_SHA1_LEN] = DER_PREFIX_SHA1; pHashAttrib->SetAttribData ( TSS_TSPATTRIB_HASH_IDENTIFIER, 0, DER_PREFIX_SHA1_LEN, pbHashOID ); } catch(_com_error e) { *o_dwError = e.Error(); } catch(...) { *o_dwError = E_FAIL; } } while(0); } VS_TSS_Hash::~VS_TSS_Hash() { } /* This method will create SHA1 hash. It will not work as we are using a hash object of HASH_ALG_OTHER type. */ HRESULT VS_TSS_Hash::UpdateHashValue(const DWORD i_cdwDataLength, const BYTE* i_cpbData) { HRESULT hResult = S_OK; do { try { m_pHashObject->UpdateHashValue(i_cdwDataLength, (unsigned char*)i_cpbData); } catch(_com_error e) { hResult = e.Error(); } catch(...) { hResult = E_FAIL; } } while(0); return hResult; } /* This method will set hash value, which can be signed later */ HRESULT VS_TSS_Hash::SetHashValue(const DWORD i_cdwHashLength, const BYTE* i_cpbHashData) { HRESULT hResult = S_OK; do { try { m_pHashObject->SetHashValue(i_cdwHashLength, (unsigned char*)i_cpbHashData); } catch(_com_error e) { hResult = e.Error(); } catch(...) { hResult = E_FAIL; } } while(0); return hResult; } /* This method returns hash value stored in the hash object */ HRESULT VS_TSS_Hash::GetHashValue(DWORD* o_pdwHashLength, BYTE** o_ppbHashData) { HRESULT hResult = S_OK; do { try { m_pHashObject->GetHashValue((unsigned int*) o_pdwHashLength, o_ppbHashData); } catch(_com_error e) { hResult = e.Error(); } catch(...) { hResult = E_FAIL; } } while(0); return hResult; } HRESULT VS_TSS_Hash::Sign(const VS_TSS_Key* i_cpTSSKey, DWORD* o_pdwSignatureLength, BYTE** o_ppbSignatureData) { HRESULT hResult = S_OK; ITCPAKeyPtr pKeyObject; do { try { ((VS_TSS_Key*)i_cpTSSKey)->GetKey( (ITCPAKeyPtr *) &pKeyObject); m_pHashObject->Sign(pKeyObject, (unsigned int*) o_pdwSignatureLength, o_ppbSignatureData); } catch(_com_error e) { hResult = e.Error(); } catch(...) { hResult = E_FAIL; } } while(0); return hResult; } /* This method verifies the signature. It will not work as we are using a hash object of HASH_ALG_OTHER type. */ HRESULT VS_TSS_Hash::VerifySignature(const VS_TSS_Key* i_cpTSSKey, const DWORD i_cdwSignatureLength, const BYTE* i_cpbSignatureData) { HRESULT hResult = S_OK; ITCPAKeyPtr pKeyObject; do { try { ((VS_TSS_Key*)i_cpTSSKey)->GetKey( (ITCPAKeyPtr *) &pKeyObject); m_pHashObject->VerifySignature(pKeyObject, i_cdwSignatureLength, (unsigned char*)i_cpbSignatureData); } catch(_com_error e) { hResult = e.Error(); } catch(...) { hResult = E_FAIL; } } while(0); return hResult; }
5614d274424681d54ff9e8909f51b5b1f6bd2cf0
4ca0884f1492cbab6e06a5174dbaaa09238434ad
/template_context.hpp
60cc518c5aba69823680f8656a517ff9e4cfab20
[]
no_license
JeffGarland/liaw2014
5be8f54bd292ce165b30097696a19e2a29faca4c
edfc0285f9d705f25a48f5bdf74ef267a9f7b612
refs/heads/master
2020-05-18T01:38:47.961337
2015-01-25T10:31:28
2015-01-25T10:31:28
19,574,272
7
0
null
2014-05-21T21:41:53
2014-05-08T13:25:31
C++
UTF-8
C++
false
false
3,331
hpp
#ifndef _TEMPLATE_CONTEXT_HPP_ #define _TEMPLATE_CONTEXT_HPP_ 0x100 #include <list> #include <map> #include <string> #include <vector> #include "template_object_interface.hpp" // Context is an example of how we could create a class that can be used by boostache class Context; class Context { // mapping of available variables std::map<std::string, std::string> mVariables; // mapping of available subcontext std::map<std::string, std::vector<Context>> mSubContext; public: // overrides a context void addVariable(std::string key, std::string value) { mVariables[key] = value; } void addSubContext(std::string key, std::vector<Context> value) { mSubContext[key] = value; } bool hasVariable(std::string key) const { return mVariables.find(key) != mVariables.end(); } // NOTE! Should this just return ""? std::string getVariable(std::string key) const { auto v = mVariables.find(key); if (v == mVariables.end()) throw std::runtime_error("variable not found"); return v->second; } bool hasSubContext(std::string key) const { auto v = mSubContext.find(key); return (v != mSubContext.end()); } std::pair<std::vector<Context>::const_iterator, std::vector<Context>::const_iterator> getSubContext(std::string key) const { auto v = mSubContext.find(key); if (v == mSubContext.end()) throw std::runtime_error("variable not found"); return { v->second.begin(), v->second.end() }; } }; struct Context_list_iterator_t; struct Context_list_t { Context_list_t(const Context& c) { mData.push_front(c); } std::list<Context> mData; typedef Context_list_iterator_t Iterator; }; struct Context_list_iterator_t { Context_list_iterator_t(std::vector<Context>::const_iterator i, const Context_list_t& p) : iter(i), parent_context(p) {} bool operator==(const Context_list_iterator_t& rhs) const { return iter == rhs.iter; } bool operator!=(const Context_list_iterator_t& rhs) const { return iter != rhs.iter; } Context_list_iterator_t& operator++() { ++iter; return *this; } Context_list_t operator*() const { auto result = parent_context; result.mData.push_front(*iter); return result; } std::vector<Context>::const_iterator iter; const Context_list_t& parent_context; }; // NOTE! putting this in the other namespace? namespace template_engine { template<> std::pair<Context_list_iterator_t, Context_list_iterator_t> GetRange<Context_list_t>(const Context_list_t& data, const std::string& key) { for (const auto& i : data.mData) { if (i.hasSubContext(key)) { auto result = i.getSubContext(key); typename Context_list_t::Iterator begin(result.first, data); typename Context_list_t::Iterator end(result.second, data); return { begin, end }; } } throw std::runtime_error("section not found"); } template <> void Render<Context_list_t>(const Context_list_t& data, std::ostream& os, const std::string& key) { for (const auto& i : data.mData) { if (i.hasVariable(key)) { os<<i.getVariable(key); return; } } return ; } template <> bool HasKey<Context_list_t>(const Context_list_t& data, const std::string& key) { for (const auto& i : data.mData) { if (i.hasVariable(key) || i.hasSubContext(key)) { return true; } } return false; } } // namespace template_engine #endif // _TEMPLATE_CONTEXT_HPP_
1726fae1e0741f77de18797e84f6a0d0091a3b6d
af5932039d97ac69b794bd591c2bf32946c34e5e
/Main.cpp
2a4e63e42b8746309811060a612bf22be1d1671a
[]
no_license
ManneMoquist/BITMAP-Header-Remover
3818b2cdcbcaa80f4dc600fbaac85d291cd3cb37
5cb518d6cfeb2a957cbe65e211fcbe4a16e2a796
refs/heads/master
2021-01-19T13:50:15.974144
2017-02-18T23:31:53
2017-02-18T23:31:53
82,422,216
0
0
null
null
null
null
UTF-8
C++
false
false
2,348
cpp
#include<fstream> #include<string.h> #include<stdio.h> #include<stdlib.h> #include<iostream> #include<windows.h> using namespace std; char* AppendString(char* in, char* append) { char* ret = (char*)malloc(sizeof(in) + sizeof(append) + 4); strcpy(ret, in); strcat(ret, append); return ret; } int main(int argc, char **argv) { char* filename; if (argc != 2) { cout << "ERROR: no input file" << endl; system("PAUSE"); exit(1); } else { filename = argv[1]; } BITMAPFILEHEADER fileHeader; BITMAPINFOHEADER infoHeader; ifstream input; input.open(filename, ifstream::in | ifstream::binary); unsigned char *fileData; if (input.bad()) { cout << "File could not be opened" << endl; system("PAUSE"); return 1; } input.read((char*)&fileHeader, sizeof(BITMAPFILEHEADER)); input.read((char*)&infoHeader, sizeof(BITMAPINFOHEADER)); input.clear(); input.seekg(fileHeader.bfOffBits, ios_base::beg); fileData = (unsigned char*)malloc(infoHeader.biSizeImage); if (!fileData) { free(fileData); input.close(); cout << "Could not allocate memory properly" << endl; system("PAUSE"); return 1; } input.read((char*)fileData, infoHeader.biSizeImage); input.close(); fstream DataFile; char* dataFilename = AppendString(filename,".data"); DataFile.open(dataFilename, fstream::binary | fstream::out); DataFile.write((char*)fileData, infoHeader.biSizeImage); DataFile.close(); if (DataFile.fail()) { cout << "Could not open " << dataFilename << endl; system("PAUSE"); exit(1); } cout << "When you are finished with databending the picture press any key" << endl; system("PAUSE"); DataFile.open(dataFilename, fstream::binary | fstream::in); if (DataFile.fail()) { cout << "Could not open " << dataFilename << endl; system("PAUSE"); exit(1); } unsigned char *newData; newData = (unsigned char*)malloc(infoHeader.biSizeImage); DataFile.read((char*)newData, infoHeader.biSizeImage); DataFile.close(); fstream output; char* outputFilename = AppendString(filename, ".output.bmp"); output.open(outputFilename, fstream::binary | fstream::out); output.write((char*)&fileHeader, sizeof(BITMAPFILEHEADER)); output.write((char*)&infoHeader, sizeof(BITMAPINFOHEADER)); output.seekg(fileHeader.bfOffBits, ios_base::beg); output.write((char*)newData, infoHeader.biSizeImage); output.close(); }
5c5bb1baefa491bd4353055064127b7368d441f2
1bb6a0b3692b5468f7d148788298320ac3ba2a23
/Real_Contests/PAC_NW_2022/i.cpp
bd499eaf5f404d8b9dc50af9f58370105de229ad
[]
no_license
ablondal/comp-prog
ee6ea5c0b32d7fbe0321a4b9919a9cec23fe85f6
725e369476993307874f9f5d6e2e7299918251a0
refs/heads/master
2022-10-08T05:40:39.206721
2022-09-25T22:29:49
2022-09-25T22:29:49
243,620,860
0
0
null
null
null
null
UTF-8
C++
false
false
1,894
cpp
#include <bits/stdc++.h> using namespace std; // incomplete #define rep(i, a, b) for(int i = a; i < (b); ++i) #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<ll> vll; typedef complex<double> cd; struct Dinic { struct Edge { int to, rev; ll c, oc; ll flow() { return max(oc - c, 0LL); } // if you need flows }; vi lvl, ptr, q; vector<vector<Edge>> adj; Dinic(int n) : lvl(n), ptr(n), q(n), adj(n) {} void addEdge(int a, int b, ll c, ll rcap = 0) { adj[a].push_back({b, sz(adj[b]), c, c}); adj[b].push_back({a, sz(adj[a]) - 1, rcap, rcap}); } ll dfs(int v, int t, ll f) { if (v == t || !f) return f; for (int& i = ptr[v]; i < sz(adj[v]); i++) { Edge& e = adj[v][i]; if (lvl[e.to] == lvl[v] + 1) if (ll p = dfs(e.to, t, min(f, e.c))) { e.c -= p, adj[e.to][e.rev].c += p; return p; } } return 0; } ll calc(int s, int t) { ll flow = 0; q[0] = s; rep(L,0,31) do { // 'int L=30' maybe faster for random data lvl = ptr = vi(sz(q)); int qi = 0, qe = lvl[s] = 1; while (qi < qe && !lvl[t]) { int v = q[qi++]; for (Edge e : adj[v]) if (!lvl[e.to] && e.c >> (30 - L)) q[qe++] = e.to, lvl[e.to] = lvl[v] + 1; } while (ll p = dfs(s, t, LLONG_MAX)) flow += p; } while (lvl[t]); return flow; } bool leftOfMinCut(int a) { return lvl[a] != 0; } }; int cap[10][10]; int Ni = 1; map<pair<int, int>, int> isec; map<pair<int, int>, int> node; int getisec(int x, int y){ if (isec.count({x,y})) return isec[{x,y}]; return isec[{x,y}] = Ni++; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; rep(i,0,n+1){ string s; cin >> s; rep(j,0,n+1){ if (s[j] == '+') cap[i][j] = 100; else cap[i][j] = s[j]-'0'; } } rep(i,0,n){ rep(j,0,n){ } } }
9584aa7839fdb74769040cad2aa8356e63af0677
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/pdfium/xfa/fxfa/parser/cxfa_soapaddress.cpp
6dae6a108bd0a5cf4bd9c9525feb212ca3d2960c
[ "BSD-3-Clause", "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
1,210
cpp
// Copyright 2017 The PDFium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/fxfa/parser/cxfa_soapaddress.h" #include "fxjs/xfa/cjx_textnode.h" #include "xfa/fxfa/parser/cxfa_document.h" namespace { const CXFA_Node::AttributeData kSoapAddressAttributeData[] = { {XFA_Attribute::Id, XFA_AttributeType::CData, nullptr}, {XFA_Attribute::Name, XFA_AttributeType::CData, nullptr}, {XFA_Attribute::Use, XFA_AttributeType::CData, nullptr}, {XFA_Attribute::Usehref, XFA_AttributeType::CData, nullptr}, }; } // namespace CXFA_SoapAddress::CXFA_SoapAddress(CXFA_Document* doc, XFA_PacketType packet) : CXFA_Node(doc, packet, XFA_XDPPACKET::kConnectionSet, XFA_ObjectType::TextNode, XFA_Element::SoapAddress, {}, kSoapAddressAttributeData, cppgc::MakeGarbageCollected<CJX_TextNode>( doc->GetHeap()->GetAllocationHandle(), this)) {} CXFA_SoapAddress::~CXFA_SoapAddress() = default;
7d1307fc656bb255b7eaf20e966332cf906e452c
1a043849bbbbd7ed218a9dc2caf14fa26cb2e863
/Prueba_EDII/DelimiterVarSize_Register.cpp
718347732f10b4fc3280629e2b2569b4cffaa460
[]
no_license
Oscarluiis/API
16efb1dbbdfff8895fbc4db2a8ee102b4fae65ec
4b2f0acdff301283b06570d1a488ca5e12a26386
refs/heads/master
2020-03-25T01:41:18.144904
2018-08-12T20:03:42
2018-08-12T20:03:42
143,251,185
0
0
null
null
null
null
UTF-8
C++
false
false
3,196
cpp
#include "stdafx.h" #include "DelimiterVarSize_Register.h" DelimiterVarSize_Register::DelimiterVarSize_Register() { this->code = code; this->name = name; this->salary = salary; this->job = job; this->file = new DataFile(); } DelimiterVarSize_Register::~DelimiterVarSize_Register() { } void DelimiterVarSize_Register::print_register() { string compare; int start = 0, end = 0; bool continuar = true; cout << "= = = = Mostrando Todos Los Registros = = = =" << endl; while (continuar) { compare.assign(this->file->read(end, 1)); if (compare == ";") { char * info = this->file->read(start, end); this->fromChar(info); } end++; if (end > this->file->tamFile) { continuar = false; } else { start = end; } } cout << "= = = = Final De Linea = = = =" << endl; } char * DelimiterVarSize_Register::toChar() { char cha_space = '|'; char cha_end = ';'; int get_size = this->get_size(); char*newr = new char[get_size]; int pos = 0; //Code memcpy(&newr[pos], (char*)&this->code, sizeof(int)); pos++; //Escribir el caracter memcpy(&newr[pos], &cha_space, 1); pos++; //name int tam_name = strlen(this->name); memcpy(&newr[pos], this->name, tam_name); pos += tam_name; //Escribir el caracter memcpy(&newr[pos], &cha_space, 1); pos++; //Salary memcpy(&newr[pos], (char*)&this->salary, sizeof(double)); pos++; //Escribir el caracter memcpy(&newr[pos], &cha_space, 1); pos++; //Job int tam_job = strlen(this->job); memcpy(&newr[pos], this->job, tam_job); pos += tam_job; memcpy(&newr[pos], &cha_end, 1); return newr; } void DelimiterVarSize_Register::fromChar(char * conver){ string tempo = ""; int i = 0, currentS = 0, currentP = 0; bool endLect = false; while (!endLect) { if (conver[i] == '|') { if (currentP == 2) { strcpy(this->name, (char*)&tempo); currentP++; } else if (currentP == 4) { strcpy(this->job, (char*)&tempo); endLect = true; } tempo = ""; currentS = 0; } tempo += conver[i]; currentS++; } cout << "Code: " << this->code << endl; cout << "Name: " << this->name << endl; cout << "Salary: " << this->salary << endl; cout << "Job: " << this->job << endl; } void DelimiterVarSize_Register::openfile() { string name; cout << " Ingrese nombre de archivo: " << endl; cin >> name; char *file; file = new char[strlen(name.c_str())]; this->file->open(file); } void DelimiterVarSize_Register::read_file() { string compare; int sZ = 0; bool continuar = true; while (continuar) { compare.assign(this->file->read(sZ, 1)); if (compare == ";") continuar = false; sZ++; } char* info = this->file->read(0, sZ); this->fromChar(info); } void DelimiterVarSize_Register::close_file(){ this->file->close(); } int DelimiterVarSize_Register::get_size() { //rS register size int rS = 0; rS += 1; rS += strlen(this->name); rS += 3; rS += strlen(this->job); return rS; } //Pendiente el writer /* void write_into_file() Escribe al final del archivo binario, la estructura de datos actual */
9b521663e2c9d976986f50a4135b8dc69bde6596
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2755486_1/C++/Echo80313/c.cpp
7680ada553da7f59f4aa4451360ff2f451d4c4f7
[]
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,266
cpp
#include <cstdio> #include <vector> #include <queue> #include <string> #include <cstring> #include <list> #include <map> #include <set> #include <stack> #include <bitset> #include <climits> #include <utility> #include <cstdlib> #include <algorithm> #include <iostream> #include <cmath> #define REP(i,n) for( int (i)=0;(i)<(int)(n); ++(i)) #define REPR(i,n) for( int (i) = n; (i)>=0; --(i)) #define REPN(i,x,y) for( int i = x; (i) < (int)(y); (i)++ ) #define REPIT(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++) #define ZERO(x) memset(x,0,sizeof(x)) #define RI(n) scanf("%d",&(n)) #define RII(x,y) scanf("%d %d",&(x),&(y)) #define OI(x) printf("%d\n",(x)) #define OII(x,y) printf("%d %d\n",(x),(y)) #define FT first #define SD second using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int,int> PII; LL LLMAX = 9223372036854775807LL; const int MOD = 1000000007; const int maxn = 1000000+10; struct tr{ int d,n,w,e,s,dd,dp,ds; bool operator<(const tr& r)const{ return d>r.d || d==r.d && s>r.s; } }; int N; tr TR[20]; int* Wall; int main() { #ifndef ONLINE_JUDGE freopen("C-large.in","r",stdin); freopen("out.txt","w",stdout); #endif return 0; int T; RI(T); Wall = new int[2000010]; REP(kase,T){ /*LL ans=0; memset(Wall,0,sizeof(int)*2000010); RI(N); priority_queue<tr> pq; REP(i,N){ scanf("%d%d%d%d%d%d%d%d",&TR[i].d,&TR[i].n,&TR[i].w,&TR[i].e,&TR[i].s,&TR[i].dd,&TR[i].dp,&TR[i].ds); TR[i].e += maxn; TR[i].w += maxn; pq.push(TR[i]); } while(!pq.empty()){ tr r=pq.top();pq.pop(); if(r.n==0)continue; bool f = 0; for(int i=r.w;i<r.e;++i){ if(Wall[i]<r.s){ f=1; Wall[i] = r.s; } } //printf("%d %d %d %d\n",r.d,r.w,r.e,r.s); if(f)ans++; r.d += r.dd; r.e += r.dp; r.w += r.dp; r.s += r.ds; r.n--; pq.push(r);*/ } int ans; printf("Case #%d: %lld\n",kase+1,ans); } }
0ac209ab9e008fcdc9acc0c229e11adf38c975ee
d6c8853843fd02ebb996390dacd55f0af6a4b0b4
/src/hnmodel.cpp
8151280f226f314834df4a01fdc727583ed20bcc
[ "MIT" ]
permissive
RobertMe/SailHN
159d19eeafcb642a4ef80940b790de45ea460d31
3ad227b6e9d2ab5cbef194798f5c1d976f1912ca
refs/heads/master
2021-01-01T05:48:09.632196
2014-10-15T16:45:36
2014-10-15T16:45:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,284
cpp
#include "hnmodel.h" #include <QJsonObject> #include <QJsonValue> #include "hnconnection.h" HnModel::HnModel(QObject *parent) : QAbstractItemModel(parent) { } void HnModel::setItemIds(const QList<int> &itemIds) { beginResetModel(); m_itemIds = itemIds; qDeleteAll(m_items); m_items.clear(); m_pendingItemIds.clear(); endResetModel(); } HnModelItem *HnModel::get(const int index) const { if (index < 0 || index >= m_itemIds.size()) { return 0; } int itemId = m_itemIds.at(index); if (!m_items.contains(itemId)) { return 0; } return m_items[itemId]; } int HnModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_itemIds.size(); } QVariant HnModel::data(const QModelIndex &index, int role) const { if (index.row() < 0 || index.row() >= m_itemIds.size()) { return QVariant(); } int itemId = m_itemIds.at(index.row()); if (role == RoleId) { return itemId; } HnModelItem* item = m_items.value(itemId); if (!item) { ((HnModel*)this)->requestItem(itemId); if (role == RoleTitle) { return tr("Loading..."); } return QVariant(); } if (role == RoleId) { return item->id(); } else if (role == RoleDeleted) { return item->deleted(); } else if (role == RoleType) { return item->type(); } else if (role == RoleBy) { return item->by(); } else if (role == RoleTime) { return item->time(); } else if (role == RoleText) { return item->text(); } else if (role == RoleDead) { return item->dead(); } else if (role == RoleParent) { return item->parent(); } else if (role == RoleKids) { //return item->kids(); } else if (role == RoleUrl) { return item->url(); } else if (role == RoleScore) { return item->score(); } else if (role == RoleTitle) { return item->title(); } else if (role == RoleParts) { //return item->parts(); } return QVariant(); } int HnModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return 1; } QModelIndex HnModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent) return createIndex(row, column); } QModelIndex HnModel::parent(const QModelIndex &child) const { Q_UNUSED(child) return QModelIndex(); } QHash<int, QByteArray> HnModel::roleNames() const { QHash<int, QByteArray> roles; roles[RoleId] = "id"; roles[RoleDeleted] = "deleted"; roles[RoleType] = "type"; roles[RoleBy] = "by"; roles[RoleTime] = "time"; roles[RoleText] = "text"; roles[RoleDead] = "dead"; roles[RoleParent] = "parent"; roles[RoleKids] = "kids"; roles[RoleUrl] = "url"; roles[RoleScore] = "score"; roles[RoleTitle] = "title"; roles[RoleParts] = "parts"; return roles; } void HnModel::requestItem(const int itemId) { if (m_pendingItemIds.contains(itemId)) { return; } HnConnection::instance()->get("v0/item/" + QString::number(itemId) + ".json", this, "itemReceived"); m_pendingItemIds.append(itemId); } void HnModel::itemReceived(const QJsonDocument document) { if (!document.isObject() || !document.object().contains("id")) { return; } QJsonObject jsonItem = document.object(); int itemId = jsonItem.value("id").toVariant().toInt(); m_pendingItemIds.removeOne(itemId); HnModelItem *item = new HnModelItem(); item->setId(itemId); item->setBy(jsonItem.value("by").toString()); item->setDead(jsonItem.value("dead").toBool()); item->setDeleted(jsonItem.value("deleted").toBool()); item->setParent(jsonItem.value("parent").toVariant().toInt()); item->setScore(jsonItem.value("score").toVariant().toInt()); item->setText(jsonItem.value("text").toString()); item->setTime(QDateTime::fromTime_t(jsonItem.value("time").toVariant().toInt())); item->setTitle(jsonItem.value("title").toString()); item->setUrl(jsonItem.value("url").toVariant().toUrl()); int row = m_itemIds.indexOf(itemId); m_items.insert(itemId, item); emit dataChanged(index(row, 0, QModelIndex()), index(row, 0, QModelIndex())); }
033f5aa1fb99e60d5de05af9465ef488b248a9cf
77ea81061e529e2efd5817654de22e482873da07
/face-pipeline/features-speakers/src/vgg_ssd_aux.cxx
9e7b0f50a158c53ac6dbf0f7e042aaa7014d9857
[ "MIT" ]
permissive
gbouritsas/cvpr18_multimodal_weakly_supervised_learning
8eaac8903bb74d83cfd6d85219257a1c2d2d6b81
f63a84ac228ee92c6170f7bda1651da496187647
refs/heads/master
2018-07-13T06:54:40.482611
2018-06-01T10:50:29
2018-06-01T10:50:29
123,573,601
2
1
null
null
null
null
UTF-8
C++
false
false
4,711
cxx
/* Compute ssd_image of image wrt mask * * * */ #include <mex.h> #include <stdlib.h> #include <math.h> #include <memory.h> #define for if(0);else for static void nssd_dispatch(double const* I, int w, int h, double const* M, int mw, int mh, int method, double* out); static double compare(double* a, double const* b, int w, int h, int method); struct method_ssd { enum { method = 0 }; }; struct method_nssd { enum { method = 1 }; }; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs != 3) mexErrMsgTxt("vgg_ssd must have 3 arguments"); if (!mxIsDouble(prhs[0])) mexErrMsgTxt("vgg_ssd takes only double arguments for I"); if (!mxIsDouble(prhs[1])) mexErrMsgTxt("vgg_ssd takes only double arguments for M"); if (!mxIsDouble(prhs[2])) mexErrMsgTxt("vgg_ssd takes only double arguments for Method"); if (nlhs > 1) mexErrMsgTxt("Must have exactly one output."); mxArray const* I_ptr = prhs[0]; mxArray const* M_ptr = prhs[1]; mxArray const* method_ptr = prhs[2]; int method = int(mxGetPr(method_ptr)[0]); int h = mxGetM(I_ptr); int w = mxGetN(I_ptr); int mh = mxGetM(M_ptr); int mw = mxGetN(M_ptr); int oh = h - mh + 1; int ow = w - mw + 1; if (oh < 1 || ow < 1) mexErrMsgTxt("vgg_ssd arguments have bad sizes: M should be smaller than I"); //printf("oi %d x %d method = %d\n", oh, ow, method); // make output array mxArray* SSD_ptr = mxCreateDoubleMatrix(oh, ow, mxREAL); double const* I = mxGetPr(I_ptr); double const* M = mxGetPr(M_ptr); double* SSD = mxGetPr(SSD_ptr); nssd_dispatch(I, w, h, M, mw, mh, method, SSD); // assign output array plhs[0] = SSD_ptr; } // zero-based accessor #define get(A,x,y,W,H) ((A)[(x)*(H) + (y)]) static inline double sqr(double x) { return x*x; } static inline double compare(method_ssd*, double* a, double const* b, int w, int h) { int n = w*h; double ssd = 0; for(int i = 0; i < n; ++i) { double d = b[i] - a[i]; ssd += d*d; } return ssd; } static inline double compare(method_nssd*, double* a, double const* b, int w, int h) { int n = w*h; // compute means double sum_a = 0; double sum_b = 0; for(int i = 0; i < n; ++i) { sum_a += a[i]; sum_b += b[i]; } double mean_a = sum_a / n; double mean_b = sum_b / n; // compute variances double sum_aa = 0; double sum_bb = 0; for(int i = 0; i < n; ++i) { sum_aa += sqr(a[i] - mean_a); sum_bb += sqr(b[i] - mean_b); } double var_a = sum_aa / (n-1); double var_b = sum_bb / (n-1); // printf("means = %g,%g vars = %g,%g\n", mean_a, mean_b, var_a, var_b); // compute sum [(a_i - mean_a)/sigma_a - ditto_b]^2 double scale_a = 1 / sqrt(var_a); double scale_b = 1 / sqrt(var_b); double nssd = 0; for(int i = 0; i < n; ++i) { double d = ((a[i] - mean_a) * scale_a - (b[i] - mean_b) * scale_b); nssd += d*d; } return nssd; } template <class Method> static void nssd_template(double const* I, int w, int h, double const* M, int mw, int mh, double* out) { #define getI(x,y) get(I,x,y,w,h) #define getM(x,y) get(M,x,y,mw,mh) int oh = h - mh + 1; int ow = w - mw + 1; double* tmp = (double*)malloc(mh*mw*sizeof (double)); // printf("[n%d]", Method::method); for(int x = 0; x < w-mw+1; ++x) for(int y = 0; y < h-mh+1; ++y) { double*p = tmp; for(int mx = 0; mx < mw; ++mx) for(int my = 0; my < mh; ++my) *p++ = getI(x+mx,y+my); get(out, x,y, ow,oh) = compare((Method*)0, tmp, M, mw, mh); } free(tmp); } static void nssd_dispatch(double const* I, int w, int h, double const* M, int mw, int mh, int method, double* out) { // printf("[nssd%d]", method); if (method == method_ssd::method) nssd_template<method_ssd>(I, w, h, M, mw, mh, out); if (method == method_nssd::method) nssd_template<method_nssd>(I, w, h, M, mw, mh, out); } ///////////////////////////////////////////////////////////////////////////// #if 0 void ssd(double const* I, int w, int h, double const* M, int mw, int mh, double* out) { #define getI(x,y) get(I,x,y,w,h) #define getM(x,y) get(M,x,y,mw,mh) int oh = h - mh + 1; int ow = w - mw + 1; double* p = out + oh*ow; while (p-- != out) *p = 255.0; for(int x = 0; x < w-mw+1; ++x) for(int y = 0; y < h-mh+1; ++y) { double ssd = 0; for(int mx = 0; mx < mw; ++mx) for(int my = 0; my < mh; ++my) { // printf("%3d %3d %10g %3d %3d %10g\n", x,y, getI(x,y), mx,my, getM(mx,my)); double d = getI(x+mx,y+my) - getM(mx, my); ssd += d*d; } get(out, x,y, ow,oh) = ssd; } } #endif
e8e5887c0635f4ce87ae927aa36c5393325ad678
6342487fd7437b7c777f79603f179b1c3a7bc5cf
/Arduino/microController/schienale-multi/schienale-multi.ino
0c76ccc5133b4b9ead69acf68ff6ecd364da84dc
[ "MIT" ]
permissive
maxmuffin/SmartSeat
6d3d1cd0d271be30ac35c1fda803b363d31b083c
b9178b6b9960f258f60a3d713feb97559145ff82
refs/heads/master
2020-09-11T07:04:13.249791
2019-11-15T20:34:46
2019-11-15T20:34:46
221,981,508
1
1
MIT
2019-11-15T20:34:47
2019-11-15T18:29:56
JavaScript
UTF-8
C++
false
false
1,230
ino
#include <HX711-multi.h> // Pins to the load cell amp #define DOUT1 1 // data pin to the 1 sensor #define DOUT2 3 // data pin to the 2 sensor #define DOUT3 4 // data pin to the 3 sensor #define CLK 5 // clock pin to the load cell amp #define TARE_TIMEOUT_SECONDS 4 byte DOUTS[3] = {DOUT1, DOUT2, DOUT3}; #define CHANNEL_COUNT sizeof(DOUTS)/sizeof(byte) long int results[CHANNEL_COUNT]; HX711MULTI scales(CHANNEL_COUNT, DOUTS, CLK); void setup() { Serial.begin(115200); Serial.flush(); tare(); } void tare() { bool tareSuccessful = false; unsigned long tareStartTime = millis(); while (!tareSuccessful && millis()<(tareStartTime+TARE_TIMEOUT_SECONDS*1000)) { tareSuccessful = scales.tare(20,10000); //reject 'tare' if still ringing } } //this is for sending raw data, for where everything else is done in processing void sendRawData() { scales.read(results); for (int i=0; i<scales.get_count(); ++i) {; Serial.print( -results[i]); Serial.print( (i!=scales.get_count()-1)?"\t":"\n"); } delay(10); } void loop() { sendRawData(); //on serial data (any data) re-tare if (Serial.available()>0) { while (Serial.available()) { Serial.read(); } tare(); } }
14d7ba2d8f34e4d81cbb64bbbcd1b17e23344e21
95990e5be338229fdd5732a96ddc9d829b23e8cb
/src/p_spec.h
32bb784c9b5f162bf3c77be6c8d29a9a5758b19c
[]
no_license
DooMJunkie/wii-doom
5e65eef1f6928729d653f6df8dc4daf4e1a4bd17
f603cc6006ee6568ae264456793830020ad52bea
refs/heads/master
2021-01-17T17:07:15.198046
2015-01-07T13:23:04
2015-01-07T13:23:04
35,858,038
0
0
null
null
null
null
UTF-8
C++
false
false
9,821
h
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // Copyright(C) 1993-1996 Id Software, Inc. // Copyright(C) 2005 Simon Howard // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // // DESCRIPTION: none // Implements special effects: // Texture animation, height or lighting changes // according to adjacent sectors, respective // utility functions, etc. // //----------------------------------------------------------------------------- #ifndef __P_SPEC__ #define __P_SPEC__ // // End-level timer (-TIMER option) // extern boolean levelTimer; extern int levelTimeCount; // Define values for map objects #define MO_TELEPORTMAN 14 // at game start void P_InitPicAnims (void); // at map load void P_SpawnSpecials (void); // every tic void P_UpdateSpecials (void); // when needed boolean P_UseSpecialLine ( mobj_t* thing, line_t* line, int side ); void P_ShootSpecialLine ( mobj_t* thing, line_t* line ); void P_CrossSpecialLine ( int linenum, int side, mobj_t* thing ); void P_PlayerInSpecialSector (player_t* player); int twoSided ( int sector, int line ); sector_t* getSector ( int currentSector, int line, int side ); side_t* getSide ( int currentSector, int line, int side ); fixed_t P_FindLowestFloorSurrounding(sector_t* sec); fixed_t P_FindHighestFloorSurrounding(sector_t* sec); fixed_t P_FindNextHighestFloor ( sector_t* sec, int currentheight ); fixed_t P_FindLowestCeilingSurrounding(sector_t* sec); fixed_t P_FindHighestCeilingSurrounding(sector_t* sec); int P_FindSectorFromLineTag ( line_t* line, int start ); int P_FindMinSurroundingLight ( sector_t* sector, int max ); sector_t* getNextSector ( line_t* line, sector_t* sec ); // // SPECIAL // int EV_DoDonut(line_t* line); // // P_LIGHTS // typedef struct { thinker_t thinker; sector_t* sector; int count; int maxlight; int minlight; } fireflicker_t; typedef struct { thinker_t thinker; sector_t* sector; int count; int maxlight; int minlight; int maxtime; int mintime; } lightflash_t; typedef struct { thinker_t thinker; sector_t* sector; int count; int minlight; int maxlight; int darktime; int brighttime; } strobe_t; typedef struct { thinker_t thinker; sector_t* sector; int minlight; int maxlight; int direction; } glow_t; #define GLOWSPEED 8 #define STROBEBRIGHT 5 #define FASTDARK 15 #define SLOWDARK 35 void P_SpawnFireFlicker (sector_t* sector); void T_LightFlash (lightflash_t* flash); void P_SpawnLightFlash (sector_t* sector); void T_StrobeFlash (strobe_t* flash); void P_SpawnStrobeFlash ( sector_t* sector, int fastOrSlow, int inSync ); void EV_StartLightStrobing(line_t* line); void EV_TurnTagLightsOff(line_t* line); void EV_LightTurnOn ( line_t* line, int bright ); void T_Glow(glow_t* g); void P_SpawnGlowingLight(sector_t* sector); // // P_SWITCH // typedef struct { char name1[9]; char name2[9]; short episode; } switchlist_t; typedef enum { top, middle, bottom } bwhere_e; typedef struct { line_t* line; bwhere_e where; int btexture; int btimer; degenmobj_t *soundorg; } button_t; // max # of wall switches in a level #define MAXSWITCHES 50 // 4 players, 4 buttons each at once, max. #define MAXBUTTONS 16 // 1 second, in ticks. #define BUTTONTIME 35 extern button_t buttonlist[MAXBUTTONS]; void P_ChangeSwitchTexture ( line_t* line, int useAgain ); void P_InitSwitchList(void); // // P_PLATS // typedef enum { up, down, waiting, in_stasis } plat_e; typedef enum { perpetualRaise, downWaitUpStay, raiseAndChange, raiseToNearestAndChange, blazeDWUS } plattype_e; typedef struct { thinker_t thinker; sector_t* sector; fixed_t speed; fixed_t low; fixed_t high; int wait; int count; plat_e status; plat_e oldstatus; boolean crush; int tag; plattype_e type; } plat_t; #define PLATWAIT 3 #define PLATSPEED FRACUNIT //#define MAXPLATS 30 // CHANGED FOR HIRES #define MAXPLATS 30*256 // CHANGED FOR HIRES extern plat_t* activeplats[MAXPLATS]; void T_PlatRaise(plat_t* plat); int EV_DoPlat ( line_t* line, plattype_e type, int amount ); void P_AddActivePlat(plat_t* plat); void P_RemoveActivePlat(plat_t* plat); void EV_StopPlat(line_t* line); void P_ActivateInStasis(int tag); // // P_DOORS // typedef enum { normal, close30ThenOpen, closed, open, raiseIn5Mins, blazeRaise, blazeOpen, blazeClose } vldoor_e; typedef struct { thinker_t thinker; vldoor_e type; sector_t* sector; fixed_t topheight; fixed_t speed; // 1 = up, 0 = waiting at top, -1 = down int direction; // tics to wait at the top int topwait; // (keep in case a door going down is reset) // when it reaches 0, start going down int topcountdown; } vldoor_t; #define VDOORSPEED FRACUNIT*2 #define VDOORWAIT 150 void EV_VerticalDoor ( line_t* line, mobj_t* thing ); int EV_DoDoor ( line_t* line, vldoor_e type ); int EV_DoLockedDoor ( line_t* line, vldoor_e type, mobj_t* thing ); void T_VerticalDoor (vldoor_t* door); void P_SpawnDoorCloseIn30 (sector_t* sec); void P_SpawnDoorRaiseIn5Mins ( sector_t* sec, int secnum ); #if 0 // UNUSED // // Sliding doors... // typedef enum { sd_opening, sd_waiting, sd_closing } sd_e; typedef enum { sdt_openOnly, sdt_closeOnly, sdt_openAndClose } sdt_e; typedef struct { thinker_t thinker; sdt_e type; line_t* line; int frame; int whichDoorIndex; int timer; sector_t* frontsector; sector_t* backsector; sd_e status; } slidedoor_t; typedef struct { char frontFrame1[9]; char frontFrame2[9]; char frontFrame3[9]; char frontFrame4[9]; char backFrame1[9]; char backFrame2[9]; char backFrame3[9]; char backFrame4[9]; } slidename_t; typedef struct { int frontFrames[4]; int backFrames[4]; } slideframe_t; // how many frames of animation #define SNUMFRAMES 4 #define SDOORWAIT 35*3 #define SWAITTICS 4 // how many diff. types of anims #define MAXSLIDEDOORS 5 void P_InitSlidingDoorFrames(void); void EV_SlidingDoor ( line_t* line, mobj_t* thing ); #endif // // P_CEILNG // typedef enum { lowerToFloor, raiseToHighest, lowerAndCrush, crushAndRaise, fastCrushAndRaise, silentCrushAndRaise } ceiling_e; typedef struct { thinker_t thinker; ceiling_e type; sector_t* sector; fixed_t bottomheight; fixed_t topheight; fixed_t speed; boolean crush; // 1 = up, 0 = waiting, -1 = down int direction; // ID int tag; int olddirection; } ceiling_t; #define CEILSPEED FRACUNIT #define CEILWAIT 150 #define MAXCEILINGS 30 extern ceiling_t* activeceilings[MAXCEILINGS]; int EV_DoCeiling ( line_t* line, ceiling_e type ); void T_MoveCeiling (ceiling_t* ceiling); void P_AddActiveCeiling(ceiling_t* c); void P_RemoveActiveCeiling(ceiling_t* c); int EV_CeilingCrushStop(line_t* line); void P_ActivateInStasisCeiling(line_t* line); // // P_FLOOR // typedef enum { // lower floor to highest surrounding floor lowerFloor, // lower floor to lowest surrounding floor lowerFloorToLowest, // lower floor to highest surrounding floor VERY FAST turboLower, // raise floor to lowest surrounding CEILING raiseFloor, // raise floor to next highest surrounding floor raiseFloorToNearest, // raise floor to shortest height texture around it raiseToTexture, // lower floor to lowest surrounding floor // and change floorpic lowerAndChange, raiseFloor24, raiseFloor24AndChange, raiseFloorCrush, // raise to next highest floor, turbo-speed raiseFloorTurbo, donutRaise, raiseFloor512 } floor_e; typedef enum { build8, // slowly build by 8 turbo16 // quickly build by 16 } stair_e; typedef struct { thinker_t thinker; floor_e type; boolean crush; sector_t* sector; int direction; int newspecial; short texture; fixed_t floordestheight; fixed_t speed; } floormove_t; #define FLOORSPEED FRACUNIT typedef enum { ok, crushed, pastdest } result_e; result_e T_MovePlane ( sector_t* sector, fixed_t speed, fixed_t dest, boolean crush, int floorOrCeiling, int direction ); int EV_BuildStairs ( line_t* line, stair_e type ); int EV_DoFloor ( line_t* line, floor_e floortype ); void T_MoveFloor( floormove_t* floor); // // P_TELEPT // int EV_Teleport ( line_t* line, int side, mobj_t* thing ); #endif
[ "vermillion57@cb9b8005-22f9-ec2e-6a47-6c8965c50df9" ]
vermillion57@cb9b8005-22f9-ec2e-6a47-6c8965c50df9
31c3475fd9fd55e51c91c26a929882e524c6d46c
7c3080a2bb960941b2931905971d9373de4c46bd
/ConsoleClock/DigitalClock.cpp
afbad3409a373ecccdbe321f12fce2e5eeb62d27
[]
no_license
joonkid/ConsoleClock
c5019ec5d6f79115ace4208ac8453345ce144f05
da77cbfa7d719fd3a0f4c93e9522dc033832b152
refs/heads/master
2020-04-04T13:04:47.584648
2018-11-09T03:55:59
2018-11-09T03:55:59
155,947,882
0
0
null
null
null
null
UTF-8
C++
false
false
513
cpp
#include"pch.h" #include<stdio.h> #include<time.h> #include<Windows.h> #include"DigitalClock.h" void DigitalClock_GetTime() { time_t now = time(NULL); struct tm time; localtime_s(&time, &now); printf("%04d-%02d-%02d %02d:%02d:%02d\n", time.tm_year + 1900, time.tm_mon + 1, time.tm_mday, time.tm_hour, time.tm_min, time.tm_sec); DigitalClock dgc = { 0, }; dgc.year = time.tm_year + 1900; dgc.month = time.tm_mon + 1; dgc.dayOfMonth = time.tm_mday; dgc.dayOfWeek = time.tm_wday; dgc.hour = }
[ "sonol02@DESKTOP-914S3J4" ]
sonol02@DESKTOP-914S3J4
9bd6a4dfbe0e4a22ad3e3e949f6b4bfb7999d01c
7a53e66bfb582e734661ba0d0cbf4684182b39b9
/InputComponent.cpp
a3b713e08c25beaa532bd76db902d5dd430b464c
[]
no_license
MHSHM/Asteroids
14340472ed4f71e3f423a33ae03b26bd339f3b3b
e8a305b19ee9ac6fe95fb23ceb752577d6ac24c5
refs/heads/master
2021-03-26T09:42:27.058756
2020-03-16T12:35:07
2020-03-16T12:35:07
247,693,432
2
0
null
null
null
null
UTF-8
C++
false
false
663
cpp
#include "pch.h" #include "InputComponent.h" #include "Actor.h" InputComponent::InputComponent(Actor *owner): MoveComponent(owner) { } void InputComponent::ProcessInput(const uint8_t* keyState) { float forwardSpeed = 0.0f; if (keyState[mForwardKey]) { forwardSpeed += mMaxForwardSpeed; } if (keyState[mBackwardKey]) { forwardSpeed -= mMaxForwardSpeed; } SetForwardSpeed(forwardSpeed); float angularSpeed = 0.0f; if (keyState[mClocwiseKey]) { angularSpeed += mMaxAngularSpeed; } if (keyState[mAntiClockwiseKey]) { angularSpeed -= mMaxAngularSpeed; } SetAngularSpeed(angularSpeed); } InputComponent::~InputComponent() { }
41315920ea5c0dd13950dae232a9d4ec32d0a9cc
d3adda0004132175f0a9cbfc603dbd3496f7ff08
/debugger/QT/SkDebuggerGUI.h
72f03c5b402c8284cd96e8416db722d2493bebbc
[ "BSD-3-Clause" ]
permissive
zhangyongfei/StudySkia
20f76c619e976b8ce324800c036cb6640671d7f0
296eec438bdbd8a5a1abcd4e5987129513618f6a
refs/heads/master
2016-09-06T20:12:00.459057
2014-07-16T09:43:55
2014-07-16T09:43:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,448
h
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SKDEBUGGERUI_H #define SKDEBUGGERUI_H #include "SkCanvas.h" #include "SkCanvasWidget.h" #include "SkDebugger.h" #include "SkGLWidget.h" #include "SkListWidget.h" #include "SkInspectorWidget.h" #include "SkRasterWidget.h" #include "SkImageWidget.h" #include "SkSettingsWidget.h" #include <QtCore/QVariant> #include <QAction> #include <QApplication> #include <QButtonGroup> #include <QHBoxLayout> #include <QHeaderView> #include <QListView> #include <QListWidget> #include <QMainWindow> #include <QSplitter> #include <QStatusBar> #include <QToolBar> #include <QVBoxLayout> #include <QWidget> #include <QMenu> #include <QMenuBar> #include <vector> class SkTimedPicture; namespace sk_tools { class PictureRenderer; } /** \class SkDebuggerGUI Container for the UI and it's functions. */ class SkDebuggerGUI : public QMainWindow { Q_OBJECT public: /** Constructs the view of the application. @param parent The parent container of this widget. */ SkDebuggerGUI(QWidget *parent = 0); ~SkDebuggerGUI(); /** Updates the directory widget with the latest directory path stored in the global class variable fPath. */ void setupDirectoryWidget(const QString& path); /** Loads the specified file. */ void openFile(const QString& filename); signals: void commandChanged(int command); private slots: /** Toggles breakpoint view in the list widget. */ void actionBreakpoints(); /** Toggles between count and offset style of command indexing in GUI */ void actionToggleIndexStyle(); /** Profile the commands */ void actionProfile(); /** Cancels the command filter in the list widget. */ void actionCancel(); /** Clears the breakpoint state off of all commands marked as breakpoints. */ void actionClearBreakpoints(); /** Clears the deleted state off of all commands marked as deleted. */ void actionClearDeletes(); /** Applies a visible filter to all drawing commands other than the previous. */ void actionCommandFilter(); /** Closes the application. */ void actionClose(); /** Deletes the command in question. */ void actionDelete(); #if SK_SUPPORT_GPU /** Updates the visibility of the GL canvas widget and sample count of the GL surface. */ void actionGLWidget(); #endif /** Toggles the visibility of the inspector widget. */ void actionInspector(); /** Plays from the current step to the next breakpoint if it exists, otherwise executes all remaining draw commands. */ void actionPlay(); /** Toggles the visibility of the raster canvas widget. */ void actionRasterWidget(bool isToggled); /** Toggles the the overdraw visualization on and off */ void actionOverdrawVizWidget(bool isToggled); /** Toggles the the mega visualization on and off */ void actionMegaVizWidget(bool isToggled); /** Toggles using path ops to simplify the clip stack */ void actionPathOpsWidget(bool ); /** Applies the new texture filter override */ void actionTextureFilter(); /** Rewinds from the current step back to the start of the commands. */ void actionRewind(); /** Saves the current SKP with all modifications. */ void actionSave(); /** Saves the current SKP under a different name and/or location. */ void actionSaveAs(); /** Sends the scale factor information to the settings widget. */ void actionScale(float scaleFactor); /** Toggles the settings widget visibility. */ void actionSettings(); /** Steps forward to the next draw command. */ void actionStepBack(); /** Steps backwards to the next draw command. */ void actionStepForward(); /** Called when the canvas is done being drawn to by SkCanvasWidget. */ void drawComplete(); /** Loads an skpicture selected from the directory. */ void loadFile(QListWidgetItem *item); /** Toggles a dialog with a file browser for navigating to a skpicture. Loads the selected file. */ void openFile(); /** Toggles whether drawing to a new command requires a double click or simple focus. */ void pauseDrawing(bool isPaused = true); /** Executes draw commands up to the selected command */ void registerListClick(QListWidgetItem *item); /** Sets the command to active in the list widget. */ void selectCommand(int command); /** Toggles the exclusive listing of commands set as deleted. */ void showDeletes(); /** Toggles a breakpoint on the current step in the list widget. */ void toggleBreakpoint(); /** Toggles the visibility of the directory widget. */ void toggleDirectory(); /** Filters the list widgets command visibility based on the currently active selection. */ void toggleFilter(QString string); private: QSplitter fCentralSplitter; QStatusBar fStatusBar; QToolBar fToolBar; QAction fActionOpen; QAction fActionBreakpoint; QAction fActionToggleIndexStyle; QAction fActionProfile; QAction fActionCancel; QAction fActionClearBreakpoints; QAction fActionClearDeletes; QAction fActionClose; QAction fActionCreateBreakpoint; QAction fActionDelete; QAction fActionDirectory; QAction fActionGoToLine; QAction fActionInspector; QAction fActionSettings; QAction fActionPlay; QAction fActionPause; QAction fActionRewind; QAction fActionSave; QAction fActionSaveAs; QAction fActionShowDeletes; QAction fActionStepBack; QAction fActionStepForward; QAction fActionZoomIn; QAction fActionZoomOut; QSignalMapper fMapper; QWidget fSpacer; QComboBox fFilter; QSplitter fLeftColumnSplitter; QWidget fMainAndRightColumnWidget; QVBoxLayout fMainAndRightColumnLayout; QHBoxLayout fCanvasSettingsAndImageLayout; QVBoxLayout fSettingsAndImageLayout; QListWidget fListWidget; QListWidget fDirectoryWidget; SkDebugger fDebugger; SkCanvasWidget fCanvasWidget; SkImageWidget fImageWidget; SkInspectorWidget fInspectorWidget; SkSettingsWidget fSettingsWidget; QString fPath; SkString fFileName; SkTDArray<bool> fSkipCommands; // has a specific command been deleted? bool fDirectoryWidgetActive; QMenuBar fMenuBar; QMenu fMenuFile; QMenu fMenuEdit; QMenu fMenuNavigate; QMenu fMenuView; QMenu fMenuWindows; bool fBreakpointsActivated; bool fIndexStyleToggle; bool fDeletesActivated; bool fPause; bool fLoading; int fPausedRow; /** Creates the entire UI. */ void setupUi(QMainWindow *SkDebuggerGUI); /** Pipes a QString in with the location of the filename, proceeds to updating the listwidget, combowidget and inspectorwidget. */ void loadPicture(const SkString& fileName); /** Creates a picture of the current canvas. */ void saveToFile(const SkString& filename); /** Populates the list widget with the vector of strings passed in. */ void setupListWidget(SkTArray<SkString>* commands, SkTDArray<size_t>* offsets); /** Populates the combo box widget with the vector of strings passed in. */ void setupComboBox(SkTArray<SkString>* command); /** Fills in the overview pane with text */ void setupOverviewText(const SkTDArray<double>* typeTimes, double totTime, int numRuns); /** Fills in the clip stack pane with text */ void setupClipStackText(); /** Render the supplied picture several times tracking the time consumed by each command. */ void run(const SkPicture* pict, sk_tools::PictureRenderer* renderer, int repeats); }; #endif // SKDEBUGGERUI_H
da17eccbfb00ca80b95c724b813e92bc2ad664c6
377cc88e079d7f6ae2599fd437125eb5a81e50d7
/SpectroHelp/DemoPixelDiagram.cpp
97abcee842aff8dd6c859fbd41b13bc0dadc6696
[]
no_license
neurocod/SpectroHelp
5d1c2227cd7fd257c689c57546e83c8adf207070
6132ed9243dc8cf7adad0753da9999a3c530239f
refs/heads/master
2021-04-11T14:03:26.483646
2014-05-04T11:58:57
2014-05-04T11:58:57
249,025,982
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,672
cpp
//DemoPixelDiagram.cpp by Kostya Kozachuck as neurocod #include "pch.h" #include "TextWithBorderGraphicsItem.h" #include "GridItemsLayout.h" #include "DemoPixelDiagram.h" #include "DemoScene.h" DemoPixelDiagram::DemoPixelDiagram(ColorProfile pr, Mode mode, QString str): m_layout(this), r0("Red"), g0("Green"), b0("Blue"), r1("Red"), g1("Green"), b1("Blue") { auto desc = ColorProfileDesc::get(pr); if(str.isEmpty()) str = rtr(L"%2 (Профиль: %1, Режим: %2)", "%2 (Profile: %1, Mode: %2)") .arg(desc->name) .arg(desc->mode(mode).name); QString tooltip = desc->mode(mode).tooltip; m_layout.setSizeBetween(50, 50); int row = 0; if(!str.isEmpty()) { New<GraphicsTextItem> item(str); item->setData(DemoScene::s_nKeyProfile, (int)pr); item->setData(DemoScene::s_nKeyMode, (int)mode); item->setToolTip(tooltip); m_layout.place(1.5, 0.2 + row, item); row++; } QList<QGraphicsItem*> li; li << r0 << g0 << b0 << r1 << g1 << b1; for(auto item: li) { item->setData(DemoScene::s_nKeyProfile, (int)pr); item->setData(DemoScene::s_nKeyMode, (int)mode); item->setToolTip(tooltip); } m_layout.place(0, row, r0); m_layout.place(1, row, g0); m_layout.place(2, row, b0); row++; m_layout.place(0, row, r1); m_layout.place(1, row, g1); m_layout.place(2, row, b1); QColor clr; if(ProfileR==pr || ModeR==mode) clr = Qt::red; if(ProfileG==pr || ModeG==mode) clr = Qt::green; if(ProfileB==pr || ModeB==mode) clr = Qt::blue; if(clr.isValid()) { QList<TextWithBorderGraphicsItem*> li; li << r0 << r1 << g0 << g1 << b0 << b1; for(auto i: li) i->setBorderColor(clr); } }
aff5df2c727119140f26b33e4fe950f3816a1877
4b36550e781dc52c4778ee3b79abed2a23764f33
/bench/BenchMain.cpp
01c9aff7941ad363c4e10042afe86e3c59a63140
[ "BSD-3-Clause" ]
permissive
rafgitdz/bimodal-scheduler-rstm
c1ab80bca9990fb0912f48c6a00fc51802d6ce66
7d6f795e6a2820a4c59cdc195bcea4d13c5d20c8
refs/heads/master
2016-09-16T02:30:04.118997
2015-09-24T09:30:01
2015-09-24T09:30:01
42,301,787
0
0
null
null
null
null
UTF-8
C++
false
false
8,945
cpp
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2005, 2006 // University of Rochester // Department of Computer Science // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the University of Rochester nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef USE_BIMODAL #define USE_BIMODAL #endif #include <unistd.h> #include <cstdlib> #include <pthread.h> #include <string> #include <iostream> #include "Benchmark.h" #include "Counter.h" #include "FGL.h" #include "CGHash.h" #include "Hash.h" #include "LFUCache.h" #include "LinkedList.h" #include "LinkedListRelease.h" #include "PrivList.h" #include "RBTree.h" #include "RBTreeLarge.h" #include "RandomGraphList.h" #ifdef USE_BIMODAL #include "LinkedListBM.h" #endif using namespace bench; using std::cerr; using std::cout; using std::endl; using std::string; using namespace stm; BenchmarkConfig BMCONFIG; static void usage() { cerr << "Usage: Bench -B benchmark -C contention manager "; cerr << "-V validation strategy [flags]" << endl; cerr << " Benchmarks:" << endl; cerr << " Counter Shared counter" << endl; cerr << " LinkedList Sorted linked list" << endl; cerr << " LinkedListRelease LinkedList, early release" << endl; cerr << " HashTable 256-bucket hash table" << endl; cerr << " RBTree (default) Red-black tree" << endl; cerr << " RBTreeLarge Red-black tree with 4KB nodes" << endl; cerr << " LFUCache Web cache simulation" << endl; cerr << " RandomGraph Graph with 4 connections per node" << endl; cerr << " PrivList Linked list privatization test" << endl; cerr << " FineGrainList Lock-based sorted linked list" << endl; cerr << " CoarseGrainHash 256-bucket hash table, per-node locks" << endl; cerr << " FineGrainHash 256-bucket hash table, per-bucket locks" << endl; cerr << endl; cerr << " Contention Managers:" << endl; cerr << " Polka (default), Eruption, Highlander, Karma, Killblocked, "; cerr << "Polite" << endl; cerr << " Polkaruption, Timestamp, Aggressive, Whpolka, Greedy, "; cerr << "Polkavis" << endl; cerr << endl; cerr << " Validation Strategies:" << endl; cerr << " invis-eager (default), invis-lazy, vis-eager, vis-lazy "; cerr << endl; cerr << endl; cerr << " Flags:" << endl; cerr << " -d: number of seconds to time (default 5)" << endl; cerr << " -m: number of distinct elements (default 256)" << endl; cerr << " -p: number of threads (default 2)" << endl; cerr << endl; cerr << " Other:" << endl; cerr << " -h: print help (this message)" << endl; cerr << " -q: quiet mode" << endl; cerr << " -v: verbose mode" << endl; cerr << " -!: toggle verification at end of benchmark" << endl; cerr << " -1: 80/10/10 lookup/insert/remove breakdown" << endl; cerr << " -2: 33/33/33 lookup/insert/remove breakdown (default)" << endl; cerr << " -3: 0/50/50 lookup/insert/remove breakdown" << endl; cerr << " -T:[lh] perform light or heavy unit testing" << endl; cerr << " -W/-X specify warmup and execute numbers" << endl; cerr << endl; } int main(int argc, char** argv) { int opt; // parse the command-line options while ((opt = getopt(argc, argv, "B:C:H:a:d:m:p:hqv!xV:1234T:W:X:")) != -1) { switch(opt) { case 'B': BMCONFIG.bm_name = string(optarg); break; case 'V': BMCONFIG.stm_validation = string(optarg); break; case 'T': BMCONFIG.unit_testing = string(optarg)[0]; break; case 'C': BMCONFIG.cm_type = string(optarg); BMCONFIG.use_static_cm = false; break; case 'W': BMCONFIG.warmup = atoi(optarg); break; case 'X': BMCONFIG.execute = atoi(optarg); break; case 'd': BMCONFIG.duration = atoi(optarg); break; case 'm': BMCONFIG.datasetsize = atoi(optarg); break; case 'p': BMCONFIG.threads = atoi(optarg); break; case 'h': stm::about(); usage(); return 0; case 'q': BMCONFIG.verbosity = 0; break; case 'v': BMCONFIG.verbosity = 2; break; case '!': BMCONFIG.verify = !BMCONFIG.verify; break; case '1': BMCONFIG.lThresh = 24; BMCONFIG.iThresh = 27; break; case '2': BMCONFIG.lThresh = 10; BMCONFIG.iThresh = 20; break; case '3': BMCONFIG.lThresh = 0; BMCONFIG.iThresh = 15; break; case '4': BMCONFIG.lThresh = 15; BMCONFIG.iThresh = 0; break; } } // make sure that the parameters all make sense BMCONFIG.verifyParameters(); // initialize stm so that we have transactional mm, then verify the // benchmark parameter and construct the benchmark object stm::init(BMCONFIG.cm_type, BMCONFIG.stm_validation, BMCONFIG.use_static_cm); Benchmark* B = 0; if (BMCONFIG.bm_name == "Counter") B = new CounterBench(); else if (BMCONFIG.bm_name == "FineGrainList") B = new IntSetBench(new FGL(), BMCONFIG.datasetsize); else if (BMCONFIG.bm_name == "FineGrainHash") B = new IntSetBench(new bench::HashTable<FGL>(), BMCONFIG.datasetsize); else if (BMCONFIG.bm_name == "CoarseGrainHash") B = new IntSetBench(new CGHash(), BMCONFIG.datasetsize); else if (BMCONFIG.bm_name == "RandomGraph") B = new RGBench<>(new RandomGraph(BMCONFIG.datasetsize), BMCONFIG.datasetsize); else if (BMCONFIG.bm_name == "HashTable") B = new IntSetBench(new bench::Hash(), BMCONFIG.datasetsize); else if (BMCONFIG.bm_name == "LFUCache") B = new LFUTest(); else if (BMCONFIG.bm_name == "LinkedList") B = new IntSetBench(new LinkedList(), BMCONFIG.datasetsize); #ifdef USE_BIMODAL else if (BMCONFIG.bm_name == "LinkedListBM") B = new IntSetBench(new LinkedListBM(), BMCONFIG.datasetsize); #endif else if (BMCONFIG.bm_name == "LinkedListRelease") B = new IntSetBench(new LinkedListRelease(), BMCONFIG.datasetsize); else if (BMCONFIG.bm_name == "PrivList") B = new PrivList(BMCONFIG.datasetsize); else if (BMCONFIG.bm_name == "RBTree") B = new IntSetBench(new RBTree(), BMCONFIG.datasetsize); else if (BMCONFIG.bm_name == "RBTreeLarge") B = new IntSetBench(new RBTreeLarge(), BMCONFIG.datasetsize); else argError("Unrecognized benchmark name " + BMCONFIG.bm_name); // print the configuration for this run of the benchmark BMCONFIG.printConfig(); // either verify the data structure or run a timing experiment if (BMCONFIG.unit_testing != ' ') { if (B->verify(BMCONFIG.unit_testing == 'l' ? LIGHT : HEAVY)) cout << "Verification succeeded" << endl; else cout << "Verification failed" << endl; } else { B->measure_speed(); } stm::shutdown(); return 0; }
[ "foucault.matthieu@532f2ef2-ef11-80ae-07eb-e5a816fadd2e" ]
foucault.matthieu@532f2ef2-ef11-80ae-07eb-e5a816fadd2e
86e4233798e3039f73b36bebeb7e609ea6eb0000
09e5cfe06e437989a2ccf2aeecb9c73eb998a36c
/modules/cctbx_project/mmtbx/secondary_structure/ext.cpp
3ae4b13a8d5bac535e23b21e4c7ffbedc2076293
[ "BSD-3-Clause", "BSD-3-Clause-LBNL" ]
permissive
jorgediazjr/dials-dev20191018
b81b19653624cee39207b7cefb8dfcb2e99b79eb
77d66c719b5746f37af51ad593e2941ed6fbba17
refs/heads/master
2020-08-21T02:48:54.719532
2020-01-25T01:41:37
2020-01-25T01:41:37
216,089,955
0
1
BSD-3-Clause
2020-01-25T01:41:39
2019-10-18T19:03:17
Python
UTF-8
C++
false
false
719
cpp
#include <boost/python/module.hpp> #include <boost/python/def.hpp> #include <boost/python/args.hpp> #include <mmtbx/secondary_structure/identify.hpp> namespace mmtbx { namespace secondary_structure { namespace { void wrap_identification () { using namespace boost::python; def("delta_distance_squared", delta_distance_squared, ( arg("base_1"), arg("base_2"), arg("name_1"), arg("name_2"), arg("atom_names"), arg("sites_cart"), arg("distance_ideal"))); } } namespace boost_python { void wrap_sec_str () { wrap_identification(); } } }} BOOST_PYTHON_MODULE(mmtbx_secondary_structure_ext) { mmtbx::secondary_structure::boost_python::wrap_sec_str(); }
616d72bebe7bfbaecefca1b85b60e7e5fd22f5ee
3da7c1cd3ec52ba1a8fb060808fb492f0d8ac1fd
/src/basis_function/Cutoff_cusp_2D.h
0e5f99d18ae7c5931a1378637ba0479c60ad5b2b
[]
no_license
guoshi1984/qwalk_spin
afb1cfc5bf0c2c255a66feb44c2ce8114d5ab7de
837f8e3ad5d0ce1f0f98487b3c319f44959b81be
refs/heads/master
2020-04-25T17:29:43.937755
2019-02-27T22:19:22
2019-02-27T22:19:22
172,950,136
0
0
null
null
null
null
UTF-8
C++
false
false
2,042
h
/* Copyright (C) 2007 Lucas K. Wagner This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef CUTOFF_CUSP_2D_H_INCLUDED #define CUTOFF_CUSP_2D_H_INCLUDED #include "Basis_function.h" /*! */ class Cutoff_cusp_2D: public Basis_function { public: //----------------------------------------------------- virtual int read( vector <string> & words, //!< The words from the basis section that will create this basis function unsigned int & pos ); int nfunc(); virtual string label() { return centername; } doublevar cutoff(int ) { return rcut; } int showinfo(string & indent, ostream & os); int writeinput(string &, ostream &); void raw_input(ifstream & input); void calcVal(const Array1 <doublevar> & r, Array1 <doublevar> & symvals, const int startfill=0); void calcLap( const Array1 <doublevar> & r, Array2 <doublevar> & symvals, const int startfill=0 ); virtual void getVarParms(Array1 <doublevar> & parms); virtual void setVarParms(Array1 <doublevar> & parms); virtual int nparms() { return 1; } private: doublevar rcut; doublevar rcutinv; //inverse of rcut, to save on divisions string centername; doublevar gamma; doublevar cusp; doublevar pade0; }; #endif // CUTOFF_CUSP_2D_H_INCLUDED //--------------------------------------------------------------------------
0ad16a779b8522c65d6112dfa190432271997a6d
ce1a15e57fe4e6dc3f3aa0ee32479367c31a0bf8
/Math/Sphere.cpp
4f330eb18c92370ddec49253c831aad5c4626377
[ "MIT" ]
permissive
saggita/cryphous
579aaa6745223d372a0b2a28a1972c37f2a8a790
da8e777b06970a88ed6b20ac6fa7f249bac4cd9a
refs/heads/master
2021-01-21T00:18:01.292073
2014-02-17T05:56:27
2014-02-17T05:56:27
32,535,752
0
0
null
null
null
null
UTF-8
C++
false
false
626
cpp
#include "Sphere.h" using namespace Crystal::Math; std::vector<Vector3d> Sphere::createPoints(const float divideLength ) const { std::vector<Vector3d> points; Box box( center, center ); box.outerOffset( radius ); for( float x = box.getMinX(); x <= box.getMaxX(); x+= divideLength ) { for( float y = box.getMinY(); y <= box.getMaxY(); y += divideLength ) { for( float z = box.getMinZ(); z <= box.getMaxZ(); z += divideLength ) { const Vector3d pos( x, y, z ); if( pos.getDistanceSquared( center ) < radius * radius ) { points.push_back( pos ); } } } } return points; }
[ "[email protected]@c4768a9b-8396-9c1e-e381-6b4412480993" ]
[email protected]@c4768a9b-8396-9c1e-e381-6b4412480993
bb89824708988dbd56f788fc28d090a09930d4e7
80ed71415caf00c62bb7d9a3728979e20abb3a40
/NextEngine/src/graphics/pass/shadow.cpp
b370738d47eec6a87146f7ea90de086a9fb887b1
[ "MIT" ]
permissive
CompilerLuke/NextEngine
352aee5428a0ec662c0fe77546335faff9e8d51b
1ffaad76ec2d574927612da325404e7c247eecec
refs/heads/master
2022-09-10T19:50:11.490827
2022-08-22T08:38:29
2022-08-22T08:38:29
194,880,130
18
5
null
2021-09-02T10:14:06
2019-07-02T14:31:30
C++
UTF-8
C++
false
false
9,184
cpp
#include "graphics/rhi/frame_buffer.h" #include "graphics/pass/shadow.h" #include "graphics/assets/assets.h" #include "components/lights.h" #include "components/transform.h" #include "components/camera.h" #include "graphics/rhi/draw.h" #include "graphics/rhi/primitives.h" #include "graphics/renderer/renderer.h" #include "core/io/logger.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/glm.hpp> #include "ecs/ecs.h" #include "graphics/culling/culling.h" // shadow ubo 272 void make_shadow_resources(ShadowResources& resources, UBOBuffer simulation_ubo[MAX_FRAMES_IN_FLIGHT], const ShadowSettings& settings) { SamplerDesc shadow_sampler_desc; shadow_sampler_desc.mag_filter = Filter::Linear; shadow_sampler_desc.min_filter = Filter::Linear; shadow_sampler_desc.wrap_u = Wrap::ClampToBorder; shadow_sampler_desc.wrap_v = Wrap::ClampToBorder; shadow_sampler_desc.depth_compare = true; resources.shadow_sampler = query_Sampler(shadow_sampler_desc); for (uint frame = 0; frame < MAX_FRAMES_IN_FLIGHT; frame++) { resources.shadow_ubos[frame] = alloc_ubo_buffer(sizeof(ShadowUBO), UBO_PERMANENT_MAP); } for (uint i = 0; i < MAX_SHADOW_CASCADES; i++) { FramebufferDesc desc{ settings.shadow_resolution, settings.shadow_resolution }; add_depth_attachment(desc, &resources.cascade_maps[i]); make_Framebuffer((RenderPass::ID)(RenderPass::Shadow0 + i), desc); for (uint frame = 0; frame < MAX_FRAMES_IN_FLIGHT; frame++) { resources.cascade_ubos[frame][i] = alloc_ubo_buffer(sizeof(PassUBO), UBO_PERMANENT_MAP); DescriptorDesc desc; add_ubo(desc, VERTEX_STAGE, resources.cascade_ubos[frame][i], 0); add_ubo(desc, VERTEX_STAGE | FRAGMENT_STAGE, simulation_ubo[frame], 1); update_descriptor_set(resources.cascade_descriptors[frame][i], desc); } } resources.cascade_layout = query_Layout(resources.cascade_descriptors[0][0]); } void add_shadow_descriptors(DescriptorDesc& desc, ShadowResources& shadow, uint frame) { CombinedSampler* cascade_samplers = TEMPORARY_ARRAY(CombinedSampler, MAX_SHADOW_CASCADES); for (uint i = 0; i < MAX_SHADOW_CASCADES; i++) { cascade_samplers[i] = { shadow.shadow_sampler, shadow.cascade_maps[i] }; } add_ubo(desc, FRAGMENT_STAGE, shadow.shadow_ubos[frame], 4); add_combined_sampler(desc, FRAGMENT_STAGE, { cascade_samplers, MAX_SHADOW_CASCADES }, 5); } glm::mat4 calc_dir_light_view_matrix(const Transform& trans, const DirLight& dir_light) { return glm::lookAt(trans.position, trans.position + dir_light.direction, glm::vec3(0, 1, 0)); } //modified https://www.gamedev.net/forums/topic/673197-cascaded-shadow-map-shimmering-effect/ //for (uint i = 0; i < 8; i++) { // assert(glm::min(aabb.min, glm::vec3(frustumCorners[i])) == aabb.min); // assert(glm::max(aabb.max, glm::vec3(frustumCorners[i])) == aabb.max); //} void calc_shadow_cascades(ShadowCascadeProj cascades[MAX_SHADOW_CASCADES], const ShadowSettings& settings, Viewport viewports[MAX_SHADOW_CASCADES], const Camera& camera, glm::vec3 lightDir, Viewport& viewport) { float nearClip = camera.near_plane; float farClip = camera.far_plane; float clipRange = farClip - nearClip; float minZ = nearClip; float maxZ = nearClip + clipRange; float range = maxZ - minZ; float ratio = maxZ / minZ; float cascadeSplitLambda = settings.cascade_split_lambda; float cascadeSplits[MAX_SHADOW_CASCADES]; // Calculate split depths based on view camera frustum // Based on method presented in https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch10.html for (uint32_t i = 0; i < MAX_SHADOW_CASCADES; i++) { float p = (i + 1) / static_cast<float>(MAX_SHADOW_CASCADES); float log = minZ * std::pow(ratio, p); float uniform = minZ + range * p; float d = cascadeSplitLambda * (log - uniform) + uniform; cascadeSplits[i] = (d - nearClip) / clipRange; } // Calculate orthographic projection matrix for each cascade float lastSplitDist = 0.0; for (uint32_t i = 0; i < MAX_SHADOW_CASCADES; i++) { float splitDist = cascadeSplits[i]; glm::vec3 frustumCorners[8] = { glm::vec3(-1.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 0.0f), glm::vec3(1.0f, -1.0f, 0.0f), glm::vec3(-1.0f, -1.0f, 0.0f), glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(1.0f, -1.0f, 1.0f), glm::vec3(-1.0f, -1.0f, 1.0f), }; // Project frustum corners into world space glm::mat4 invCam = glm::inverse(viewport.proj * viewport.view); for (uint32_t i = 0; i < 8; i++) { glm::vec4 invCorner = invCam * glm::vec4(frustumCorners[i], 1.0f); frustumCorners[i] = invCorner / invCorner.w; } for (uint32_t i = 0; i < 4; i++) { glm::vec3 dist = frustumCorners[i + 4] - frustumCorners[i]; frustumCorners[i + 4] = frustumCorners[i] + (dist * splitDist); frustumCorners[i] = frustumCorners[i] + (dist * lastSplitDist); } // Get frustum center glm::vec3 frustumCenter = glm::vec3(0.0f); for (uint32_t i = 0; i < 8; i++) { frustumCenter += frustumCorners[i]; } frustumCenter /= 8.0f; float radius = 0.0f; for (uint32_t i = 0; i < 8; i++) { float distance = glm::length(frustumCorners[i] - frustumCenter); radius = glm::max(radius, distance); } int round = (MAX_SHADOW_CASCADES - i); radius = std::ceil(radius * round) / round; //float world_space_per_texel = radius*2 / settings.shadow_resolution; //glm::vec3 frustumCenterSnapped = frustumCenter / world_space_per_texel; //frustumCenterSnapped = glm::floor(frustumCenterSnapped); //frustumCenterSnapped *= world_space_per_texel; //frustumCenter glm::vec3 maxExtents = glm::vec3(radius); glm::vec3 minExtents = -maxExtents; //maxExtents += (frustumCenterSnapped - frustumCenter); //minExtents += (frustumCenterSnapped - frustumCenter); glm::mat4 lightViewMatrix = glm::lookAt(frustumCenter - lightDir * -minExtents.z, frustumCenter, glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 lightOrthoMatrix = glm::ortho(minExtents.x, maxExtents.x, minExtents.y, maxExtents.y, 0.0f, maxExtents.z - minExtents.z); glm::vec3 ndc_per_texel = glm::vec3(2.0, 2.0, 1.0) / (float)settings.shadow_resolution; glm::vec4 quantOrigin = lightOrthoMatrix * lightViewMatrix * glm::vec4(0, 0, 0, 1.0); glm::vec3 quantOriginRounded = quantOrigin; quantOriginRounded /= ndc_per_texel; quantOriginRounded = glm::floor(quantOriginRounded); quantOriginRounded *= ndc_per_texel; lightOrthoMatrix[3].x += quantOriginRounded.x - quantOrigin.x; lightOrthoMatrix[3].y += quantOriginRounded.y - quantOrigin.y; lightOrthoMatrix[3].z += quantOriginRounded.z - quantOrigin.z; float endDistance = splitDist * clipRange; glm::vec4 endClipSpace = viewport.proj * glm::vec4(0, 0, -endDistance, 1.0); endClipSpace /= endClipSpace.w; //cascades[i].splitDepth = (camera.getNearClip() + splitDist * clipRange) * -1.0f; // Store split distance and matrix in cascade //cascades[i].end_clip_space = splitDist; // (splitDist * clipRange) * -1.0f; //cascades[i].ndc_to_light = glm::inverse(proj_m * cam_m); cascades[i].to_light = lightOrthoMatrix * lightViewMatrix; cascades[i].light_projection = lightOrthoMatrix; cascades[i].light_view = lightViewMatrix; cascades[i].end_clip_space = endClipSpace.z; cascades[i].end_distance = endDistance; viewports[i].proj = lightOrthoMatrix; viewports[i].view = lightViewMatrix; viewports[i].cam_pos = frustumCenter; extract_planes(viewports[i]); lastSplitDist = splitDist; } } void extract_shadow_cascades(ShadowCascadeProj cascades[MAX_SHADOW_CASCADES], Viewport viewports[], const ShadowSettings& settings, World& world, Viewport& viewport, EntityQuery query) { auto some_camera = world.first<Camera>(query); auto some_dir_light = world.first<Transform, DirLight>(); if (some_camera && some_dir_light) { auto [e1, camera] = *some_camera; auto [e2, dir_light_trans, dir_light] = *some_dir_light; glm::mat4 light_m = calc_dir_light_view_matrix(dir_light_trans, dir_light); calc_shadow_cascades(cascades, settings, viewports, camera, dir_light.direction, viewport); } } void fill_shadow_ubo(ShadowUBO& shadow_ubo, const ShadowCascadeProj info[MAX_SHADOW_CASCADES]) { for (uint i = 0; i < MAX_SHADOW_CASCADES; i++) { shadow_ubo.cascade_end_clipspace[i].x = info[i].end_clip_space; shadow_ubo.cascade_end_clipspace[i].y = info[i].end_distance; shadow_ubo.to_light_space[i] = info[i].to_light; } } void bind_cascade_viewports(ShadowResources& resources, RenderPass render_pass[MAX_SHADOW_CASCADES], const ShadowSettings& settings, const ShadowCascadeProj info[MAX_SHADOW_CASCADES]) { uint frame_index = get_frame_index(); for (uint i = 0; i < MAX_SHADOW_CASCADES; i++) { PassUBO pass_ubo = {}; pass_ubo.resolution = glm::vec4(settings.shadow_resolution); pass_ubo.proj = info[i].light_projection; pass_ubo.view = info[i].light_view; memcpy_ubo_buffer(resources.cascade_ubos[frame_index][i], &pass_ubo); CommandBuffer& cmd_buffer = render_pass[i].cmd_buffer; bind_pipeline_layout(cmd_buffer, resources.cascade_layout); bind_descriptor(cmd_buffer, 0, resources.cascade_descriptors[frame_index][i]); set_depth_bias(cmd_buffer, settings.constant_depth_bias, settings.slope_depth_bias); } }
f0d330f46187de0c8da995319cf6fed77c58c6c6
11a8bde3ba3799f406f9c4bf7619094c6f936d06
/vuforia_build/include/Vuforia/PositionalDeviceTracker.h
02926644e5ee4dde0a12bde34cc4e1958b85c84d
[]
no_license
cheethath/cuboid2
ea097c7fd2dae162feedd8a29c4a869bf493c31e
1ebb5b16a8d77c0b44e9e83c1bbf10667caf600c
refs/heads/master
2020-03-25T07:03:50.151592
2018-09-26T10:10:02
2018-09-26T10:10:02
143,539,331
0
0
null
null
null
null
UTF-8
C++
false
false
8,576
h
/*============================================================================== Copyright (c) 2015-2018 PTC Inc. All Rights Reserved. Copyright (c) 2015 Qualcomm Connected Experiences, Inc. All Rights Reserved. Vuforia is a trademark of PTC Inc., registered in the United States and other countries. \file PositionalDeviceTracker.h \brief Header file for PositionalDeviceTracker class. ==============================================================================*/ #ifndef _VUFORIA_POSITIONAL_DEVICE_TRACKER_H_ #define _VUFORIA_POSITIONAL_DEVICE_TRACKER_H_ #include <Vuforia/DeviceTracker.h> namespace Vuforia { // Forward declarations class Anchor; class HitTestResult; /// A type of DeviceTracker that tracks the world-relative position and rotation of the device. /** * The PositionalDeviceTracker tracks the device in the world based on the * environment. * * While this Tracker is running, the device's position and rotation are made * available on the State class as a DeviceTrackableResult containing a 6DOF * pose, specified in meters in the world coordinate system. The origin of the * world coordinate system corresponds to the position and orientation of the * device when tracking starts. * * \par Extended Tracking * * PositionalDeviceTracker also provides extended tracking functionality. As long * as the PositionalDeviceTracker is running, previously detected Trackables will * continue to report poses via the State class, even if they are no longer visible * in the device's camera. * * This assumes that the Trackable remains static relative to the user's environment. * If the Trackable is moved while it is out of view of the camera, its pose will * snap to its new location once it comes back into view of the camera and %Vuforia * re-detects it. For some Trackables, the detection distance may be closer than * the tracking distance. You may need to move the camera closer than expected * to the Trackable so that it updates its pose after it has moved. * * You can use TrackableResult::getStatus() to determine whether a Trackable is * being tracked directly or using extended tracking. * * \par Initialization * * The PositionalDeviceTracker may need some extra manual initialization steps * on some devices, depending on the active Fusion provider (as returned by * Vuforia::getActiveFusionProvider()). * * - For FUSION_PROVIDER_PLATFORM_SENSOR_FUSION (which is the default for iOS * devices that support ARKit, Android devices that support ARCore, and UWP * devices that support Windows Holographic), the PositionalDeviceTracker * will be initialized automatically. * * - For FUSION_PROVIDER_VUFORIA_SENSOR_FUSION, the PositionalDeviceTracker cannot * fully initialize on its own. You need to either a) detect and track an * ObjectTarget, or b) call createAnchor(const char*, const HitTestResult&) with * a hit test result obtained from SmartTerrain. * * - For FUSION_PROVIDER_VUFORIA_VISION_ONLY, you need to initialize the * PositionalDeviceTracker by detecting and tracking an ObjectTarget. */ class VUFORIA_API PositionalDeviceTracker : public DeviceTracker { public: /// Get the Type for class 'PositionalDeviceTracker'. static Type getClassType(); /// Create a named Anchor with a particular world position and rotation. /** * This method creates an Anchor at an arbitrary position and orientation * in the world. * * Depending on the active Fusion provider (see * Vuforia::getActiveFusionProvider()), tracking of Anchors created with this * method may be poor under certain conditions. For this reason, it is * recommended that you only create Anchors using * createAnchor(const char*, const HitTestResult&), rather than using this * method. If you want to render something at an arbitrary position in the * world, for example floating in the air, create a hit-test-based Anchor and * then apply an offset transform in your application logic. * * For platform-independent behavior, you should always create the first * anchor from a HitTestResult. * * To destroy an Anchor, call destroyAnchor(). Do not delete the pointer * yourself. A call to stop() invalidates (destroys) all Anchors. Do not access * the returned pointer after calling stop(). * * \note Creating anchors is not supported if the active Fusion provider is * FUSION_PROVIDER_VUFORIA_VISION_ONLY (see Vuforia::getActiveFusionProvider()). * * \note If the active Fusion provider is FUSION_PROVIDER_VUFORIA_SENSOR_FUSION, * extra steps are required to fully initialize the PositionalDeviceTracker * before using this method. See the <b>Initialization</b> section in the class * documentation above for more details. * * \note When using FUSION_PROVIDER_VUFORIA_SENSOR_FUSION, reported Anchor * poses may fluctuate at first, until %Vuforia has learned enough about * the environment to provide a stable pose estimate. This typically takes * a few seconds after creating the first Anchor from a HitTestResult, depending * on how the user moves their device. * * \note When using FUSION_PROVIDER_VUFORIA_SENSOR_FUSION, Anchors created with * this method are not guaranteed to receive any further position updates after * the device tracker recovers from a limited tracking state. * * \param name The name for the new anchor. * \param pose The pose (position and orientation) for the anchor. * * \returns The newly created anchor, or NULL on failure (check application * log for details). */ virtual Anchor* createAnchor(const char* name, const Matrix34F& pose) = 0; /// Create a named Anchor using the result of a hit test from a SmartTerrain. /** * This method is the preferred way to attach augmentations to arbitrary points * in the user's environment. If you need the augmentation to appear somewhere * other than the surface of the plane detected by the hit test, apply an offset * transform in your application logic. * * To destroy an Anchor, call destroyAnchor(). Do not delete the pointer * yourself. A call to stop() invalidates (destroys) all Anchors. Do not access * the returned pointer after calling stop(). * * \note When using FUSION_PROVIDER_VUFORIA_SENSOR_FUSION, reported Anchor * poses may fluctuate initially until %Vuforia has learned enough about * the environment to provide a stable pose estimate (typically until a * few seconds after creating the first Anchor from a HitTestResult, depending * on how the user moves their device). * * \param name The name for the new Anchor. * \param hitTestResult a HitTestResult as returned from SmartTerrain::hitTest(). * The HitTestResult must not have been already used to create an Anchor. * \returns The newly created Anchor, or NULL on failure (check application * log for details). * */ virtual Anchor* createAnchor(const char* name, const HitTestResult& hitTestResult) = 0; /// Destroy the given Anchor. /** * Deletes the given Anchor and cleans up all associated internal resources. * * Do not access the pointer after calling this method. * * \returns true if destroyed successfully, false if the Anchor is invalid * (e.g. null). */ virtual bool destroyAnchor(Anchor* anchor) = 0; /// Get the number of Anchors currently managed by the PositionalDeviceTracker. virtual int getNumAnchors() const = 0; /// Get the Anchor at the specified index. /** * \param idx The index, in the range 0..getNumAnchors() - 1. * \returns the requested Anchor instance, or NULL if the index is out of * bounds. */ virtual Anchor* getAnchor(int idx) = 0; /// Reset the tracker. /** * Calling this function invalidates (destroys) all Anchors. Do not hold on to * any existing Anchor pointers after calling this function. * * \note On some platforms a new world origin will be defined at the device's * current position and orientation. * * \note On some platforms the underlying Vuforia Fusion provider may also * be reset. * * \returns true if the tracker was successfully reset, otherwise false (check * application logs for failure details). */ virtual bool reset() = 0; }; } // namespace Vuforia #endif //_VUFORIA_POSITIONAL_DEVICE_TRACKER_H_
b05a3b0ad7df0ab9287a7014c0fa5399e205492a
3c55ad828e43d9ef7cf04c7b1d115cb59c4436f1
/Algorithms/Implementation/Angry-Professor.cpp
7502401b0c708a307808924cf42cb848821785fb
[]
no_license
Yagrini/HackerRank-Solutions
85db73e549c14feac28f17378e2fe7d182b03250
95669551180b84a5f1a791874e0f2aa057945605
refs/heads/master
2020-03-09T01:39:03.744276
2018-04-07T11:08:00
2018-04-07T11:08:00
128,520,319
11
6
null
null
null
null
UTF-8
C++
false
false
511
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int t , n , k , arrival; cin >> t ; while(t--){ int count = 0; cin >> n >> k; while(n--){ cin >> arrival; if(arrival<=0) count++; } if(count<k) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
06dca63d6cd1d42560092d722a00b0c59ba6bcc5
afc311930f8eba3aabac84becd1b4895408a5af8
/sdf_play/SDFPlay/VertexModel.h
b85706ef9ef4972368ed52b338a7d528df82a8b1
[]
no_license
nosnickid/sdf_play
26275f4c63f48b20630c6aa6ccf66487911b8c40
fe8892806840b63f97c3bcc09eb98babe2c1d87d
refs/heads/master
2021-01-19T09:49:30.341969
2012-11-03T14:48:59
2012-11-03T14:48:59
2,295,076
0
0
null
null
null
null
UTF-8
C++
false
false
237
h
#ifndef SDF_PLAY_VERTEX_MODEL_H__ #define SDF_PLAY_VERTEX_MODEL_H__ #include "Sys.h" class VertexModel { public: VertexModel(GLfloat *vertices, int vertCount, GLint vertTriIdx, int triCount); protected: }; #endif
09ef4458c972af67dd5caa95f44585152181908b
5389410ce4795c371dbf1ad64006221d06f46c7d
/Rx/CPP/src/cpprx/operators/Where.hpp
d0089bda4f8003ba060773006ec6621e6262752e
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
Herdinger/RxCpp
395facd4e100aecfac81c4b6a5e1cbfe955cc921
59d9d055fe64e4f9b56e0ed125b985e319004bb0
refs/heads/master
2020-12-25T06:45:10.417386
2014-05-04T08:13:29
2014-05-04T08:13:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,973
hpp
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #pragma once #include "../rx-operators.hpp" #if !defined(CPPRX_RX_OPERATORS_WHERE_HPP) #define CPPRX_RX_OPERATORS_WHERE_HPP namespace rxcpp { namespace detail { template<class T> class WhereObservable : public Producer<WhereObservable<T>, T> { typedef std::shared_ptr<WhereObservable<T>> Parent; typedef std::function<bool(T)> Predicate; std::shared_ptr<Observable<T>> source; Predicate predicate; class _ : public Sink<_, T>, public Observer<T> { Parent parent; public: typedef Sink<_, T> SinkBase; _(Parent parent, std::shared_ptr < Observer < T >> observer, Disposable cancel) : SinkBase(std::move(observer), std::move(cancel)), parent(parent) { } virtual void OnNext(const T& t) { util::maybe<bool> shouldRun; try { shouldRun.set(parent->predicate(t)); } catch (...) { SinkBase::observer->OnError(std::current_exception()); SinkBase::Dispose(); } if (!!shouldRun && *shouldRun.get()) { SinkBase::observer->OnNext(t); } } virtual void OnCompleted() { SinkBase::observer->OnCompleted(); SinkBase::Dispose(); } virtual void OnError(const std::exception_ptr& e) { SinkBase::observer->OnError(e); SinkBase::Dispose(); } }; typedef Producer<WhereObservable<T>, T> ProducerBase; public: WhereObservable(const std::shared_ptr<Observable<T>>& source, Predicate predicate) : ProducerBase([this](Parent parent, std::shared_ptr < Observer < T >> observer, Disposable && cancel, typename ProducerBase::SetSink setSink) -> Disposable { auto sink = std::shared_ptr<WhereObservable::_>(new WhereObservable::_(parent, observer, std::move(cancel))); setSink(sink->GetDisposable()); return this->source->Subscribe(sink); }), source(source), predicate(std::move(predicate)) { } }; } template <class T, class P> std::shared_ptr<Observable<T>> Where( const std::shared_ptr<Observable<T>>& source, P predicate ) { return std::make_shared<detail::WhereObservable<T>>(source, std::move(predicate)); } } #endif
d89f5a8fd610b0a79770b34e3e55fac9ebd27181
a6e29d648e5ea15cd060a5eefd5022ba36c0588a
/rt.h
8a52c079332186027da4c8424b10090b022b9bf9
[]
no_license
paulhuangkm/ICG_Final_Project
976bd41862d5396cf2cff30fc0277ce779466107
9dfb52ac414a30db9bd18a7705c1ac36c0acbcaa
refs/heads/master
2023-05-10T11:25:59.292101
2021-06-19T11:37:16
2021-06-19T11:37:16
374,116,994
1
0
null
null
null
null
UTF-8
C++
false
false
770
h
#ifndef RT_H #define RT_H #include <cmath> #include <limits> #include <memory> #include <random> // Usings using std::shared_ptr; using std::make_shared; using std::sqrt; // Constants const double infinity = std::numeric_limits<double>::infinity(); const double pi = 3.1415926535897932385; // Utility Functions inline double degrees_to_radians(double degrees) { return degrees * pi / 180.0; } inline double random_double() { return rand() / (RAND_MAX + 1.0); } inline double random_double(double min, double max) { return min + (max-min)*random_double(); } inline double clamp(double x, double min, double max) { if (x < min) return min; if (x > max) return max; return x; } // Common Headers #include "ray.h" #include "vec3.h" #endif
f9965bf17cd894c5281301b9c93edfed201e831a
282d37eb162dfc84e51dcea6d738cfb3ea700531
/angelscript/stl_containers/aatc_enginestorage.cpp
bc98099cefd14e947c2055ade07b5fe7b913bad8
[]
no_license
Sephirothbahamut/Graph-Maker
180eff977c76b2f6d47dfd8529040903f5a08fa5
f8d5558c02f9b2380948c827b69b489e07ab68da
refs/heads/master
2020-05-07T19:54:28.353314
2019-07-18T11:43:36
2019-07-18T11:43:36
180,833,044
1
1
null
null
null
null
UTF-8
C++
false
false
6,354
cpp
#include "stdafx.h"/* The zlib/libpng License http://opensource.org/licenses/zlib-license.php Angelscript addon Template Containers Copyright (c) 2014 Sami Vuorela This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; You must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Sami Vuorela [email protected] */ #include "aatc_enginestorage.hpp" #include "string.h" BEGIN_AS_NAMESPACE namespace aatc { namespace enginestorage { engine_level_storage::engine_level_storage(asIScriptEngine* _engine) : engine(_engine) {} engine_level_storage::~engine_level_storage(){} template_specific_storage* containertype_specific_storage::GetTemplateSpecificStorage(config::t::uint32 id){ template_specific_storage* result; template_specific_storages_lock.lock(); tmap_tss::iterator it = template_specific_storages.find(id); if (it == template_specific_storages.end()){ result = new template_specific_storage(this,id); template_specific_storages.insert(tpair_tss(id, result)); }else{ result = it->second; } template_specific_storages_lock.unlock(); return result; } containertype_specific_storage* engine_level_storage::GetContainerTypeSpecificStorage(config::t::uint32 id){ return &(containertype_specific_storages[id]); } containertype_specific_storage::~containertype_specific_storage(){ for (auto it = template_specific_storages.begin(); it != template_specific_storages.end(); it++){ const auto& pp = *it; delete pp.second; } } void engine_level_storage::Clean(){ for (auto it = context_cache.begin(); it != context_cache.end(); it++){ auto* a = *it; a->Release(); } context_cache.clear(); } template_specific_storage::template_specific_storage(containertype_specific_storage* ctss,config::t::uint32 subtypeid) : ctss(ctss), func_equals(NULL), func_cmp(NULL), func_hash(NULL) { asIScriptEngine* engine = ctss->els->engine; asITypeInfo* typeinfo = engine->GetTypeInfoById(subtypeid); //get opEquals or opCmp function for this type to be stored bool mustBeConst = (subtypeid & asTYPEID_HANDLETOCONST) ? true : false; if (typeinfo){ for (asUINT i = 0; i < typeinfo->GetMethodCount(); i++){ asIScriptFunction *func = typeinfo->GetMethodByIndex(i); asDWORD flags = 0; int returnTypeId = func->GetReturnTypeId(&flags); if(func->GetParamCount() == 0){ if(strcmp(func->GetName(), config::scriptname::method::content::hash) == 0){ if((returnTypeId == asTYPEID_UINT64) || (returnTypeId == asTYPEID_UINT32) || (returnTypeId == asTYPEID_UINT16) || (returnTypeId == asTYPEID_UINT8)){ func_hash = func; } } } if (func->GetParamCount() == 1 && (!mustBeConst || func->IsReadOnly())){ // The method must not return a reference if (flags != asTM_NONE) continue; // opCmp returns an int and opEquals returns a bool bool isCmp = false, isEq = false; if (returnTypeId == asTYPEID_INT32 && strcmp(func->GetName(), "opCmp") == 0){ isCmp = true; } if (returnTypeId == asTYPEID_BOOL && strcmp(func->GetName(), "opEquals") == 0){ isEq = true; } if(!isCmp && !isEq){ continue; } // The parameter must either be a reference to the subtype or a handle to the subtype int paramTypeId; func->GetParam(0, &paramTypeId, &flags); if ((paramTypeId & ~(asTYPEID_OBJHANDLE | asTYPEID_HANDLETOCONST)) != (subtypeid & ~(asTYPEID_OBJHANDLE | asTYPEID_HANDLETOCONST))){ continue; } if ((flags & asTM_INREF)){ if ((paramTypeId & asTYPEID_OBJHANDLE) || (mustBeConst && !(flags & asTM_CONST))){ continue; } }else if (paramTypeId & asTYPEID_OBJHANDLE){ if (mustBeConst && !(paramTypeId & asTYPEID_HANDLETOCONST)){ continue; } }else{ continue; } if (isCmp){ func_cmp = func; }else if (isEq){ func_equals = func; } } } } missing_functions = ctss->func_errorcheck_missing_functions_make_bitfield_for_template(this); } asIScriptContext* engine_level_storage::contextcache_Get(){ asIScriptContext* result; context_cache_lock.lock(); if (context_cache.empty()){ result = engine->CreateContext(); }else{ result = context_cache.back(); context_cache.pop_back(); } context_cache_lock.unlock(); return result; } void engine_level_storage::contextcache_Return(asIScriptContext* a){ context_cache_lock.lock(); context_cache.push_back(a); context_cache_lock.unlock(); } engine_level_storage* Get_ELS(asIScriptEngine* engine){ return (engine_level_storage*)engine->GetUserData(config::detail::engine_userdata_id); } asIScriptContext* contextcache_Get(){ engine_level_storage* els = Get_ELS(asGetActiveContext()->GetEngine()); return els->contextcache_Get(); } void contextcache_Return(asIScriptContext* c){ engine_level_storage* els = Get_ELS(asGetActiveContext()->GetEngine()); els->contextcache_Return(c); } void engine_cleanup(asIScriptEngine* engine) { enginestorage::engine_level_storage* els = enginestorage::Get_ELS(engine); els->Clean(); delete els; } void enginestorage::engine_level_storage::RegisterFuncdefIfNeeded(std::string const& this_funcdef_def) { if (registered_funcdefs.find(this_funcdef_def) == registered_funcdefs.end()) { engine->RegisterFuncdef(this_funcdef_def.c_str()); registered_funcdefs.insert(this_funcdef_def); } } };//namespace enginestorage };//namespace aatc END_AS_NAMESPACE
51d01fb496f054e0d34b6a54c1b47550ba662c18
e9d6b85cb8f16678e45f2493922b9ef53dd0197a
/sources/trabajo_practico_01/consigna_01/src/Complejo.h
a0dd94dde7bdb713f65738984a0bdb60bb41795f
[]
no_license
dqmdz/Computacion.2018.Quinteros.Daniel
2c1e0fe725ceb454e954d2bde128907c24cd469f
8bcd56dbd6db5f95d9878d8c0da78b9913187b0d
refs/heads/master
2021-04-06T08:52:02.223958
2018-06-28T18:36:24
2018-06-28T18:36:24
125,375,003
2
0
null
null
null
null
UTF-8
C++
false
false
330
h
/* * Complejo.h * * Created on: 15 mar. 2018 * Author: dquinteros */ #ifndef COMPLEJO_H_ #define COMPLEJO_H_ class Complejo { private: int real; int imag; public: int getImag() const; void setImag(int imag); int getReal() const; void setReal(int real); void input(); void show(); }; #endif /* COMPLEJO_H_ */
c3dc683eafc33d7f70bfd8dfca03b093111e7a28
6e112573830a54c6baff30bd94e36994117e9aa1
/src/pane/BattleShipMap.h
3214b339ba324e9cf03f80bef6e371f57e676ba0
[ "WTFPL" ]
permissive
brightface/battleship-game
9dc3e729f2dd3dc49947ef2a874644d8f46dd38f
4b61049b75a03e66d66da7174a5e01be26bbd8a6
refs/heads/master
2020-03-19T10:05:32.324896
2018-06-06T14:33:37
2018-06-06T14:33:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
857
h
/* * Copyright 2018 MinChul Lee. * * Use of this source code is governed by a WTFPL license that can be * found in the LICENSE file. * * C++ BattleShip Project * 2018-06-02 * 20163137 이민철 */ #ifndef BATTLESHIP_PANE_BATTLESHIPMAP_H_ #define BATTLESHIP_PANE_BATTLESHIPMAP_H_ #include "Pane.h" #include "../ship/Ship.h" #define MAP_SIZE 8 typedef char (*MapData)[MAP_SIZE]; class BattleShipMap : public Pane { public: BattleShipMap(); BattleShipMap(int x, int y, const char *title); void Draw() override; MapData GetMapData(); char ShipToChar(Ship *ship); void SetMapData(char c, Position *a, Position *b); void SetMapData(Ship *ship, Position *a, Position *b); int GetMapData(int x, int y); protected: char map_data_[MAP_SIZE][MAP_SIZE]; void InitMap(const char *title); }; #endif //BATTLESHIP_BATTLESHIPMAP_H_
0e8da51dbcee9c139057170060c6baa2f9357043
3c6f78340a66112492908b02c214f59465056b47
/CoolProp/FluidClass.cpp
5b2ace7b1b9edcc533a0069b9a42cbed7b53c5e5
[ "MIT" ]
permissive
ashuraj25/coolprop
5865a6deb7c9f71eef7f38acc6bbc8fbfe7fca75
d1995c7cb5e0ed3aef2d7bd4b65f4cafdc919b95
refs/heads/master
2021-01-10T19:24:58.126896
2014-02-23T22:30:09
2014-02-23T22:30:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
116,327
cpp
#define _CRT_SECURE_NO_WARNINGS #include "rapidjson_CoolProp.h" #include <stdlib.h> #include <string> #include <vector> #include <map> #include <algorithm> #include <list> #include <exception> #include <iostream> #include <fstream> #include <stdlib.h> #include <stdio.h> #include "math.h" #include <cmath> #include "MatrixMath.h" #include "Helmholtz.h" #include "FluidClass.h" #include "CoolProp.h" #include "REFPROP.h" #include "Solvers.h" #include "CPState.h" #include "Brine.h" #include "CriticalSplineConstants.h" #ifdef __ISWINDOWS__ #define _USE_MATH_DEFINES #include "float.h" #else #ifndef DBL_EPSILON #include <limits> #define DBL_EPSILON std::numeric_limits<double>::epsilon() #endif #endif #ifndef M_PI #define M_PI 3.14159265358979323846 #endif static const bool use_cache = false; static bool UseCriticalSpline = true; double JSON_lookup_double(rapidjson::Document &root, std::string FluidName, std::string key) { if (root.HasMember(FluidName.c_str()) && root[FluidName.c_str()][key.c_str()].IsDouble()){ return root[FluidName.c_str()][key.c_str()].GetDouble(); } else if (root.HasMember(FluidName.c_str()) && root[FluidName.c_str()][key.c_str()].IsInt()){ return root[FluidName.c_str()][key.c_str()].GetInt(); } else{ return _HUGE; } } std::string JSON_lookup_string(rapidjson::Document &root, std::string FluidName, std::string key) { if (root.HasMember(FluidName.c_str()) && root[FluidName.c_str()][key.c_str()].IsString()){ return root[FluidName.c_str()][key.c_str()].GetString(); } else{ return ""; } } std::string JSON_lookup_CAS(rapidjson::Document &root, std::string FluidName) { if (root.HasMember(FluidName.c_str()) && root[FluidName.c_str()].IsString()){ return root[FluidName.c_str()].GetString(); } else{ return ""; } } std::vector<double> JSON_lookup_dblvector(rapidjson::Document &root, std::string FluidName, std::string key) { std::vector<double> v; if (root.HasMember(FluidName.c_str()) && root[FluidName.c_str()][key.c_str()].IsArray()){ rapidjson::Value& arr = root[FluidName.c_str()][key.c_str()]; v.resize(arr.Size()); for (rapidjson::SizeType i = 0; i < arr.Size(); i++) { v[i] = arr[i].GetDouble(); } return v; } else{ v.resize(0); return v; } } std::vector<int> JSON_lookup_intvector(rapidjson::Document &root, std::string FluidName, std::string key) { std::vector<int> v; if (root.HasMember(FluidName.c_str()) && root[FluidName.c_str()][key.c_str()].IsArray()){ rapidjson::Value& arr = root[FluidName.c_str()][key.c_str()]; v.resize(arr.Size()); for (rapidjson::SizeType i = 0; i < arr.Size(); i++) { v[i] = arr[i].GetInt(); } return v; } else{ v.resize(0); return v; } } /// A stub class to do the density(T,p) calculations for near the critical point using Brent solver class DensityTpResids : public FuncWrapper1D { private: double p,T; Fluid *pFluid; public: DensityTpResids(Fluid *pFluid, double T, double p){this->pFluid = pFluid; this->p = p; this->T = T;}; ~DensityTpResids(){}; double call(double rho) { return this->p - pFluid->pressure_Trho(T,rho); } }; // // Destructor needs to free all dynamically allocated objects // In this case, the phir and phi0 components Fluid::~Fluid() { while (!phirlist.empty()) { delete phirlist.back(); phirlist.pop_back(); } while (!phi0list.empty()) { delete phi0list.back(); phi0list.pop_back(); } if (h_ancillary != NULL){ delete h_ancillary; h_ancillary = NULL;} if (s_ancillary != NULL){ delete s_ancillary; s_ancillary = NULL;} } void Fluid::post_load(rapidjson::Document &JSON, rapidjson::Document &JSON_CAS) { // Set the reducing values from the pointer reduce = *preduce; // Get the critical molar density in mol/m^3 (kg/m^3)*(kmol/kg)*(1000 mol/kmol) reduce.rhobar = reduce.rho/params.molemass*1000; crit.rhobar = crit.rho/params.molemass*1000; // Set the enthalpy and entropy at the critical point and the reducing point crit.h = enthalpy_Trho(crit.T, crit.rho); crit.s = entropy_Trho(crit.T, crit.rho); reduce.h = enthalpy_Trho(reduce.T, reduce.rho); reduce.s = entropy_Trho(reduce.T, reduce.rho); // REFPROP name is equal to fluid name if not provided if (REFPROPname.empty()) { REFPROPname = name; } // Set the triple-point pressure if not set in code //// Limits for the entropy at the minimum temperature (usually the triple point temperature) double pL,pV,rhoL,rhoV; saturation_T(limits.Tmin, false, pL, pV, rhoL, rhoV); HS.sV_Tmin = entropy_Trho(limits.Tmin, rhoV); HS.sL_Tmin = entropy_Trho(limits.Tmin, rhoL); HS.hV_Tmin = enthalpy_Trho(limits.Tmin, rhoV); HS.hL_Tmin = enthalpy_Trho(limits.Tmin, rhoL); params.rhoVtriple = rhoV; params.rhoLtriple = rhoL; // Set the triple-point pressure, over-writing whatever is provided by the class // Use the dewpoint pressure for pseudo-pure fluids params.ptriple = pV; //// Instantiate the ancillary curve classes h_ancillary = new AncillaryCurveClass(this,std::string("H")); s_ancillary = new AncillaryCurveClass(this,std::string("S")); // The CAS number for the fluid params.CAS = JSON_lookup_CAS(JSON_CAS,this->name); // Load up environmental factors for this fluid including ODP, GWP, etc. environment.ODP = JSON_lookup_double(JSON,this->params.CAS,"ODP"); environment.GWP20 = JSON_lookup_double(JSON,this->params.CAS,"GWP20"); environment.GWP100 = JSON_lookup_double(JSON,this->params.CAS,"GWP100"); environment.GWP500 = JSON_lookup_double(JSON,this->params.CAS,"GWP500"); environment.HH = JSON_lookup_double(JSON,this->params.CAS,"HH"); environment.FH = JSON_lookup_double(JSON,this->params.CAS,"FH"); environment.PH = JSON_lookup_double(JSON,this->params.CAS,"PH"); environment.ASHRAE34 = JSON_lookup_string(JSON,this->params.CAS,"ASHRAE34"); // Inputs for the enthalpy-entropy solver which is the most problematic solver HS.hmax = JSON_lookup_double(JSON,this->params.CAS,"hsatVmax"); HS.T_hmax = JSON_lookup_double(JSON,this->params.CAS,"T_hsatVmax"); HS.s_hmax = JSON_lookup_double(JSON,this->params.CAS,"s_hsatVmax"); HS.rho_hmax = JSON_lookup_double(JSON,this->params.CAS,"rho_hsatVmax"); HS.a_hs_satL = JSON_lookup_dblvector(JSON,this->params.CAS,"a_hs_satL"); HS.n_hs_satL = JSON_lookup_intvector(JSON,this->params.CAS,"n_hs_satL"); // REFPROP name is equal to fluid name if not provided if (!params.HSReferenceState.empty()) { set_reference_stateP(this,params.HSReferenceState); } } //-------------------------------------------- // Residual Part //-------------------------------------------- double Fluid::phir(double tau, double delta) { if (use_cache && double_equal(tau,cache.phir.tau) && double_equal(delta,cache.phir.delta)) { return cache.phir.cached_val; } else { double summer = 0; for (std::vector<phi_BC*>::iterator it = phirlist.begin(); it != phirlist.end(); it++) summer += (*it)->base(tau,delta); cache.phir.tau = tau; cache.phir.delta = delta; cache.phir.cached_val = summer; return summer; } } double Fluid::dphir_dDelta(double tau, double delta) { if (use_cache && double_equal(tau,cache.dphir_dDelta.tau) && double_equal(delta,cache.dphir_dDelta.delta)) { return cache.dphir_dDelta.cached_val; } else { double summer = 0; for (std::vector<phi_BC*>::iterator it = phirlist.begin(); it != phirlist.end(); it++) { summer += (*it)->dDelta(tau,delta); } cache.dphir_dDelta.tau = tau; cache.dphir_dDelta.delta = delta; cache.dphir_dDelta.cached_val = summer; return summer; } } double Fluid::d2phir_dDelta2(double tau, double delta) { if (use_cache && double_equal(tau,cache.d2phir_dDelta2.tau) && double_equal(delta,cache.d2phir_dDelta2.delta)) { return cache.d2phir_dDelta2.cached_val; } else { double summer = 0; for (std::vector<phi_BC*>::iterator it = phirlist.begin(); it != phirlist.end(); it++) summer += (*it)->dDelta2(tau,delta); cache.d2phir_dDelta2.tau = tau; cache.d2phir_dDelta2.delta = delta; cache.d2phir_dDelta2.cached_val = summer; return summer; } } double Fluid::dphir_dTau(double tau, double delta) { if (use_cache && double_equal(tau,cache.dphir_dTau.tau) && double_equal(delta,cache.dphir_dTau.delta)) { return cache.dphir_dTau.cached_val; } else { double summer = 0; for (std::vector<phi_BC*>::iterator it = phirlist.begin(); it != phirlist.end(); it++) summer += (*it)->dTau(tau,delta); cache.dphir_dTau.tau = tau; cache.dphir_dTau.delta = delta; cache.dphir_dTau.cached_val = summer; return summer; } } double Fluid::d2phir_dTau2(double tau, double delta) { if (use_cache && double_equal(tau,cache.d2phir_dTau2.tau) && double_equal(delta,cache.d2phir_dTau2.delta)) { return cache.d2phir_dTau2.cached_val; } else { double summer = 0; for (std::vector<phi_BC*>::iterator it = phirlist.begin(); it != phirlist.end(); it++) summer += (*it)->dTau2(tau,delta); cache.d2phir_dTau2.tau = tau; cache.d2phir_dTau2.delta = delta; cache.d2phir_dTau2.cached_val = summer; return summer; } } double Fluid::d2phir_dDelta_dTau(double tau, double delta) { if (use_cache && double_equal(tau,cache.d2phir_dDelta_dTau.tau) && double_equal(delta,cache.d2phir_dDelta_dTau.delta)) { return cache.d2phir_dDelta_dTau.cached_val; } else { double summer = 0; for (std::vector<phi_BC*>::iterator it = phirlist.begin(); it != phirlist.end(); it++) summer += (*it)->dDelta_dTau(tau,delta); cache.d2phir_dDelta_dTau.tau = tau; cache.d2phir_dDelta_dTau.delta = delta; cache.d2phir_dDelta_dTau.cached_val = summer; return summer; } } double Fluid::d3phir_dTau3(double tau, double delta) { double summer = 0; for (std::vector<phi_BC*>::iterator it = phirlist.begin(); it != phirlist.end(); it++) summer += (*it)->dTau3(tau,delta); return summer; } double Fluid::d3phir_dDelta3(double tau, double delta) { double summer = 0; for (std::vector<phi_BC*>::iterator it = phirlist.begin(); it != phirlist.end(); it++) { summer += (*it)->dDelta3(tau,delta); } return summer; } double Fluid::d3phir_dDelta_dTau2(double tau, double delta) { double summer = 0; for (std::vector<phi_BC*>::iterator it = phirlist.begin(); it != phirlist.end(); it++) summer += (*it)->dDelta_dTau2(tau,delta); return summer; } double Fluid::d3phir_dDelta2_dTau(double tau, double delta) { double summer = 0; for (std::vector<phi_BC*>::iterator it = phirlist.begin(); it != phirlist.end(); it++) summer += (*it)->dDelta2_dTau(tau,delta); return summer; } //-------------------------------------------- // Ideal Gas Part //-------------------------------------------- double Fluid::phi0(double tau, double delta) { double summer = 0; for (std::vector<phi_BC*>::iterator it = phi0list.begin(); it != phi0list.end(); it++){ summer += (*it)->base(tau,delta); } return summer; } double Fluid::dphi0_dDelta(double tau, double delta) { double summer = 0; for (std::vector<phi_BC*>::iterator it = phi0list.begin(); it != phi0list.end(); it++) summer += (*it)->dDelta(tau,delta); return summer; } double Fluid::d2phi0_dDelta2(double tau, double delta) { double summer = 0; for (std::vector<phi_BC*>::iterator it = phi0list.begin(); it != phi0list.end(); it++) summer += (*it)->dDelta2(tau,delta); return summer; } double Fluid::dphi0_dTau(double tau, double delta) { double summer = 0; for (std::vector<phi_BC*>::iterator it = phi0list.begin(); it != phi0list.end(); it++){ summer += (*it)->dTau(tau,delta); } return summer; } double Fluid::d2phi0_dTau2(double tau, double delta) { double summer = 0; for (std::vector<phi_BC*>::iterator it = phi0list.begin(); it != phi0list.end(); it++){ summer += (*it)->dTau2(tau,delta); } return summer; } double Fluid::d3phi0_dTau3(double tau, double delta) { double summer = 0; for (std::vector<phi_BC*>::iterator it = phi0list.begin(); it != phi0list.end(); it++){ summer += (*it)->dTau3(tau,delta); } return summer; } double Fluid::d2phi0_dDelta_dTau(double tau, double delta) { double summer = 0; for (std::vector<phi_BC*>::iterator it = phi0list.begin(); it != phi0list.end(); it++) summer += (*it)->dDelta_dTau(tau,delta); return summer; } bool Fluid::isAlias(std::string name) { // Returns true if name is an alias of the fluid for (std::vector<std::string>::iterator it = aliases.begin(); it != aliases.end(); it++) if (name.compare((*it))==0) { return true; } return false; } // ---------------------------------------- // Properties // ---------------------------------------- double Fluid::pressure_Trho(double T, double rho) { double delta,tau; tau=reduce.T/T; delta=rho/reduce.rho; return R()*T*rho*(1.0+delta*dphir_dDelta(tau,delta)); } double Fluid::enthalpy_Trho(double T, double rho) { double delta,tau; tau=reduce.T/T; delta=rho/reduce.rho; return R()*T*(1.0+tau*(dphi0_dTau(tau,delta)+dphir_dTau(tau,delta))+delta*dphir_dDelta(tau,delta)); } double Fluid::internal_energy_Trho(double T, double rho) { double delta,tau; tau=reduce.T/T; delta=rho/reduce.rho; return R()*T*tau*(dphi0_dTau(tau,delta)+dphir_dTau(tau,delta)); } double Fluid::entropy_Trho(double T, double rho) { double delta,tau; tau=reduce.T/T; delta=rho/reduce.rho; return R()*(tau*(dphi0_dTau(tau,delta)+dphir_dTau(tau,delta))-phi0(tau,delta)-phir(tau,delta)); } double Fluid::specific_heat_v_Trho(double T, double rho) { double delta,tau; tau=reduce.T/T; delta=rho/reduce.rho; return -R()*tau*tau*(d2phi0_dTau2(tau,delta)+d2phir_dTau2(tau,delta)); } double Fluid::specific_heat_p_Trho(double T, double rho) { double delta,tau,c1,c2,dphir_dDelta_; tau=reduce.T/T; delta=rho/reduce.rho; dphir_dDelta_=dphir_dDelta(tau,delta); c1=pow(1.0+delta*dphir_dDelta_-delta*tau*d2phir_dDelta_dTau(tau,delta),2); c2=(1.0+2.0*delta*dphir_dDelta_+pow(delta,2)*d2phir_dDelta2(tau,delta)); return R()*(-pow(tau,2)*(d2phi0_dTau2(tau,delta)+d2phir_dTau2(tau,delta))+c1/c2); } double Fluid::specific_heat_p_ideal_Trho(double T) { double tau; tau=reduce.T/T; return R()*(1-tau*tau*d2phi0_dTau2(tau, 1e-12)); } double Fluid::speed_sound_Trho(double T, double rho) { double delta,tau,c1,c2; tau=reduce.T/T; delta=rho/reduce.rho; c1=-specific_heat_v_Trho(T,rho)/R(); c2=(1.0+2.0*delta*dphir_dDelta(tau,delta)+pow(delta,2)*d2phir_dDelta2(tau,delta)); return sqrt(-c2*T*specific_heat_p_Trho(T,rho)/c1); } double Fluid::gibbs_Trho(double T,double rho) { double delta,tau; tau=reduce.T/T; delta=rho/reduce.rho; return R()*T*(1+phi0(tau,delta)+phir(tau,delta)+delta*dphir_dDelta(tau,delta)); } double Fluid::dpdT_Trho(double T,double rho) { double delta,tau; tau=reduce.T/T; delta=rho/reduce.rho; return rho*R()*(1+delta*dphir_dDelta(tau,delta)-delta*tau*d2phir_dDelta_dTau(tau,delta)); } double Fluid::dpdrho_Trho(double T,double rho) { double delta,tau; tau=reduce.T/T; delta=rho/reduce.rho; return R()*T*(1+2*delta*dphir_dDelta(tau,delta)+delta*delta*d2phir_dDelta2(tau,delta)); } double Fluid::drhodT_p_Trho(double T,double rho) { return DerivTerms(iDERdrho_dT__p,T,rho,this); } /// Get the density using the Soave EOS double Fluid::density_Tp_Soave(double T, double p, int iValue) { double omega, R, m, a, b, A, B, r, q, D, u, Y, Y1, Y2, Y3, theta, phi, rho; omega = params.accentricfactor; R = params.R_u/params.molemass*1000; // SI units are used internally m = 0.480+1.574*omega-0.176*omega*omega; a = 0.42747*R*R*crit.T*crit.T/crit.p.Pa*pow(1+m*(1-sqrt(T/reduce.T)),2); b = 0.08664*R*crit.T/crit.p.Pa; A = a*p/(R*R*T*T); B = b*p/(R*T); // Terms in reduced cubic equation r = (3*(A-B-B*B)-1)/3; q = -2/27.0+1.0/3.0*(A-B-B*B)-A*B; // Discriminant D = pow(r/3,3)+pow(q/2,2); if (D>0) { // One real root u = pow(-q/2+sqrt(D),1.0/3.0); Y = u-r/(3*u); rho = p/(R*T*(Y+1.0/3.0)); return rho; } else { theta = sqrt(-r*r*r/27); phi = acos(-q/(2*theta)); Y1 = 2*pow(theta,1.0/3.0)*cos(phi/3.0); Y2 = 2*pow(theta,1.0/3.0)*cos(phi/3.0+2.0*M_PI/3.0); Y3 = 2*pow(theta,1.0/3.0)*cos(phi/3.0+4.0*M_PI/3.0); double rho1 = p/(R*T*(Y1+1.0/3.0)); double rho2 = p/(R*T*(Y2+1.0/3.0)); double rho3 = p/(R*T*(Y3+1.0/3.0)); double p1 = pressure_Trho(T,rho1); double p2 = pressure_Trho(T,rho2); double p3 = pressure_Trho(T,rho3); double min_error = 9e50; if (ValidNumber(p1) && fabs(p1-p) < min_error){min_error = fabs(p1-p); rho = rho1;} if (ValidNumber(p2) && fabs(p2-p) < min_error){min_error = fabs(p2-p); rho = rho2;} if (ValidNumber(p3) && fabs(p3-p) < min_error){min_error = fabs(p3-p); rho = rho3;} if (iValue > -1) { if (iValue == 0) { return rho1; } else if (iValue == 1) { return rho3; } } return rho; } } double Fluid::density_Tp_PengRobinson(double T, double p, int solution) { double A, B, m, a, b, Z, rhobar; double Rbar = 8314.472; // Using SI units internally b = 0.077796074*(Rbar*reduce.T)/(reduce.p.Pa); B = 0.077796074*p/reduce.p.Pa*reduce.T/T; m = 0.37464 + 1.54226*params.accentricfactor-0.26992*pow(params.accentricfactor,2); a = 0.45724*pow(Rbar*reduce.T,2)/reduce.p.Pa*pow(1+m*(1-sqrt(T/reduce.T)),2)*1000; A = a*p/(Rbar*Rbar*T*T)/1000; double x0, x1, x2; solve_cubic(1, -1+B, A-3*B*B-2*B, -A*B+B*B+B*B*B, &x0, &x1, &x2); std::vector<double> solns; solns.push_back(x0); solns.push_back(x1); solns.push_back(x2); // Erase negative solutions and unstable solutions // Stable solutions are those for which dpdrho is positive for (int i = (int)solns.size()-1; i >= 0; i--) { if (solns[i] < 0) { solns.erase(solns.begin()+i); } else { //double v = (solns[i]*Rbar*T)/p; //[mol/L] //double dpdrho = -v*v*(-Rbar*T/pow(v-b,2)+a*(2*v+2*b)/pow(v*v+2*b*v-b*b,2)); //if (dpdrho < 0) //{ // solns.erase(solns.begin()+i); //} } } if (solution == 0) { Z = *std::min_element(solns.begin(), solns.end()); } else if (solution == 1) { Z = *std::max_element(solns.begin(), solns.end()); } else { throw ValueError(); } rhobar = p/(Z*Rbar*T); //[mol/L] //double vbar = 1/rhobar; //double p_check = Rbar*T/(vbar-b)-a/(vbar*vbar+2*b*vbar-b*b); return rhobar*params.molemass; } /*! \f[ \begin{array}{l} p = \frac{{RT}}{{v - b}} - \frac{{a\alpha }}{{v\left( {v + b} \right)}}\\ \alpha = \left( {1 + \kappa \left( {1 - \sqrt {{T_r}} } \right)} \right)\left( {1 + \kappa \left( {1 - \sqrt {{T_r}} } \right)} \right) = 1 + 2\kappa \left( {1 - \sqrt {{T_r}} } \right) + {\kappa ^2}{\left( {1 - \sqrt {{T_r}} } \right)^2}\\ \alpha = 1 + 2\kappa \left( {1 - \sqrt {{T_r}} } \right) + {\kappa ^2}{\left( {1 - \sqrt {{T_r}} } \right)^2}\\ \alpha = 1 + 2\kappa - 2\kappa \sqrt {{T_r}} + {\kappa ^2}\left[ {1 - 2\sqrt {{T_r}} + {T_r}} \right]\\ T = {T_r}{T_c}\\ p = \frac{{R{T_r}{T_c}}}{{v - b}} - \frac{{a\left( {1 + 2\kappa - 2\kappa \sqrt {{T_r}} + {\kappa ^2}\left[ {1 - 2\sqrt {{T_r}} + {T_r}} \right]} \right)}}{{v\left( {v + b} \right)}}\\ \\ {\rm{Factor in terms of }}\sqrt {{T_r}} \\ \\ p = \frac{{R{T_r}{T_c}}}{{v - b}} - \frac{{a\left( {1 + 2\kappa + {\kappa ^2} - 2\kappa \sqrt {{T_r}} + {\kappa ^2}\left[ { - 2\sqrt {{T_r}} + {T_r}} \right]} \right)}}{{v\left( {v + b} \right)}}\\ p = \frac{{R{T_r}{T_c}}}{{v - b}} - \frac{{a\left( {1 + 2\kappa + {\kappa ^2} - 2\kappa (1 + \kappa )\sqrt {{T_r}} + {\kappa ^2}{T_r}} \right)}}{{v\left( {v + b} \right)}}\\ p = \frac{{R{T_r}{T_c}}}{{v - b}} - \frac{{a\left( {1 + 2\kappa + {\kappa ^2}} \right)}}{{v\left( {v + b} \right)}} + \frac{{2a\kappa (1 + \kappa )}}{{v\left( {v + b} \right)}}\sqrt {{T_r}} - \frac{{a{\kappa ^2}}}{{v\left( {v + b} \right)}}{T_r}\\ 0 = \left[ {\frac{{R{T_c}}}{{v - b}} - \frac{{a{\kappa ^2}}}{{v\left( {v + b} \right)}}} \right]{T_r} + \frac{{2a\kappa (1 + \kappa )}}{{v\left( {v + b} \right)}}\sqrt {{T_r}} - \frac{{a\left( {1 + 2\kappa + {\kappa ^2}} \right)}}{{v\left( {v + b} \right)}} - p \end{array} \f] */ double Fluid::temperature_prho_PengRobinson(double p, double rho) { double omega, R, kappa, a, b, A, B, C, D, V= 1/rho; omega = params.accentricfactor; R = this->R(); kappa = 0.37464+1.54226*omega-0.26992*omega*omega; a = 0.457235*R*R*crit.T*crit.T/crit.p.Pa; b = 0.077796*R*crit.T/crit.p.Pa; double den = V*V+2*b*V-b*b; // A sqrt(Tr)^2 + B sqrt(Tr) + C = 0 A = R*reduce.T/(V-b)-a*kappa*kappa/(den); B = +2*a*kappa*(1+kappa)/(den); C = -a*(1+2*kappa+kappa*kappa)/(den)-p; D = B*B-4*A*C; double sqrt_Tr1 = (-B+sqrt(B*B-4*A*C))/(2*A); //double sqrt_Tr2 = (-B-sqrt(B*B-4*A*C))/(2*A); return sqrt_Tr1*sqrt_Tr1*reduce.T; } double Fluid::temperature_prho_VanDerWaals(double p, double rho) { double R = 8314.472; // Using SI units internally double a = 27*pow(R*reduce.T,2)/(64*reduce.p.Pa); double b = R*reduce.T/(8*reduce.p.Pa); double Vm = 1/rho*params.molemass; return 1.0/R*(p+a/Vm/Vm)*(Vm-b); } double Fluid::density_Tp(double T, double p) { // If the guess value is not provided, calculate the guess density using Peng-Robinson // This overload is used to pre-calculate the guess for density using PR if possible if (get_debug_level()>8){ std::cout << format("%s:%d: Fluid::density_Tp(double T, double p)\n", __FILE__, __LINE__, T, p).c_str(); } return density_Tp(T,p,_get_rho_guess(T,p)); } double Fluid::density_Tp(double T, double p, double rho_guess) { double tau,dpdrho__constT,error=999,R,p_EOS,rho,change=999; R = params.R_u/params.molemass*1000; // SI units are used internally tau = reduce.T/T; if (get_debug_level()>8){ std::cout << format("%s:%d: Fluid::density_Tp(T=%g, p=%g, rho_guess=%g)\n",__FILE__,__LINE__,T,p,rho_guess).c_str(); } // Start with the guess value // The first step, use the derivative of dp/drho|T in order to get the next value // In subsequent steps, use secant method because each evaluation of newton step requires two evaluations of derivatives with respect to delta rho=rho_guess; int iter=1; double delta = rho/reduce.rho; //while (fabs(error) > 1e-10 && fabs(change/rho)>DBL_EPSILON*10) while (fabs(error) > 1e-12 && fabs(change)>1e-14) { // Needed for both kinds // Run and save to cut down on calculations double dphirdDelta = dphir_dDelta(tau, delta); // Pressure from equation of state p_EOS = reduce.rho*delta*R*T*(1+delta*dphirdDelta); // Residual error = p_EOS-p; // Use Newton's method to find the density since the derivative of pressure w.r.t. density is known from EOS dpdrho__constT = R*T*(1+2*delta*dphirdDelta+delta*delta*d2phir_dDelta2(tau,delta)); double dpddelta__constT = dpdrho__constT*reduce.rho; // Update the step using Newton's method change = (p_EOS-p)/dpddelta__constT; delta -= change; iter++; if (iter>50) { throw SolutionError(format("Number of steps in density_TP has exceeded 30 with inputs T=%g,p=%g,rho_guess=%g for fluid %s",T,p,rho_guess,name.c_str())); } if (!ValidNumber(rho)) { throw SolutionError(format("Non-numeric density obtained in density_TP with inputs T=%g,p=%g,rho_guess=%g for fluid %s",T,p,rho_guess,name.c_str())); } } if (get_debug_level()>8){ std::cout << format("%s:%d: Fluid::density_Tp(T = %g, p = %g, rho_guess = %g) = %g\n",__FILE__,__LINE__,T,p,rho_guess,rho).c_str(); } return delta*reduce.rho; } double Fluid::viscosity_Trho( double T, double rho) { long iFluid = get_Fluid_index(ECSReferenceFluid); // Calculate the ECS double mu = viscosity_ECS_Trho(T, rho, get_fluid(iFluid)); return mu; } double Fluid::conductivity_Trho( double T, double rho) { long iFluid = get_Fluid_index(ECSReferenceFluid); // Calculate the ECS double lambda = conductivity_ECS_Trho(T, rho, get_fluid(iFluid)); return lambda; } void Fluid::saturation_s(double s, int Q, double &Tsatout, double &rhoout, double &TLout, double &TVout, double &rhoLout, double &rhoVout) { class SatFuncClass : public FuncWrapper1D { private: int Q; double s; Fluid * pFluid; public: double rho,pL,pV,rhoL,rhoV,T; SatFuncClass(double s, int Q, Fluid *pFluid){ this->s = s; this->Q = Q; this->pFluid = pFluid; }; double call(double T){ pFluid->saturation_T(T, false, pL, pV, rhoL, rhoV); if (Q == 0){ this->rho = rhoL; return pFluid->entropy_Trho(T,rhoL) - this->s; } else if (Q == 1){ this->rho = rhoV; return pFluid->entropy_Trho(T,rhoV) - this->s; } else{ throw ValueError("Q must be 0 or 1"); } //this->T = T; return -_HUGE; }; } SatFunc(s, Q, this); if (get_debug_level()>5){ std::cout << format("%s:%d: Fluid::saturation_s(%g,%d) \n",__FILE__,__LINE__,s,Q).c_str(); } if (isPure == true) { if (enabled_TTSE_LUT) { throw NotImplementedError(format("saturation_s not implemented for TTSE")); return; } else { std::string errstr; Tsatout = Brent(&SatFunc,limits.Tmin,crit.T,1e-16,1e-8,100,&errstr); rhoout = SatFunc.rho; rhoLout = SatFunc.rhoL; rhoVout = SatFunc.rhoV; TLout = SatFunc.T; TVout = SatFunc.T; } } else { throw NotImplementedError("Pseudo-pure not currently supported for saturation_s"); //// Pseudo-pure fluid //*psatLout = psatL(T); //*psatVout = psatV(T); //try{ // *rhosatLout = density_Tp(T, *psatLout, rhosatL(T)); // *rhosatVout = density_Tp(T, *psatVout, rhosatV(T)); //} //catch (std::exception){ // // Near the critical point, the behavior is not very nice, so we will just use the ancillary near the critical point // *rhosatLout = rhosatL(T); // *rhosatVout = rhosatV(T); //} //return; } } void Fluid::saturation_h(double h, double Tmin, double Tmax, int Q, double &Tsatout, double &rhoout, double &TsatLout, double &TsatVout, double &rhoLout, double &rhoVout) { class SatFuncClass : public FuncWrapper1D { private: int Q; double h; Fluid * pFluid; public: double rho,pL,pV,rhoL,rhoV,T; SatFuncClass(double h, int Q, Fluid *pFluid){ this->h = h; this->Q = Q; this->pFluid = pFluid; }; double call(double T){ this->T = T; pFluid->saturation_T(T, false, pL, pV, rhoL, rhoV); if (Q == 0){ this->rho = rhoL; return pFluid->enthalpy_Trho(T,rhoL) - this->h; } else if (Q == 1){ this->rho = rhoV; return pFluid->enthalpy_Trho(T,rhoV) - this->h; } else{ throw ValueError("Q must be 0 or 1"); } }; } SatFunc(h, Q, this); if (get_debug_level()>5){ std::cout << format("%s:%d: Fluid::saturation_h(%g,%d) \n",__FILE__,__LINE__,h,Q).c_str(); } if (isPure == true) { if (enabled_TTSE_LUT) { throw NotImplementedError(format("saturation_h not implemented for TTSE")); return; } else { std::string errstr; Tsatout = Brent(&SatFunc,Tmin,Tmax,1e-16,1e-10,100,&errstr); rhoout = SatFunc.rho; rhoLout = SatFunc.rhoL; rhoVout = SatFunc.rhoV; TsatLout = SatFunc.T; TsatVout = SatFunc.T; } } else { throw NotImplementedError("Pseudo-pure not currently supported"); //// Pseudo-pure fluid //*psatLout = psatL(T); //*psatVout = psatV(T); //try{ // *rhosatLout = density_Tp(T, *psatLout, rhosatL(T)); // *rhosatVout = density_Tp(T, *psatVout, rhosatV(T)); //} //catch (std::exception){ // // Near the critical point, the behavior is not very nice, so we will just use the ancillary near the critical point // *rhosatLout = rhosatL(T); // *rhosatVout = rhosatV(T); //} //return; } } void Fluid::saturation_T(double T, bool UseLUT, double &psatLout, double &psatVout, double &rhosatLout, double &rhosatVout) { double p; if (get_debug_level()>5){ std::cout << format("%s:%d: Fluid::saturation_T(%g,%d) \n",__FILE__,__LINE__,T,UseLUT).c_str(); } if (T < limits.Tmin){ throw ValueError(format("Your temperature to saturation_T [%g K] is below the minimum temp [%g K]",T,limits.Tmin));} if (isPure==true) { if (enabled_TTSE_LUT) { throw NotImplementedError(format("saturation_T not implemented for TTSE")); return; } else { if (UseCriticalSpline && ValidNumber(CriticalSpline_T.Tend) && T > CriticalSpline_T.Tend) { //// Use the spline (or linear) interpolation since you are very close to the critical point rhosatLout = CriticalSpline_T.interpolate_rho(this,0,T); rhosatVout = CriticalSpline_T.interpolate_rho(this,1,T); psatLout = pressure_Trho(T,rhosatLout); psatVout = psatLout; return; } try{ // Reduce omega in uniform steps double omega = 1.0; do { try{ rhosatPure_Akasaka(T, rhosatLout, rhosatVout, p, omega); psatLout = p; psatVout = p; return; break; } catch (std::exception) { omega -= 0.3; } } while(omega > 0); // We ran out of steps in omega if (omega < 0.05) { throw ValueError(); } } catch(std::exception &) { try{ // Reduce omega in uniform steps double omega = 1.0; do { try{ rhosatPure(T, rhosatLout, rhosatVout, p, omega, false); psatLout = p; psatVout = p; return; } catch (std::exception) { omega -= 0.3; } } while(omega > 0); // We ran out of steps in omega if (omega < 0.05) { throw ValueError(); } } catch (std::exception){ rhosatPure_Brent(T,rhosatLout,rhosatVout,p); psatLout = p; psatVout = p; return; } } } } else { // Pseudo-pure fluid psatLout = psatL(T); // These ancillaries are used explicitly psatVout = psatV(T); // These ancillaries are used explicitly try{ double rhoLanc = rhosatL(T); double rhoVanc = rhosatV(T); if (!ValidNumber(rhoLanc) || !ValidNumber(rhoVanc)) { throw ValueError("pseudo-pure failed"); } rhosatLout = density_Tp(T, psatLout, rhosatL(T)); rhosatVout = density_Tp(T, psatVout, rhosatV(T)); if (!ValidNumber(rhosatLout) || !ValidNumber(rhosatVout) || fabs(rhoLanc/rhosatLout-1) > 0.1 || fabs(rhoVanc/rhosatVout-1) > 0.1) { throw ValueError("pseudo-pure failed"); } } catch (std::exception &){ // Near the critical point, the behavior is not very nice, so we will just use the ancillary near the critical point rhosatLout = rhosatL(T); rhosatVout = rhosatV(T); } return; } } void Fluid::rhosatPure_Brent(double T, double &rhoLout, double &rhoVout, double &pout) { /* Use Brent's method around when Akasaka's method fails. Slow but reliable */ class SatFuncClass : public FuncWrapper1D { private: double T,gL,gV; Fluid * pFluid; public: double p,rhoL,rhoV; SatFuncClass(double T, Fluid *pFluid) :T(T), pFluid(pFluid){}; double call(double p){ // Span, 2000 p 56 DensityTpResids DTPR = DensityTpResids(this->pFluid,T,p); std::string errstr; //this->rhoL = this->pFluid->rhosatL(T); //std::cout << Props("D",'Q',0,'T',T,"REFPROP-R245fa") <<std::endl; rhoL = Brent(&DTPR,rhoL+1e-3,rhoL-1e-3,DBL_EPSILON,1e-8,30,&errstr); rhoV = Brent(&DTPR,rhoV,pFluid->crit.rho-10*DBL_EPSILON,DBL_EPSILON,1e-8,40,&errstr); gL = pFluid->gibbs_Trho(T,rhoL); gV = pFluid->gibbs_Trho(T,rhoV); return gL-gV; }; } SatFunc(T,this); std::string errstr; double pmax = reduce.p.Pa; double pmin; try { pmin = psatV_anc(T-0.1); } catch (std::exception) { pmin = 1e-10; } if (pmin < params.ptriple) pmin = params.ptriple; Brent(&SatFunc,pmin,pmax,DBL_EPSILON,1e-8,30,&errstr); } class rhosatPure_BrentrhoVResidClass : public FuncWrapper1D { public: Fluid * pFluid; double T,gL,gV,rhoL,rhoV,p; rhosatPure_BrentrhoVResidClass(double T, Fluid *pFluid):T(T), pFluid(pFluid){ this->rhoL = pFluid->rhosatL(T); }; double call(double rhoV){ double pV = pFluid->pressure_Trho(T,rhoV); rhoL = pFluid->density_Tp(T,pV,rhoL); gL = pFluid->gibbs_Trho(T,rhoL); gV = pFluid->gibbs_Trho(T,rhoV); this->p = pV; this->rhoV = rhoV; return gL-gV; }; }; void Fluid::rhosatPure_BrentrhoV(double T, double &rhoLout, double &rhoVout, double &pout) { rhosatPure_BrentrhoVResidClass SF = rhosatPure_BrentrhoVResidClass(T,this); std::string errstr; Brent(&SF,(reduce.rho+0.95*rhosatV(T))/2,0.95*rhosatV(T),DBL_EPSILON,1e-12,30,&errstr); rhoLout = SF.rhoL; rhoVout = SF.rhoV; pout = SF.p; } /// This function implements the method of Akasaka to do analytic Newton-Raphson for the /// saturation calcs void Fluid::rhosatPure_Akasaka(double T, double &rhoLout, double &rhoVout, double &pout, double omega = 1.0, bool use_guesses) { /* This function implements the method of Akasaka R. Akasaka,"A reliable and Useful Method to Determine the Saturation State from Helmholtz Energy Equations of State", Journal of Thermal Science and Technology v3 n3,2008 Ancillary equations are used to get a sensible starting point */ long double rhoL,rhoV,dphirL,dphirV,ddphirL,ddphirV,phirL,phirV,JL,JV,KL,KV,dJL,dJV,dKL,dKV; long double DELTA, deltaL=0, deltaV=0, tau=0, error, PL, PV, stepL, stepV; int iter=0; // Use the density ancillary function as the starting point for the solver try { if (!use_guesses) { // If very close to the critical temp, evaluate the ancillaries for a slightly lower temperature if (T > 0.99*reduce.T) { rhoL=rhosatL(T-1); rhoV=rhosatV(T-1); } else { rhoL=rhosatL(T); rhoV=rhosatV(T); } } else { rhoL = rhoLout; rhoV = rhoVout; } deltaL = rhoL/reduce.rho; deltaV = rhoV/reduce.rho; tau = reduce.T/T; } catch(NotImplementedError &) { double Tc = crit.T; double pc = crit.p.Pa; double w = 6.67228479e-09*Tc*Tc*Tc-7.20464352e-06*Tc*Tc+3.16947758e-03*Tc-2.88760012e-01; double q = -6.08930221451*w -5.42477887222; double pt = exp(q*(Tc/T-1))*pc; double rhoL = density_Tp_Soave(T, pt, 0), rhoV = density_Tp_Soave(T, pt, 1); deltaL = rhoL/reduce.rho; deltaV = rhoV/reduce.rho; tau = reduce.T/T; } if (get_debug_level()>5){ std::cout << format("%s:%d: Akasaka guess values deltaL = %g deltaV = %g tau = %g\n",__FILE__,__LINE__,deltaL, deltaV, tau).c_str(); } do{ if (get_debug_level()>8){ std::cout << format("%s:%d: right before the derivs with deltaL = %g deltaV = %g tau = %g\n",__FILE__,__LINE__,deltaL, deltaV, tau).c_str(); } // Calculate once to save on calls to EOS dphirL = dphir_dDelta(tau,deltaL); dphirV = dphir_dDelta(tau,deltaV); ddphirL = d2phir_dDelta2(tau,deltaL); ddphirV = d2phir_dDelta2(tau,deltaV); phirL = phir(tau,deltaL); phirV = phir(tau,deltaV); JL = deltaL * (1 + deltaL*dphirL); JV = deltaV * (1 + deltaV*dphirV); KL = deltaL*dphirL + phirL + log(deltaL); KV = deltaV*dphirV + phirV + log(deltaV); PL = R()*reduce.rho*T*JL; PV = R()*reduce.rho*T*JV; // At low pressure, the magnitude of ddphirL and ddphirV are enormous, truncation problems arise for all the partials dJL = 1 + 2*deltaL*dphirL + deltaL*deltaL*ddphirL; dJV = 1 + 2*deltaV*dphirV + deltaV*deltaV*ddphirV; dKL = 2*dphirL + deltaL*ddphirL + 1/deltaL; dKV = 2*dphirV + deltaV*ddphirV + 1/deltaV; DELTA = dJV*dKL-dJL*dKV; error = fabs(KL-KV)+fabs(JL-JV); // Get the predicted step stepL = omega/DELTA*( (KV-KL)*dJV-(JV-JL)*dKV); stepV = omega/DELTA*( (KV-KL)*dJL-(JV-JL)*dKL); if (deltaL+stepL > 1 && deltaV+stepV < 1 && deltaV+stepV > 0) { deltaL += stepL; deltaV += stepV; } else { throw ValueError(format("rhosatPure_Akasaka failed")); } iter++; if (iter > 100) { throw SolutionError(format("Akasaka solver did not converge after 100 iterations")); } } while (error > 1e-10 && fabs(stepL) > 10*DBL_EPSILON*fabs(stepL) && fabs(stepV) > 10*DBL_EPSILON*fabs(stepV)); rhoLout = deltaL*reduce.rho; rhoVout = deltaV*reduce.rho; pout = PV; return; } void Fluid::saturation_VdW(double T, double &rhoL, double &rhoV, double &p, double s0) { class resid : public FuncWrapper1D { protected: double Tr; public: resid(double Tr){this->Tr = Tr;}; double call(double s) { double w = sqrt(s*s-32*Tr/s+36-12*s); double val = log((s*(6-s)-(16*Tr/3)+s*w)/(s*(6-s)-(16*Tr/3)-s*w))-3*(6-s)*w/8*Tr; return val; } }; resid r(T/this->crit.T); std::string errstr; if (s0 < 0) { s0 = 2; } double v1 = r.call(s0-1); double v2 = r.call(s0); double v3 = r.call(s0+1); double s = Secant(&r,s0,0.01,1e-8,100,&errstr); } void Fluid::rhosatPure(double T, double &rhoLout, double &rhoVout, double &pout, double omega = 1.0, bool use_guesses = false) { // Only works for pure fluids (no blends) // At equilibrium, saturated vapor and saturated liquid are at the same pressure and the same Gibbs energy double rhoL,rhoV,p=_HUGE,error=999,x1=0,x2=0,x3,y1=0,y2,f,p_guess; int iter; if (T>=crit.T || T<(params.Ttriple-0.0001)) { throw ValueError(format("Temperature of fluid [%g] is out of range from %g K to %g K in rhosatPure",T,params.Ttriple,crit.T)); } if (!use_guesses) { // Use the density ancillary function as the starting point for the secant solver rhoL = rhosatL(T); rhoV = rhosatV(T); } else { // Use the guesses provided rhoL = rhoLout; rhoV = rhoVout; } p_guess = pressure_Trho(T,rhoV); iter=1; // Use a secant method to obtain pressure while ((iter<=3 || fabs(error)>1e-6) && iter<100) { if (iter==1){x1=p_guess; p=x1;} else if (iter==2){x2=1.000001*p_guess; p=x2;} else {p=x2;} //Recalculate the densities based on the current pressure rhoL = density_Tp(T,p,rhoL); rhoV = density_Tp(T,p,rhoV); // Residual between saturated liquid and saturated vapor gibbs function f = gibbs_Trho(T,rhoL) - gibbs_Trho(T,rhoV); if (iter==1){y1=f;} else //(iter>1) { y2=f; x3=x2-omega*y2/(y2-y1)*(x2-x1); error=f; y1=y2; x1=x2; x2=x3; } iter++; if (iter>100) { //ERROR throw SolutionError(format("rhosatPure failed, current values of rhoL and rhoV are %g,%g\n",rhoL,rhoV).c_str()); } } rhoLout=rhoL; rhoVout=rhoV; pout=p; return; } bool isBetween(double x1,double x2, double x) { if (x2>x1 && x>=x1 && x<=x2) return true; else if (x1>x2 && x<=x1 && x>=x2) return true; else return false; } // Ancillary equations composed by interpolating within 50-point // curve that is calculated once double Fluid::hsatV_anc(double T) { if (!h_ancillary->built) h_ancillary->build(50); return h_ancillary->interpolateV(T); } double Fluid::ssatV_anc(double T) { if (!s_ancillary->built) s_ancillary->build(50); return s_ancillary->interpolateV(T); } double Fluid::hsatL_anc(double T) { if (!h_ancillary->built) h_ancillary->build(50); return h_ancillary->interpolateL(T); } double Fluid::ssatL_anc(double T) { if (!s_ancillary->built) s_ancillary->build(50); return s_ancillary->interpolateL(T); } double Fluid::_get_rho_guess(double T, double p) { double Tc,rho_simple; Tc = reduce.T; // Then based on phase, select the useful solution(s) double pL,pV,rhoL,rhoV; long phase = phase_Tp_indices(T,p,pL,pV,rhoL,rhoV); if (get_debug_level()>5){ std::cout << format("%s:%d: Fluid::_get_rho_guess(%g,%g) phase = %d\n",__FILE__,__LINE__,T,p,phase).c_str(); } // These are very simplistic guesses for the density, but they work ok if (phase == iGas) { // Perfect gas relation for initial guess rho_simple = p/(R()*T); } else if (phase == iSupercritical) { // Use Soave to get first guess rho_simple = density_Tp_Soave(T,p); } else if (phase == iLiquid) { // Start at the saturation state, with a known density, using the ancillary double rhoL = rhosatL(T); double pL = psatL_anc(T); if (get_debug_level()>5){ std::cout<<format("%s:%d: pL = %g rhoL = %g \n",__FILE__,__LINE__,pL,rhoL).c_str(); } double delta = rhoL / reduce.rho; double tau = reduce.T/T; double dp_drho = R()*T*(1+2*delta*dphir_dDelta(tau,delta)+delta*delta*d2phir_dDelta2(tau,delta)); double drho_dp = 1/dp_drho; if (drho_dp*(pL-p)> rhoL) { rho_simple = rhoL; } else { rho_simple = rhoL-drho_dp*(pL-p); } } else if (fabs(psatL_anc(T)-p)<1e-8 || fabs(psatV_anc(T)-p)<1e-8) { throw ValueError(format("Input T [%0.16g] & p [%0.16g] are two-phase or saturated which is thermodynamically undefined\n",T,p)); } else { // It is two-phase, we are going to skip the process of // solving and just return a value somewhere in the two-phase region. return (rhoL+rhoV)/2; } if (get_debug_level()>5){ std::cout << format("%s:%d: _get_rho_guess = %g\n",__FILE__,__LINE__,rho_simple).c_str(); } return rho_simple; } std::string Fluid::phase_Tp(double T, double p, double &pL, double &pV, double &rhoL, double &rhoV) { // Get the value from the long-output function long iPhase = phase_Tp_indices(T, p, pL, pV, rhoL, rhoV); if (get_debug_level()>5){ std::cout << format("%s:%d: phase_Tp() phase index is %d\n",iPhase).c_str(); } // Convert it to a std::string switch (iPhase) { case iTwoPhase: return std::string("Two-Phase"); case iSupercritical: return std::string("Supercritical"); case iGas: return std::string("Gas"); case iLiquid: return std::string("Liquid"); default: return std::string(""); } } long Fluid::phase_Tp_indices(double T, double p, double &pL, double &pV, double &rhoL, double &rhoV) { /* | | | | Supercritical | | p | Liquid (b)------------ | / | / | / Gas | / | (a) | - |------------------------ T a: triple point b: critical point a-b: Saturation line */ if (get_debug_level()>5){ std::cout << format("%s:%d: phase_Tp_indices(%g,%g)\n",__FILE__,__LINE__,T,p).c_str(); } if (T>crit.T && p>=crit.p.Pa){ return iSupercritical; } else if (T>crit.T && p<crit.p.Pa){ return iGas; } else if (T<crit.T && p>crit.p.Pa){ return iLiquid; } else if (p<params.ptriple){ return iGas; } else{ // Now start to think about the saturation stuff // First try to use the ancillary equations if you are far enough away // Ancillary equations are good to within 1% in pressure in general // Some industrial fluids might not be within 3% if (isPure && p<0.94*psat(T)){ return iGas; } else if (isPure && p>1.06*psat(T)){ return iLiquid; } else if (!isPure && p<0.94*psatV(T)){ return iGas; } else if (!isPure && p>1.06*psatL(T)){ return iLiquid; } else{ // Actually have to use saturation information sadly // For the given temperature, find the saturation state // Run the saturation routines to determine the saturation densities and pressures saturation_T(T,enabled_TTSE_LUT,pL,pV,rhoL,rhoV); if (p>(pL+10*DBL_EPSILON)){ return iLiquid; } else if (p<(pV-10*DBL_EPSILON)){ return iGas; } else{ return iTwoPhase; } } } } std::string Fluid::phase_Trho(double T, double rho, double &pL, double &pV, double &rhoL, double &rhoV) { // Get the value from the long-output function long iPhase = phase_Trho_indices(T, rho, pL, pV, rhoL, rhoV); if (get_debug_level()>5){ std::cout << format("%s:%d: phase index is %d\n",__FILE__,__LINE__,iPhase).c_str(); } // Convert it to a std::string switch (iPhase) { case iTwoPhase: return std::string("Two-Phase"); case iSupercritical: return std::string("Supercritical"); case iGas: return std::string("Gas"); case iLiquid: return std::string("Liquid"); default: return std::string(""); } } long Fluid::phase_Trho_indices(double T, double rho, double &pL, double &pV, double &rhoL, double &rhoV) { /* | | Liquid | | --- | \ | \ rho | a | / | / | -- | | Gas | |------------------------ T a: triple point b: critical point a-b: Saturation line */ // If temperature is below the critical temperature, it is either // subcooled liquid, superheated vapor, or two-phase if (T < crit.T) { // Start to think about the saturation stuff // First try to use the ancillary equations if you are far enough away // Ancillary equations are good to within 1% in pressure in general // Some industrial fluids might not be within 3% if (rho < 0.95*rhosatV(T)){ return iGas; } else if (rho > 1.05*rhosatL(T)){ return iLiquid; } else{ // Actually have to use saturation information sadly // For the given temperature, find the saturation state // Run the saturation routines to determine the saturation densities and pressures // Use the passed in variables to save calls to the saturation routine so the values can be re-used again saturation_T(T, enabled_TTSE_LUT, pL, pV, rhoL, rhoV); double Q = (1/rho-1/rhoL)/(1/rhoV-1/rhoL); if (Q < -100*DBL_EPSILON){ return iLiquid; } else if (Q > 1+100*DBL_EPSILON){ return iGas; } else{ return iTwoPhase; } } } // Now check the states above the critical temperature double p = pressure_Trho(T,rho); if (T>reduce.T && p>reduce.p.Pa){ return iSupercritical; } else if (T>reduce.T && p<reduce.p.Pa){ return iGas; } else if (T<reduce.T && p>reduce.p.Pa){ return iLiquid; } else if (p<params.ptriple){ return iGas; } else{ return -1; } } long Fluid::phase_prho_indices(double p, double rho, double &T, double &TL, double &TV, double &rhoL, double &rhoV) { // If temperature is below the critical temperature, it is either // subcooled liquid, superheated vapor, or two-phase if (p < crit.p.Pa) { // Actually have to use saturation information sadly // For the given temperature, find the saturation state // Run the saturation routines to determine the saturation densities and pressures // Use the passed in variables to save calls to the saturation routine so the values can be re-used again saturation_p(p,false,TL,TV,rhoL,rhoV); double Q = (1/rho-1/rhoL)/(1/rhoV-1/rhoL); if (Q < -1e-10){ return iLiquid; } else if (Q > 1+1e-10){ return iGas; } else{ T = TL; return iTwoPhase; } } // Now check the states above the critical pressure double T0 = temperature_prho_PengRobinson(p,rho); T = temperature_prho(p, rho, T0); if (T > crit.T){ return iSupercritical; } else{ // T < crit.T return iLiquid; } } double Fluid::temperature_prho(double p, double rho, double T0) { // solve for T to yield the desired pressure double error, T, drdT, r; int iter = 0; CoolPropStateClassSI CPS(this); T = T0; CPS.update(iT,T,iD,rho); do { double pEOS = CPS.p(); r = pEOS-p; drdT = CPS.dpdT_constrho(); T -= r/drdT; CPS.update(iT,T,iD,rho); error = fabs(r/pEOS); iter++; if (fabs(r/drdT) < 1e-12) { return T; break; } if (iter > 100) throw SolutionError(format("temperature_prho failed with inputs p=%g rho=%g T0=%g for fluid %s",p,rho,T0,name.c_str())); } while (error > 1e-10 ); return T; } void Fluid::temperature_ph(double p, double h, double &Tout, double &rhoout, double &rhoLout, double &rhoVout, double &TsatLout, double &TsatVout, double T0, double rho0) { int iter; bool failed = false; double A[2][2], B[2][2],T_guess, omega =1.0; double dar_ddelta,da0_dtau,d2a0_dtau2,dar_dtau,d2ar_ddelta_dtau,d2ar_ddelta2,d2ar_dtau2,d2a0_ddelta_dtau; double f1,f2,df1_dtau,df1_ddelta,df2_ddelta,df2_dtau; double rhoL, rhoV, hsatL,hsatV,TsatL,TsatV,tau,delta,worst_error; double h_guess, hc, rho_guess, T1, T2, h1, h2, rho1, rho2; double hsat_tol = 3000; //[J/kg] // A starting set of temperature and pressure are provided, use them as the guess value // Their default values are -1 and -1, which are unphysical values if (T0 > 0 && rho0 > 0) { T_guess = T0; delta = rho0/reduce.rho; } else { // It is supercritical pressure (or just below the critical pressure) if (p > 0.999*crit.p.Pa) { hc = enthalpy_Trho(crit.T+0.001,crit.rho); if (h > hc) { // Supercritical pseudo-gas - extrapolate to find guess temperature at critical density T_guess = crit.T+30; h_guess = enthalpy_Trho(T_guess,crit.rho); T_guess = (crit.T-T_guess)/(hc-h_guess)*(h-h_guess)+T_guess; rho_guess = density_Tp(T_guess,p); delta = rho_guess/reduce.rho; } else { // Supercritical pseudo-liquid T_guess = params.Ttriple; rho_guess = density_Tp(T_guess,p); h_guess = enthalpy_Trho(T_guess,rho_guess); // Update the guess with linear interpolation T_guess = (crit.T-T_guess)/(hc-h_guess)*(h-h_guess)+T_guess; // Solve for the density rho_guess = density_Tp(T_guess,p,rho_guess); delta = rho_guess/reduce.rho; } } else if (p < params.ptriple) { rho_guess = params.rhoVtriple; T_guess = params.ptriple; delta = rho_guess/reduce.rho; } else { // Set to a negative value as a dummy value delta = -1; // If using TTSE, TTSE is the arbiter of two-phase/single-phase boundary // if (enabled_TTSE_LUT) { hsatL = TTSESatL.evaluate(iH,p); hsatV = TTSESatV.evaluate(iH,p); // If TTSE is enabled and we have gotten to this point if (h>hsatV || h<hsatL) { } } else { //************************************************** // Step 1: Try to just use the ancillary equations //************************************************** TsatL = Tsat_anc(p,0); if (pure()) TsatV = TsatL; else TsatV = Tsat_anc(p,1); rhoL = rhosatL(TsatL); rhoV = rhosatV(TsatV); hsatL = hsatL_anc(TsatL); //[J/kg] hsatV = hsatV_anc(TsatV); //[J/kg] rhoLout = -1; rhoVout = -1; TsatLout = -1; TsatVout = -1; if (h > hsatV + hsat_tol) { // Start at saturated vapor rho1 = rhoV; T1 = TsatV; T2 = 1.1*TsatV; h1 = hsatV; do{ rho2 = density_Tp(T2,p,rho1); h2 = enthalpy_Trho(T2,rho2); T2 *= 1.1; } while (h2 <= h); // Linearly interpolate in each parameter to guess the solution T_guess = (T2-T1)/(h2-h1)*(h-h1)+T1; rho_guess = (rho2-rho1)/(h2-h1)*(h-h1)+rho1; // Reduced density delta = rho_guess/reduce.rho; if (get_debug_level() > 8){ std::cout << format("%s:%d: temperature_ph; it is vapor(anc), hsatV = %g\n",__FILE__,__LINE__, hsatV) ; } } else if (h < hsatL - hsat_tol) { T_guess = params.Ttriple+1; rho_guess = density_Tp(T_guess,p); h_guess = enthalpy_Trho(T_guess,rho_guess); // Update the guess with linear interpolation T_guess = (TsatL-T_guess)/(hsatL-h_guess)*(h-h_guess)+T_guess; // Solve for the density rho_guess = density_Tp(T_guess,p,rho_guess); delta = rho_guess/reduce.rho; if (get_debug_level() > 8){ std::cout << format("%s:%d: temperature_ph; it is liquid(anc), hsatL = %g\n",__FILE__,__LINE__, hsatL) ; } } } if (delta < 0) // No solution found using ancillary equations (or the saturation LUT is in use) - need to use saturation call (or LUT) { //************************************************** // Step 2: Not far away from saturation (or it is two-phase) - need to solve saturation as a function of p :( - this is slow //************************************************** CoolPropStateClassSI sat(name); sat.update(iP, p, iQ, 0); rhoL = sat.rhoL(); rhoV = sat.rhoV(); hsatL = sat.hL(); hsatV = sat.hV(); TsatL = sat.TL(); TsatV = sat.TV(); rhoLout = rhoL; rhoVout = rhoV; TsatLout = TsatL; TsatVout = TsatV; if (fabs((h-hsatL)/(hsatV-hsatL)) < 1e-8) { Tout = TsatL; rhoout = rhoLout; return; } else if (fabs((h-hsatL)/(hsatV-hsatL)-1) < 1e-8) { Tout = TsatV; rhoout = rhoVout; return; } else if (h > hsatV) { // Start at saturated vapor rho1 = rhoV; T1 = TsatV; T2 = 1.1*TsatV; h1 = hsatV; do{ rho2 = density_Tp(T2,p,rho1); h2 = enthalpy_Trho(T2,rho2); T2 *= 1.1; } while (h2 <= h); // Linearly interpolate in each parameter to guess the solution T_guess = (T2-T1)/(h2-h1)*(h-h1)+T1; rho_guess = (rho2-rho1)/(h2-h1)*(h-h1)+rho1; // Reduced density delta = rho_guess/reduce.rho; if (get_debug_level() > 8){ std::cout << format("%s:%d: temperature_ph; it is vapor, hsatV = %g\n",__FILE__,__LINE__, hsatV) ; } } else if (h<hsatL) { double rho_mid; T_guess = params.Ttriple; rho_guess = density_Tp(T_guess,p,rhoL); h_guess = enthalpy_Trho(T_guess,rho_guess); // Same thing at the midpoint temperature double Tmid = (T_guess + TsatL)/2.0; try{ rho_mid = density_Tp(Tmid, p, (rho_guess+rhoL)/2.0); if (!ValidNumber(rho_mid)){ rho_guess = (rhoLout-rho_guess)/(hsatL-h_guess)*(h-h_guess) + rho_guess; T_guess = (TsatL-T_guess)/(hsatL-h_guess)*(h-h_guess) + T_guess; } else { double h_mid = enthalpy_Trho(Tmid,rho_mid); // Quadratic interpolation T_guess = QuadInterp(h_guess, h_mid, hsatL, T_guess, Tmid, TsatL, h); rho_guess = QuadInterp(h_guess, h_mid, hsatL, rho_guess, rho_mid, rhoL, h); } } catch(std::exception &e) { T_guess = TsatL; rho_guess = rhoLout; } delta = rho_guess / reduce.rho; if (get_debug_level() > 8){ std::cout << format("%s:%d: temperature_ph; it is liquid, hsatL = %g, T = %g, rho = %g\n",__FILE__,__LINE__, hsatL, T_guess, rho_guess) ; } } else { // It is two-phase // Return the quality weighted values double quality = (h-hsatL)/(hsatV-hsatL); Tout = quality*TsatV+(1-quality)*TsatL; double v = quality*(1/rhoV)+(1-quality)*1/rhoL; rhoout = 1/v; if (get_debug_level() > 8){ std::cout << format("%s:%d: temperature_ph; it is 2phase,Q = %g\n",__FILE__,__LINE__, quality) ; } return; } } } } tau=reduce.T/T_guess; double Tc = reduce.T; double rhoc = reduce.rho; if (get_debug_level() > 8){ std::cout << format("%s:%d: temperature_ph guesses(p=%g,h=%g,tau=%g,delta=%g)\n",__FILE__,__LINE__, p, h, tau, delta) ; } // Now we enter into a Jacobian loop that attempts to simultaneously solve // for temperature and density using Newton-Raphson worst_error=999; iter=0; while (worst_error>1e-6 && failed == false) { // All the required partial derivatives da0_dtau = dphi0_dTau(tau,delta); d2a0_dtau2 = d2phi0_dTau2(tau,delta); d2a0_ddelta_dtau = 0.0; dar_dtau = dphir_dTau(tau,delta); dar_ddelta = dphir_dDelta(tau,delta); d2ar_ddelta_dtau = d2phir_dDelta_dTau(tau,delta); d2ar_ddelta2 = d2phir_dDelta2(tau,delta); d2ar_dtau2 = d2phir_dTau2(tau,delta); f1 = delta/tau*(1+delta*dar_ddelta)-p/(rhoc*R()*Tc); f2 = (1+delta*dar_ddelta)+tau*(da0_dtau+dar_dtau)-tau*h/(R()*Tc); df1_dtau = (1+delta*dar_ddelta)*(-delta/tau/tau)+delta/tau*(delta*d2ar_ddelta_dtau); df1_ddelta = (1.0/tau)*(1+2.0*delta*dar_ddelta+delta*delta*d2ar_ddelta2); df2_dtau = delta*d2ar_ddelta_dtau+da0_dtau+dar_dtau+tau*(d2a0_dtau2+d2ar_dtau2)-h/(R()*Tc); df2_ddelta = (dar_ddelta+delta*d2ar_ddelta2)+tau*(d2a0_ddelta_dtau+d2ar_ddelta_dtau); //First index is the row, second index is the column A[0][0]=df1_dtau; A[0][1]=df1_ddelta; A[1][0]=df2_dtau; A[1][1]=df2_ddelta; //double det = A[0][0]*A[1][1]-A[1][0]*A[0][1]; MatInv_2(A,B); tau -= omega*(B[0][0]*f1+B[0][1]*f2); delta -= omega*(B[1][0]*f1+B[1][1]*f2); if (fabs(f1)>fabs(f2)) worst_error=fabs(f1); else worst_error=fabs(f2); if (!ValidNumber(f1) || !ValidNumber(f2)) { throw SolutionError(format("Invalid values for inputs p=%g h=%g for fluid %s",p,h,(char*)name.c_str())); } iter+=1; if (iter>100) { throw SolutionError(format("Thp did not converge with inputs p=%g h=%g for fluid %s",p,h,(char*)name.c_str())); Tout = _HUGE; rhoout = _HUGE; } } //std::cout<<"Temperature_ph took "<<iter-1<<" steps\n"; Tout = reduce.T/tau; rhoout = delta*reduce.rho; } void Fluid::temperature_ps(double p, double s, double &Tout, double &rhoout, double &rhoLout, double &rhoVout, double &TsatLout, double &TsatVout) { int iter; double A[2][2], B[2][2],T_guess; double dar_ddelta,da0_dtau,d2a0_dtau2,dar_dtau,d2ar_ddelta_dtau,d2ar_ddelta2,d2ar_dtau2,d2a0_ddelta_dtau,a0,ar,da0_ddelta; double f1,f2,df1_dtau,df1_ddelta,df2_ddelta,df2_dtau; double rhoL, rhoV, ssatL,ssatV,TsatL,TsatV,tau,delta,worst_error; double s_guess, sc, rho_guess; double ssat_tol = 1; // It is supercritical pressure (or just below the critical pressure) if (p > 0.999*crit.p.Pa) { sc = entropy_Trho(crit.T+0.001,crit.rho); if (s > sc) { // Supercritical pseudo-gas - extrapolate to find guess temperature at critical density T_guess = crit.T+30; s_guess = entropy_Trho(T_guess,crit.rho); T_guess = (crit.T-T_guess)/(sc-s_guess)*(s-s_guess)+T_guess; // Solve for the density rho_guess = density_Tp(T_guess,p); delta = rho_guess/reduce.rho; } else { // Supercritical pseudo-liquid T_guess = params.Ttriple; rho_guess = density_Tp(T_guess,p); s_guess = entropy_Trho(T_guess,rho_guess); // Update the guess with linear interpolation T_guess = (crit.T-T_guess)/(sc-s_guess)*(s-s_guess)+T_guess; // Solve for the density rho_guess = density_Tp(T_guess,p,rho_guess); delta = rho_guess/reduce.rho; } } else { // Set to a negative value as a dummy value delta = -1; //************************************************** // Step 1: Try to just use the ancillary equations //************************************************** TsatL = Tsat_anc(p,0); if (pure()) TsatV = TsatL; else TsatV = Tsat_anc(p,1); rhoL = rhosatL(TsatL); rhoV = rhosatV(TsatV); ssatL = ssatL_anc(TsatL); ssatV = ssatV_anc(TsatV); rhoLout = -1; rhoVout = -1; TsatLout = -1; TsatVout = -1; if (s > ssatV + ssat_tol) { T_guess = TsatV+30; s_guess = entropy_Trho(T_guess,rhoV); T_guess = (TsatV-T_guess)/(ssatV-s_guess)*(s-s_guess)+T_guess; delta = p/(R()*T_guess)/reduce.rho; } else if (s < ssatL - ssat_tol) { T_guess = params.Ttriple; rho_guess = density_Tp(T_guess,p); s_guess = entropy_Trho(T_guess,rho_guess); // Update the guess with linear interpolation T_guess = (TsatL-T_guess)/(ssatL-s_guess)*(s-s_guess)+T_guess; // Solve for the density rho_guess = density_Tp(T_guess,p,rho_guess); delta = rho_guess/reduce.rho; } if (delta<0) // No solution found using ancillary equations - need to use saturation call { //************************************************** // Step 2: Not far away from saturation (or it is two-phase) - need to solve saturation as a function of p :( - this is slow //************************************************** CoolPropStateClassSI sat(name); sat.update(iP,p,iQ,0); rhoL = sat.rhoL(); rhoV = sat.rhoV(); ssatL = sat.sL(); ssatV = sat.sV(); TsatL = sat.TL(); TsatV = sat.TV(); rhoLout = rhoL; rhoVout = rhoV; TsatLout = TsatL; TsatVout = TsatV; if (fabs(s-ssatL) < 1e-4) { Tout = TsatL; rhoout = rhoLout; return; } else if (fabs(s-ssatV) < 1e-4) { Tout = TsatV; rhoout = rhoVout; return; } else if (s > ssatV) { T_guess = TsatV+30; s_guess = entropy_Trho(T_guess,rhoV); T_guess = (TsatV-T_guess)/(ssatV-s_guess)*(s-s_guess)+T_guess; delta = p/(R()*T_guess)/reduce.rho; } else if (s < ssatL) { T_guess = params.Ttriple; rho_guess = density_Tp(T_guess,p,rhoL); s_guess = entropy_Trho(T_guess,rho_guess); // Update the guess with linear interpolation T_guess = (TsatL-T_guess)/(ssatL-s_guess)*(s-s_guess)+T_guess; // Solve for the density rho_guess = density_Tp(T_guess,p,rho_guess); delta = rho_guess/reduce.rho; } else { // It is two-phase // Return the quality weighted values double quality = (s-ssatL)/(ssatV-ssatL); Tout = quality*TsatV+(1-quality)*TsatL; rhoout = 1/(quality/rhoV+(1-quality)/rhoL); return; } } } tau=reduce.T/T_guess; double Tc = reduce.T; double rhoc = reduce.rho; // Now we enter into a Jacobian loop that attempts to simultaneously solve // for temperature and density using Newton-Raphson worst_error=999; iter=0; while (worst_error>1e-6) { // All the required partial derivatives a0 = phi0(tau,delta); da0_dtau = dphi0_dTau(tau,delta); d2a0_dtau2 = d2phi0_dTau2(tau,delta); da0_ddelta = dphi0_dDelta(tau,delta); d2a0_ddelta_dtau = 0.0; ar = phir(tau,delta); dar_dtau = dphir_dTau(tau,delta); d2ar_dtau2 = d2phir_dTau2(tau,delta); dar_ddelta = dphir_dDelta(tau,delta); d2ar_ddelta2 = d2phir_dDelta2(tau,delta); d2ar_ddelta_dtau = d2phir_dDelta_dTau(tau,delta); // Residual and derivatives thereof for entropy f1 = tau*(da0_dtau+dar_dtau)-ar-a0-s/R(); df1_dtau = tau*(d2a0_dtau2 + d2ar_dtau2)+(da0_dtau+dar_dtau)-dar_dtau-da0_dtau; df1_ddelta = tau*(d2a0_ddelta_dtau+d2ar_ddelta_dtau)-dar_ddelta-da0_ddelta; // Residual and derivatives thereof for pressure f2 = delta/tau*(1+delta*dar_ddelta)-p/(rhoc*R()*Tc); df2_dtau = (1+delta*dar_ddelta)*(-delta/tau/tau)+delta/tau*(delta*d2ar_ddelta_dtau); df2_ddelta = (1.0/tau)*(1+2.0*delta*dar_ddelta+delta*delta*d2ar_ddelta2); //First index is the row, second index is the column A[0][0]=df1_dtau; A[0][1]=df1_ddelta; A[1][0]=df2_dtau; A[1][1]=df2_ddelta; MatInv_2(A,B); tau -= B[0][0]*f1+B[0][1]*f2; delta -= B[1][0]*f1+B[1][1]*f2; if (fabs(f1)>fabs(f2)) worst_error=fabs(f1); else worst_error=fabs(f2); iter+=1; if (iter>100) { throw SolutionError(format("Tsp did not converge with inputs p=%g s=%g for fluid %s",p,s,(char*)name.c_str())); Tout = _HUGE; rhoout = _HUGE; } } Tout = reduce.T/tau; rhoout = delta*reduce.rho; } /// This class is used to match the desired enthalpy/entropy /// pair by adjusting the saturation temperature until /// the enthalpy/entropy pair is satisfied. class HSSatFuncClass : public FuncWrapper1D { private: double h, s, r; Fluid * pFluid; public: double rho,pL,pV,rhoL,rhoV,hL,hV,sL,sV,Q; HSSatFuncClass(double h, double s, Fluid *pFluid){ this->h = h; this->s = s; this->pFluid = pFluid; }; double call(double T){ // Try to find a Tsat that yields the same quality when considering enthalpy and entropy pFluid->saturation_T(T, false, pL, pV, rhoL, rhoV); hL = pFluid->enthalpy_Trho(T,rhoL); hV = pFluid->enthalpy_Trho(T,rhoV); sL = pFluid->entropy_Trho(T,rhoL); sV = pFluid->entropy_Trho(T,rhoV); // Enthalpy from the linear h-s curve for the isotherm through the two-phase double h_s = (hV-hL)/(sV-sL)*(this->s-sL)+hL; Q = (h-hL)/(hV-hL); rho = 1/(Q/rhoV+(1-Q)/rhoL); return this->h-h_s; }; }; void Fluid::temperature_hs(double h, double s, double &Tout, double &rhoout, double &rhoLout, double &rhoVout, double &TsatLout, double &TsatVout) { bool singlephase_initialized = false; int iter; double A[2][2], B[2][2], T_guess; double dar_ddelta,da0_dtau,d2a0_dtau2,dar_dtau,d2ar_ddelta_dtau,d2ar_ddelta2,d2ar_dtau2,d2a0_ddelta_dtau,a0,ar,da0_ddelta; double f1,f2,df1_dtau,df1_ddelta,df2_ddelta,df2_dtau; double tau,delta,worst_error,rho_guess, ssat, htriple_s; double ssat_tol = 0.0001; std::string errstr; // The enthalpy at the triple point (or minimum) temperature corresponding to the entropy // Might not be in the two-phase region htriple_s = (HS.hV_Tmin-HS.hL_Tmin)/(HS.sV_Tmin-HS.sL_Tmin)*(s-HS.sL_Tmin)+HS.hL_Tmin; // It's a solid state - not allowed if (h < htriple_s) { throw ValueError(format("HS inputs are solid - not allowed h: %g s: %g",h,s).c_str()); } // If you are AT the critical point, yield the critical point data else if (fabs(h-crit.h) < 1e-6 && fabs(s-crit.s) < 1e-6) { Tout = crit.T; rhoout = crit.rho; rhoLout = crit.rho; rhoVout = crit.rho; TsatLout = crit.T; TsatVout = crit.T; return; } // If above the maximum enthalpy, no need to do any saturation calls, just determine // your state using interval bisection on the pressure using the p-h code (slow) else if (h > HS.hmax) { int iter = 0; double logpL, logpR, logpM, TM,rhoM,dummy, sM; logpL = log(1e-10); logpR = log(100*crit.p.Pa); do { logpM = (logpL + logpR)/2; temperature_ph(exp(logpM),h,TM,rhoM,dummy,dummy,dummy,dummy); sM = entropy_Trho(TM,rhoM); if (sM < s) {logpR = logpM;} // Keep the left half of the domain else {logpL = logpM;}// Keep the right half of the domain iter += 1; } while (iter < 10); rho_guess = rhoM; T_guess = TM; singlephase_initialized = true; } // Branch #1 (liquid curve) if (h < HS.hV_Tmin && h < crit.h && !singlephase_initialized) { double Tsat,rhosat,TL,TV,rhoL,rhoV; // Get the saturated liquid state for the given enthalpy this->saturation_h(h, limits.Tmin, crit.T, 0, Tsat, rhosat, TL, TV, rhoL, rhoV); // Check the saturated entropy for the given value of the entropy ssat = this->entropy_Trho(Tsat, rhosat); if (fabs(s - ssat) < ssat_tol) // It's saturated liquid { Tout = Tsat; rhoout = rhoL; rhoLout = rhoL; rhoVout = rhoV; TsatLout = TL; TsatVout = TV; return; } // If entropy greater than ssat, two-phase solution // (or it solid which is handled above) else if (s > ssat) { // First check for two-phase HSSatFuncClass SatFunc(h, s, this); try{ Tout = Secant(&SatFunc,limits.Tmin,1,1e-8,100,&errstr); if (SatFunc.Q > 1+1e-8 || SatFunc.Q < 0-1e-8){ throw ValueError("Solution must be within the two-phase region"); } // It is two-phase, we are done, no exceptions were raised } catch(std::exception &) { // Split the range into two pieces try { Tout = Brent(&SatFunc, limits.Tmin, crit.T-1e-4, 1e-16, 1e-8, 100, &errstr); if (SatFunc.Q > 1+1e-8 || SatFunc.Q < 0-1e-8){ throw ValueError("Solution must be within the two-phase region"); } } catch(std::exception) { try { Tout = Brent(&SatFunc, (limits.Tmin+crit.T)/2.0, crit.T-1e-4, 1e-16, 1e-8, 100, &errstr); if (SatFunc.Q > 1+1e-8 || SatFunc.Q < 0-1e-8){ throw ValueError("Solution must be within the two-phase region"); } } catch (std::exception) { try{ Tout = Brent(&SatFunc, limits.Tmin, (limits.Tmin+crit.T)/2.0, 1e-16, 1e-8, 100, &errstr); if (SatFunc.Q > 1+1e-8 || SatFunc.Q < 0-1e-8){ throw ValueError("Solution must be within the two-phase region"); } } catch (std::exception) { throw ValueError(format("For HS:Branch1, twophase failed").c_str()); } } } } rhoout = SatFunc.rho; rhoLout = SatFunc.rhoL; rhoVout = SatFunc.rhoV; TsatLout = Tout; TsatVout = Tout; return; } else // It's subcooled liquid { int iter = 0; double logpL, logpR, logpM,TM,rhoM,dummy, sM; logpL = log(pressure_Trho(Tsat,rhosat)); logpR = log(10*crit.p.Pa); do { logpM = (logpL + logpR)/2; temperature_ph(exp(logpM),h,TM,rhoM,dummy,dummy,dummy,dummy); sM = entropy_Trho(TM,rhoM); if (sM < s) {logpR = logpM;} // Keep the left half of the domain else {logpL = logpM;}// Keep the right half of the domain iter += 1; } while (iter < 10); rho_guess = rhoM; T_guess = TM; singlephase_initialized = true; } } // Branch #2 (vapor curve) between hmax and the maximum of the enthalpy corresponding to the // critical point and the enthalpy corresponding to the // saturated vapor at the minimum temperature if ((h > HS.hV_Tmin && h > crit.h) && !singlephase_initialized) { double Tsat,rhosat,TL,TV,rhoL,rhoV; // Get the saturated vapor state for the given enthalpy this->saturation_h(h, limits.Tmin, HS.T_hmax, 1, Tsat, rhosat, TL, TV, rhoL, rhoV); // Get the saturated vapor entropy for the given value of the enthalpy ssat = this->entropy_Trho(Tsat, rhosat); if (fabs(s-ssat) < ssat_tol) // It's saturated vapor { Tout = Tsat; rhoout = rhoV; rhoLout = rhoL; rhoVout = rhoV; TsatLout = TL; TsatVout = TV; return; } else if (s > ssat) // It's superheated vapor { int iter = 0; double logpL, logpR, logpM, TM,rhoM,dummy,sM; logpL = log(1e-10); logpR = log(pressure_Trho(Tsat,rhosat)); do { logpM = (logpL + logpR)/2; temperature_ph(exp(logpM),h,TM,rhoM,dummy,dummy,dummy,dummy); sM = entropy_Trho(TM,rhoM); if (sM < s) {logpR = logpM;} // Keep the left half of the domain else {logpL = logpM;}// Keep the right half of the domain iter += 1; } while (iter < 10); rho_guess = rhoM; T_guess = TM; singlephase_initialized = true; } else { HSSatFuncClass SatFunc(h,s,this); Tout = Secant(&SatFunc,limits.Tmin,0.4*(crit.T-limits.Tmin),1e-8,100,&errstr); // It is two-phase, we are done, no exceptions were raised rhoout = SatFunc.rho; rhoLout = SatFunc.rhoL; rhoVout = SatFunc.rhoV; TsatLout = Tout; TsatVout = Tout; return; } } // Branch #3 (vapor curve) for enthalpy between critical enthalpy and maximum saturated enthalpy if (h > crit.h && !singlephase_initialized) // By the above conditional the enthalpy is below max { double Tsat,rhosat,TL,TV,rhoL,rhoV; // Get the saturated vapor state for the given enthalpy this->saturation_h(h, HS.T_hmax, crit.T, 1, Tsat, rhosat, TL, TV, rhoL, rhoV); // Check the saturated entropy for the given value of the enthalpy ssat = this->entropy_Trho(Tsat, rhosat); if (fabs(s - ssat) < ssat_tol) // It's saturated vapor { Tout = Tsat; rhoout = rhoV; rhoLout = rhoL; rhoVout = rhoV; TsatLout = TL; TsatVout = TV; return; } else if (s < ssat)// It's subcooled liquid { int iter = 0; double logpL, logpR, logpM,TM,rhoM,dummy, sM; logpL = log(pressure_Trho(Tsat,rhosat)); logpR = log(10*crit.p.Pa); do { logpM = (logpL + logpR)/2; temperature_ph(exp(logpM),h,TM,rhoM,dummy,dummy,dummy,dummy); sM = entropy_Trho(TM,rhoM); if (sM < s) {logpR = logpM;} // Keep the left half of the domain else {logpL = logpM;}// Keep the right half of the domain iter += 1; } while (iter < 10); rho_guess = rhoM; T_guess = TM; singlephase_initialized = true; } // If entropy greater than ssat, two-phase solution else { HSSatFuncClass SatFunc(h,s,this); Tout = Secant(&SatFunc,limits.Tmin,0.4*(crit.T-limits.Tmin),1e-8,100,&errstr); // It is two-phase, we are done, no exceptions were raised rhoout = SatFunc.rho; rhoLout = SatFunc.rhoL; rhoVout = SatFunc.rhoV; TsatLout = Tout; TsatVout = Tout; return; } } // Branch #4 (liquid curve) for enthalpy between critical enthalpy and minimum of enthalpy corresponding to the // critical point and the enthalpy corresponding to the // saturated vapor at the minimum temperature // (This branch might not exist) else if (crit.h > HS.hV_Tmin && !singlephase_initialized) { double Tsat,rhosat,TL,TV,rhoL,rhoV; // Get the saturated liquid state for the given enthalpy this->saturation_h(h, limits.Tmin, crit.T, 0, Tsat, rhosat, TL, TV, rhoL, rhoV); //double hcheck = this->enthalpy_Trho(TL,rhoL); // Check the saturated entropy for the given value of the entropy ssat = this->entropy_Trho(Tsat, rhosat); if (fabs(s - ssat) < ssat_tol) // It's saturated liquid { Tout = Tsat; rhoout = rhoL; rhoLout = rhoL; rhoVout = rhoV; TsatLout = TL; TsatVout = TV; return; } else if (s < ssat) // It's subcooled liquid { int iter = 0; double logpL, logpR, logpM,TM,rhoM,dummy, sM; logpL = log(pressure_Trho(Tsat,rhosat)); logpR = log(10*crit.p.Pa); do { logpM = (logpL + logpR)/2; temperature_ph(exp(logpM),h,TM,rhoM,dummy,dummy,dummy,dummy); sM = entropy_Trho(TM,rhoM); if (sM < s) {logpR = logpM;} // Keep the left half of the domain else {logpL = logpM;}// Keep the right half of the domain iter += 1; } while (iter < 10); rho_guess = rhoM; T_guess = TM; singlephase_initialized = true; } else { HSSatFuncClass SatFunc(h,s,this); Tout = Secant(&SatFunc,limits.Tmin,0.4*(crit.T-limits.Tmin),1e-8,100,&errstr); // It is two-phase, we are done, no exceptions were raised rhoout = SatFunc.rho; rhoLout = SatFunc.rhoL; rhoVout = SatFunc.rhoV; TsatLout = Tout; TsatVout = Tout; return; } } //// Two-phase solutions not handled in branch #1 that are not saturated //if (!singlephase_initialized && TsatL_initialized && TsatV_initialized) //{ // // First check for two-phase // HSSatFuncClass SatFunc(h,s,this); // try{ // *Tout = Brent(&SatFunc, TsatL_candidate, TsatV_candidate, 1e-16, 1e-8, 100, &errstr); // if (SatFunc.Q > 1+1e-8 || SatFunc.Q < 0-1e-8){ // throw ValueError("Solution must be within the two-phase region"); // } // // It is two-phase, we are done, no exceptions were raised // *rhoout = SatFunc.rho; *rhoLout = SatFunc.rhoL; *rhoVout = SatFunc.rhoV; *TsatLout = *Tout; *TsatVout = *Tout; // return; // } // catch(std::exception){ // throw ValueError(format("HS:2phase failed").c_str()); // } //} if (!singlephase_initialized) { throw ValueError(format("HS:1phase, but not initialized").c_str()); } //HSSatFuncClass SatFunc(h,s,this); // Evaluate the function at the minimum temperature which is // usually the triple point temperature //double Ttriple_func = SatFunc.call(limits.Tmin); /*FILE *fp = fopen("rr.txt","w"); for (double T = limits.Tmin; T < 300; T += 1) { double f = SatFunc.call(T); fprintf(fp, "%g %g %g\n",T,f,SatFunc.Q); } fclose(fp);*/ // If using the minimum temperature yields the h/s pair, quit /*if (fabs(Ttriple_func)<DBL_EPSILON*10) { *Tout = limits.Tmin; *rhoout = SatFunc.rho; *rhoLout = SatFunc.rhoL; *rhoVout = SatFunc.rhoV; *TsatLout = *Tout; *TsatVout = *Tout; return; } else if (Ttriple_func < 0){throw ValueError(format("Value for h,s [%g,%g] is solid",h,s));}*/ //try{ // //*Tout = Brent(&SatFunc,limits.Tmin,reduce.T-100,1e-16,1e-8,100,&errstr); // *Tout = Secant(&SatFunc,limits.Tmin,1,1e-8,100,&errstr); // if (SatFunc.Q >1 || SatFunc.Q < 0){ throw ValueError("Solution must be within the two-phase region"); } // // It is two-phase, we are done, no exceptions were raised // *rhoout = SatFunc.rho; // *rhoLout = SatFunc.rhoL; // *rhoVout = SatFunc.rhoV; // *TsatLout = *Tout; // *TsatVout = *Tout; // return; //} //catch(ValueError) //{ // double Tsat, rhosat, cp, hsat; // // It is single-phase, either liquid, gas, or supercritical, but we don't know which yet // try{ // if (s < crit.s){ this->saturation_s(s, 0, &Tsat, &rhosat); } // else{ this->saturation_s(s, 1, &Tsat, &rhosat); } // // Check the saturated enthalpy for the given value of the entropy // hsat = this->enthalpy_Trho(Tsat, rhosat); // cp = this->specific_heat_p_Trho(Tsat, rhosat); // if (cp > 10) cp = 10; // Near critical point cp goes to infinity, clip it // T_guess = Tsat + (h-hsat)/cp; // rho_guess = rhosat; // } // catch(ValueError) // { // double cp0 = specific_heat_p_ideal_Trho(reduce.T); // T_guess = 298; // rho_guess = 0.001; // } //} tau = reduce.T/T_guess; delta = rho_guess/reduce.rho; //// Now we enter into a loop that attempts to simultaneously solve //// for temperature and density using Newton-Raphson worst_error=999; iter=0; while (worst_error>1e-6) { // All the required partial derivatives a0 = phi0(tau,delta); da0_dtau = dphi0_dTau(tau,delta); d2a0_dtau2 = d2phi0_dTau2(tau,delta); da0_ddelta = dphi0_dDelta(tau,delta); d2a0_ddelta_dtau = 0.0; ar = phir(tau,delta); dar_dtau = dphir_dTau(tau,delta); d2ar_dtau2 = d2phir_dTau2(tau,delta); dar_ddelta = dphir_dDelta(tau,delta); d2ar_ddelta2 = d2phir_dDelta2(tau,delta); d2ar_ddelta_dtau = d2phir_dDelta_dTau(tau,delta); // Residual and derivatives thereof for entropy f1 = tau*(da0_dtau+dar_dtau)-ar-a0-s/R(); df1_dtau = tau*(d2a0_dtau2 + d2ar_dtau2)+(da0_dtau+dar_dtau)-dar_dtau-da0_dtau; df1_ddelta = tau*(d2a0_ddelta_dtau+d2ar_ddelta_dtau)-dar_ddelta-da0_ddelta; // Residual and derivatives thereof for enthalpy f2 = (1+delta*dar_ddelta)+tau*(da0_dtau+dar_dtau)-tau*h/(R()*reduce.T); df2_dtau = delta*d2ar_ddelta_dtau+da0_dtau+dar_dtau+tau*(d2a0_dtau2+d2ar_dtau2)-h/(R()*reduce.T); df2_ddelta = (dar_ddelta+delta*d2ar_ddelta2)+tau*(d2a0_ddelta_dtau+d2ar_ddelta_dtau); //First index is the row, second index is the column A[0][0]=df1_dtau; A[0][1]=df1_ddelta; A[1][0]=df2_dtau; A[1][1]=df2_ddelta; MatInv_2(A,B); tau -= B[0][0]*f1+B[0][1]*f2; delta -= B[1][0]*f1+B[1][1]*f2; if (fabs(f1)>fabs(f2)) worst_error=fabs(f1); else worst_error=fabs(f2); iter += 1; if (iter>100) { throw SolutionError(format("Ths did not converge with inputs h=%g s=%g for fluid %s",h,s,(char*)name.c_str())); Tout = _HUGE; rhoout = _HUGE; } } Tout = reduce.T/tau; rhoout = delta*reduce.rho; } void Fluid::density_Ts(double T, double s, double &rhoout, double &pout, double &rhoLout, double &rhoVout, double &psatLout, double &psatVout) { double rho_guess, ssatL, ssatV; bool _SinglePhase; // Density is solved from entropy_Trho method for single phase and from // saturation information for two-phase. First get the phase. if (T >= crit.T) { _SinglePhase = true; rho_guess = crit.p.Pa/R()/T; } else { // T < crit.T // First try to define the phase with the ancillary equations, if we are // far enough away from saturation. ssatL = ssatL_anc(T); ssatV = ssatV_anc(T); if (s < ssatL - 0.05*abs(ssatL)) { // liquid _SinglePhase = true; rho_guess = rhosatL(T); } else if (s > ssatV + 0.05*abs(ssatV)) { // superheated vapor _SinglePhase = true; rho_guess = params.ptriple/R()/T; } else { // Actually have to use saturation information sadly // For the given temperature, find the saturation state // Run the saturation routines to determine the saturation densities and pressures saturation_T(T, enabled_TTSE_LUT, psatLout, psatVout, rhoLout, rhoVout); ssatL = entropy_Trho(T, rhoLout); ssatV = entropy_Trho(T, rhoVout); double Q = (s-ssatL)/(ssatV-ssatL); if (Q < -100*DBL_EPSILON) { // liquid _SinglePhase = true; rho_guess = rhosatL(T); } else if (Q > 1+100*DBL_EPSILON) { // superheated vapor _SinglePhase = true; rho_guess = params.ptriple/R()/T; } else { // two-phase // Return the quality weighted values _SinglePhase = false; rhoout = 1/(Q/rhoVout +(1-Q)/rhoLout); pout = Q* psatVout +(1-Q)*psatLout; return; } } } // Function class for iterative solution of entropy_Trho for rho class rhoFuncClass : public FuncWrapper1D { private: double T, s; Fluid *pFluid; public: rhoFuncClass(double T, double s, Fluid *pFluid) { this->T = T; this->s = s; this->pFluid = pFluid; }; double call(double rho) { return pFluid->entropy_Trho(T, rho) - s; }; }; // Calculate density and pressure for single phase states if (_SinglePhase == true) { rhoFuncClass rhoFunc(T, s, this); std::string errstr; rhoout = BoundedSecant(&rhoFunc, rho_guess, 0.0, 1e10, 0.1*rho_guess, 1e-8, 100, &errstr); pout = pressure_Trho(T, rhoout); } } double Fluid::Tsat_anc(double p, double Q) { // This one only uses the ancillary equations double Tc,Tmax,Tmin,Tmid; Tc=reduce.T; Tmax=Tc; Tmin=limits.Tmin; Tmid = (Tmax+Tmin)/2.0; double tau_max = Tc/Tmin; double tau_min = Tc/Tmax; class SatFuncClass : public FuncWrapper1D { private: double p,Q,Tc; std::string name; Fluid * pFluid; public: SatFuncClass(double p_, double Q_, double Tc_, std::string name_,Fluid *_pFluid){ p=p_;Q=Q_;Tc=Tc_,name=name_,pFluid = _pFluid; }; double call(double tau){ if (fabs(Q-1)<10*DBL_EPSILON) return log(pFluid->psatV_anc(Tc/tau)/p); else if (fabs(Q)<10*DBL_EPSILON) return log(pFluid->psatL_anc(Tc/tau)/p); else throw ValueError("Quality must be 1 or 0"); }; } SatFunc(p,Q,reduce.T,name,this); // Use Brent's method to find tau = Tc/T std::string errstr; try { double tau = Brent(&SatFunc,tau_min,tau_max,1e-10,1e-8,50,&errstr); if (errstr.size()>0) throw SolutionError("Saturation calculation failed"); return reduce.T/tau; } catch(std::exception &) { // At very low pressures the above solver will sometimes fail due to // the uncertainty of the ancillary pressure equation at low temperature (pressure) // Here we just do a quadratic interpolation double logp_min, logp_mid, logp_max; double Tmid = (Tmax+Tmin)/2.0; double tau_mid = Tc/Tmid; if (fabs(Q-1)<1e-10) { // reduced pressures logp_min = log(psatV_anc(Tmin)); logp_mid = log(psatV_anc(Tmid)); logp_max = log(psatV_anc(Tmax)); } else if (fabs(Q)<1e-10) { logp_min = log(psatL_anc(Tmin)); logp_mid = log(psatL_anc(Tmid)); logp_max = log(psatL_anc(Tmax)); } else { throw ValueError(format("Quality [%g] must be either 1 or 0",Q)); } // plotting tc/t versus log(p) tends to give very close to straight line // use this fact find t more easily using reverse quadratic interpolation double tau_interp = QuadInterp(logp_min,logp_mid,logp_max,tau_max,tau_mid,tau_min,log(p)); //std::cout << "tsat_anc" << psatV_anc(reduce.T/tau_interp) << '\n'; return reduce.T/tau_interp; } throw ValueError("Something went wrong"); return -_HUGE; } /// A wrapper class to do the calculations to get densities and saturation temperature /// as a function of pressure for pure fluids /// This class has been deprecated as it is in general 4 times slower than the method below that is based on the secant solver class SaturationFunctionOfPressureResids : public FuncWrapperND { private: double arL, arV, dar_ddeltaL, dar_ddeltaV, d2ar_ddelta2L, d2ar_ddelta2V, d2ar_ddelta_dtauL, d2ar_ddelta_dtauV; double dar_dtauL,dar_dtauV; double p,R,rhoc,Tc,deltaL,deltaV,tau; Fluid *pFluid; public: SaturationFunctionOfPressureResids(Fluid *pFluid, double p, double R, double rhoc, double Tc){ this->pFluid = pFluid; this->p = p; this->R = R; this->rhoc = rhoc; this->Tc = Tc; }; ~SaturationFunctionOfPressureResids(){}; void calculate_parameters(double deltaV, double deltaL, double tau) { arL = pFluid->phir(tau,deltaL); arV = pFluid->phir(tau,deltaV); dar_ddeltaL = pFluid->dphir_dDelta(tau,deltaL); dar_ddeltaV = pFluid->dphir_dDelta(tau,deltaV); dar_dtauL = pFluid->dphir_dTau(tau,deltaL); dar_dtauV = pFluid->dphir_dTau(tau,deltaV); d2ar_ddelta2L = pFluid->d2phir_dDelta2(tau,deltaL); d2ar_ddelta2V = pFluid->d2phir_dDelta2(tau,deltaV); d2ar_ddelta_dtauL = pFluid->d2phir_dDelta_dTau(tau,deltaL); d2ar_ddelta_dtauV = pFluid->d2phir_dDelta_dTau(tau,deltaV); } double J(char Q) { if (Q=='L') return deltaL*(1+deltaL*dar_ddeltaL); else return deltaV*(1+deltaV*dar_ddeltaV); } double J_delta(char Q) { if (Q=='L') return 1+2*deltaL*dar_ddeltaL+deltaL*deltaL*d2ar_ddelta2L; else return 1+2*deltaV*dar_ddeltaV+deltaV*deltaV*d2ar_ddelta2V; } double J_tau(char Q) { if (Q=='L') return deltaL*deltaL*d2ar_ddelta_dtauL; else return deltaV*deltaV*d2ar_ddelta_dtauV; } double K(char Q) { if (Q=='L') return deltaL*dar_ddeltaL+arL+log(deltaL); else return deltaV*dar_ddeltaV+arV+log(deltaV); } double K_delta(char Q) { if (Q=='L') return 2*dar_ddeltaL+deltaL*d2ar_ddelta2L+1/deltaL; else return 2*dar_ddeltaV+deltaV*d2ar_ddelta2V+1/deltaV; } double K_tau(char Q) { if (Q=='L') return deltaL*d2ar_ddelta_dtauL+dar_dtauL; else return deltaV*d2ar_ddelta_dtauV+dar_dtauV; } std::vector<double> call(std::vector<double> x) { deltaV = x[0]; deltaL = x[1]; tau = x[2]; // Calculate all the parameters that are needed for the derivatives calculate_parameters(deltaV,deltaL,tau); std::vector<double> out = std::vector<double>(3,0); out[0]=J('V')-J('L'); out[1]=K('V')-K('L'); out[2]=1+deltaV*dar_ddeltaV-p*tau/(R*Tc*deltaV*rhoc); return out; } std::vector<std::vector<double> > Jacobian(std::vector<double> x) { deltaV = x[0]; deltaL = x[1]; tau = x[2]; std::vector<std::vector<double> > out; out.resize(x.size(),std::vector<double>(x.size(),0)); out[0][0] = J_delta('V'); out[0][1] = -J_delta('L'); out[0][2] = J_tau('V')-J_tau('L'); out[1][0] = K_delta('V'); out[1][1] = -K_delta('L'); out[1][2] = K_tau('V')-K_tau('L'); out[2][0] = deltaV*d2ar_ddelta2V+dar_ddeltaV+p*tau/(R*Tc*deltaV*deltaV*rhoc); out[2][1] = 0; out[2][2] = deltaV*d2ar_ddelta_dtauV-p/(R*Tc*deltaV*rhoc); return out; } }; class SaturationPressureGivenResids : public FuncWrapper1D { private: double p; Fluid *pFluid; public: double rhoL, rhoV, resid; SaturationPressureGivenResids(Fluid *pFluid, double p) : pFluid(pFluid), p(p) {}; ~SaturationPressureGivenResids(){}; double call(double T) { rhoL = pFluid->density_Tp(T,p,rhoL); rhoV = pFluid->density_Tp(T,p,rhoV); resid = pFluid->gibbs_Trho(T,rhoL)-pFluid->gibbs_Trho(T,rhoV); return resid; } }; class Saturation_p_IterateSaturationT_Resids : public FuncWrapper1D { private: double p; Fluid *pFluid; public: double rhoL, rhoV, resid; Saturation_p_IterateSaturationT_Resids(Fluid *pFluid, double p) : pFluid(pFluid), p(p) {}; ~Saturation_p_IterateSaturationT_Resids(){}; double call(double T) { double psatL,psatV; pFluid->saturation_T(T,pFluid->enabled_TTSE_LUT,psatL,psatV,rhoL,rhoV); resid = psatL-this->p; return resid; } }; void Fluid::saturation_p(double p, bool UseLUT, double &TsatL, double &TsatV, double &rhoLout, double &rhoVout) { double Tsat,rhoL,rhoV; // Pseudo-critical pressure based on critical density and temperature // The highest pressure that be achieved with a temperature <= Tc // For some EOS, pc != p(Tc,rhoc) double pc_EOS = pressure_Trho(reduce.T,reduce.rho); if (fabs(p-reduce.p.Pa)<DBL_EPSILON || p > pc_EOS) { TsatL = reduce.T; TsatV = reduce.T; rhoLout = reduce.rho; rhoVout = reduce.rho; return; } if (get_debug_level()>5){ std::cout<<format("%s:%d: Fluid::saturation_p(%g,%d) \n",__FILE__,__LINE__,p,UseLUT).c_str(); } if (isPure==true) { if (UseLUT) { throw NotImplementedError(); } else { //// Use Secant method to find T that gives the same gibbs function in both phases - a la REFPROP SATP function std::string errstr; SaturationPressureGivenResids SPGR = SaturationPressureGivenResids(this,p); Tsat = Tsat_anc(p,0); rhoL = rhosatL(Tsat); rhoV = rhosatV(Tsat); SPGR.rhoL = rhoL; SPGR.rhoV = rhoV; try{ //Tsat = Secant(&SPGR,Tsat,1e-2*Tsat,1e-8,50,&errstr); Tsat = Secant(&SPGR,Tsat,1e-4,1e-10,50,&errstr); if (errstr.size()>0 || !ValidNumber(Tsat)|| !ValidNumber(SPGR.rhoV)|| !ValidNumber(SPGR.rhoL)) throw SolutionError("Saturation calculation failed"); rhoVout = SPGR.rhoV; rhoLout = SPGR.rhoL; TsatL = Tsat; TsatV = Tsat; return; } catch(std::exception &) // Whoops that failed... { errstr.clear(); // Now try to get Tsat by using Brent's method on saturation_T calls Saturation_p_IterateSaturationT_Resids SPISTR = Saturation_p_IterateSaturationT_Resids(this,p); Tsat = Tsat_anc(p,0); if (Tsat >= crit.T){ Tsat = crit.T-0.0000001; } rhoL = rhosatL(Tsat); rhoV = rhosatV(Tsat); SPGR.rhoL = rhoL; SPGR.rhoV = rhoV; double Tmin = Tsat-3; if (Tmin < limits.Tmin){ Tmin = limits.Tmin; } Tsat = Brent(&SPISTR,Tmin,reduce.T,DBL_EPSILON,1e-10,30,&errstr); if (errstr.size()>0 || !ValidNumber(Tsat)|| !ValidNumber(SPGR.rhoV)|| !ValidNumber(SPGR.rhoL)) throw SolutionError("Saturation calculation yielded invalid number using Brent's method"); rhoVout = SPGR.rhoV; rhoLout = SPGR.rhoL; TsatL = Tsat; TsatV = Tsat; return; } } } else { // Pseudo-pure fluid TsatL = Tsat_anc(p,0); TsatV = Tsat_anc(p,1); rhoLout = rhosatL(TsatL); rhoVout = rhosatV(TsatV); return; } /*SaturationFunctionOfPressureResids SFPR = SaturationFunctionOfPressureResids(this,p,params.R_u/params.molemass,reduce.rho,reduce.T); Eigen::Vector3d x0_initial, x; Tsat = Tsat_anc(p,0); rhoL = rhosatL(Tsat); rhoV = rhosatV(Tsat); x0_initial << rhoV/reduce.rho, rhoL/reduce.rho, reduce.T/Tsat; std::string errstring; x=NDNewtonRaphson_Jacobian(&SFPR,x0_initial,1e-7,30,&errstring); *rhoVout = reduce.rho*x(0); *rhoLout = reduce.rho*x(1); *Tout = reduce.T/x(2); if (errstring.size()>0 && !ValidNumber(Tsat)) throw SolutionError("Saturation calculation failed"); return;*/ } double Fluid::Tsat(double p, double Q, double T_guess) { double rhoLout,rhoVout; return Tsat(p, Q, T_guess, false, rhoLout, rhoVout); } double Fluid::Tsat(double p, double Q, double T_guess, bool UseLUT, double &rhoLout, double &rhoVout) { if (isPure && !UseLUT) { double TL,TV; saturation_p(p,UseLUT,TL,TV,rhoLout,rhoVout); return TL; } else { double Tc,Tmax,Tmin; Tc=crit.T; Tmax=Tc-0.001; Tmin=params.Ttriple+1; if (Tmin <= limits.Tmin) Tmin = limits.Tmin; // Plotting Tc/T versus log(p) tends to give very close to straight line // Use this fact find T more easily class SatFuncClass : public FuncWrapper1D { private: double p,Q,Tc; std::string name; Fluid * pFluid; public: SatFuncClass(double p_, double Q_, double Tc_, std::string name, Fluid * pFluid){ p=p_;Q=Q_;Tc=Tc_,this->name=name,this->pFluid = pFluid; }; double call(double tau){ if (fabs(Q)<10*DBL_EPSILON) { return log(pFluid->psatL(Tc/tau)/p); } else if (fabs(Q-1)<10*DBL_EPSILON) { return log(pFluid->psatV(Tc/tau)/p); } else { throw ValueError(format("Must be either saturated liquid or vapor")); } }; } SatFunc(p,Q,reduce.T,name,this); double tau_max = Tc/Tmin; double tau_min = Tc/Tmax; // Use Brent's method to find tau = Tc/T std::string errstr; double tau = Brent(&SatFunc,tau_min,tau_max,1e-10,1e-10,50,&errstr); if (errstr.size()>0) throw SolutionError("Saturation calculation failed"); if (!isPure) { rhoLout = rhosatL(reduce.T/tau); rhoVout = rhosatV(reduce.T/tau); } return reduce.T/tau; } } double Fluid::R() { return params.R_u*1000.0/params.molemass; } double Fluid::viscosity_dilute(double T, double e_k, double sigma) { // T in [K], e_k in [K], sigma in [nm] // viscosity returned is in [Pa-s] /* Model for the Viscosity and Thermal Conductivity of Refrigerants, Including a New Correlation for the Viscosity of R134a, Marcia L. Huber, Arno Laesecke, and Richard A. Perkins Ind. Eng. Chem. Res. 2003, 42, 3163-3178 */ double eta_star, Tstar, OMEGA_2_2; Tstar = T/e_k; // From Neufeld, 1972, Journal of Chemical Physics - checked coefficients OMEGA_2_2 = 1.16145*pow(Tstar,-0.14874)+ 0.52487*exp(-0.77320*Tstar)+2.16178*exp(-2.43787*Tstar); // Using the leading constant from McLinden, 2000 since the leading term from Huber 2003 gives crazy values eta_star = 26.692e-3*sqrt(params.molemass*T)/(pow(sigma,2)*OMEGA_2_2)/1e6; return eta_star; } double Fluid::conductivity_critical(double T, double rho, double qd, double GAMMA, double zeta0) { // Olchowy and Sengers cross-over term double k=1.3806488e-23, //[J/K] R0=1.03, gamma=1.239, nu=0.63, Pcrit = reduce.p.Pa, //[Pa] Tref = 1.5*reduce.T, //[K] cp,cv,delta,num,zeta,mu, OMEGA_tilde,OMEGA_tilde0,pi=M_PI,tau; delta = rho/reduce.rho; tau = reduce.T/T; double dp_drho=R()*T*(1+2*delta*dphir_dDelta(tau,delta)+delta*delta*d2phir_dDelta2(tau,delta)); double X = Pcrit/pow(reduce.rho,2)*rho/dp_drho; tau = reduce.T/Tref; double dp_drho_ref=R()*Tref*(1+2*delta*dphir_dDelta(tau,delta)+delta*delta*d2phir_dDelta2(tau,delta)); double Xref = Pcrit/pow(reduce.rho,2)*rho/dp_drho_ref*Tref/T; num=X-Xref; // no critical enhancement if numerator is negative if (num<0) return 0.0; else zeta=zeta0*pow(num/GAMMA,nu/gamma); //[m] cp = specific_heat_p_Trho(T,rho); //[J/kg/K] cv = specific_heat_v_Trho(T,rho); //[J/kg/K] mu = viscosity_Trho(T,rho)*1e6; //[uPa-s] OMEGA_tilde=2.0/pi*((cp-cv)/cp*atan(zeta*qd)+cv/cp*(zeta*qd)); //[-] OMEGA_tilde0=2.0/pi*(1.0-exp(-1.0/(1.0/(qd*zeta)+1.0/3.0*(zeta*qd)*(zeta*qd)/delta/delta))); //[-] double lambda=rho*cp*1e6*(R0*k*T)/(6*pi*mu*zeta)*(OMEGA_tilde-OMEGA_tilde0); //[W/m/K] return lambda; //[W/m/K] } double Fluid::surface_tension_T(double T) { /* Implements the method of Miqeu et al., "An extended scaled equation for the temperature dependence of the surface tension of pure compounds inferred from an analysis of experimental data",Fluid Phase Equilibria 172 (2000) 169–182 This correlation is used as the default, in the absence of other correlation, which can be provided for fluids if desired sigma in [mN/m]-->[N/m] */ double N_A = 6.02214129e23, //[-] CODATA 2010 k = 1.3806488e-23, //[J/K] CODATA 2010 w = params.accentricfactor, //[-] Vc, //[cm^3/mol] Tc, //[K] t, //[K] sigma; //[mN/m] Tc=reduce.T; t=1-T/Tc; //[m3/kg]*[kg/kmol]*[0.001 kmol/mol] --> [m3/mol] Vc = 1/reduce.rho*params.molemass/1000; // N_A has units of 1/mol, Vc has units of m3/mol , (1/m3)^(2/3)->1/m^2 // k has units of J/K // Tc has units of K // k*Tc has units of J, or N-m sigma = k*Tc*pow(N_A/Vc,2.0/3.0)*(4.35+4.14*w)*pow(t,1.26)*(1+0.19*sqrt(t)-0.25*t); return sigma; } void Fluid::ECSParams(double *e_k, double *sigma) { // The default ECS parameters that are used if none are coded for the fluid by overloading this function. // Applies the method of Chung; double rhobarc = reduce.rho/params.molemass; *e_k = reduce.T/1.2593; *sigma = 0.809/pow(rhobarc,1.0/3.0); } class ConformalTempResids : public FuncWrapperND { private: Fluid * InterestFluid, * ReferenceFluid; double alpha_j, Z_j; public: ConformalTempResids(Fluid *InterestFluid, Fluid *ReferenceFluid, double alpha_j, double Z_j){ this->InterestFluid = InterestFluid; this->ReferenceFluid = ReferenceFluid; this->alpha_j = alpha_j; this->Z_j = Z_j; }; ~ConformalTempResids(){}; std::vector<double> call(std::vector<double> x) { double T0 = x[0]; double rho0 = x[1]; double alpha_0 = DerivTerms(iDERphir,T0,rho0,ReferenceFluid); double Z_0 = DerivTerms(iDERZ,T0,rho0,ReferenceFluid); std::vector<double> out = std::vector<double>(2,0); out[0]=alpha_j-alpha_0; out[1]=Z_j-Z_0; return out; } std::vector<std::vector<double> > Jacobian(std::vector<double> x) { double T0=x[0]; double rho0=x[1]; double dtau_dT = -ReferenceFluid->reduce.T/T0/T0; double ddelta_drho = 1/ReferenceFluid->reduce.rho; std::vector<std::vector<double> > out; out.resize(x.size(),std::vector<double>(x.size(),0)); // Terms for the fluid of interest drop out double dalpha_dT0 = -DerivTerms(iDERdphir_dTau,T0,rho0,ReferenceFluid)*dtau_dT; out[0][0] = dalpha_dT0; double dalpha_drho0 = -DerivTerms(iDERdphir_dDelta,T0,rho0,ReferenceFluid)*ddelta_drho; out[0][1] = dalpha_drho0; double dZ_dT0 = -DerivTerms(iDERdZ_dTau,T0,rho0,ReferenceFluid)*dtau_dT; out[1][0] = dZ_dT0; double dZ_drho0 = -DerivTerms(iDERdZ_dDelta,T0,rho0,ReferenceFluid)*ddelta_drho; out[1][1] = dZ_drho0; return out; } }; std::vector<double> Fluid::ConformalTemperature(Fluid *InterestFluid, Fluid *ReferenceFluid,double T, double rho, double T0, double rho0, std::string *errstring) { int iter=0; double error,v0,v1,delta,tau,dp_drho; //The values for the fluid of interest that are the target double alpha_j = DerivTerms(iDERphir,T,rho,InterestFluid); double Z_j = DerivTerms(iDERZ,T,rho,InterestFluid); std::vector<double> f0,v,negative_f0; std::vector<std::vector<double> > J; ConformalTempResids CTR = ConformalTempResids(InterestFluid,ReferenceFluid,alpha_j,Z_j); std::vector<double> x0 = std::vector<double>(2,0); x0[0] = T0; x0[1] = rho0; // Check whether the starting guess is already pretty good error = root_sum_square(CTR.call(x0)); // Make a copy so that if the calculations fail, we can return the original values std::vector<double> x0_initial = x0; try{ // First naively try to just use the Newton-Raphson solver without any // special checking of the values. x0=NDNewtonRaphson_Jacobian(&CTR,x0_initial,1e-10,30,errstring); error = root_sum_square(CTR.call(x0)); if (fabs(error)>1e-2 || x0[0]<0.0 || x0[1]<0.0 || !ValidNumber(x0[0]) || !ValidNumber(x0[1])){ throw ValueError("Error calculating the conformal state for ECS"); } // convert to STL vector to avoid Eigen library in header std::vector<double> xout(2,x0[0]); xout[1] = x0[1]; return xout; } catch(std::exception &){} // Ok, that didn't work, so we need to try something more interesting // Local Newton-Raphson solver with bounds checking on the step values error=999; iter=0; x0 = x0_initial; // Start back at unity shape factors while (iter<30 && fabs(error)>1e-6) { T = x0[0]; rho = x0[1]; tau = reduce.T/T; delta = rho/reduce.rho; dp_drho=R()*T*(1+2*delta*dphir_dDelta(tau,delta)+delta*delta*d2phir_dDelta2(tau,delta)); //if (dp_drho<0) //{ // if (rho > ReferenceFluid->reduce.rho) // x0(1)*=1.04; // else // x0(0)*=0.96; //} //Try to take a step f0 = CTR.call(x0); J = CTR.Jacobian(x0); // Negate f0 negative_f0 = f0; for (unsigned int i = 0; i<f0.size(); i++){ negative_f0[i] *= -1;} v = linsolve(J,negative_f0); v0 = v[0]; v1 = v[1]; if (x0[0]-v[0]>0 && x0[1]-v[1]>0) { x0[0] -= v[0]; x0[1] -= v[1]; } else { x0[0] -= 1.05*x0[0]; x0[1] -= 1.05*x0[1]; } error = root_sum_square(f0); iter += 1; if (iter>29) { *errstring = std::string("ConformalTemperature reached maximum number of steps without reaching solution"); return x0_initial; } } // convert to STL vector std::vector<double> xout(2,x0[0]); xout[1] = x0[1]; return xout; }; double Fluid::viscosity_ECS_Trho(double T, double rho, Fluid * ReferenceFluid) { /* Implements the method of Marcia L. Huber, Arno Laesecke, and Richard A. Perkins "Model for the Viscosity and Thermal Conductivity of Refrigerants, Including a New Correlation for the Viscosity of R134a" Ind. Eng. Chem. Res. 2003, 42, 3163-3178 */ double e_k,sigma,e0_k, sigma0, Tc0,rhoc0,T0,rho0,rhoc,Tc, eta_dilute,theta,phi,f,h,eta_resid,M,M0,F_eta,eta,psi, rhoc0bar,rhobar,rhocbar,rho0bar; std::vector<double> x0; Tc0=ReferenceFluid->reduce.T; rhoc0=ReferenceFluid->reduce.rho; M0=ReferenceFluid->params.molemass; rhoc0bar = rhoc0/M0; Tc = reduce.T; rhoc = reduce.rho; M = params.molemass; rhocbar=rhoc/M; rhobar=rho/M; try{ // Get the ECS params for the fluid if it has them ECSParams(&e_k,&sigma); } catch (const NotImplementedError &){ try{ // Get the ECS parameters from the reference fluid ReferenceFluid->ECSParams(&e0_k,&sigma0); } catch (const NotImplementedError &){ // Doesn't have e_k and sigma for reference fluid throw NotImplementedError(format("Your reference fluid for ECS [%s] does not have an implementation of ECSParams",(char *)ReferenceFluid->get_name().c_str())); } //Estimate the ECS parameters from Huber and Ely, 2003 e_k = e0_k*Tc/Tc0; sigma = sigma0*pow(rhoc/rhoc0,1.0/3.0); } // The dilute portion is for the fluid of interest, not for the reference fluid // It is the viscosity in the limit of zero density eta_dilute = viscosity_dilute(T,e_k,sigma); //[uPa-s] if (1)//(T>reduce.T) { // Get the conformal temperature. To start out here, assume that the shape factors are unity theta=1; phi=1; } else { /* Use the method from Isabel M. Marruchoa, James F. Ely, "Extended corresponding states for pure polar and non-polar fluids: an improved method for component shape factor prediction", Fluid Phase Equilibria 150–151 1998 215–223 Reynes and Thodos, APPLICATION OF A REDUCED VAPOR PRESSURE EQUATION TO NONHYDROROCARBON SUBSTANCES beta = 5/9*gamma-40/27 gamma = 9/5*beta + 9/5*40/27 gamma = 9/5*beta + 8/3 */ double Bstar,Bstar0,Cstar,Cstar0,DELTABstar,DELTACstar,Zc,Zc0; double omega = params.accentricfactor; double omega0 = ReferenceFluid->params.accentricfactor; double Tstar = T/reduce.T; Zc = reduce.p.Pa/(reduce.rho*R()*reduce.T); Zc0 = ReferenceFluid->reduce.p.Pa/(ReferenceFluid->reduce.rho*ReferenceFluid->R()*ReferenceFluid->reduce.T); Bstar = -6.207612-15.37641*omega-0.574946*pow(10,-omega); Bstar0 = -6.207612-15.37641*omega0-0.574946*pow(10,-omega0); Cstar = 8/3+9*Bstar/5.0/log(10.0); Cstar0 = 8/3+9*Bstar0/5.0/log(10.0); DELTABstar = Bstar-Bstar0; DELTACstar = Cstar-Cstar0; theta = (1-Cstar0+2*pow(1-Tstar,2.0/7.0)*log(Zc/Zc0)-DELTABstar+DELTACstar*log(Tstar)+Bstar/Tstar)/(1-Cstar0+Bstar0/Tstar); phi = pow(Zc,pow(1-Tstar,2.0/7.0))/pow(Zc0,pow(1-Tstar/theta,2.0/7.0)); } psi = ECS_psi_viscosity(rho/reduce.rho); f=Tc/Tc0*theta; //Must be the ratio of MOLAR densities!! h=rhoc0bar/rhocbar*phi; T0=T/f; rho0bar=rhobar*h; //Get the mass density for the reference fluid [kg/m3] rho0=rho0bar*M0; std::string errstring; // First check whether you should use this code in the first place. // Implementing the method of TRNECS from REFPROP double delta = rho/reduce.rho; double tau = reduce.T/T; double Z = 1+delta*dphir_dDelta(tau,delta); double p0 = Z*R()*T0*rho0; if (Z<0.3 || p0>1.1*ReferenceFluid->reduce.p.Pa || rho0>ReferenceFluid->reduce.rho){ // Use the code to calculate the conformal state x0=ConformalTemperature(this,ReferenceFluid,T,rho,T0,rho0,&errstring); T0=x0[0]; rho0=x0[1]; } rho0bar = rho0/M0; h = rho0bar/rhobar; f = T/T0; eta_resid = ReferenceFluid->viscosity_background(T0,rho0*psi); F_eta = sqrt(f)*pow(h,-2.0/3.0)*sqrt(M/M0); eta = eta_dilute+eta_resid*F_eta; return eta; } double Fluid::conductivity_ECS_Trho(double T, double rho, Fluid * ReferenceFluid) { /* Implements the method of Marcia L. Huber, Arno Laesecke, and Richard A. Perkins "Model for the Viscosity and Thermal Conductivity of Refrigerants, Including a New Correlation for the Viscosity of R134a" Ind. Eng. Chem. Res. 2003, 42, 3163-3178 */ double e_k,sigma,e0_k, sigma0, Tc0,rhoc0,T0,rho0,rhoc,Tc, eta_dilute,theta,phi,f,h,lambda_resid,M,M0,F_lambda,lambda,chi, f_int,lambda_int,lambda_crit,lambda_star,rhoc0bar,rhobar,rhocbar,rho0bar; std::vector<double> x0; // Properties for the reference fluid Tc0=ReferenceFluid->reduce.T; rhoc0=ReferenceFluid->reduce.rho; M0=ReferenceFluid->params.molemass; rhoc0bar = rhoc0/M0; // Properties for the given fluid Tc = reduce.T; rhoc = reduce.rho; M = params.molemass; rhocbar=rhoc/M; rhobar=rho/M; try{ // Get the ECS params for the fluid if it has them ECSParams(&e_k,&sigma); } catch(NotImplementedError &){ try{ //Estimate the ECS parameters from Huber and Ely, 2003 ReferenceFluid->ECSParams(&e0_k,&sigma0); } catch (NotImplementedError &){ // Doesn't have e_k and sigma for reference fluid throw NotImplementedError(format("Your reference fluid for ECS [%s] does not have an implementation of ECSParams",(char *)ReferenceFluid->get_name().c_str())); } e_k = e0_k*Tc/Tc0; sigma = sigma0*pow(rhoc/rhoc0,1.0/3.0); } // The dilute portion is for the fluid of interest, not for the reference fluid // It is the viscosity in the limit of zero density // It has units of Pa-s here eta_dilute = viscosity_dilute(T,e_k,sigma); //[Pa-s] chi = ECS_chi_conductivity(rho/reduce.rho); f_int = ECS_f_int(T); // Get the conformal temperature. To start out here, assume that the shape factors are unity theta=1.0; phi=1.0; f=Tc/Tc0*theta; h=rhoc0bar/rhocbar*phi; T0=T/f; rho0bar=rhobar*h; //Get the mass density for the reference fluid [kg/m3] rho0=rho0bar*M0; std::string errstring; // First check whether you should use this code in the first place. // Implementing the method of TRNECS from REFPROP double delta = rho/reduce.rho; double tau = reduce.T/T; double Z = 1+delta*dphir_dDelta(tau,delta); double p0 = Z*R()*T0*rho0; //[Pa] if (Z<0.3 || p0 > 1.1*ReferenceFluid->reduce.p.Pa || rho0 > ReferenceFluid->reduce.rho){ // Use the code to calculate the conformal state x0=ConformalTemperature(this,ReferenceFluid,T,rho,T0,rho0,&errstring); T0=x0[0]; rho0=x0[1]; } rho0bar = rho0/M0; h=rho0bar/rhobar; f=T/T0; // Ideal-gas specific heat in the limit of zero density double cpstar = specific_heat_p_ideal_Trho(T); //[J/kg/K] lambda_star = 15e-3*R()*(eta_dilute*1e3)/4.0; //[W/m/K] lambda_int = f_int*(eta_dilute*1e3)*(cpstar-5.0/2.0*R() ); //[W/m/K] F_lambda = sqrt(f)*pow(h,-2.0/3.0)*sqrt(M0/M); //[-] //Get the background conductivity from the reference fluid lambda_resid = ReferenceFluid->conductivity_background(T0,rho0*chi);//[W/m/K] lambda_crit = conductivity_critical(T,rho); //[W/m/K] lambda = lambda_int+lambda_star+lambda_resid*F_lambda+lambda_crit; //[W/m/K] return lambda; //[W/m/K] } bool Fluid::build_TTSE_LUT(bool force_build) { if (!built_TTSE_LUT || force_build) { // No value has been set for the parameters if (pmin_TTSE>1e100 && pmax_TTSE > 1e100 && hmin_TTSE > 1e00 && hmax_TTSE > 1e100) { double psatL,psatV,rhoL,rhoV; this->disable_TTSE_LUT(); // Disable TTSE to do these calculations saturation_T(limits.Tmin, false, psatL, psatV, rhoL, rhoV); double hL = enthalpy_Trho(limits.Tmin,rhoL); double hV = enthalpy_Trho(limits.Tmin,rhoV); hmin_TTSE = hL; hmax_TTSE = hL+(hV-hL)*2; pmin_TTSE = std::min(psatL, psatV); pmax_TTSE = 2*reduce.p.Pa; } // Turn off the use of LUT while you are building it, // otherwise you get an infinite recursion enabled_TTSE_LUT = false; TTSESatL = TTSETwoPhaseTableClass(this,0); TTSESatL.set_size(Nsat_TTSE); TTSESatV = TTSETwoPhaseTableClass(this,1); TTSESatV.set_size(Nsat_TTSE); TTSESatV.build(pmin_TTSE,crit.p.Pa,&TTSESatL); TTSESinglePhase = TTSESinglePhaseTableClass(this); TTSESinglePhase.enable_writing_tables_to_files = enable_writing_tables_to_files; TTSESinglePhase.set_size_ph(Np_TTSE,Nh_TTSE); // T,rho will mirror the size and range of h,p TTSESinglePhase.set_size_Trho(Np_TTSE, Nh_TTSE); TTSESinglePhase.hmin = hmin_TTSE; TTSESinglePhase.hmax = hmax_TTSE; TTSESinglePhase.pmin = pmin_TTSE; TTSESinglePhase.pmax = pmax_TTSE; TTSESinglePhase.SatL = &TTSESatL; TTSESinglePhase.SatV = &TTSESatV; // If we can read the LUT from file, we are done and don't need to rebuild if (!TTSESinglePhase.read_all_from_file(TTSESinglePhase.root_path)) { // Build all the tables TTSESinglePhase.build_ph(hmin_TTSE, hmax_TTSE, pmin_TTSE, pmax_TTSE, &TTSESatL, &TTSESatV); TTSESinglePhase.build_Trho(-1, -1, -1, -1, &TTSESatL, &TTSESatV);// Allow method to figure out the range using h,p since -1 passed for T and rho limits // Write all the matrices and arrays to files if (TTSESinglePhase.enable_writing_tables_to_files){ TTSESinglePhase.write_all_to_file(TTSESinglePhase.root_path); } } built_TTSE_LUT = true; enabled_TTSE_LUT = true; } return true; } /// Enable the two-phase properties /// If you want to over-ride parameters, must be done before calling this function void Fluid::enable_EXTTP(void){enabled_EXTTP = true;}; /// Check if TTSE is enabled bool Fluid::isenabled_EXTTP(void){return enabled_EXTTP;}; /// Disable the TTSE void Fluid::disable_EXTTP(void){enabled_EXTTP = false;}; /// Enable the TTSE /// If you want to over-ride parameters, must be done before calling this function void Fluid::enable_TTSE_LUT(void){enabled_TTSE_LUT = true;}; /// Check if TTSE is enabled bool Fluid::isenabled_TTSE_LUT(void){return enabled_TTSE_LUT;}; /// Disable the TTSE void Fluid::disable_TTSE_LUT(void){enabled_TTSE_LUT = false;}; /// Enable the writing of TTSE tables to file void Fluid::enable_TTSE_LUT_writing(void){enable_writing_tables_to_files = true;}; /// Check if the writing of TTSE tables to file is enabled bool Fluid::isenabled_TTSE_LUT_writing(void){return enable_writing_tables_to_files;}; /// Disable the writing of TTSE tables to file void Fluid::disable_TTSE_LUT_writing(void){enable_writing_tables_to_files = false;}; /// Over-ride the default size of both of the saturation LUT void Fluid::set_TTSESat_LUT_size(int Nsat){Nsat_TTSE = Nsat;}; /// Over-ride the default size of the single-phase LUT void Fluid::set_TTSESinglePhase_LUT_size(int Np, int Nh){Np_TTSE = Np; Nh_TTSE = Nh;}; /// Over-ride the default range of the single-phase LUT void Fluid::set_TTSESinglePhase_LUT_range(double hmin, double hmax, double pmin, double pmax){hmin_TTSE = hmin; hmax_TTSE = hmax; pmin_TTSE = pmin; pmax_TTSE = pmax;}; /// Get the current range of the single-phase LUT void Fluid::get_TTSESinglePhase_LUT_range(double *hmin, double *hmax, double *pmin, double *pmax){*hmin = hmin_TTSE; *hmax = hmax_TTSE; *pmin = pmin_TTSE; *pmax = pmax_TTSE;}; void AncillaryCurveClass::update(Fluid *_pFluid, std::string Output) { pFluid = _pFluid; iOutput = get_param_index(Output); } int AncillaryCurveClass::build(int N) { double T,rhoV,rhoL; // Output values long iFluid = get_Fluid_index(pFluid->get_name()); double Tmin = pFluid->params.Ttriple+1e-6; if (Tmin<pFluid->limits.Tmin) Tmin = pFluid->limits.Tmin+1e-6; double Tmax = pFluid->reduce.T-10*DBL_EPSILON; for(int i = 0; i<N; i++) { T = Tmin+(Tmax-Tmin)/(N-1)*i; xL.push_back(T); xV.push_back(T); rhoL = pFluid->rhosatL(T); rhoV = pFluid->rhosatV(T); // IProps will always return value in standard units, convert to SI if (iOutput==iH) { yL.push_back(pFluid->enthalpy_Trho(T,rhoL)); yV.push_back(pFluid->enthalpy_Trho(T,rhoV)); } else if (iOutput == iS) { yL.push_back(pFluid->entropy_Trho(T,rhoL)); yV.push_back(pFluid->entropy_Trho(T,rhoV)); } else { throw ValueError(format("iOutput [%d] in build is invalid", iOutput).c_str()); } } built = true; return 1; } double AncillaryCurveClass::interpolateL(double T){ return interp1d(&xL,&yL,T); } double AncillaryCurveClass::interpolateV(double T){ return interp1d(&xV,&yV,T); } double AncillaryCurveClass::reverseinterpolateL(double y){ return interp1d(&yL,&xL,y); } double AncillaryCurveClass::reverseinterpolateV(double y){ return interp1d(&yV,&xV,y); } double CriticalSplineStruct_T::interpolate_rho(Fluid *pFluid, int phase, double T) { // Use the spline interpolation since you are very close to the critical point // R = rho/rhoc-1 => we are solving for R for liquid and vapor using a spline // since we know that dtaudR|crit = 0, tau|crit = 1, R|crit = 0, and we know // rho and drhodT_sat at Tend, the end of the normal Akasaka solving method // // Essentially you have tau = aR^3+bR^2+cR+d, where c = 0 and d = 1 from constraints // at critical point // Can check cubic solution from http://www.akiti.ca/Quad3Deg.html // Also, wikipedia has good docs on cubics: http://en.wikipedia.org/wiki/Cubic_function, especially the "Trigonometric (and hyperbolic) method" section double rhoc = pFluid->reduce.rho; double Tc = pFluid->reduce.T; double tauend = Tc/Tend, tau = Tc/T; double k1,k2,R,Rend,a,b,c,d,rhoend; // If you are within a microKelvin of critical point, return critical point if (fabs(T-Tc)<1e-6) { return rhoc; } if (phase == 0) { k1 = -tauend/Tend*rhoc/drhoLdT_sat; // k1 = dtaudR|sat at Tend k2 = tauend; Rend = rhoendL/rhoc-1; // R at Tend rhoend = rhoendL; } else if (phase == 1) { k1 = -tauend/Tend*rhoc/drhoVdT_sat; // k1 = dtaudR|sat at Tend k2 = tauend; Rend = rhoendV/rhoc-1; // R at Tend rhoend = rhoendV; } else { throw ValueError(); } // Linear system to find constants a,b for the spline cubic /* k2 = aR^3+bR^2+1 k1 = 3aR^2+2bR */ double a11 = Rend*Rend*Rend; double a12 = Rend*Rend; double b1 = k2-1; double a21 = 3*Rend*Rend; double a22 = 2*Rend; double b2 = k1; // Cramer's rule to find a,b double det = a11*a22-a21*a12; a = (b1*a22-a12*b2)/det; b = (b2*a11-a21*b1)/det; // Constants from critical point c = 0; d = 1-tau; // Discriminant double DELTA = 18*a*b*c*d-4*b*b*b*d+b*b*c*c-4*a*c*c*c-27*a*a*d*d; // Coefficients for the depressed cubic t^3+p*t+q = 0 double p = (3*a*c-b*b)/(3*a*a); double q = (2*b*b*b-9*a*b*c+27*a*a*d)/(27*a*a*a); if (DELTA<0) { // One real root double t0; if (4*p*p*p+27*q*q>0 && p<0) { t0 = -2.0*fabs(q)/q*sqrt(-p/3.0)*cosh(1.0/3.0*acosh(-3.0*fabs(q)/(2.0*p)*sqrt(-3.0/p))); } else { t0 = -2.0*sqrt(p/3.0)*sinh(1.0/3.0*asinh(3.0*q/(2.0*p)*sqrt(3.0/p))); } R = t0-b/(3*a); } else //(DELTA>0) { // Three real roots double t0 = 2.0*sqrt(-p/3.0)*cos(1.0/3.0*acos(3.0*q/(2.0*p)*sqrt(-3.0/p))-0*2.0*M_PI/3.0); double t1 = 2.0*sqrt(-p/3.0)*cos(1.0/3.0*acos(3.0*q/(2.0*p)*sqrt(-3.0/p))-1*2.0*M_PI/3.0); double t2 = 2.0*sqrt(-p/3.0)*cos(1.0/3.0*acos(3.0*q/(2.0*p)*sqrt(-3.0/p))-2*2.0*M_PI/3.0); double R0 = t0-b/(3*a); double R1 = t1-b/(3*a); double R2 = t2-b/(3*a); // The solution for R must be bounded between Rend and 0 if (R0*Rend > 0 && fabs(R0)<=fabs(Rend)) { R = R0; } else if (R1*Rend > 0 && fabs(R1)<=fabs(Rend)) { R = R1; } else if (R2*Rend > 0 && fabs(R2)<=fabs(Rend)) { R = R2; } else { throw ValueError(format("No solution found for R")); } } return rhoc*(1+R); } void rebuild_CriticalSplineConstants_T() { UseCriticalSpline = false; FluidsContainer Fluids = FluidsContainer(); std::vector<std::string> fluid_names = strsplit(Fluids.FluidList(),','); double rhoL=0, rhoV=0, drhodTL=0, drhodTV=0; FILE *fp; fp = fopen("CriticalSplineConstants_T.h","w"); for (unsigned int i = 0; i < fluid_names.size(); i++) { std::cout << format("%s:\n",fluid_names[i].c_str()).c_str(); CoolPropStateClass CPS(fluid_names[i]); double Tc = CPS.pFluid->reduce.T; double Tt = CPS.pFluid->params.Ttriple; if (!CPS.pFluid->pure()) { // Skip pseudo-pure fluids continue; } double good; try{ if (Tc-5>Tt) { CPS.update(iT,Tc-5,iQ,1); rhoV = CPS.rhoV(); rhoL = CPS.rhoL(); drhodTV = CPS.drhodT_along_sat_vapor(); drhodTL = CPS.drhodT_along_sat_liquid(); if (!ValidNumber(drhodTV) || !ValidNumber(drhodTL)){throw ValueError();} good = 5; } else { CPS.update(iT,Tc-1,iQ,1); rhoV = CPS.rhoV(); rhoL = CPS.rhoL(); drhodTV = CPS.drhodT_along_sat_vapor(); drhodTL = CPS.drhodT_along_sat_liquid(); if (!ValidNumber(drhodTV) || !ValidNumber(drhodTL)){throw ValueError();} good = 1; } } catch(std::exception &) { if (CPS.pFluid->reduce.T > 100) { std::cout << format("%s : failed at 20 K \n",fluid_names[i].c_str()).c_str(); continue; } else { std::cout << format("%s : failed at 1 K \n",fluid_names[i].c_str()).c_str(); continue; } } bool valid = false; for (double step = 0.5; step > 1e-10; step /= 100.0) { valid = true; for (double b = good; b>0; b -= step) { try{ CPS.update(iT, Tc - b, iQ, 1); rhoV = CPS.rhoV(); rhoL = CPS.rhoL(); drhodTV = CPS.drhodT_along_sat_vapor(); drhodTL = CPS.drhodT_along_sat_liquid(); } catch(std::exception &){ valid = false; break; } if (!ValidNumber(drhodTV) || !ValidNumber(drhodTL) || drhodTV*drhodTL > 0){ //std::cout << format("%0.20g",good) << std::endl; valid = false; break; } else { good = b; } } if (!valid){ break; } } CoolPropStateClass CPS2(fluid_names[i]); CPS2.update(iT,Tc-good,iQ,1.0); rhoV = CPS2.rhoV(); rhoL = CPS2.rhoL(); drhodTV = CPS2.drhodT_along_sat_vapor(); drhodTL = CPS2.drhodT_along_sat_liquid(); std::cout << format("%0.20g",good).c_str() << std::endl; fprintf(fp,"\tstd::make_pair(std::string(\"%s\"),CriticalSplineStruct_T(%0.12e,%0.12e,%0.12e,%0.12e,%0.12e) ),\n",fluid_names[i].c_str(),Tc-good,rhoL,rhoV,drhodTL,drhodTV); } fclose(fp); UseCriticalSpline = true; }
429ba668b6f7d185afdbd6261656a56e71e8a693
b51a16b9dd3d481f20f505ec520eac473db3fe56
/at/53_Ak/D.cc
3aa5ca8504a2283be3f30289c888fc76aeb9ca9e
[ "MIT" ]
permissive
xsthunder/acm
18b0d23c7456b1f57a9c68f94b8b6c0ce5580349
3c30f31c59030d70462b71ef28c5eee19c6eddd6
refs/heads/master
2021-06-03T23:52:27.140081
2019-05-25T05:38:49
2019-05-25T05:38:49
69,569,543
1
0
null
null
null
null
UTF-8
C++
false
false
1,263
cc
const bool TEST=1; #include<iostream> #include<cctype> #include<algorithm> #include<cstdio> #include<cstdlib> #include<vector> #include<map> #include<queue> #include<set> #include<cctype> #include<cstring> #include<utility> #include<cmath> #include<sstream> #include<stack> const int inf=0x7fffffff; #define IF if(TEST) #define FI if(!TEST) #define gts(s) fgets((s),sizeof(s),stdin) #define ALL(s) (s).begin(),(s).end() #define MK(a,b) make_pair((a),(b)) typedef long long int LL; typedef unsigned int U; typedef unsigned long long ULL; using namespace std; typedef pair<int,int> Point; template <typename T> void pA(T *begin,int n){ for(int i=0;i<n;i++){ cout<<*(begin++); } printf("\n"); } const int N =1e5+1e5; int dat[N]; void sol(){ int n; cin>>n; int x; bool flag2=0; while(n--){ scanf("%d", &x); dat[x]++; if(dat[x]==3)dat[x]-=2; } IF pA(dat,9); for(int i =0 ;i < N ;i++){ if(dat[i]==2){ if(flag2){ dat[x]--; flag2=0; dat[i]--; } else { x=i; flag2=1; } } } IF pA(dat,9); if(flag2){ dat[x]-=2; } IF pA(dat,9); int cnt=0; for(int i = 0;i<N;i++){ if(dat[i])cnt++; } cout<<cnt<<endl; } int main() { sol(); return 0; } //D.cc //generated automatically at Sat Jan 28 20:34:39 2017 //by xsthunder
539ed183eabbbc454a377c0aaa4642145ae800cb
6337193bf59c2f60491166bc399dffeee26ede37
/include/hash_multi_classifier.hpp
ae02791c19222f31fbec75e6f1348911de353de0
[]
no_license
gpzhang7/LSH
4cd22a70fde6dbb38d73b85ae7fe929a47eda284
5a07efa0cc73a986dbdf2093a7af1d7b5f377388
refs/heads/master
2020-09-05T22:31:07.344204
2012-12-30T16:17:38
2012-12-30T16:17:38
220,232,395
1
0
null
2019-11-07T12:30:17
2019-11-07T12:30:17
null
UTF-8
C++
false
false
2,603
hpp
/** * @file hash_multi_classifier.hpp * @author Mitsuhisa Ohta * @brief * * @date Fri Sep 24 18:09:10 2010 last updated * @date Fri Sep 24 15:35:20 2010 created */ #ifndef COLFIL_HASH_MULTI_CLASSIFIER__ #define COLFIL_HASH_MULTI_CLASSIFIER__ #include "array.hpp" #include "container_traits.hpp" #include "random.hpp" namespace colfil { template<unsigned int N, typename HASH_T, typename INPUT_T = typename HASH_T::InputType, typename VALUE_T = Array<typename HASH_T::ValueType, N>, typename RANDOM_T = NLRandom> class HashMultiClassifier{ public: typedef HASH_T HashType; typedef INPUT_T InputType; typedef VALUE_T ValueType; typedef RANDOM_T RandomType; private: RandomType random_; HashType hashes_[N]; public: HashMultiClassifier() { } HashMultiClassifier(int seed) { setSeed(seed); } void setSeed(int seed) { random_.setSeed(seed); for (int i = 0; i < 314; ++i) { random_(); } for (unsigned int i = 0; i < N; ++i) { hashes_[i].setSeed(random_()); } } int getSeed() const { return random_.getSeed(); } unsigned int size() const { return N; } virtual void classify(InputType input, ValueType *output) const { for (unsigned int i = 0; i < N; ++i) { MapTraits<VALUE_T>::set(output, i, hashes_[i](input)); } } }; template<unsigned int N, typename HASH_T, typename INPUT_T, typename RANDOM_T> class HashMultiClassifier<N, HASH_T, INPUT_T, typename HASH_T::ValueType*, RANDOM_T>{ public: typedef HASH_T HashType; typedef INPUT_T InputType; typedef typename HashType::ValueType *ValueType; typedef RANDOM_T RandomType; private: RandomType random_; HashType hashes_[N]; public: HashMultiClassifier() { } HashMultiClassifier(int seed) { setSeed(seed); } void setSeed(int seed) { random_.setSeed(seed); for (unsigned int i = 0; i < N; ++i) { hashes_[i].setSeed(random_()); } } int getSeed() const { return random_.getSeed(); } unsigned int size() const { return N; } virtual void classify(InputType input, ValueType output) const { for (unsigned int i = 0; i < N; ++i) { output[i] = hashes_[i](input); } } }; } #endif /* COLFIL_HASH_MULTI_CLASSIFIER__ */
ead772b0d1a8926eea9f3c5decfa0f08ecf88d3c
20617a5d85d4758918d5ef73b6c4b10a58be6078
/RawToMetric/src/RawToMetric.cpp
9fcd475dc8126e03974d900446db6c311a4c0560
[]
no_license
techmc/MoPred
5ee88d8b6e7ca3c4783a3185a256ae81c6c73ccf
2d6a5cf5a837d3db8a356d793bc5295b5b016014
refs/heads/master
2016-09-06T15:58:04.201240
2013-01-30T12:03:53
2013-01-30T12:03:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,559
cpp
//============================================================================ // Name : RawToMetric.cpp // Author : Zassa Kavuma // Version : 0.2 // Copyright : Released under the GNU General Public License // Description : Program for saving metric data //============================================================================ // Includes #include <iostream> #include <fstream> #include <cmath> #include <algorithm> #include <stdio.h> #include <fftw3.h> #include <fann.h> #include <sstream> // Defines #define FILES 60 // max number of files #define PAIRS 32 // Sets the number of data pairs to record #define PAIRSOUT ((PAIRS/2)+1) // Set the number of DFT output pairs #define VALUES 12 #define POLARS 8 #define DAT 3 // sets the current DCT file // Globals using namespace std; int main(int argc, char** argv) { fftw_complex *dctdata, *fft_result; fftw_plan plan_forward; stringstream ss; string track; ifstream inFile; dctdata = ( fftw_complex* ) fftw_malloc( sizeof( fftw_complex ) * PAIRS ); fft_result = ( fftw_complex* ) fftw_malloc( sizeof( fftw_complex ) * PAIRS ); plan_forward = fftw_plan_dft_1d( PAIRS, dctdata, fft_result, FFTW_FORWARD, FFTW_ESTIMATE ); // Position floats (12) int i; // Buffers float positbuffer[PAIRS][VALUES]; double polarbuffer[PAIRS][POLARS]; printf("Welcome Trainer!\n"); for (int x = 0; x < FILES; ++x) // For each data file { ss << x; track = ss.str(); cout << track << endl; string basename; if (DAT==1){ basename = "../Shared/RAW/RAW000001dualwaveX.dat"; basename.replace(27, 1, track); } if (DAT==2){ basename = "../Shared/RAW/RAW000010dualrowX.dat"; basename.replace(26, 1, track); } if (DAT==3){ basename = "../Shared/RAW/RAW000100dualriseX.dat"; basename.replace(27, 1, track); } if (DAT==4){ basename = "../Shared/RAW/RAW001000timeX.dat"; basename.replace(23, 1, track); } if (DAT==5){ basename = "../Shared/RAW/RAW010000clapX.dat"; basename.replace(23, 1, track); } if (DAT==6){ basename = "../Shared/RAW/RAW100000crossX.dat"; basename.replace(24, 1, track); } cout << basename << endl; ss.str(""); // open file if it exists ifstream fp(basename.c_str()); if (fp) { inFile.open(basename.c_str()); cout << "Entering polar area" << endl; for (int j = 0; j < PAIRS; ++j) // for each row { // Convert row of values into polar values for (int k = 0; k < VALUES; ++k) // read each value into calculation array { inFile >> positbuffer[j][k]; // Read file to row j column k } // 1 Compute XZ polar radius polarbuffer[0][j] = sqrt(((positbuffer[j][0]-positbuffer[j][6])*(positbuffer[j][0]-positbuffer[j][6]))+((positbuffer[j][5]-positbuffer[j][8])*(positbuffer[j][2]-positbuffer[j][8]))); // 2 Compute XZ angle polarbuffer[1][j] = atan((positbuffer[j][0]-positbuffer[j][6])/(positbuffer[j][2]-positbuffer[j][8])); // 3 Compute YZ polar radius polarbuffer[2][j] = sqrt(((positbuffer[j][1]-positbuffer[j][7])*(positbuffer[j][1]-positbuffer[j][7]))+((positbuffer[j][2]-positbuffer[j][8])*(positbuffer[j][2]-positbuffer[j][8]))); // 4 Compute YZ angle polarbuffer[3][j] = atan((positbuffer[j][1]-positbuffer[j][7])/(positbuffer[j][2]-positbuffer[j][8])); // 5 Compute XZ polar radius polarbuffer[4][j] = sqrt(((positbuffer[j][3]-positbuffer[j][9])*(positbuffer[j][3]-positbuffer[j][9]))+((positbuffer[j][5]-positbuffer[j][11])*(positbuffer[j][5]-positbuffer[j][11]))); // 6 Compute XZ angle polarbuffer[5][j] = atan((positbuffer[j][3]-positbuffer[j][9])/(positbuffer[j][5]-positbuffer[j][11])); // 7 Compute YZ polar radius polarbuffer[6][j] = sqrt(((positbuffer[j][4]-positbuffer[j][10])*(positbuffer[j][4]-positbuffer[j][10]))+((positbuffer[j][5]-positbuffer[j][11])*(positbuffer[j][2]-positbuffer[j][11]))); // 8 Compute YZ angle polarbuffer[7][j] = atan((positbuffer[j][4]-positbuffer[j][10])/(positbuffer[j][5]-positbuffer[j][11])); } inFile.close(); // DCT computation cout << "Entering DCT area" << endl; ofstream myfile2; if (DAT==1){ myfile2.open ("../Shared/DCT/DCT000001.data", ios::app); } if (DAT==2){ myfile2.open ("../Shared/DCT/DCT000010.data", ios::app); } if (DAT==3){ myfile2.open ("../Shared/DCT/DCT000100.data", ios::app); } if (DAT==4){ myfile2.open ("../Shared/DCT/DCT001000.data", ios::app); } if (DAT==5){ myfile2.open ("../Shared/DCT/DCT010000.data", ios::app); } if (DAT==6){ myfile2.open ("../Shared/DCT/DCT100000.data", ios::app); } float absmat[PAIRSOUT]; // Array to hold absolute outputs int a; // 1 XZ radius for( i = 0 ; i < PAIRS ; i++ ) { dctdata[i][0] = polarbuffer[0][i]; dctdata[i][1] = 0.0; } fftw_execute( plan_forward ); for (a=0; a<PAIRSOUT; a++){ absmat[a] = sqrt(((fft_result[a][0])*(fft_result[a][0]))+((fft_result[a][1])*(fft_result[a][1]))); } sort(absmat, absmat+PAIRSOUT); for (a=(PAIRSOUT-5); a<PAIRSOUT; a++){ // Save the 5 largest values myfile2 << absmat[a] << " "; } // 2 XZ angle for( i = 0 ; i < PAIRS ; i++ ) { dctdata[i][0] = polarbuffer[1][i]; dctdata[i][1] = 0.0; } fftw_execute( plan_forward ); for (a=0; a<PAIRSOUT; a++){ absmat[a] = sqrt(((fft_result[a][0])*(fft_result[a][0]))+((fft_result[a][1])*(fft_result[a][1]))); } sort(absmat, absmat+PAIRSOUT); for (a=(PAIRSOUT-5); a<PAIRSOUT; a++){ myfile2 << absmat[a] << " "; } // 3 YZ radius for( i = 0 ; i < PAIRS ; i++ ) { dctdata[i][0] = polarbuffer[2][i]; dctdata[i][1] = 0.0; } fftw_execute( plan_forward ); for (a=0; a<PAIRSOUT; a++){ absmat[a] = sqrt(((fft_result[a][0])*(fft_result[a][0]))+((fft_result[a][1])*(fft_result[a][1]))); } sort(absmat, absmat+PAIRSOUT); for (a=(PAIRSOUT-5); a<PAIRSOUT; a++){ myfile2 << absmat[a] << " "; } // 4 YZ angle for( i = 0 ; i < PAIRS ; i++ ) { dctdata[i][0] = polarbuffer[3][i]; dctdata[i][1] = 0.0; } fftw_execute( plan_forward ); for (a=0; a<PAIRSOUT; a++){ absmat[a] = sqrt(((fft_result[a][0])*(fft_result[a][0]))+((fft_result[a][1])*(fft_result[a][1]))); } sort(absmat, absmat+PAIRSOUT); for (a=(PAIRSOUT-5); a<PAIRSOUT; a++){ myfile2 << absmat[a] << " "; } // 5 for( i = 0 ; i < PAIRS ; i++ ) { dctdata[i][0] = polarbuffer[4][i]; dctdata[i][1] = 0.0; } fftw_execute( plan_forward ); for (a=0; a<PAIRSOUT; a++){ absmat[a] = sqrt(((fft_result[a][0])*(fft_result[a][0]))+((fft_result[a][1])*(fft_result[a][1]))); } sort(absmat, absmat+PAIRSOUT); for (a=(PAIRSOUT-5); a<PAIRSOUT; a++){ myfile2 << absmat[a] << " "; } // 6 for( i = 0 ; i < PAIRS ; i++ ) { dctdata[i][0] = polarbuffer[5][i]; dctdata[i][1] = 0.0; } fftw_execute( plan_forward ); for (a=0; a<PAIRSOUT; a++){ absmat[a] = sqrt(((fft_result[a][0])*(fft_result[a][0]))+((fft_result[a][1])*(fft_result[a][1]))); } sort(absmat, absmat+PAIRSOUT); for (a=(PAIRSOUT-5); a<PAIRSOUT; a++){ myfile2 << absmat[a] << " "; } // 7 for( i = 0 ; i < PAIRS ; i++ ) { dctdata[i][0] = polarbuffer[6][i]; dctdata[i][1] = 0.0; } fftw_execute( plan_forward ); for (a=0; a<PAIRSOUT; a++){ absmat[a] = sqrt(((fft_result[a][0])*(fft_result[a][0]))+((fft_result[a][1])*(fft_result[a][1]))); } sort(absmat, absmat+PAIRSOUT); for (a=(PAIRSOUT-5); a<PAIRSOUT; a++){ myfile2 << absmat[a] << " "; } // 8 for( i = 0 ; i < PAIRS ; i++ ) { dctdata[i][0] = polarbuffer[7][i]; dctdata[i][1] = 0.0; } fftw_execute( plan_forward ); for (a=0; a<PAIRSOUT; a++){ absmat[a] = sqrt(((fft_result[a][0])*(fft_result[a][0]))+((fft_result[a][1])*(fft_result[a][1]))); } sort(absmat, absmat+PAIRSOUT); for (a=(PAIRSOUT-5); a<PAIRSOUT; a++){ myfile2 << absmat[a] << " "; } // Write the binary classifier if (DAT==1){ myfile2 << "\n" << "-1 -1 -1 -1 -1 1" << "\n"; } if (DAT==2){ myfile2 << "\n" << "-1 -1 -1 -1 1 -1" << "\n"; } if (DAT==3){ myfile2 << "\n" << "-1 -1 -1 1 -1 -1" << "\n"; } if (DAT==4){ myfile2 << "\n" << "-1 -1 1 -1 -1 -1" << "\n"; } if (DAT==5){ myfile2 << "\n" << "-1 1 -1 -1 -1 -1" << "\n"; } if (DAT==6){ myfile2 << "\n" << "1 -1 -1 -1 -1 -1" << "\n"; } cout << "Leaving DCT area \n" << endl; // Close data file myfile2.close(); } else { cout << "File not found \n" << endl; } } // Shuffle file data struct fann_train_data *data; if (DAT==1){ data = fann_read_train_from_file("../Shared/DCT/DCT000001.data"); // Import data remove("../Shared/DCT/DCT000001.data"); fann_shuffle_train_data(data); // Shuffle data fann_save_train(data, "../Shared/DCT/DCT000001.data"); } if (DAT==2){ data = fann_read_train_from_file("../Shared/DCT/DCT000010.data"); // Import data remove("../Shared/DCT/DCT000010.data"); fann_shuffle_train_data(data); // Shuffle data fann_save_train(data, "../Shared/DCT/DCT000010.data"); } if (DAT==3){ data = fann_read_train_from_file("../Shared/DCT/DCT000100.data"); // Import data remove("../Shared/DCT/DCT000100.data"); fann_shuffle_train_data(data); // Shuffle data fann_save_train(data, "../Shared/DCT/DCT000100.data"); } if (DAT==4){ data = fann_read_train_from_file("../Shared/DCT/DCT001000.data"); // Import data remove("../Shared/DCT/DCT001000.data"); fann_shuffle_train_data(data); // Shuffle data fann_save_train(data, "../Shared/DCT/DCT001000.data"); } if (DAT==5){ data = fann_read_train_from_file("../Shared/DCT/DCT010000.data"); // Import data remove("../Shared/DCT/DCT010000.data"); fann_shuffle_train_data(data); // Shuffle data fann_save_train(data, "../Shared/DCT/DCT010000.data"); } if (DAT==6){ data = fann_read_train_from_file("../Shared/DCT/DCT100000.data"); // Import data remove("../Shared/DCT/DCT100000.data"); fann_shuffle_train_data(data); // Shuffle data fann_save_train(data, "../Shared/DCT/DCT100000.data"); } // Free memory fftw_free( dctdata ); fftw_free( fft_result ); fftw_destroy_plan( plan_forward ); cout<< "Computations are complete. DCT file created, Goodbye!" <<endl; return 0; }
fb209ffec7ee1b500c8e7aa34a6f79706a3732f0
69edc451cdb4bf23de322c9d8335af39d583cc82
/UVa/011764.cpp
9960499869fa80c144534d85d1086ee47c126077
[]
no_license
jesusmoraleda/competitive-programming
cbd90384641565b651ac2694f98f5d10870b83a9
97511d4fd00e90fe6676bfd134c0eb56be3c7580
refs/heads/master
2020-09-04T17:09:37.607768
2017-08-13T10:06:04
2017-08-13T10:06:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,177
cpp
#include <iostream> #include <iomanip> #include <sstream> #include <cstdlib> #include <cstdio> #include <vector> #include <queue> #include <map> #include <set> #include <stack> #include <algorithm> // max... #include <utility> // pair #include <complex> #include <climits> // int, ll... #include <limits> // double... #include <cmath> // abs, atan... #include <cstring> // memset #include <string> #include <functional> // greater, less... #include <bitset> using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef pair<ll, ll> ll_ll; typedef pair<double, double> dd; typedef vector<int> vi; typedef map<int, int> mii; typedef vector<ii> vii; typedef vector<dd> vdd; typedef vector<ll> vll; typedef vector<vi> vvi; int main() { int T; cin >> T; for (int i = 1; i <= T; i++) { int N, wall1, wall2, highs = 0, lows = 0; cin >> N; cin >> wall1; N--; while (N--) { cin >> wall2; if (wall2 > wall1) highs++; else if (wall2 < wall1) lows++; wall1 = wall2; } printf("Case %d: %d %d\n", i, highs, lows); } return 0; }
37098662b556e0dd745fe87e0eab739911aa171b
01ab791f54e388c62209ce0af66219bfbc030c3c
/250th/7/bwmaze.cpp
fdf5c4aecc1331d3521be0502a97e87af21234a7
[]
no_license
warpdev/koi-exercise-2011-2016
d2335696d33fa23bcc9a3f5f33b0a1610d530989
d948f978a6d32e2e01aa1fdf8dc272e2a4c0384a
refs/heads/master
2023-04-06T06:58:51.031574
2021-04-14T07:27:32
2021-04-14T07:27:32
357,812,551
0
0
null
null
null
null
UTF-8
C++
false
false
340
cpp
#include <stdio.h> #define N 500 FILE *fp1,*fp2; int a[N*5+1][N*5+1] int w,h,a,b,c,d; void input(void) { int i,j; fscanf(fp1,"%d %d %d %d %d %d",&w,&h,&a,&b,&c,&d); for(i=1; i<=2h+1; i++) { if(i%2==1) { for(j=1; j<=w; j++) } int main(void) { fp1=fopen("input.txt","r"); fp2=fopen("output.txt","w"); input(); return 0; }
ca0997fb5d7c8f52354978626a3d6bb54b5e10dc
e79fc7914f92f8f7ac349f65b1468deb521f2801
/Game/source/Demo7/Demo7.h
21a22be04320f0e5eb0d479b4ec7a1f75a3c3650
[]
no_license
Fabmaur/Hyperion-Engine
c8d2525f3d4ed86ce1e158efc397a957af8ec8bf
8829356b823f01449ec86de62ab88e43a20ff833
refs/heads/master
2022-02-24T15:59:26.879852
2019-04-05T08:48:29
2019-04-05T08:48:29
153,529,422
0
0
null
null
null
null
UTF-8
C++
false
false
585
h
#pragma once #include "graphics/renderer/Layer.h" #include "graphics/renderer/Shader.h" #include "graphics/renderer/Mesh.h" #include "graphics/renderer/Texture.h" #include "graphics/renderer/CameraFPS.h" #include "graphics/renderer/Renderer2D.h" #include "graphics/renderer/Text.h" class Demo7 : public graphics::Layer { /* Demo to show the event system. */ public: Demo7() = default; virtual void onEvent(EventMessage& event) override; virtual void Init() override; virtual void RunMain() override; ~Demo7(); private: graphics::Renderer2D* renderer; graphics::Text text; };
ffbbf744abd1989485ce1013514fc5c94b67d5e2
0dd9cf13c4a9e5f28ae5f36e512e86de335c26b4
/LeetCode/leetcode_max-value-of-equation.cpp
120cbf5713114f683b88fdf4ba39352670f6e40c
[]
no_license
yular/CC--InterviewProblem
908dfd6d538ccd405863c27c65c78379e91b9fd3
c271ea63eda29575a7ed4a0bce3c0ed6f2af1410
refs/heads/master
2021-07-18T11:03:07.525048
2021-07-05T16:17:43
2021-07-05T16:17:43
17,499,294
37
13
null
null
null
null
UTF-8
C++
false
false
1,058
cpp
/* * * Tag: Sliding Window + Heap (Data Structure) * Time: O(nlgn) * Space: O(n) */ class Solution { private: struct node { int id, val; bool operator < (const node &a)const{ return val < a.val; } }; public: int findMaxValueOfEquation(vector<vector<int>>& points, int k) { if(k < 1 || points.size() < 2) { return 0; } node nd; nd.id = points[0][0], nd.val = points[0][1] - points[0][0]; priority_queue<node> pq; pq.push(nd); int ans = INT_MIN; for(int i = 1; i < points.size(); ++ i) { int v = points[i][1] + points[i][0]; while(!pq.empty() && points[i][0] - pq.top().id > k) { pq.pop(); } if(!pq.empty()) { ans = max(ans, pq.top().val + v); } node nd; nd.id = points[i][0], nd.val = points[i][1] - points[i][0]; pq.push(nd); } return ans; } };
63243d5f7639407e9022cdf2ed7bfbd9580edc0b
9791a7a24160c3acacb1d0bb1b5b4453361b2151
/WinDDK/7600.16385.1/src/network/ndis/mux/notifyob/notify.h
c6a3b7663c18465a8d69d9917416f35736bc5de5
[]
no_license
kcrazy/winekit
fedc7bfa3fa702423f93447a8a19e2a4d358241e
7948f5f42a60225d9f94930be539f0a1d6202dbc
refs/heads/master
2021-01-10T08:18:48.598427
2017-02-17T05:34:15
2017-02-17T05:34:15
50,400,541
2
0
null
null
null
null
UTF-8
C++
false
false
7,513
h
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992-2001. // // File: N O T I F Y . H // // Contents: Header file for sample notify object. // // Notes: // // Author: Alok Sinha // //---------------------------------------------------------------------------- #ifndef NOTIFY_H_INCLUDE #define NOTIFY_H_INCLUDE #include <windows.h> #include <atlbase.h> extern CComModule _Module; // required by atlcom.h #include <atlcom.h> #include <devguid.h> #include <setupapi.h> #include <notifyn.h> #include "list.h" #include "adapter.h" #include "resource.h" #include "common.h" // // CMuxNotify Object - Base class for the entire notify object // class CMuxNotify : // // Must inherit from CComObjectRoot(Ex) for reference count // management and default threading model. // public CComObjectRoot, // // Define the default class factory and aggregation model. // public CComCoClass<CMuxNotify, &CLSID_CMuxNotify>, // // Notify Object's interfaces. // public INetCfgComponentControl, public INetCfgComponentSetup, public INetCfgComponentPropertyUi, public INetCfgComponentNotifyBinding, public INetCfgComponentNotifyGlobal { // // Public members. // public: // // Constructor // CMuxNotify(VOID); // // Destructors. // ~CMuxNotify(VOID); // // Notify Object's interfaces. // BEGIN_COM_MAP(CMuxNotify) COM_INTERFACE_ENTRY(INetCfgComponentControl) COM_INTERFACE_ENTRY(INetCfgComponentSetup) COM_INTERFACE_ENTRY(INetCfgComponentPropertyUi) COM_INTERFACE_ENTRY(INetCfgComponentNotifyBinding) COM_INTERFACE_ENTRY(INetCfgComponentNotifyGlobal) END_COM_MAP() // // Uncomment the the line below if you don't want your object to // support aggregation. The default is to support it // // DECLARE_NOT_AGGREGATABLE(CMuxNotify) // DECLARE_REGISTRY_RESOURCEID(IDR_REG_SAMPLE_NOTIFY) // // INetCfgComponentControl // STDMETHOD (Initialize) ( IN INetCfgComponent *pIComp, IN INetCfg *pINetCfg, IN BOOL fInstalling); STDMETHOD (CancelChanges) (); STDMETHOD (ApplyRegistryChanges) (); STDMETHOD (ApplyPnpChanges) ( IN INetCfgPnpReconfigCallback* pICallback); // // INetCfgComponentSetup // STDMETHOD (Install) ( IN DWORD dwSetupFlags); STDMETHOD (Upgrade) ( IN DWORD dwSetupFlags, IN DWORD dwUpgradeFromBuildNo); STDMETHOD (ReadAnswerFile) ( IN PCWSTR szAnswerFile, IN PCWSTR szAnswerSections); STDMETHOD (Removing) (); // // INetCfgComponentPropertyUi // STDMETHOD (QueryPropertyUi) ( IN IUnknown* pUnk); STDMETHOD (SetContext) ( IN IUnknown* pUnk); STDMETHOD (MergePropPages) ( IN OUT DWORD* pdwDefPages, OUT LPBYTE* pahpspPrivate, OUT UINT* pcPrivate, IN HWND hwndParent, OUT PCWSTR* pszStartPage); STDMETHOD (ValidateProperties) ( HWND hwndSheet); STDMETHOD (CancelProperties) (); STDMETHOD (ApplyProperties) (); // // INetCfgNotifyBinding // STDMETHOD (QueryBindingPath) ( IN DWORD dwChangeFlag, IN INetCfgBindingPath* pncbp); STDMETHOD (NotifyBindingPath) ( IN DWORD dwChangeFlag, IN INetCfgBindingPath* pncbp); // // INetCfgNotifyGlobal // STDMETHOD (GetSupportedNotifications) ( OUT DWORD* pdwNotificationFlag ); STDMETHOD (SysQueryBindingPath) ( IN DWORD dwChangeFlag, IN INetCfgBindingPath* pncbp); STDMETHOD (SysNotifyBindingPath) ( IN DWORD dwChangeFlag, IN INetCfgBindingPath* pncbp); STDMETHOD (SysNotifyComponent) ( IN DWORD dwChangeFlag, IN INetCfgComponent* pncc); // // Private members. // private: // // Private member variables. // INetCfgComponent *m_pncc; // Protocol's Net Config component INetCfg *m_pnc; ConfigAction m_eApplyAction; IUnknown* m_pUnkContext; // // List of physical adapters currently installed. // List<CMuxPhysicalAdapter *, GUID> m_AdaptersList; // // List of physical adapters to be removed. // List<CMuxPhysicalAdapter *, GUID> m_AdaptersToRemove; // // List of physical adapters to be added. // List<CMuxPhysicalAdapter *, GUID> m_AdaptersToAdd; // // Private member functions. // HRESULT HrLoadAdapterConfiguration (VOID); HRESULT HrGetUpperAndLower (INetCfgBindingPath* pncbp, INetCfgComponent **ppnccUpper, INetCfgComponent **ppnccLower); HRESULT HrAddAdapter (INetCfgComponent *pnccAdapter); HRESULT HrRemoveAdapter (INetCfgComponent *pnccAdapter); HRESULT HrAddMiniport (CMuxPhysicalAdapter *pAdapter, GUID *guidAdapter); HRESULT HrRemoveMiniport (CMuxPhysicalAdapter *pAdapter, GUID *guidAdapter); #ifdef DISABLE_PROTOCOLS_TO_PHYSICAL VOID EnableBindings (INetCfgComponent *pnccAdapter, BOOL bEnable); BOOL IfExistMux (INetCfgBindingPath *pncbp); HRESULT HrGetBindingPathEnum (INetCfgComponent *pnccAdapter, DWORD dwBindingType, IEnumNetCfgBindingPath **ppencbp); HRESULT HrGetBindingPath (IEnumNetCfgBindingPath *pencbp, INetCfgBindingPath **ppncbp); HRESULT HrGetBindingInterfaceEnum (INetCfgBindingPath *pncbp, IEnumNetCfgBindingInterface **ppencbi); HRESULT HrGetBindingInterface (IEnumNetCfgBindingInterface *pencbi, INetCfgBindingInterface **ppncbi); #endif public: LRESULT OnInitDialog (IN HWND hWnd); LRESULT OnOk (IN HWND hWnd); LRESULT OnCancel (IN HWND hWnd); }; INT_PTR CALLBACK NotifyDialogProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); UINT CALLBACK NotifyPropSheetPageProc (HWND hWnd, UINT uMsg, LPPROPSHEETPAGE ppsp); #endif // NOTIFY_H_INCLUDE
e1bcf65ed35329da87f9cb80946b058464d57d8c
2c4498b999b205e457c4d60d4e8426316e9f89a6
/aaa.cpp
517331fac8a7f6adb251e676159a33cd87ce9322
[]
no_license
wsnbb163/text
e4be6339fc994540b114bc4cd67795b7192ad17f
993eb30b928c38c7581b93f6b8c77171ddf02d58
refs/heads/master
2021-01-10T19:31:21.296452
2015-07-22T03:04:07
2015-07-22T03:04:07
39,482,424
0
0
null
null
null
null
UTF-8
C++
false
false
22
cpp
asgduiagdsagvcbhgdasjg
720b6489ed29c52d7fbcf12ef8f8fe2918159c34
959190a719f81a4dee1a50a3a47ddae2cbd010f9
/Source/ShooterGame/Private/UI/Widgets/SChatWidget.cpp
2f7cea46f1ce5e39e0e61ab6304f71e90d5575ce
[]
no_license
denfrost/UE4ShooterGame
ba0c0b4ed88bc4da09138e1204a0e3cbbfba7911
6c68cb097fdcff86878279b8bda91b7bb521722f
refs/heads/master
2020-03-26T05:14:21.439512
2018-03-26T11:57:10
2018-03-26T12:02:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,359
cpp
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "ShooterGame.h" #include "SChatWidget.h" #include "ShooterStyle.h" #include "ShooterChatWidgetStyle.h" #define CHAT_BOX_WIDTH 576.0f #define CHAT_BOX_HEIGHT 192.0f #define CHAT_BOX_PADDING 20.0f void SChatWidget::Construct(const FArguments& InArgs, const FLocalPlayerContext& InContext) { ShooterHUDPCTrackerBase::Init(InContext); ChatStyle = &FShooterStyle::Get().GetWidgetStyle<FShooterChatStyle>("DefaultShooterChatStyle"); bAlwaysVisible = InArgs._bAlwaysVisible; bDismissAfterSay = InArgs._bDismissAfterSay; ChatFadeTime = 10.0; LastChatLineTime = -1.0; bVisibiltyNeedsFocus = true; //some constant values const int32 PaddingValue = 2; // Copy the font we'll be using for chat, and limit the font fallback to localized only, for performance reasons ChatFont = FShooterStyle::Get().GetFontStyle("ShooterGame.ChatFont"); ChatFont.FontFallback = EFontFallback::FF_LocalizedFallback; // Initialize Menu ChildSlot .HAlign(HAlign_Left) .VAlign(VAlign_Center) [ SNew(SVerticalBox) + SVerticalBox::Slot() // The main background .AutoHeight() [ SNew(SBorder) .BorderImage(&ChatStyle->BackingBrush) .Padding(FMargin(CHAT_BOX_PADDING, 16.0f, CHAT_BOX_PADDING, 24.0f)) .BorderBackgroundColor(this, &SChatWidget::GetBorderColor) [ SNew(SBox) .HeightOverride(CHAT_BOX_HEIGHT) .WidthOverride(CHAT_BOX_WIDTH) [ SAssignNew(ChatHistoryListView, SListView< TSharedPtr<FChatLine> >) .SelectionMode(ESelectionMode::None) .ListItemsSource(&ChatHistory) .OnGenerateRow(this, &SChatWidget::GenerateChatRow) ] ] ] // Chat input + SVerticalBox::Slot() .AutoHeight() [ SNew(SBox) .WidthOverride(CHAT_BOX_WIDTH) .Padding(FMargin(11.0f, 0.0f)) [ SAssignNew(ChatEditBox, SEditableTextBox) .OnTextCommitted(this, &SChatWidget::OnChatTextCommitted) .MinDesiredWidth(CHAT_BOX_WIDTH) .ClearKeyboardFocusOnCommit(false) .HintText(NSLOCTEXT("ChatWidget", "SaySomething", "Say Something...")) .Font(ChatFont) .Style(&ChatStyle->TextEntryStyle) ] ] ]; // Setup visibilty LastVisibility = bAlwaysVisible ? EVisibility::Visible : EVisibility::Hidden; SetEntryVisibility( LastVisibility ); } FSlateColor SChatWidget::GetBorderColor() const { return GetStyleColor(ChatStyle->BoxBorderColor.GetSpecifiedColor()); } FSlateColor SChatWidget::GetChatLineColor() const { return GetStyleColor(ChatStyle->TextColor.GetSpecifiedColor()); } FSlateColor SChatWidget::GetStyleColor( const FLinearColor& InColor ) const { const double EndTime = LastChatLineTime + ChatFadeTime; const double CurrentTime = FSlateApplication::Get().GetCurrentTime(); // Get the requested color.on FLinearColor ReturnColor = InColor; // Set the alpha to zero if we are not visible. (We could also fade out here if the time has ALMOST expired). if (bAlwaysVisible == false) { if ((ChatEditBox->GetVisibility() == EVisibility::Hidden) || (CurrentTime > EndTime)) { ReturnColor.A = 0.0f; } } return FSlateColor( ReturnColor ); } void SChatWidget::AddChatLine(const FText& ChatString, bool SetFocus) { ChatHistory.Add(MakeShareable(new FChatLine(ChatString))); if(ChatHistoryListView.IsValid()) { FChatLine* LastLine = ChatHistory[ChatHistory.Num() - 1].Get(); UE_LOG(LogOnline, Warning, TEXT("request scroll last=%s"), *LastLine->ChatString.ToString()); ChatHistoryListView->RequestScrollIntoView(ChatHistory[ChatHistory.Num() - 1]); } FSlateApplication::Get().PlaySound(ChatStyle->RxMessgeSound); SetEntryVisibility( EVisibility::Visible ); bVisibiltyNeedsFocus = SetFocus; } EVisibility SChatWidget::GetEntryVisibility() const { return ChatEditBox->GetVisibility(); } void SChatWidget::SetEntryVisibility( TAttribute<EVisibility> InVisibility ) { // If we are making it visible reset the 'start' time if( InVisibility.Get() == EVisibility::Visible ) { LastChatLineTime = FSlateApplication::Get().GetCurrentTime(); } ChatEditBox->SetVisibility(InVisibility); ChatHistoryListView->SetVisibility(InVisibility); SetVisibility(InVisibility); } void SChatWidget::OnChatTextCommitted(const FText& InText, ETextCommit::Type InCommitInfo) { if (InCommitInfo == ETextCommit::OnEnter) { if (GetPlayerController().IsValid() && !InText.IsEmpty()) { // broadcast chat to other players GetPlayerController()->Say(InText.ToString()); if(ChatEditBox.IsValid()) { // Add the string so we see it too (we will ignore our own strings in the receive function) AddChatLine( InText, true ); // Clear the text ChatEditBox->SetText(FText()); // Audible indication we sent a message FSlateApplication::Get().PlaySound(ChatStyle->TxMessgeSound); } } } // If we want to dismiss chat after say, and we are not always visible, hide it now. if ((bAlwaysVisible == false) && ( bDismissAfterSay == true ) ) { SetEntryVisibility(EVisibility::Hidden); } } void SChatWidget::Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime ) { // Always tick the super. SCompoundWidget::Tick( AllottedGeometry, InCurrentTime, InDeltaTime ); // If we have not got the keep visible flag set, and the fade time has expired hide the widget const double CurrentTime = FSlateApplication::Get().GetCurrentTime(); if( ( bAlwaysVisible == false ) && ( CurrentTime > ( LastChatLineTime + ChatFadeTime ) ) ) { if (LastVisibility != EVisibility::Hidden) { SetEntryVisibility(EVisibility::Hidden); } LastVisibility = GetEntryVisibility(); } // Update the visibility. if (GetEntryVisibility() != LastVisibility) { LastVisibility = GetEntryVisibility(); if (LastVisibility == EVisibility::Visible) { // Enter UI mode FSlateApplication::Get().SetKeyboardFocus( SharedThis(this) ); if (ChatEditBox.IsValid()) { FWidgetPath WidgetToFocusPath; bool bFoundPath = FSlateApplication::Get().FindPathToWidget(ChatEditBox.ToSharedRef(), WidgetToFocusPath); if (bFoundPath && WidgetToFocusPath.IsValid() && bVisibiltyNeedsFocus == true ) { FSlateApplication::Get().SetKeyboardFocus(WidgetToFocusPath, EFocusCause::SetDirectly); } } } else { // Exit UI mode FSlateApplication::Get().SetAllUserFocusToGameViewport(); } } FSlateApplication::Get().GetPlatformApplication().Get()->Cursor->SetType(EMouseCursor::None); } FReply SChatWidget::OnFocusReceived( const FGeometry& MyGeometry, const FFocusEvent& InFocusEvent ) { return FReply::Handled().ReleaseMouseCapture().LockMouseToWidget( SharedThis( this ) ); } TSharedRef<ITableRow> SChatWidget::GenerateChatRow(TSharedPtr<FChatLine> ChatLine, const TSharedRef<STableViewBase>& OwnerTable) { return SNew(STableRow< TSharedPtr< FChatLine> >, OwnerTable ) [ SNew(STextBlock) .Text(ChatLine->ChatString) .Font(ChatFont) .ColorAndOpacity(this, &SChatWidget::GetChatLineColor) .WrapTextAt(CHAT_BOX_WIDTH - CHAT_BOX_PADDING) ]; } TSharedRef<SWidget> SChatWidget::AsWidget() { return SharedThis(this); }
a1d5b7205c1a8f7c41dc9d47d747d34ccb54a4fe
c03bf1c42039e3ef9af073328f199546d26db146
/BackuleleBluetooth.ino
4da7ba09f31c08abffb64d4e0f26ee80c4052d94
[]
no_license
trunk-studio/backulele-arduino
e74a73794307d07014fc3636ab11e38363db59c9
eedb978ba6c4f83a3b585fa089ada9c287f1b476
refs/heads/master
2021-01-20T21:11:54.082538
2016-07-31T07:55:13
2016-07-31T07:55:13
64,583,150
0
0
null
null
null
null
UTF-8
C++
false
false
430
ino
#include <SoftwareSerial.h> SoftwareSerial BT(10, 11); //RX, TX void setup() { // pinMode(9, OUTPUT); // digitalWrite(8, HIGH); Serial.begin(9600); Serial.println("Bluetooth ready to go."); //Options: 115200, 38400, 9600 BT.begin(9600); } void loop() { if (BT.available()) { Serial.write(BT.read()); //Serial.println(char(BT.read())); } if (Serial.available()) { BT.write(Serial.read()); } }
b204375426954ad8e34771811bdd250c2d3e26be
0c7dba57fe7c76634d4776d8d3969d159ab845eb
/practice/17/gen.cpp
ce45062278c739bf6a509008ad61f0fe4a2c928f
[]
no_license
ccwu0918/JG-testdata
093511152a98a1038b3ecde3249f19ea8b3a4861
4ce2ec45560e18d2c1829d0bb71643b21dd565f4
refs/heads/master
2022-04-03T09:13:50.517843
2016-01-13T05:49:52
2016-01-13T05:49:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
#include <bits/stdc++.h> using namespace std; int main() { srand(time(NULL)); int n = rand()%100+1, m = rand()%100+1; printf("%d %d\n", n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int x = rand()%1000 + 1; printf("%d%c", x, i == m-1 ? '\n' : ' '); } } return 0; }
902ad7ee3a503ad05eed36aa11177d875f768ca1
b392c81ac2462ef8c06c89e56630e5f3e3d46b65
/GALPROP_56.0.2870_Source/source/store_bremss_HIR_skymap.cc
e33b9a0152ead19982768fff8e11b2970d65e97b
[]
no_license
sadkoeni/galprop
a577cde365008297dca13b241b1ce3ebff60a124
002838850041b2d560a0926e2bf810acc433e6ee
refs/heads/master
2023-01-08T22:38:59.428165
2020-11-16T15:08:39
2020-11-16T15:08:39
312,309,109
0
1
null
null
null
null
UTF-8
C++
false
false
2,928
cc
#include <cassert> #include <string> #include <cstring> #include <valarray> using namespace std;//AWS20050624 #include "galprop_classes.h" #include "galprop_internal.h" #include "fitsio.h" #include <ErrorLogger.h> #include <BaseSkyFitsIO.h> int Galprop::store_bremss_HIR_skymap() { INFO("Entry"); int status = 0; if (3 == galdef.skymap_format) { char index[3]; string fileprefix = configure.fOutputDirectory + configure.fOutputPrefix; fileprefix += "bremss_HIR_ring_"; for (int i_Ring=0; i_Ring<galaxy.n_Ring; i_Ring++){ sprintf(index, "%d", i_Ring+1); string filename = fileprefix + index; filename += "_healpix_"; filename += galdef.galdef_ID; filename += ".gz"; SM::writeToFits(*galaxy.bremss_HIR_hp_skymap[i_Ring], filename, true, true, "Energy", "MeV"); } }else{ //fitsfile *fptr; // pointer to the FITS file; defined in fitsio.h int status, ii, jj; long nelements; long naxes[4]; double crval[4], cdelt[4]; naxes[0]=galaxy.n_long; naxes[1]=galaxy.n_lat; naxes[2]=galaxy.bremss_HIR_skymap.n_zgrid; // number of Galactocentric rings naxes[3]=galaxy.n_E_gammagrid; nelements=naxes[0]*naxes[1]*naxes[2]*naxes[3]; valarray<float> array(0., nelements); if (galdef.skymap_format != 1){ //!< Old output int i=0; for (int ip =0; ip <naxes[3]; ip++) for (int i_Ring =0; i_Ring <naxes[2]; i_Ring++) for (int ib =0; ib <naxes[1]; ib++) for (int il =0; il <naxes[0]; il++) { array[i]=0.0; array[i]+=galaxy.bremss_HIR_skymap .d3[il][ib][i_Ring].s[ip] *pow(galaxy.E_gamma[ip],2); i++; } crval[0]=galaxy.long_min; crval[1]=galaxy. lat_min; crval[2]=0; //IMOS20080114 crval[3]=log10(galaxy.E_gamma_min); cdelt[0]=galaxy.d_long; cdelt[1]=galaxy.d_lat; cdelt[2]=1; cdelt[3]=log10(galaxy.E_gamma_factor); //Use the standard method to store the skymap status = store_skymap(&array[0], naxes, "bremss_HIR_skymap_", crval, cdelt); } if(galdef.skymap_format == 1 || galdef.skymap_format == 2){ //!< Mapcube output compatable with Glast science tools int i=0; for (int i_Ring =0; i_Ring <naxes[2]; i_Ring++) for (int ip =0; ip <naxes[3]; ip++) // IMOS20080114 for (int ib =0; ib <naxes[1]; ib++) for (int il =0; il <naxes[0]; il++) { array[i]=galaxy.bremss_HIR_skymap .d3[il][ib][i_Ring].s[ip]; i++; } status = store_mapcube_skymap(&array[0], &galaxy.E_gamma[0], galaxy.bremss_HIR_skymap.n_zgrid, galaxy.n_E_gammagrid, "bremss_HIR_mapcube_", true); } } INFO("Exit"); return status; }
71367c5ee1d455869fa46f6b7357c0f94a0b5b38
74212aa37999516a0aeba7ba1e71620a217f8e9d
/GameDemonstrator/helper/MapToVectorSorter.cpp
4f5ef314a9711cb0cab7ced0ad16a18b52d14a3c
[]
no_license
raubwuerger/StrategicGameProject
21729192518baa541f2c74f35cb0558a64292c2b
ce3e4c31383c44809e970996091067b94602fd92
refs/heads/master
2022-04-30T18:31:55.283915
2021-11-08T19:14:43
2021-11-08T19:14:43
19,796,707
0
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
#include "stdafx.h" #include "MapToVectorSorter.h" #include <algorithm> #include <functional> std::vector<float> MapToVectorSorter::TransformAndSort(std::vector< std::vector<float> >& map) { std::vector<float> unsortedVector; for (int rowIndex = 0; rowIndex < map.size(); rowIndex++) { for (int colIndex = 0; colIndex < map[rowIndex].size(); colIndex++) { unsortedVector.push_back(map[rowIndex][colIndex]); } } std::sort(unsortedVector.begin(), unsortedVector.end(), std::less<float>()); return unsortedVector; }
0a0d586fb7c0bd5abe72acbb030ec01ba2839116
cb3ccc721b48175edffd8136738d8ce10fa1a9c2
/src/engine/model/obj.cpp
93538fb0a4aa955fe4e467ffe3d2e82ee1bb5acf
[ "BSD-3-Clause" ]
permissive
stuhacking/SGEngine-Cpp
3dc9aae7a16a926b47e28c9e10f8142a4d8d33cc
bf531b7ba02a20a2c0d756f6422b68461095664a
refs/heads/master
2020-12-20T22:34:35.779695
2018-04-26T08:49:05
2018-04-27T15:53:54
48,138,333
1
0
null
null
null
null
UTF-8
C++
false
false
6,763
cpp
// // Wavefront .obj Importer // #include "../engine.h" #include <iostream> #include <fstream> namespace sge { static inline void logParseError (const std::string &file, const u32 line, const std::string &el) { gConsole.errorf("Malformed %s in %s at line: %u.\n", el.c_str(), file.c_str(), line); } bool ObjDocument::readFromFile (const char * const filename) { std::ifstream input(filename); if (!input) { gConsole.errorf("File not found -- %s.\n", filename); return false; } std::string line; u32 lineNumber = 1; while (std::getline(input, line)) { // Skip comments & blank lines if (line.size() > 1 && !str::startsWith(line, "#")) { std::vector<std::string> tokens = str::split(str::trim(line)); if ("o" == tokens[0] && !parseName(tokens)) { logParseError(filename, lineNumber, "object name"); return false; } if ("g" == tokens[0] && !parseGroup(tokens)) { logParseError(filename, lineNumber, "group name"); return false; } if ("v" == tokens[0] && !parsePosition(tokens)) { logParseError(filename, lineNumber, "vertex position"); return false; } if ("vn" == tokens[0] && !parseNormal(tokens)) { logParseError(filename, lineNumber, "normal"); return false; } if ("vt" == tokens[0] && !parseTexCoord(tokens)) { logParseError(filename, lineNumber, "texture coordinate"); return false; } if ("f" == tokens[0] && !parseFace(tokens)) { logParseError(filename, lineNumber, "face"); return false; } } ++lineNumber; } return true; } bool ObjDocument::parseName (const std::vector<std::string> &tokens) { if (tokens.size() > 1) { name = tokens[1]; return true; } return false; } bool ObjDocument::parseGroup (const std::vector<std::string> &tokens) { if (tokens.size() >= 2) { groups.emplace_back(ObjGroup(tokens[1])); return true; } else { groups.emplace_back(ObjGroup("name.")); return false; } } bool ObjDocument::parsePosition (const std::vector<std::string> &tokens) { if (tokens.size() >= 4) { float x = std::stof(tokens[1]); float y = std::stof(tokens[2]); float z = std::stof(tokens[3]); mPositions.emplace_back(x, y, z); return true; } else { mPositions.emplace_back(0.0f, 0.0f, 0.0f); return false; } } bool ObjDocument::parseNormal (const std::vector<std::string> &tokens) { mHasNormals = true; if (tokens.size() >= 4) { float x = std::stof(tokens[1]); float y = std::stof(tokens[2]); float z = std::stof(tokens[3]); mNormals.emplace_back(x, y, z); return true; } else { mNormals.emplace_back(0.0f, 0.0f, 0.0f); return false; } } bool ObjDocument::parseTexCoord (const std::vector<std::string> &tokens) { mHasTexture = true; if (tokens.size() >= 3) { float x = std::stof(tokens[1]); float y = std::stof(tokens[2]); mTexCoords.emplace_back(x, y); return true; } else { mTexCoords.emplace_back(0.0f, 0.0f); return false; } } bool ObjDocument::parseFace (const std::vector<std::string> &tokens) { // Make sure we have at least one group by the time we // start parsing faces. if (groups.empty()) { groups.emplace_back(ObjGroup("default")); } if (tokens.size() < 4) { return false; } // Add new faces to the most recent group. ObjGroup *curGroup = &groups.back(); // Convert n-sided faces to tris as we go. for (std::vector<std::string>::size_type k = 3, kMax = tokens.size(); k < kMax; ++k) { std::vector<std::string> indices[3]; indices[0] = str::split(tokens[1], '/'); indices[1] = str::split(tokens[k - 1], '/'); indices[2] = str::split(tokens[k], '/'); curGroup->positionIndex.emplace_back(std::stoi(indices[0][0]) - 1); curGroup->positionIndex.emplace_back(std::stoi(indices[1][0]) - 1); curGroup->positionIndex.emplace_back(std::stoi(indices[2][0]) - 1); if (mHasTexture) { curGroup->textureIndex.emplace_back(indices[0][1].empty() ? 0 : std::stoi(indices[0][1]) - 1); curGroup->textureIndex.emplace_back(indices[1][1].empty() ? 0 : std::stoi(indices[1][1]) - 1); curGroup->textureIndex.emplace_back(indices[2][1].empty() ? 0 : std::stoi(indices[2][1]) - 1); } if (mHasNormals) { curGroup->normalIndex.emplace_back(indices[0][2].empty() ? 0 : std::stoi(indices[0][2]) - 1); curGroup->normalIndex.emplace_back(indices[1][2].empty() ? 0 : std::stoi(indices[1][2]) - 1); curGroup->normalIndex.emplace_back(indices[2][2].empty() ? 0 : std::stoi(indices[2][2]) - 1); } } return true; } // -------------------------------------------------------------------------- Mesh meshFromObjDocument (const ObjDocument &doc) { Mesh m; if (doc.isValid()) { for (const auto &g : doc.groups) { for (size_t k = 2, kMax = g.vertexCount(); k < kMax; k += 3) { Vec3f p1, p2, p3; Vec3f n1, n2, n3; Vec2f t1, t2, t3; p1 = doc.position(g.positionIndex[k - 2]); p2 = doc.position(g.positionIndex[k - 1]); p3 = doc.position(g.positionIndex[k]); if (doc.hasNormals()) { n1 = doc.normal(g.normalIndex[k - 2]); n2 = doc.normal(g.normalIndex[k - 1]); n3 = doc.normal(g.normalIndex[k]); } if (doc.hasTexture()) { t1 = doc.texCoord(g.textureIndex[k - 2]); t2 = doc.texCoord(g.textureIndex[k - 1]); t3 = doc.texCoord(g.textureIndex[k]); } const Color col = Color(255, 255, 255, 255); m.autoFace(Vertex(p1, n1, t1, col), Vertex(p2, n2, t2, col), Vertex(p3, n3, t3, col)); } } } else { gConsole.errorf("ObjDocument is invalid -- %s\n", doc.name.c_str()); } return m; } Mesh meshFromObjDocument (const char * const filename) { ObjDocument doc = ObjDocument(filename); return meshFromObjDocument(doc); } } /* namespace sge */
f414216741659265a978489577479f4a98d62ab3
12f441018818dc2dcb1a8a89bccd946d87e0ac9e
/cppwinrt/winrt/Windows.UI.Xaml.Core.Direct.h
96588a212df795d1d96dc70b4ec22280ae70da8c
[ "MIT" ]
permissive
dlech/bleak-winrt
cc7dd76fca9453b7415d65a428e22b2cbfe36209
a6c1f3fd073a7b5678304ea6bc08b9b067544320
refs/heads/main
2022-09-12T00:15:01.497572
2022-09-09T22:57:53
2022-09-09T22:57:53
391,440,675
10
1
null
null
null
null
UTF-8
C++
false
false
60,384
h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.220608.4 #pragma once #ifndef WINRT_Windows_UI_Xaml_Core_Direct_H #define WINRT_Windows_UI_Xaml_Core_Direct_H #include "winrt/base.h" static_assert(winrt::check_version(CPPWINRT_VERSION, "2.0.220608.4"), "Mismatched C++/WinRT headers."); #define CPPWINRT_VERSION "2.0.220608.4" #include "winrt/Windows.UI.Xaml.h" #include "winrt/impl/Windows.Foundation.2.h" #include "winrt/impl/Windows.UI.2.h" #include "winrt/impl/Windows.UI.Xaml.2.h" #include "winrt/impl/Windows.UI.Xaml.Media.2.h" #include "winrt/impl/Windows.UI.Xaml.Media.Media3D.2.h" #include "winrt/impl/Windows.UI.Xaml.Core.Direct.2.h" namespace winrt::impl { template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetObject(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject) const { void* result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetObject(*(void**)(&xamlDirectObject), &result)); return winrt::Windows::Foundation::IInspectable{ result, take_ownership_from_abi }; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetXamlDirectObject(winrt::Windows::Foundation::IInspectable const& object) const { void* result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetXamlDirectObject(*(void**)(&object), &result)); return winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject{ result, take_ownership_from_abi }; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::CreateInstance(winrt::Windows::UI::Xaml::Core::Direct::XamlTypeIndex const& typeIndex) const { void* result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->CreateInstance(static_cast<int32_t>(typeIndex), &result)); return winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject{ result, take_ownership_from_abi }; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetObjectProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::Foundation::IInspectable const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetObjectProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), *(void**)(&value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetXamlDirectObjectProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetXamlDirectObjectProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), *(void**)(&value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetBooleanProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, bool value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetBooleanProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), value)); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetDoubleProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, double value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetDoubleProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), value)); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetInt32Property(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, int32_t value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetInt32Property(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), value)); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetStringProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, param::hstring const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetStringProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), *(void**)(&value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetDateTimeProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::Foundation::DateTime const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetDateTimeProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetPointProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::Foundation::Point const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetPointProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetRectProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::Foundation::Rect const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetRectProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetSizeProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::Foundation::Size const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetSizeProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetTimeSpanProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::Foundation::TimeSpan const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetTimeSpanProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetColorProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::UI::Color const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetColorProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetCornerRadiusProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::UI::Xaml::CornerRadius const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetCornerRadiusProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetDurationProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::UI::Xaml::Duration const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetDurationProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetGridLengthProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::UI::Xaml::GridLength const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetGridLengthProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetThicknessProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::UI::Xaml::Thickness const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetThicknessProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetMatrixProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::UI::Xaml::Media::Matrix const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetMatrixProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetMatrix3DProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, winrt::Windows::UI::Xaml::Media::Media3D::Matrix3D const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetMatrix3DProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), impl::bind_in(value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::SetEnumProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex, uint32_t value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->SetEnumProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), value)); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetObjectProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { void* result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetObjectProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), &result)); return winrt::Windows::Foundation::IInspectable{ result, take_ownership_from_abi }; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetXamlDirectObjectProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { void* result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetXamlDirectObjectProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), &result)); return winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject{ result, take_ownership_from_abi }; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetBooleanProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { bool result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetBooleanProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), &result)); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetDoubleProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { double result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetDoubleProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), &result)); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetInt32Property(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { int32_t result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetInt32Property(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), &result)); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetStringProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { void* result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetStringProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), &result)); return hstring{ result, take_ownership_from_abi }; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetDateTimeProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::Foundation::DateTime result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetDateTimeProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetPointProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::Foundation::Point result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetPointProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetRectProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::Foundation::Rect result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetRectProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetSizeProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::Foundation::Size result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetSizeProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetTimeSpanProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::Foundation::TimeSpan result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetTimeSpanProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetColorProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::UI::Color result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetColorProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetCornerRadiusProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::UI::Xaml::CornerRadius result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetCornerRadiusProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetDurationProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::UI::Xaml::Duration result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetDurationProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetGridLengthProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::UI::Xaml::GridLength result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetGridLengthProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetThicknessProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::UI::Xaml::Thickness result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetThicknessProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetMatrixProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::UI::Xaml::Media::Matrix result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetMatrixProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetMatrix3DProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { winrt::Windows::UI::Xaml::Media::Media3D::Matrix3D result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetMatrix3DProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), put_abi(result))); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetEnumProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { uint32_t result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetEnumProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex), &result)); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::ClearProperty(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const& propertyIndex) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->ClearProperty(*(void**)(&xamlDirectObject), static_cast<int32_t>(propertyIndex))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetCollectionCount(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject) const { uint32_t result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetCollectionCount(*(void**)(&xamlDirectObject), &result)); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::GetXamlDirectObjectFromCollectionAt(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, uint32_t index) const { void* result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->GetXamlDirectObjectFromCollectionAt(*(void**)(&xamlDirectObject), index, &result)); return winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject{ result, take_ownership_from_abi }; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::AddToCollection(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->AddToCollection(*(void**)(&xamlDirectObject), *(void**)(&value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::InsertIntoCollectionAt(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, uint32_t index, winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& value) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->InsertIntoCollectionAt(*(void**)(&xamlDirectObject), index, *(void**)(&value))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::RemoveFromCollection(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& value) const { bool result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->RemoveFromCollection(*(void**)(&xamlDirectObject), *(void**)(&value), &result)); return result; } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::RemoveFromCollectionAt(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, uint32_t index) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->RemoveFromCollectionAt(*(void**)(&xamlDirectObject), index)); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::ClearCollection(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->ClearCollection(*(void**)(&xamlDirectObject))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::AddEventHandler(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlEventIndex const& eventIndex, winrt::Windows::Foundation::IInspectable const& handler) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->AddEventHandler(*(void**)(&xamlDirectObject), static_cast<int32_t>(eventIndex), *(void**)(&handler))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::AddEventHandler(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlEventIndex const& eventIndex, winrt::Windows::Foundation::IInspectable const& handler, bool handledEventsToo) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->AddEventHandler_HandledEventsToo(*(void**)(&xamlDirectObject), static_cast<int32_t>(eventIndex), *(void**)(&handler), handledEventsToo)); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirect<D>::RemoveEventHandler(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const& xamlDirectObject, winrt::Windows::UI::Xaml::Core::Direct::XamlEventIndex const& eventIndex, winrt::Windows::Foundation::IInspectable const& handler) const { check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect)->RemoveEventHandler(*(void**)(&xamlDirectObject), static_cast<int32_t>(eventIndex), *(void**)(&handler))); } template <typename D> auto consume_Windows_UI_Xaml_Core_Direct_IXamlDirectStatics<D>::GetDefault() const { void* result{}; check_hresult(WINRT_IMPL_SHIM(winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectStatics)->GetDefault(&result)); return winrt::Windows::UI::Xaml::Core::Direct::XamlDirect{ result, take_ownership_from_abi }; } #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect> : produce_base<D, winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect> { int32_t __stdcall GetObject(void* xamlDirectObject, void** result) noexcept final try { clear_abi(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::Foundation::IInspectable>(this->shim().GetObject(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetXamlDirectObject(void* object, void** result) noexcept final try { clear_abi(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject>(this->shim().GetXamlDirectObject(*reinterpret_cast<winrt::Windows::Foundation::IInspectable const*>(&object))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall CreateInstance(int32_t typeIndex, void** result) noexcept final try { clear_abi(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject>(this->shim().CreateInstance(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlTypeIndex const*>(&typeIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetObjectProperty(void* xamlDirectObject, int32_t propertyIndex, void* value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetObjectProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::Foundation::IInspectable const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetXamlDirectObjectProperty(void* xamlDirectObject, int32_t propertyIndex, void* value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetXamlDirectObjectProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetBooleanProperty(void* xamlDirectObject, int32_t propertyIndex, bool value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetBooleanProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), value); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetDoubleProperty(void* xamlDirectObject, int32_t propertyIndex, double value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetDoubleProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), value); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetInt32Property(void* xamlDirectObject, int32_t propertyIndex, int32_t value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetInt32Property(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), value); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetStringProperty(void* xamlDirectObject, int32_t propertyIndex, void* value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetStringProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<hstring const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetDateTimeProperty(void* xamlDirectObject, int32_t propertyIndex, int64_t value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetDateTimeProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::Foundation::DateTime const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetPointProperty(void* xamlDirectObject, int32_t propertyIndex, winrt::Windows::Foundation::Point value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetPointProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::Foundation::Point const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetRectProperty(void* xamlDirectObject, int32_t propertyIndex, winrt::Windows::Foundation::Rect value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetRectProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::Foundation::Rect const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetSizeProperty(void* xamlDirectObject, int32_t propertyIndex, winrt::Windows::Foundation::Size value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetSizeProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::Foundation::Size const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetTimeSpanProperty(void* xamlDirectObject, int32_t propertyIndex, int64_t value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetTimeSpanProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::Foundation::TimeSpan const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetColorProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Color value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetColorProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::UI::Color const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetCornerRadiusProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_CornerRadius value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetCornerRadiusProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::UI::Xaml::CornerRadius const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetDurationProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_Duration value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetDurationProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::UI::Xaml::Duration const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetGridLengthProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_GridLength value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetGridLengthProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::UI::Xaml::GridLength const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetThicknessProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_Thickness value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetThicknessProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::UI::Xaml::Thickness const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetMatrixProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_Media_Matrix value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetMatrixProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::UI::Xaml::Media::Matrix const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetMatrix3DProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_Media_Media3D_Matrix3D value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetMatrix3DProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), *reinterpret_cast<winrt::Windows::UI::Xaml::Media::Media3D::Matrix3D const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall SetEnumProperty(void* xamlDirectObject, int32_t propertyIndex, uint32_t value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().SetEnumProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex), value); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetObjectProperty(void* xamlDirectObject, int32_t propertyIndex, void** result) noexcept final try { clear_abi(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::Foundation::IInspectable>(this->shim().GetObjectProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetXamlDirectObjectProperty(void* xamlDirectObject, int32_t propertyIndex, void** result) noexcept final try { clear_abi(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject>(this->shim().GetXamlDirectObjectProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetBooleanProperty(void* xamlDirectObject, int32_t propertyIndex, bool* result) noexcept final try { typename D::abi_guard guard(this->shim()); *result = detach_from<bool>(this->shim().GetBooleanProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetDoubleProperty(void* xamlDirectObject, int32_t propertyIndex, double* result) noexcept final try { typename D::abi_guard guard(this->shim()); *result = detach_from<double>(this->shim().GetDoubleProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetInt32Property(void* xamlDirectObject, int32_t propertyIndex, int32_t* result) noexcept final try { typename D::abi_guard guard(this->shim()); *result = detach_from<int32_t>(this->shim().GetInt32Property(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetStringProperty(void* xamlDirectObject, int32_t propertyIndex, void** result) noexcept final try { clear_abi(result); typename D::abi_guard guard(this->shim()); *result = detach_from<hstring>(this->shim().GetStringProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetDateTimeProperty(void* xamlDirectObject, int32_t propertyIndex, int64_t* result) noexcept final try { zero_abi<winrt::Windows::Foundation::DateTime>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::Foundation::DateTime>(this->shim().GetDateTimeProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetPointProperty(void* xamlDirectObject, int32_t propertyIndex, winrt::Windows::Foundation::Point* result) noexcept final try { zero_abi<winrt::Windows::Foundation::Point>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::Foundation::Point>(this->shim().GetPointProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetRectProperty(void* xamlDirectObject, int32_t propertyIndex, winrt::Windows::Foundation::Rect* result) noexcept final try { zero_abi<winrt::Windows::Foundation::Rect>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::Foundation::Rect>(this->shim().GetRectProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetSizeProperty(void* xamlDirectObject, int32_t propertyIndex, winrt::Windows::Foundation::Size* result) noexcept final try { zero_abi<winrt::Windows::Foundation::Size>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::Foundation::Size>(this->shim().GetSizeProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetTimeSpanProperty(void* xamlDirectObject, int32_t propertyIndex, int64_t* result) noexcept final try { zero_abi<winrt::Windows::Foundation::TimeSpan>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::Foundation::TimeSpan>(this->shim().GetTimeSpanProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetColorProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Color* result) noexcept final try { zero_abi<winrt::Windows::UI::Color>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Color>(this->shim().GetColorProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetCornerRadiusProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_CornerRadius* result) noexcept final try { zero_abi<winrt::Windows::UI::Xaml::CornerRadius>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Xaml::CornerRadius>(this->shim().GetCornerRadiusProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetDurationProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_Duration* result) noexcept final try { zero_abi<winrt::Windows::UI::Xaml::Duration>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Xaml::Duration>(this->shim().GetDurationProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetGridLengthProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_GridLength* result) noexcept final try { zero_abi<winrt::Windows::UI::Xaml::GridLength>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Xaml::GridLength>(this->shim().GetGridLengthProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetThicknessProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_Thickness* result) noexcept final try { zero_abi<winrt::Windows::UI::Xaml::Thickness>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Xaml::Thickness>(this->shim().GetThicknessProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetMatrixProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_Media_Matrix* result) noexcept final try { zero_abi<winrt::Windows::UI::Xaml::Media::Matrix>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Xaml::Media::Matrix>(this->shim().GetMatrixProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetMatrix3DProperty(void* xamlDirectObject, int32_t propertyIndex, struct struct_Windows_UI_Xaml_Media_Media3D_Matrix3D* result) noexcept final try { zero_abi<winrt::Windows::UI::Xaml::Media::Media3D::Matrix3D>(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Xaml::Media::Media3D::Matrix3D>(this->shim().GetMatrix3DProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetEnumProperty(void* xamlDirectObject, int32_t propertyIndex, uint32_t* result) noexcept final try { typename D::abi_guard guard(this->shim()); *result = detach_from<uint32_t>(this->shim().GetEnumProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall ClearProperty(void* xamlDirectObject, int32_t propertyIndex) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().ClearProperty(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlPropertyIndex const*>(&propertyIndex)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetCollectionCount(void* xamlDirectObject, uint32_t* result) noexcept final try { typename D::abi_guard guard(this->shim()); *result = detach_from<uint32_t>(this->shim().GetCollectionCount(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall GetXamlDirectObjectFromCollectionAt(void* xamlDirectObject, uint32_t index, void** result) noexcept final try { clear_abi(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject>(this->shim().GetXamlDirectObjectFromCollectionAt(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), index)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall AddToCollection(void* xamlDirectObject, void* value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().AddToCollection(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall InsertIntoCollectionAt(void* xamlDirectObject, uint32_t index, void* value) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().InsertIntoCollectionAt(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), index, *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&value)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall RemoveFromCollection(void* xamlDirectObject, void* value, bool* result) noexcept final try { typename D::abi_guard guard(this->shim()); *result = detach_from<bool>(this->shim().RemoveFromCollection(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&value))); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall RemoveFromCollectionAt(void* xamlDirectObject, uint32_t index) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().RemoveFromCollectionAt(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), index); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall ClearCollection(void* xamlDirectObject) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().ClearCollection(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall AddEventHandler(void* xamlDirectObject, int32_t eventIndex, void* handler) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().AddEventHandler(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlEventIndex const*>(&eventIndex), *reinterpret_cast<winrt::Windows::Foundation::IInspectable const*>(&handler)); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall AddEventHandler_HandledEventsToo(void* xamlDirectObject, int32_t eventIndex, void* handler, bool handledEventsToo) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().AddEventHandler(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlEventIndex const*>(&eventIndex), *reinterpret_cast<winrt::Windows::Foundation::IInspectable const*>(&handler), handledEventsToo); return 0; } catch (...) { return to_hresult(); } int32_t __stdcall RemoveEventHandler(void* xamlDirectObject, int32_t eventIndex, void* handler) noexcept final try { typename D::abi_guard guard(this->shim()); this->shim().RemoveEventHandler(*reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject const*>(&xamlDirectObject), *reinterpret_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlEventIndex const*>(&eventIndex), *reinterpret_cast<winrt::Windows::Foundation::IInspectable const*>(&handler)); return 0; } catch (...) { return to_hresult(); } }; #endif template <typename D> struct produce<D, winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject> : produce_base<D, winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject> { }; #ifndef WINRT_LEAN_AND_MEAN template <typename D> struct produce<D, winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectStatics> : produce_base<D, winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectStatics> { int32_t __stdcall GetDefault(void** result) noexcept final try { clear_abi(result); typename D::abi_guard guard(this->shim()); *result = detach_from<winrt::Windows::UI::Xaml::Core::Direct::XamlDirect>(this->shim().GetDefault()); return 0; } catch (...) { return to_hresult(); } }; #endif } WINRT_EXPORT namespace winrt::Windows::UI::Xaml::Core::Direct { inline auto XamlDirect::GetDefault() { return impl::call_factory_cast<winrt::Windows::UI::Xaml::Core::Direct::XamlDirect(*)(IXamlDirectStatics const&), XamlDirect, IXamlDirectStatics>([](IXamlDirectStatics const& f) { return f.GetDefault(); }); } } namespace std { #ifndef WINRT_LEAN_AND_MEAN template<> struct hash<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirect> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectObject> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::UI::Xaml::Core::Direct::IXamlDirectStatics> : winrt::impl::hash_base {}; template<> struct hash<winrt::Windows::UI::Xaml::Core::Direct::XamlDirect> : winrt::impl::hash_base {}; #endif #ifdef __cpp_lib_format #endif } #endif
fca6f8db75dd6827d629162804acd21897589298
f712a65139113f637a0d854989ed2f931c02d79d
/P3/Carreres-Pablo-2305/readfile.cpp
93b7d8defd93a15f892c9cfed8a88b4e031a41c9
[]
no_license
alsolanes/Carreres
865679de291fb69c116574a2df4ab65106514eb8
bad09aa608425e1a0745860f36c85ae34e16c36e
refs/heads/master
2021-01-10T14:30:09.671738
2014-05-28T07:53:39
2014-05-28T07:53:39
17,371,003
0
0
null
null
null
null
UTF-8
C++
false
false
4,785
cpp
#include"readfile.h" //read files functions #include<QString> /* Lectura d'un fitxer OBJ Fragments de codi de obj_2_ply.c (C) Greg Turk ----------------------------------------------------------------------- Copyright (c) 1998 Georgia Institute of Technology. All rights reserved. Permission to use, copy, modify and distribute this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice and this permission notice appear in all copies of this software and that you do not sell the software. */ int ReadFile::max_words = 0; int ReadFile::num_words = 0; /* for file reading */ #define BIG_STRING 4096 char ReadFile::str[BIG_STRING]; char ReadFile::str_orig[BIG_STRING]; char**ReadFile::words; void ReadFile::get_indices ( char *word, int *vindex, int *tindex, int *nindex ) /****************************************************************************** GET_INDICES breaks up a word that may have slash-separated numbers into one or more numbers. Entry: word - word to break up Exit: vindex - first number (vertex index) tindex - second number (texture index) nindex - third number (normal vector index) ******************************************************************************/ { char *null = " "; char *ptr; char *tp; char *np; /* by default, the texture and normal pointers are set to the null string */ tp = null; np = null; /* replace slashes with null characters and cause tp and np to point */ /* to character immediately following the first or second slash */ for (ptr = word; *ptr != '\0'; ptr++) { if (*ptr == '/') { if (tp == null) tp = ptr + 1; else np = ptr + 1; *ptr = '\0'; } } QString v(word); QString t(tp); QString n(tp); *vindex = v.toInt(); *tindex = t.toInt(); *nindex = n.toInt(); } char *ReadFile::fetch_line ( FILE *fp ) { //int i,j; char *ptr; char *ptr2; char *result; //char *comment_ptr; /* read in a line */ result = fgets (ReadFile::str, BIG_STRING, fp); /* return NULL if we're at the end-of-file */ if (result == NULL) return ((char *) -1); /* convert line-feed and tabs into spaces */ /* (this guarentees that there will be a space before the */ /* null character at the end of the string) */ ReadFile::str[BIG_STRING-2] = ' '; ReadFile::str[BIG_STRING-1] = '\0'; for (ptr = ReadFile::str; *ptr != '\0'; ptr++) { if (*ptr == '\t') { *ptr = ' '; } else if (*ptr == '\n') { *ptr = ' '; break; } } /* copy the line */ for (ptr = ReadFile::str, ptr2 = ReadFile::str_orig; *ptr != '\0'; ptr++, ptr2++) *ptr2 = *ptr; *ptr2 = '\0'; /* look to see if this is a comment line (first non-space is '#') */ for (ptr = ReadFile::str; *ptr != '\0'; ptr++) { if (*ptr == '#') { ptr++; while (*ptr == ' ') ptr++; return (ptr); } else if (*ptr != ' ') { break; } } /* if we get here, we've got a non-comment line */ /* strip off trailing comments */ while (*ptr != '\0') { if (*ptr == '#') { *ptr++ = ' '; *ptr = '\0'; break; } ptr++; } return (NULL); } int ReadFile::fetch_words () { char *ptr; /* allocate room for words if necessary */ if (max_words == 0) { max_words = 20; words = (char **) malloc (sizeof (char *) * max_words); } /* find the words in the line */ ptr = ReadFile::str; num_words = 0; while (*ptr != '\0') { /* jump over leading spaces */ while (*ptr == ' ') ptr++; /* break if we reach the end */ if (*ptr == '\0') break; /* allocate more room for words if necessary */ if (num_words >= max_words) { max_words += 10; words = (char **) realloc (words, sizeof (char *) * max_words); } /* save pointer to beginning of word */ words[num_words++] = ptr; /* jump over non-spaces */ while (*ptr != ' ') ptr++; /* place a null character here to mark the end of the word */ *ptr++ = '\0'; } /* return the number of words */ return (num_words); } std::string ReadFile::getPath(const std::string& filename) { int i=filename.length()-1; bool found = false; while (i>=0 && !found) { if (filename[i]=='/' || filename[i]=='\\') found=true; else --i; } return filename.substr(0, i+1); }
52b8c268c3540eb7f69fba78150b060700d36c35
290e9dd635cf50634c93a95625dd23b909cafc3b
/C++/ChannelService_server.skeleton.cpp
ef71d6c4883ce65f5f3a530cb5eb74277c36fc5b
[]
no_license
chimerakang/linethrift
a10546198bf8d677e5f2793a27e58af8a8f7b408
3cade23b470ed4e80162bcccc97ad3cdab1e0928
refs/heads/master
2022-04-18T11:47:14.065158
2020-03-22T15:39:15
2020-03-22T15:39:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,482
cpp
// This autogenerated skeleton file illustrates how to build a server. // You should copy it to another filename to avoid overwriting it. #include "ChannelService.h" #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/server/TSimpleServer.h> #include <thrift/transport/TServerSocket.h> #include <thrift/transport/TBufferTransports.h> using namespace ::apache::thrift; using namespace ::apache::thrift::protocol; using namespace ::apache::thrift::transport; using namespace ::apache::thrift::server; class ChannelServiceHandler : virtual public ChannelServiceIf { public: ChannelServiceHandler() { // Your initialization goes here } void issueOTP(OTPResult& _return, const std::string& channelId) { // Your implementation goes here printf("issueOTP\n"); } void approveChannelAndIssueChannelToken(ChannelToken& _return, const std::string& channelId) { // Your implementation goes here printf("approveChannelAndIssueChannelToken\n"); } void approveChannelAndIssueRequestToken(std::string& _return, const std::string& channelId, const std::string& otpId) { // Your implementation goes here printf("approveChannelAndIssueRequestToken\n"); } void fetchNotificationItems(NotificationFetchResult& _return, const int64_t localRev) { // Your implementation goes here printf("fetchNotificationItems\n"); } void getApprovedChannels(ApprovedChannelInfos& _return, const int64_t lastSynced, const std::string& locale) { // Your implementation goes here printf("getApprovedChannels\n"); } void getChannelInfo(ChannelInfo& _return, const std::string& channelId, const std::string& locale) { // Your implementation goes here printf("getChannelInfo\n"); } void getChannelNotificationSetting(ChannelNotificationSetting& _return, const std::string& channelId, const std::string& locale) { // Your implementation goes here printf("getChannelNotificationSetting\n"); } void getChannelNotificationSettings(std::vector<ChannelNotificationSetting> & _return, const std::string& locale) { // Your implementation goes here printf("getChannelNotificationSettings\n"); } void getChannels(ChannelInfos& _return, const int64_t lastSynced, const std::string& locale) { // Your implementation goes here printf("getChannels\n"); } void getDomains(ChannelDomains& _return, const int64_t lastSynced) { // Your implementation goes here printf("getDomains\n"); } void getFriendChannelMatrices(FriendChannelMatricesResponse& _return, const std::vector<std::string> & channelIds) { // Your implementation goes here printf("getFriendChannelMatrices\n"); } bool updateChannelSettings(const ChannelSettings& channelSettings) { // Your implementation goes here printf("updateChannelSettings\n"); } void getCommonDomains(ChannelDomains& _return, const int64_t lastSynced) { // Your implementation goes here printf("getCommonDomains\n"); } int32_t getNotificationBadgeCount(const int64_t localRev) { // Your implementation goes here printf("getNotificationBadgeCount\n"); } void issueChannelToken(ChannelToken& _return, const std::string& channelId) { // Your implementation goes here printf("issueChannelToken\n"); } void issueRequestToken(std::string& _return, const std::string& channelId, const std::string& otpId) { // Your implementation goes here printf("issueRequestToken\n"); } void issueRequestTokenWithAuthScheme(RequestTokenResponse& _return, const std::string& channelId, const std::string& otpId, const std::vector<std::string> & authScheme, const std::string& returnUrl) { // Your implementation goes here printf("issueRequestTokenWithAuthScheme\n"); } void issueRequestTokenForAutoLogin(std::string& _return, const std::string& channelId, const std::string& otpId, const std::string& redirectUrl) { // Your implementation goes here printf("issueRequestTokenForAutoLogin\n"); } void getUpdatedChannelIds(std::vector<std::string> & _return, const std::vector<ChannelIdWithLastUpdated> & channelIds) { // Your implementation goes here printf("getUpdatedChannelIds\n"); } void reserveCoinUse(std::string& _return, const CoinUseReservation& request, const std::string& locale) { // Your implementation goes here printf("reserveCoinUse\n"); } void revokeChannel(const std::string& channelId) { // Your implementation goes here printf("revokeChannel\n"); } void syncChannelData(ChannelSyncDatas& _return, const int64_t lastSynced, const std::string& locale) { // Your implementation goes here printf("syncChannelData\n"); } void updateChannelNotificationSetting(const std::vector<ChannelNotificationSetting> & setting) { // Your implementation goes here printf("updateChannelNotificationSetting\n"); } }; int main(int argc, char **argv) { int port = 9090; ::std::shared_ptr<ChannelServiceHandler> handler(new ChannelServiceHandler()); ::std::shared_ptr<TProcessor> processor(new ChannelServiceProcessor(handler)); ::std::shared_ptr<TServerTransport> serverTransport(new TServerSocket(port)); ::std::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory()); ::std::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory()); TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory); server.serve(); return 0; }
97154f718b7cbec52430edcd9c82009974d55d23
74dccff173c78b4939458cdb47064f5fba3caaa4
/common/video/mpeg4/vtc/zte/ztscan_dec.cpp
861a84554958b779556a6692de2cd8da92beed77
[]
no_license
weltion158/MPEG-4IP
f1f3f963017a5cb6a1adc08b669202eb93908bdc
b0b93c12773077ca29f5a1c00ae421fd4850a239
refs/heads/master
2021-01-12T13:26:17.560247
2016-09-25T11:22:15
2016-09-25T11:22:15
69,160,282
0
0
null
null
null
null
UTF-8
C++
false
false
41,305
cpp
/* $Id: ztscan_dec.cpp,v 1.3 2001/04/30 20:51:45 dmackie Exp $ */ /****************************************************************************/ /* MPEG4 Visual Texture Coding (VTC) Mode Software */ /* */ /* This software was jointly developed by the following participants: */ /* */ /* Single-quant, multi-quant and flow control */ /* are provided by Sarnoff Corporation */ /* Iraj Sodagar ([email protected]) */ /* Hung-Ju Lee ([email protected]) */ /* Paul Hatrack ([email protected]) */ /* Shipeng Li ([email protected]) */ /* Bing-Bing Chai ([email protected]) */ /* B.S. Srinivas ([email protected]) */ /* */ /* Bi-level is provided by Texas Instruments */ /* Jie Liang ([email protected]) */ /* */ /* Shape Coding is provided by OKI Electric Industry Co., Ltd. */ /* Zhixiong Wu ([email protected]) */ /* Yoshihiro Ueda ([email protected]) */ /* Toshifumi Kanamaru ([email protected]) */ /* */ /* OKI, Sharp, Sarnoff, TI and Microsoft contributed to bitstream */ /* exchange and bug fixing. */ /* */ /* */ /* In the course of development of the MPEG-4 standard, this software */ /* module is an implementation of a part of one or more MPEG-4 tools as */ /* specified by the MPEG-4 standard. */ /* */ /* The copyright of this software belongs to ISO/IEC. ISO/IEC gives use */ /* of the MPEG-4 standard free license to use this software module or */ /* modifications thereof for hardware or software products claiming */ /* conformance to the MPEG-4 standard. */ /* */ /* Those intending to use this software module in hardware or software */ /* products are advised that use may infringe existing patents. The */ /* original developers of this software module and their companies, the */ /* subsequent editors and their companies, and ISO/IEC have no liability */ /* and ISO/IEC have no liability for use of this software module or */ /* modification thereof in an implementation. */ /* */ /* Permission is granted to MPEG members to use, copy, modify, */ /* and distribute the software modules ( or portions thereof ) */ /* for standardization activity within ISO/IEC JTC1/SC29/WG11. */ /* */ /* Copyright 1995, 1996, 1997, 1998 ISO/IEC */ /****************************************************************************/ /************************************************************/ /* Sarnoff Very Low Bit Rate Still Image Coder */ /* Copyright 1995, 1996, 1997, 1998 Sarnoff Corporation */ /************************************************************/ /************************************************************/ /* Filename: ztscan_dec.c */ /* Author: Bing-Bing CHai */ /* Date: Dec. 17, 1997 */ /* */ /* Descriptions: */ /* This file contains the routines that performs */ /* zero tree scanning and entropy decoding. */ /* */ /************************************************************/ #include <stdio.h> #include <stdlib.h> #ifndef WIN32 #include <unistd.h> #endif #include <ctype.h> #include <string.h> #include <math.h> #include "basic.hpp" #include "Utils.hpp" #include "startcode.hpp" #include "dataStruct.hpp" #include "states.hpp" #include "globals.hpp" #include "errorHandler.hpp" #include "ac.hpp" #include "bitpack.hpp" //#include "context.hpp" #include "ztscan_common.hpp" #include "ztscanUtil.hpp" static ac_decoder acd; /******************************************************************/ /**************************** DC ********************************/ /******************************************************************/ /*******************************************************/ /************** Inverse DC Prediction ****************/ /*******************************************************/ /******************************************************** Function Name ------------- static DATA iDC_pred_pix(Int i, Int j) Arguments --------- Int i, Int j: Index of wavelet coefficient (row, col) Description ----------- Inverse DPCM prediction for a DC coefficient, refer to syntax for algorithm. Functions Called ---------------- None. Return Value ------------ inverse prediction for coeffinfo[i][j].quantized_value ********************************************************/ Short CVTCDecoder::iDC_pred_pix(Int i, Int j) { /* modified by Z. Wu @ OKI */ Int pred_i, pred_j, pred_d; if ( i==0 || coeffinfo[i-1][j].mask == 0 ) pred_i = 0; else pred_i = coeffinfo[i-1][j].quantized_value; if ( j==0 || coeffinfo[i][j-1].mask == 0 ) pred_j = 0; else pred_j = coeffinfo[i][j-1].quantized_value; if ( i==0 || j== 0 || coeffinfo[i-1][j-1].mask == 0 ) pred_d = 0; else pred_d = coeffinfo[i-1][j-1].quantized_value; if ( abs(pred_d-pred_j) < abs(pred_d-pred_i)) return(pred_i); else return(pred_j); } /***************************************************** Function Name ------------- Void iDC_predict() Arguments --------- None Description ----------- control program for inverse DC prediction Functions Called ---------------- iDC_pred_pix(i,j). Return Value ------------ none ******************************************************/ Void CVTCDecoder::iDC_predict(Int color) { Int i,j,dc_h,dc_w,offset_dc; dc_h=mzte_codec.m_iDCHeight; dc_w=mzte_codec.m_iDCWidth; coeffinfo=mzte_codec.m_SPlayer[color].coeffinfo; offset_dc=mzte_codec.m_iOffsetDC; for(i=0;i<dc_h;i++) for(j=0;j<dc_w;j++) if (coeffinfo[i][j].mask != 0) coeffinfo[i][j].quantized_value += offset_dc; for(i=0;i<dc_h;i++) for(j=0;j<dc_w;j++) if (coeffinfo[i][j].mask != 0) coeffinfo[i][j].quantized_value+=iDC_pred_pix(i,j); } /******************************************************** Function Name ------------- Void wavelet_dc_decode(Int c) Arguments --------- Int c - color component. Description ----------- Control program for decode DC information for one color component. Functions Called ---------------- None. iDC_predict() get_param() cacll_decode() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::wavelet_dc_decode(Int c) { noteDetail("Decoding DC (wavelet_dc_decode)...."); color=c; mzte_codec.m_iMean[color] = get_X_bits(8); /* mzte_codec.m_iQDC[color] = get_X_bits(8); */ mzte_codec.m_iQDC[color] = get_param(7); mzte_codec.m_iOffsetDC=-get_param(7); mzte_codec.m_iMaxDC=get_param(7); /* mzte_codec.m_iMaxDC=get_param(7)-mzte_codec.m_iOffsetDC; */ /* hjlee */ callc_decode(); iDC_predict(color); noteDetail("Completed decoding DC."); } /******************************************************** Function Name ------------- static Void cacll_decode() Arguments --------- None. Description ----------- Decode DC information for one color component. Functions Called ---------------- mzte_ac_decoder_init() mzte_ac_model_init() mzte_ac_decode_symbol() mzte_ac_model_done() mzte_ac_decoder_done() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::callc_decode() { Int dc_h, dc_w,i,j; Int numBP, bp; // 1127 dc_w=mzte_codec.m_iDCWidth; dc_h=mzte_codec.m_iDCHeight; /* init arithmetic model */ /* ac_decoder_open(acd,NULL); */ mzte_ac_decoder_init(&acd); // 1127 numBP = ceilLog2(mzte_codec.m_iMaxDC + 1); if ((acm_bpdc=(ac_model *)calloc(numBP,sizeof(ac_model)))==NULL) errorHandler("Can't allocate memory for prob model."); for (i=0; i<numBP; i++) { acm_bpdc[i].Max_frequency = Bitplane_Max_frequency; mzte_ac_model_init(&(acm_bpdc[i]),2,NULL,ADAPT,1); } coeffinfo=mzte_codec.m_SPlayer[color].coeffinfo; for (bp=numBP-1; bp>=0; bp--) { for(i=0;i<dc_h;i++) for(j=0;j<dc_w;j++){ if(coeffinfo[i][j].mask == 1) coeffinfo[i][j].quantized_value += (mzte_ac_decode_symbol(&acd,&(acm_bpdc[bp])) << bp); else coeffinfo[i][j].quantized_value=-mzte_codec.m_iOffsetDC; } } for (i=0; i<numBP; i++) mzte_ac_model_done(&(acm_bpdc[i])); free(acm_bpdc); #if 0 // 1127 if ((acm_vz=(ac_model *)calloc(1,sizeof(ac_model)))==NULL) errorHandler("Can't allocate memory for prob model."); acm_vz->Max_frequency = DEFAULT_MAX_FREQ; mzte_ac_model_init(acm_vz,mzte_codec.m_iMaxDC+1,NULL,ADAPT,1); coeffinfo=mzte_codec.m_SPlayer[color].coeffinfo; for(i=0;i<dc_h;i++) for(j=0;j<dc_w;j++){ if( coeffinfo[i][j].mask == 1) coeffinfo[i][j].quantized_value= mzte_ac_decode_symbol(&acd,acm_vz); else coeffinfo[i][j].quantized_value=-mzte_codec.m_iOffsetDC; } /* close arithmetic coder */ mzte_ac_model_done(acm_vz); free(acm_vz); #endif // 1127 mzte_ac_decoder_done(&acd); } /*********************************************************************/ /***************************** AC **********************************/ /************************* Single quant ****************************/ /*********************************************************************/ Int CVTCDecoder::bitplane_decode(Int l,Int max_bplane) { register Int i,val=0,k=0; for(i=max_bplane-1;i>=0;i--,k++) val+=mzte_ac_decode_symbol(&acd,&acm_bpmag[l][k])<<i; return val; } /******************************************************* The following single quant routines are for band by band scan order. *******************************************************/ /******************************************************** Function Name ------------- Void wavelet_higher_bands_decode_SQ_band(Int col) Arguments --------- None. Description ----------- Control program for decoding AC information for one color component. Single quant mode. Functions Called ---------------- cachb_encode_SQ_band() ac_encoder_init() mzte_ac_model_init() mzte_ac_model_done() ac_encoder_done() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::wavelet_higher_bands_decode_SQ_band(Int col) { SNR_IMAGE *snr_image; noteDetail("Encoding AC (wavelet_higher_bands_encode_SQ)...."); color=col; snr_image=&(mzte_codec.m_SPlayer[color].SNRlayer.snr_image); /* init arithmetic coder */ mzte_ac_decoder_init(&acd); probModelInitSQ(color); // hjlee 0901 cachb_decode_SQ_band(snr_image); probModelFreeSQ(color); // hjlee 0901 mzte_ac_decoder_done(&acd); noteDetail("Completed encoding AC."); } /******************************************************** Function Name ------------- static Void cachb_decode_SQ_band(SNR_IMAGE *snr_img) Arguments --------- None. Description ----------- Decode AC information for single quant mode, tree-depth scan. Functions Called ---------------- codeBlocks(); decode_pixel_SQ_band() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::cachb_decode_SQ_band(SNR_IMAGE *snr_image) { Int h,w,ac_h,ac_w,ac_h2,ac_w2; Int n; /* layer index - for codeBlocks function */ Int k; /* block jump for the layer */ /* ac_h, ac_w init */ ac_h2=mzte_codec.m_SPlayer[color].height;; ac_w2=mzte_codec.m_SPlayer[color].width; ac_h=ac_h2>>1; ac_w=ac_w2>>1; height=mzte_codec.m_Image[color].height; width=mzte_codec.m_Image[color].width; /* Get layer index - for codeBlocks function */ n = -1; for (w=mzte_codec.m_iDCWidth; w < ac_w2; w<<=1) n++; setProbModelsSQ(color); // hjlee 0901 coeffinfo=mzte_codec.m_SPlayer[color].coeffinfo; /* scan each coefficients in the spatial layer */ k = 1<<n; for(h=0;h<ac_h;h+=k) for(w=ac_w;w<ac_w2;w+=k) { /* LH */ decodeSQBlocks(h,w,n); /* HL */ h += ac_h; w -= ac_w; decodeSQBlocks(h,w,n); /* HH */ w += ac_w; decodeSQBlocks(h,w,n); /* Set h back to where it started. w is already there */ h -= ac_h; } } #if 0 /******************************************************** Function Name ------------- static Void decode_pixel_SQ_band(Int h,Int w) Arguments --------- Int h,Int w - position of a pixel in height and width Description ----------- Decoding the type and/or value of a coefficient, a recursive function. Functions Called ---------------- mag_sign_decode_SQ() mzte_ac_decode_symbol() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::decode_pixel_SQ_band(Int h,Int w) { UChar zt_type; Int l; if(coeffinfo[h][w].type == ZTR_D) return; l=xy2wvtDecompLev(w,h); /* decode leave coefficients, value only */ if(IS_STATE_LEAF(coeffinfo[h][w].state)){ /* zero value. no sign */ #ifdef _SHAPE_ if(coeffinfo[h][w].mask==1) { #endif /* Map leaf code word to type 0->ZTR, 1->VZTR */ coeffinfo[h][w].type = mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_LINIT]) ? VZTR : ZTR; if (coeffinfo[h][w].type==VZTR) mag_sign_decode_SQ(h,w); else coeffinfo[h][w].quantized_value = 0; #ifdef _SHAPE_ } else coeffinfo[h][w].quantized_value = 0; #endif return; } /* decode zero tree symbols */ #ifdef _SHAPE_ if(coeffinfo[h][w].mask==1) #endif coeffinfo[h][w].type=zt_type= mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_INIT]); #ifdef _SHAPE_ else coeffinfo[h][w].type=zt_type = IZ; #endif /* code magnitude and sign */ switch(zt_type){ case IZ : break; case VZTR: mag_sign_decode_SQ(h,w); case ZTR: mark_ZTR_D(h,w); /* necessary for checking purpose bandwise scan */ return; case VAL: mag_sign_decode_SQ(h,w); break; default: errorHandler("Invalid zerotree symbol in single quant decode"); } } #endif /* 0 */ /******************************************************* The following single quant routines are for tree depth scan order. *******************************************************/ /******************************************************** Function Name ------------- Void wavelet_higher_bands_decode_SQ_tree() Arguments --------- None. Description ----------- Control program for decoding AC information for single quant mode. All colors decoded. Functions Called ---------------- cachb_decode_SQ_tree() mzte_ac_decoder_init() mzte_ac_model_init() mzte_ac_model_done() mzte_ac_decoder_done() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::wavelet_higher_bands_decode_SQ_tree() { noteDetail("Decoding AC band (wavelet_higher_bands_decode_SQ)...."); /* init arithmetic coder */ mzte_ac_decoder_init(&acd); for (color=0; color<mzte_codec.m_iColors; color++) { probModelInitSQ(color); // hjlee 0901 } // cachb_decode_SQ(); // hjlee 0901 cachb_decode_SQ_tree(); for (color=0; color<mzte_codec.m_iColors; color++) /* close arithmetic coder */ probModelFreeSQ(color); mzte_ac_decoder_done(&acd); noteDetail("Completed decoding AC band."); } /******************************************************** Function Name ------------- static Void cachb_decode_SQ() Arguments --------- None. Description ----------- Decode AC information for one color component. Single quant mode, tree-depth scan Functions Called ---------------- decode_pixel_SQ() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::cachb_decode_SQ_tree() { Int h,w,dc_h,dc_w,dc_h2,dc_w2; dc_h=mzte_codec.m_iDCHeight; dc_w=mzte_codec.m_iDCWidth; dc_h2=dc_h<<1; dc_w2=dc_w<<1; for(h=0;h<dc_h;h++) for(w=0;w<dc_w;w++) // 1127 for (color=0; color<mzte_codec.m_iColors; color++) { SNR_IMAGE *snr_image; int tw,sw,sh,n; // 1127 snr_image=&(mzte_codec.m_SPlayer[color].SNRlayer.snr_image); height=mzte_codec.m_SPlayer[color].height; width=mzte_codec.m_SPlayer[color].width; setProbModelsSQ(color); // hjlee 0901 coeffinfo=mzte_codec.m_SPlayer[color].coeffinfo; /* LH */ n = 0; for (tw=mzte_codec.m_iDCWidth; tw < width; tw<<=1) { sh = h << n; sw = (w+dc_w) << n; decodeSQBlocks(sh,sw,n); n++; } /* HL */ n = 0; for (tw=mzte_codec.m_iDCWidth; tw < width; tw<<=1) { sh = (h+dc_h) << n; sw = w << n; decodeSQBlocks(sh,sw,n); n++; } /* HH */ n = 0; for (tw=mzte_codec.m_iDCWidth; tw < width; tw<<=1) { sh = (h+dc_h) << n; sw = (w+dc_w) << n; decodeSQBlocks(sh,sw,n); n++; } #if 0 // hjlee 0901 decode_pixel_SQ_tree(h,w); /* LH */ decode_pixel_SQ_tree(h+dc_h,w-dc_w); /* HL */ decode_pixel_SQ_tree(h+dc_h,w); /* HH */ #endif } } /******************************************************** Function Name ------------- static Void decode_pixel_SQ(Int h,Int w) Arguments --------- Int h,Int w - position of a pixel in height and width Description ----------- Decoding the type and/or value of a coefficient, a recursive function. Functions Called ---------------- mag_sign_decode_SQ() mzte_ac_decode_symbol() decode_pixel_SQ() Return Value ------------ None. ********************************************************/ // hjlee 0901 Void CVTCDecoder::decode_pixel_SQ(Int h,Int w) { UChar zt_type; Int l; if(coeffinfo[h][w].type == ZTR_D) return; l=xy2wvtDecompLev(w,h); /* decode leave coefficients, value only */ if(IS_STATE_LEAF(coeffinfo[h][w].state)){ /* zero value. no sign */ /* Map leaf code word to type 0->ZTR, 1->VZTR */ coeffinfo[h][w].type = mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_LINIT]) ? VZTR : ZTR; if (coeffinfo[h][w].type==VZTR) mag_sign_decode_SQ(h,w); else coeffinfo[h][w].quantized_value = 0; return; } /* decode zero tree symbols */ coeffinfo[h][w].type=zt_type= mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_INIT]); /* code magnitude and sign */ switch(zt_type){ case IZ : break; case VZTR: mag_sign_decode_SQ(h,w); case ZTR: mark_ZTR_D(h,w); /* necessary for checking purpose bandwise scan */ return; case VAL: mag_sign_decode_SQ(h,w); break; default: errorHandler("Invalid zerotree symbol in single quant decode"); } #if 0 UChar zt_type; Int h, w, k; Int dcc[4]; /* Don't Code Children */ Int nSib; /* number siblings */ Int l; l=xy2wvtDecompLev(w0,h0); nSib = (h0<(mzte_codec.m_iDCHeight<<1) && w0<(mzte_codec.m_iDCWidth<<1)) ? 1 : 4; /********************* CODE SIBLINGS *****************************/ for (k=0; k<nSib; ++k) { h = h0 + (k/2); w = w0 + (k%2); /* decode leave coefficients, value only */ if(IS_STATE_LEAF(coeffinfo[h][w].state)){ /* zero value. no sign */ #ifdef _SHAPE_ if(coeffinfo[h][w].mask==1) { #endif /* Map leaf code word to type 0->ZTR, 1->VZTR */ coeffinfo[h][w].type = mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_LINIT]) ? VZTR : ZTR; if (coeffinfo[h][w].type==VZTR) mag_sign_decode_SQ(h,w); else coeffinfo[h][w].quantized_value = 0; #ifdef _SHAPE_ } else coeffinfo[h][w].quantized_value = 0; #endif continue; } /* decode zero tree symbols */ #ifdef _SHAPE_ if(coeffinfo[h][w].mask==1) #endif coeffinfo[h][w].type=zt_type= mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_INIT]); #ifdef _SHAPE_ else coeffinfo[h][w].type=zt_type = IZ; #endif /* code magnitude and sign */ switch(zt_type){ case IZ : dcc[k]=0; break; case VZTR: mag_sign_decode_SQ(h,w); case ZTR: dcc[k]=1; break; case VAL: dcc[k]=0; mag_sign_decode_SQ(h,w); break; default: errorHandler("Invalid zerotree symbol in single quant decode"); } } /********************* CODE CHILDREN *****************************/ if (!IS_STATE_LEAF(coeffinfo[h0][w0].state)) { Int i, j; for (k=0; k<nSib; ++k) { if (dcc[k]==0) { h = h0 + (k/2); w = w0 + (k%2); /* scan children */ i=h<<1; j=w<<1; decode_pixel_SQ_tree(i,j); } } } #endif } /******************************************************** Function Name ------------- static Void mag_sign_decode_SQ(Int h,Int w) Arguments --------- Int h,Int w - position of a pixel Description ----------- Decode the value of a coefficient. Functions Called ---------------- mzte_ac_decode_symbol() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::mag_sign_decode_SQ(Int h,Int w) { Int value,v_sign; Int l; l=xy2wvtDecompLev(w,h); value=bitplane_decode(l,WVTDECOMP_NUMBITPLANES(color,l))+1; v_sign=mzte_ac_decode_symbol(&acd,acm_sign[l]); coeffinfo[h][w].quantized_value=(v_sign==0) ? value : -value; } /*********************************************************************/ /****************************** AC *********************************/ /************************** Multi quant ****************************/ /*********************************************************************/ Int CVTCDecoder::bitplane_res_decode(Int l,Int max_bplane) { register Int i,val=0,k=0; for(i=max_bplane-1;i>=0;i--,k++) val+=mzte_ac_decode_symbol(&acd,&acm_bpres[l][k])<<i; return val; } /******************************************************** Function Name ------------- Void wavelet_higher_bands_decode_MQ(Int scanDirection) Arguments --------- Int scanDirection - 0 <=> tree, 1 <=> band Description ----------- Control program for decoding AC information for one color component. Multi quant mode. Functions Called ---------------- cachb_decode_MQ_band() mzte_ac_decoder_init() mzte_ac_model_init() mzte_ac_model_done() mzte_ac_decoder_done() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::wavelet_higher_bands_decode_MQ(Int scanDirection) { noteDetail("Decoding AC band (wavelet_higher_bands_decode_MQ)...."); /* init arithmetic coder */ mzte_ac_decoder_init(&acd); if (scanDirection==0) cachb_decode_MQ_tree(); else cachb_decode_MQ_band(); /* close arithmetic coder */ mzte_ac_decoder_done(&acd); } /**********************************************************************/ /*************** MQ BAND ********************************/ /**********************************************************************/ /******************************************************** Function Name ------------- static Void cachb_decode_MQ_band() Arguments --------- None. Description ----------- Decode AC information for one color component. Multiple quant, bandwise scan. Functions Called ---------------- clear_ZTR_D(); codeBlocks(); decode_pixel_MQ_band() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::cachb_decode_MQ_band() { Int h,w; Int ac_h,ac_w,ac_h2,ac_w2; Int acH,acW,acH2,acW2; Int layer, nCol; Int n; /* layer index - for codeBlocks function */ Int k; /* block jump for the layer */ /* clear the ZTR_D type from the previous pass */ for (color=0; color<NCOL; ++color) { coeffinfo=mzte_codec.m_SPlayer[color].coeffinfo; height=mzte_codec.m_SPlayer[color].height; width=mzte_codec.m_SPlayer[color].width; clear_ZTR_D(coeffinfo, width, height); } for (color=0; color<NCOL; ++color) probModelInitMQ(color); acH=mzte_codec.m_iDCHeight; acW=mzte_codec.m_iDCWidth; acH2=acH<<1; acW2=acW<<1; /* scan each coefficients in the spatial layer */ /* assume luma dimensions are >= chroma dimensions */ layer=0; while(acH2<=mzte_codec.m_SPlayer[0].height && acW2<=mzte_codec.m_SPlayer[0].width) { nCol = (layer==0) ? 1 : NCOL; for (color=0; color < nCol; ++color) { SNR_IMAGE *snr_image; noteProgress(" Coding Layer %d, Color %d", layer - (color!=0), color); ac_h2=acH2; ac_w2=acW2; ac_h=acH; ac_w=acW; if (color) { ac_h2>>=1; ac_w2>>=1; ac_h>>=1; ac_w>>=1; } snr_image=&(mzte_codec.m_SPlayer[color].SNRlayer.snr_image); coeffinfo=mzte_codec.m_SPlayer[color].coeffinfo; height=mzte_codec.m_SPlayer[color].height; width=mzte_codec.m_SPlayer[color].width; setProbModelsMQ(color); /* Go through bands */ n = layer - (color>0); k = 1<<n; for(h=0;h<ac_h;h+=k) for(w=ac_w;w<ac_w2;w+=k) { /* LH */ decodeMQBlocks(h,w,n); /* HL */ h += ac_h; w -= ac_w; decodeMQBlocks(h,w,n); /* HH */ w += ac_w; decodeMQBlocks(h,w,n); /* Set h back to where it started. w is already there */ h -= ac_h; } } /* update ranges */ acH=acH2; acW=acW2; acW2<<=1; acH2<<=1; layer++; } for (color=0; color<NCOL; ++color) probModelFreeMQ(color); } /******************************************************** Function Name ------------- static Void decode_pixel_MQ_band(Int h,Int w) Arguments --------- Int h,Int w - position of a pixel in height and width Description ----------- Decoding the type and/or value of a coefficient, a recursive function, multi quant mode. Functions Called ---------------- mzte_ac_decode_symbol() mark_ZTR_D() mag_sign_decode_MQ() Return Value ------------ None. ********************************************************/ //Void CVTCDecoder::decode_pixel_MQ_band(Int h,Int w) Void CVTCDecoder::decode_pixel_MQ(Int h,Int w) // 1124 { Int zt_type; /*~~~~~~~~~~~~~~~~~ zerotree descendent ~~~~~~~~~~~~~~~~~~~*/ if(coeffinfo[h][w].type==ZTR_D) return; /*~~~~~~~~~~~~~~ decode zero tree symbol ~~~~~~~~~~~~~~~~~~*/ if (IS_RESID(w,h,color)) { zt_type=VAL; /* tmp assign. for next switch statement */ } else { Int czt_type; /* what to put on bitstream */ Int l; l=xy2wvtDecompLev(w,h); zt_type = coeffinfo[h][w].type; #ifdef _SHAPE_ if(coeffinfo[h][w].mask==1) /* skip out-node */ { #endif switch(coeffinfo[h][w].state) { case S_INIT: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_INIT]); coeffinfo[h][w].type=zt_type=czt_type; break; case S_ZTR: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_ZTR]); coeffinfo[h][w].type=zt_type=czt_type; break; case S_ZTR_D: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_ZTR_D]); coeffinfo[h][w].type=zt_type=czt_type; break; case S_IZ: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_IZ]); coeffinfo[h][w].type=zt_type = czt_type ? VAL : IZ; break; case S_LINIT: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_LINIT]); coeffinfo[h][w].type=zt_type = czt_type ? VZTR : ZTR; break; case S_LZTR: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_LZTR]); coeffinfo[h][w].type=zt_type = czt_type ? VZTR : ZTR; break; case S_LZTR_D: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_LZTR_D]); coeffinfo[h][w].type=zt_type = czt_type ? VZTR : ZTR; break; default: errorHandler("Invalid state (%d) in multi-quant encoding.", coeffinfo[h][w].state); } #ifdef _SHAPE_ } else /* treat out-node as isolated zero for decoding purpose */ { switch(coeffinfo[h][w].state) { case S_INIT: case S_ZTR: case S_ZTR_D: case S_IZ: zt_type = coeffinfo[h][w].type = IZ; break; case S_LINIT: case S_LZTR: case S_LZTR_D: zt_type = coeffinfo[h][w].type = ZTR; break; default: errorHandler("Invalid state (%d) in multi-quant encoding.", coeffinfo[h][w].state); } } #endif } /*~~~~~~~~~~~~~~~~ mark ztr_d and encode magnitudes ~~~~~~~~~~~~~~~~~*/ switch(zt_type) { case ZTR: #ifdef _SHAPE_ if(coeffinfo[h][w].mask!=1) return; #endif case ZTR_D: mark_ZTR_D(h,w); case IZ: coeffinfo[h][w].quantized_value=0; return; case VZTR: mark_ZTR_D(h,w); case VAL: #ifdef _SHAPE_ if(coeffinfo[h][w].mask==1) #endif mag_sign_decode_MQ(h,w); break; default: errorHandler("Invalid type in multi quant decoding."); } } /**********************************************************************/ /*************** MQ TREE ********************************/ /**********************************************************************/ /******************************************************** Function Name ------------- static Void cachb_decode_MQ_tree() Arguments --------- None. Description ----------- Decode AC information for one color component. Multiple quant, treewise scan. Functions Called ---------------- clear_ZTR_D(); decode_pixel_MQ_tree() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::cachb_decode_MQ_tree() { Int h,w, dc_h, dc_w; /* clear the ZTR_D type from the previous pass */ for (color=0; color<NCOL; ++color) { coeffinfo=mzte_codec.m_SPlayer[color].coeffinfo; height=mzte_codec.m_SPlayer[color].height; width=mzte_codec.m_SPlayer[color].width; clear_ZTR_D(coeffinfo, width, height); } for (color=0; color<NCOL; ++color) probModelInitMQ(color); /* ac_h, ac_w init */ dc_h=mzte_codec.m_iDCHeight; dc_w=mzte_codec.m_iDCWidth; for (h=0; h<dc_h; ++h) for (w=0; w<dc_w; ++w) { for (color=0; color<NCOL; ++color) { SNR_IMAGE *snr_image; int tw,sw,sh,n; // 1124 snr_image=&(mzte_codec.m_SPlayer[color].SNRlayer.snr_image); coeffinfo=mzte_codec.m_SPlayer[color].coeffinfo; height=mzte_codec.m_SPlayer[color].height; width=mzte_codec.m_SPlayer[color].width; setProbModelsMQ(color); /* LH */ n = 0; for (tw=mzte_codec.m_iDCWidth; tw < width; tw<<=1) { sh = h << n; sw = (w+dc_w) << n; decodeMQBlocks(sh,sw,n); n++; } /* HL */ n = 0; for (tw=mzte_codec.m_iDCWidth; tw < width; tw<<=1) { sh = (h+dc_h) << n; sw = w << n; decodeMQBlocks(sh,sw,n); n++; } /* HH */ n = 0; for (tw=mzte_codec.m_iDCWidth; tw < width; tw<<=1) { sh = (h+dc_h) << n; sw = (w+dc_w) << n; decodeMQBlocks(sh,sw,n); n++; } #if 0 decode_pixel_MQ_tree(h,w+dc_w); /* LH */ decode_pixel_MQ_tree(h+dc_h,w); /* HL */ decode_pixel_MQ_tree(h+dc_h,w+dc_w); /* HH */ #endif } } for (color=0; color<NCOL; ++color) probModelFreeMQ(color); } #if 0 /******************************************************** Function Name ------------- static Void decode_pixel_MQ_tree(Int h,Int w) Arguments --------- Int h,Int w - position of a pixel in height and width Description ----------- Decoding the type and/or value of a coefficient, a recursive function, multi quant mode. Functions Called ---------------- mzte_ac_decode_symbol() mark_ZTR_D() mag_sign_decode_MQ() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::decode_pixel_MQ_tree(Int h0,Int w0) { Int zt_type, h, w, k; Int dcc[4]; /* Don't Code Children */ Int nSib; /* number siblings */ nSib = (h0<(mzte_codec.m_iDCHeight<<1) && w0<(mzte_codec.m_iDCWidth<<1)) ? 1 : 4; /********************* CODE SIBLINGS *****************************/ for (k=0; k<nSib; ++k) { h = h0 + (k/2); w = w0 + (k%2); /* decode zero tree symbol */ if (IS_RESID(w,h,color)) { zt_type=VAL; } else { Int czt_type; /* what to put on bitstream */ Int l; l=xy2wvtDecompLev(w,h); zt_type = coeffinfo[h][w].type; #ifdef _SHAPE_ if(coeffinfo[h][w].mask==1) /* skip out-node */ { #endif switch(coeffinfo[h][w].state) { case S_INIT: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_INIT]); coeffinfo[h][w].type=zt_type=czt_type; break; case S_ZTR: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_ZTR]); coeffinfo[h][w].type=zt_type=czt_type; break; case S_ZTR_D: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_ZTR_D]); coeffinfo[h][w].type=zt_type=czt_type; break; case S_IZ: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_IZ]); coeffinfo[h][w].type=zt_type = czt_type ? VAL : IZ; break; case S_LINIT: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_LINIT]); coeffinfo[h][w].type=zt_type = czt_type ? VZTR : ZTR; break; case S_LZTR: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_LZTR]); coeffinfo[h][w].type=zt_type = czt_type ? VZTR : ZTR; break; case S_LZTR_D: czt_type=mzte_ac_decode_symbol(&acd,acm_type[l][CONTEXT_LZTR_D]); coeffinfo[h][w].type=zt_type = czt_type ? VZTR : ZTR; break; default: errorHandler("Invalid state (%d) in multi-quant encoding.", coeffinfo[h][w].state); } #ifdef _SHAPE_ } else /* treat out-node as isolated zero for decoding purpose */ { switch(coeffinfo[h][w].state) { case S_INIT: case S_ZTR: case S_ZTR_D: case S_IZ: zt_type = coeffinfo[h][w].type = IZ; break; case S_LINIT: case S_LZTR: case S_LZTR_D: zt_type = coeffinfo[h][w].type = ZTR; break; default: errorHandler("Invalid state (%d) in multi-quant encoding.", coeffinfo[h][w].state); } } #endif } /* mark ztr_d and decode magnitudes */ switch(zt_type) { case ZTR: #ifdef _SHAPE_ if(coeffinfo[h][w].mask==1) { #endif dcc[k]=1; mark_ZTR_D(h,w); /* here it's just to zero out descendents */ #ifdef _SHAPE_ } else { dcc[k]=0; } #endif coeffinfo[h][w].quantized_value=0; break; case IZ: dcc[k]=0; coeffinfo[h][w].quantized_value=0; break; case VZTR: dcc[k]=1; mark_ZTR_D(h,w); /* here it's just to zero out descendents */ #ifdef _SHAPE_ if(coeffinfo[h][w].mask==1) #endif mag_sign_decode_MQ(h,w); break; case VAL: dcc[k]=0; #ifdef _SHAPE_ if(coeffinfo[h][w].mask==1) #endif mag_sign_decode_MQ(h,w); break; default: errorHandler("Invalid type in multi quant decoding."); } } /********************* CODE CHILDREN *****************************/ if (!IS_STATE_LEAF(coeffinfo[h0][w0].state)) { Int i, j; for (k=0; k<nSib; ++k) { if (dcc[k]==0) { h = h0 + (k/2); w = w0 + (k%2); /* scan children */ i=h<<1; j=w<<1; decode_pixel_MQ_tree(i,j); } } } } #endif /******************************************************** Function Name ------------- static Void mark_ZTR_D(Int h,Int w) Arguments --------- Int h,Int w - position of a pixel Description ----------- Mark the coefficient at (h,w) and its descendents as zerotree descendents. Functions Called ---------------- mark_ZTR_D() Return Value ------------ None. ********************************************************/ Void CVTCDecoder::mark_ZTR_D(Int h,Int w) { Int i,j; i=h<<1; j=w<<1; if(i<height && j<width) { coeffinfo[i][j].quantized_value = 0; coeffinfo[i+1][j].quantized_value = 0; coeffinfo[i][j+1].quantized_value = 0; coeffinfo[i+1][j+1].quantized_value = 0; coeffinfo[i][j].type = ZTR_D; coeffinfo[i+1][j].type = ZTR_D; coeffinfo[i][j+1].type = ZTR_D; coeffinfo[i+1][j+1].type = ZTR_D; mark_ZTR_D(i,j); mark_ZTR_D(i+1,j); mark_ZTR_D(i,j+1); mark_ZTR_D(i+1,j+1); } } /******************************************************** Function Name ------------- static Void mag_sign_decode_MQ(Int h,Int w) Arguments --------- Int h,Int w - position of a pixel Description ----------- Decode the value of a coefficient. Functions Called ---------------- mzte_ac_decode_symbol() Return Value ------------ None. ********************************************************/ // hjlee 0901 Void CVTCDecoder::mag_sign_decode_MQ(Int h,Int w) { Int val,v_sign; Int l; if(coeffinfo[h][w].skip) { coeffinfo[h][w].quantized_value=0; return; } l=xy2wvtDecompLev(w,h); if (IS_RESID(w,h,color)) { val=bitplane_res_decode(l,WVTDECOMP_RES_NUMBITPLANES(color)); coeffinfo[h][w].quantized_value=val; } else { val=bitplane_decode(l,WVTDECOMP_NUMBITPLANES(color,l))+1; v_sign=mzte_ac_decode_symbol(&acd,acm_sign[l]); coeffinfo[h][w].quantized_value=(v_sign==0) ? val : -val; } } /************************************************************* Function Name ------------- Void decodeSQBlocks() Arguments --------- Int y, Int x - Coordinate of upper left hand corner of block. Int n - Number of 4 blocks in a side of the total block. 0 means do only pixel at (x,y). Void (*pixelFunc)(Int, Int) - Function to call for pixel locations. Description ----------- Call function pixelFunc(y,x) for all pixels (x,y) in block in band scan manner. Functions Called ---------------- decodeBlocks recursively. Return Value ------------ None. *************************************************************/ Void CVTCDecoder::decodeSQBlocks(Int y, Int x, Int n) { /* Call the encoding function for the 4 block pixels */ if (n == 0) { /* For checking scan-order : use 16x16 mono image for comparison with Figure 7-38 scan order table in document. static Int i=4; noteStat("%d: y=%d, x=%d\n",i++, y,x); */ decode_pixel_SQ(y,x); } else { Int k; --n; k = 1<<n; decodeSQBlocks(y,x,n); x += k; decodeSQBlocks(y,x,n); x -= k; y += k; decodeSQBlocks(y,x,n); x += k; decodeSQBlocks(y,x,n); } } /************************************************************* Function Name ------------- Void decodeSQBlocks() Arguments --------- Int y, Int x - Coordinate of upper left hand corner of block. Int n - Number of 4 blocks in a side of the total block. 0 means do only pixel at (x,y). Void (*pixelFunc)(Int, Int) - Function to call for pixel locations. Description ----------- Call function pixelFunc(y,x) for all pixels (x,y) in block in band scan manner. Functions Called ---------------- decodeBlocks recursively. Return Value ------------ None. *************************************************************/ Void CVTCDecoder::decodeMQBlocks(Int y, Int x, Int n) { /* Call the encoding function for the 4 block pixels */ if (n == 0) { /* For checking scan-order : use 16x16 mono image for comparison with Figure 7-38 scan order table in document. static Int i=4; noteStat("%d: y=%d, x=%d\n",i++, y,x); */ decode_pixel_MQ(y,x); } else { Int k; --n; k = 1<<n; decodeMQBlocks(y,x,n); x += k; decodeMQBlocks(y,x,n); x -= k; y += k; decodeMQBlocks(y,x,n); x += k; decodeMQBlocks(y,x,n); } }
72718007839cc1150f155b664ac0cb9e227465f0
a688b843b561a08cf0bcd45fb9d082deac745dc9
/lib/SEM/Scope.cpp
69c7eb45e9f908daad9ae666aaca57aa20ebfb5f
[ "MIT" ]
permissive
mna/locic
5c3abc94910ec01c0a0f7be7a23e856a85924c10
abb06380bfc88732b4427ae909f1c8c616593ef4
refs/heads/master
2023-06-08T23:56:47.499047
2015-06-27T03:28:57
2015-06-27T03:28:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,397
cpp
#include <string> #include <locic/Support/Array.hpp> #include <locic/Support/String.hpp> #include <locic/SEM/ExitStates.hpp> #include <locic/SEM/Scope.hpp> #include <locic/SEM/Statement.hpp> #include <locic/SEM/Var.hpp> namespace locic { namespace SEM { std::unique_ptr<Scope> Scope::Create() { return std::unique_ptr<Scope>(new Scope()); } Scope::Scope() { } ExitStates Scope::exitStates() const { // TODO: precompute this! const auto& statementList = statements(); if (statementList.empty()) { return ExitStates::Normal(); } ExitStates scopeExitStates = ExitStates::None(); // All states that aren't an exception state (e.g. UnwindStateThrow) // can be blocked by a scope(success) block that always throws. bool isNoThrowBlocked = false; // The pending states for scope(success) that occur if we have a no-throw exit. ExitStates scopeSuccessPendingStates = ExitStates::None(); for (const auto& statement: statementList) { auto statementExitStates = statement.exitStates(); // Block 'normal' exit state until we // reach the end of the scope. statementExitStates &= ~(ExitStates::Normal()); // Add pending scope(success) exit states if there's // a no-throw exit state from this statement (which isn't // just continuing to the next statement). if ((statementExitStates & (ExitStates::Return() | ExitStates::Break() | ExitStates::Continue())) != ExitStates::None()) { scopeExitStates |= scopeSuccessPendingStates; } // Also block other no-throw states as necessary. if (isNoThrowBlocked) { statementExitStates &= ~(ExitStates::Return() | ExitStates::Break() | ExitStates::Continue()); } scopeExitStates |= statementExitStates; // Handle scope(success) specially, since these statements can // be run in a 'normal' state if (statement.kind() == SEM::Statement::SCOPEEXIT && statement.getScopeExitState() == "success") { const auto scopeSuccessStates = statement.getScopeExitScope().exitStates(); assert((scopeSuccessStates & ~(ExitStates::Normal() | ExitStates::Throw() | ExitStates::Rethrow())) == ExitStates::None()); if (!scopeSuccessStates.hasNormalExit()) { // No way to return normally from this scope(success), // so all subsequent statements will have no-throw // exit states blocked (since they'd be filtered and // transferred to throwing states by this statement). isNoThrowBlocked = true; // Also reset pending scope(success) exit states // since any outer scope(success) will never be reached // from here because we always throw. scopeSuccessPendingStates = ExitStates::None(); } // Add throw and rethrow to pending states so that if // a no-throw exit state is encountered later then these // states can be added. if (scopeSuccessStates.hasThrowExit()) { scopeSuccessPendingStates |= ExitStates::Throw(); } if (scopeSuccessStates.hasRethrowExit()) { scopeSuccessPendingStates |= ExitStates::Rethrow(); } } } auto lastStatementExitStates = statementList.back().exitStates(); if ((lastStatementExitStates & (ExitStates::Normal() | ExitStates::Return() | ExitStates::Break() | ExitStates::Continue())) != ExitStates::None()) { scopeExitStates |= scopeSuccessPendingStates; } if (isNoThrowBlocked) { lastStatementExitStates &= ~(ExitStates::Normal() | ExitStates::Return() | ExitStates::Break() | ExitStates::Continue()); } scopeExitStates |= lastStatementExitStates; return scopeExitStates; } Array<Var*, 10>& Scope::variables() { return variables_; } const Array<Var*, 10>& Scope::variables() const { return variables_; } FastMap<String, Var*>& Scope::namedVariables() { return namedVariables_; } const FastMap<String, Var*>& Scope::namedVariables() const { return namedVariables_; } Array<Statement, 10>& Scope::statements() { return statementList_; } const Array<Statement, 10>& Scope::statements() const { return statementList_; } std::string Scope::toString() const { return makeString("Scope(vars: %s, statements: %s)", makeArrayPtrString(variables_).c_str(), makeArrayString(statementList_).c_str()); } } }
da6f7e8b52a2400cf45500ae2dda260ead593830
98d15649a2ca98cfb9c882fb5bab74a343be6cfb
/source/Plugins/Process/MacOSX-User/source/MacOSX/MachVMRegion.h
b12353df823ecca80d3dbee361fd87f38c710e09
[ "NCSA" ]
permissive
eightcien/lldb
ce63522fb4fdcd09e5cad312364571eb9ca00ab2
211925ad15468061135882005efd9d17e9ce8193
refs/heads/master
2016-09-02T15:48:36.938782
2011-03-04T01:54:19
2011-03-04T01:54:19
1,169,442
2
0
null
2013-07-12T20:37:29
2010-12-14T22:03:51
C++
UTF-8
C++
false
false
2,158
h
//===-- MachVMRegion.h ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef liblldb_MachVMRegion_h_ #define liblldb_MachVMRegion_h_ #include <mach/mach.h> #include "lldb/lldb-private.h" #include "lldb/Core/Error.h" class MachVMRegion { public: MachVMRegion(task_t task); ~MachVMRegion(); void Clear(); mach_vm_address_t StartAddress() const { return m_start; } mach_vm_address_t EndAddress() const { return m_start + m_size; } mach_vm_address_t BytesRemaining(mach_vm_address_t addr) const { if (ContainsAddress(addr)) return m_size - (addr - m_start); else return 0; } bool ContainsAddress(mach_vm_address_t addr) const { return addr >= StartAddress() && addr < EndAddress(); } bool SetProtections(mach_vm_address_t addr, mach_vm_size_t size, vm_prot_t prot); bool RestoreProtections(); bool GetRegionForAddress(lldb::addr_t addr); protected: #if defined (VM_REGION_SUBMAP_SHORT_INFO_COUNT_64) typedef vm_region_submap_short_info_data_64_t RegionInfo; enum { kRegionInfoSize = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64 }; #else typedef vm_region_submap_info_data_64_t RegionInfo; enum { kRegionInfoSize = VM_REGION_SUBMAP_INFO_COUNT_64 }; #endif task_t m_task; mach_vm_address_t m_addr; lldb_private::Error m_err; mach_vm_address_t m_start; mach_vm_size_t m_size; natural_t m_depth; RegionInfo m_data; vm_prot_t m_curr_protection; // The current, possibly modified protections. Original value is saved in m_data.protections. mach_vm_address_t m_protection_addr; // The start address at which protections were changed mach_vm_size_t m_protection_size; // The size of memory that had its protections changed }; #endif // #ifndef liblldb_MachVMRegion_h_
[ "spyffe@91177308-0d34-0410-b5e6-96231b3b80d8" ]
spyffe@91177308-0d34-0410-b5e6-96231b3b80d8
3390ade8cf5f53fac6de4f24f135839763b79daf
665943f321d8c5647ab4eeadb687508d2de08de3
/ZeroLeptonRun2/ZeroLeptonDataDrivenQCD.h
0d4a147a3815fed0e9e9bd4ad03e1a05a5425d98
[]
no_license
lawrenceleejr/ZeroLeptonRun2
15672575d1765d342c8c903c04ba0553e5a7c4a4
67042394b0bca205081175f002ef3fb44fd46b98
refs/heads/master
2021-01-19T04:45:06.991785
2015-11-18T12:01:42
2015-11-18T12:01:42
36,355,758
0
2
null
2015-09-29T14:21:02
2015-05-27T09:05:35
C++
UTF-8
C++
false
false
2,238
h
#ifndef ZeroLeptonRun2_ZeroLeptonDataDrivenQCD_H_ #define ZeroLeptonRun2_ZeroLeptonDataDrivenQCD_H_ #include "cafe/Processor.h" #include "ZeroLeptonRun2/Counter.h" #include "ZeroLeptonRun2/QCDSeedSelection.h" #include "ZeroLeptonRun2/PhysObjProxyFiller.h" #include "ZeroLeptonRun2/PhysObjProxyUtils.h" #include "ZeroLeptonRun2/ZeroLeptonUtils.h" #include "ZeroLeptonRun2/ZeroLeptonCutVal.h" #include <string> #include <vector> #include <list> #include <memory> namespace SUSY { class JetMCSmearingTool; } class TH2F; class TFile; //-------------------------------------------------------------------------- // ZeroLeptonDataDrivenQCD selectes QCD data events based on trigger // and balance requirements, applies quality cut and save these "seed events" // in xAOD format if saveSeedEvents is true, else it uses the JetSmearing // package to smear jets, recalculates MET and save the event. // // Works a bit like a cafe::Controller except that the child // Processors are called for each smearing draw. //-------------------------------------------------------------------------- class ZeroLeptonDataDrivenQCD : public cafe::Processor { public: ZeroLeptonDataDrivenQCD(const char *name); ~ZeroLeptonDataDrivenQCD(); void begin(); bool processEvent(xAOD::TEvent& event); void finish(); virtual void inputFileOpened(TFile *file); virtual void inputFileClosing(TFile *file); private: void InitialiseSmearing(); void GetResponseMaps(TFile* smearFnFile,TH2F*& nominal, TH2F*& tailHigh, TH2F*& tailLow); Counter* m_counter; int m_seed; bool m_saveSeedEvents; std::string m_jetkey; QCDSeedSelection m_QCDSeedSelector; PhysObjProxyFiller m_physobjsFiller; PhysObjProxyUtils m_proxyUtils; ZeroLeptonUtils m_ZLUtils; SUSY::JetMCSmearingTool* m_smearingTool; TFile *m_smearFnFile; TFile *m_smearFnFile2; std::string m_GaussianCoreSmearingType; std::vector<std::string> m_containers; ZeroLeptonCutVal m_cutVal; std::list<cafe::Processor*> m_processors; bool add(const std::list<cafe::Processor*>& procs); bool add(cafe::Processor *proc); ZeroLeptonDerivationTag m_derivationTag; public: ClassDef(ZeroLeptonDataDrivenQCD,0); }; #endif // ZeroLeptonRun2_ZeroLeptonDataDrivenQCD_H_
[ "lduflot@4525493e-7705-40b1-a816-d608a930855b" ]
lduflot@4525493e-7705-40b1-a816-d608a930855b
7258196ac025d6fc89f017435238d87c95a246b2
0f552fefd0c0c1c72e540c8a6d3809eee164cd06
/test/pmem_alloc_performance_tests.cpp
b336ff89eb34acd43c75cf5bd44e7db4f1b551d4
[ "BSD-3-Clause" ]
permissive
JohnSully/memkind
7fda961101f7e2e4bfdc0a2ec9965991e6d5e331
7c11836a9b0262ff23ef7f45b47a44996f25ab36
refs/heads/master
2020-06-30T05:27:22.770001
2019-08-05T23:22:51
2019-08-05T23:22:51
200,741,573
0
0
NOASSERTION
2019-08-05T23:16:24
2019-08-05T23:16:24
null
UTF-8
C++
false
false
13,580
cpp
/* * Copyright (C) 2019 Intel Corporation. * 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(s), * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice(s), * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``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(S) 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 "common.h" #include "allocator_perf_tool/TaskFactory.hpp" #include "allocator_perf_tool/Stats.hpp" #include "allocator_perf_tool/Thread.hpp" #include "allocator_perf_tool/GTestAdapter.hpp" #include "allocator_perf_tool/PmemMockup.hpp" static const size_t PMEM_PART_SIZE = 0; extern const char *PMEM_DIR; class PmemAllocPerformanceTest: public :: testing::Test { private: AllocatorFactory allocator_factory; protected: void SetUp() { allocator_factory.initialize_allocator(AllocatorTypes::STANDARD_ALLOCATOR); int err = memkind_create_pmem(PMEM_DIR, PMEM_PART_SIZE, &MEMKIND_PMEM_MOCKUP); ASSERT_EQ(0, err); ASSERT_NE(nullptr, MEMKIND_PMEM_MOCKUP); } void TearDown() { int err = memkind_destroy_kind(MEMKIND_PMEM_MOCKUP); ASSERT_EQ(0, err); } float run(unsigned kind, unsigned call, size_t threads_number, size_t alloc_size, unsigned mem_operations_num) { TaskFactory task_factory; std::vector<Thread *> threads; std::vector<Task *> tasks; TypesConf func_calls; TypesConf allocator_types; func_calls.enable_type(FunctionCalls::FREE); func_calls.enable_type(call); allocator_types.enable_type(kind); TaskConf conf = { mem_operations_num, //number of memory operations { mem_operations_num, //number of memory operations alloc_size, //min. size of single allocation alloc_size //max. size of single allocatioion }, func_calls, //enable function calls allocator_types, //enable allocators 11, //random seed false, //do not log memory operations and statistics to csv file }; for (int i=0; i<threads_number; i++) { Task *task = task_factory.create(conf); tasks.push_back(task); threads.push_back(new Thread(task)); conf.seed += 1; } ThreadsManager threads_manager(threads); threads_manager.start(); threads_manager.barrier(); TimeStats time_stats; for (int i=0; i<tasks.size(); i++) { time_stats += tasks[i]->get_results(); } return time_stats.stats[kind][call].total_time; } void run_test(unsigned kind, unsigned call, size_t threads_number, size_t alloc_size, unsigned mem_operations_num) { allocator_factory.initialize_allocator(kind); float ref_time = run(AllocatorTypes::STANDARD_ALLOCATOR, call, threads_number, alloc_size, mem_operations_num); float perf_time = run(kind, call, threads_number, alloc_size, mem_operations_num); float ref_delta_time_percent = allocator_factory.calc_ref_delta(ref_time, perf_time); GTestAdapter::RecordProperty("total_time_spend_on_alloc", perf_time); GTestAdapter::RecordProperty("alloc_operations_per_thread", mem_operations_num); GTestAdapter::RecordProperty("ref_delta_time_percent", ref_delta_time_percent); } }; TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 1, 100, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 1, 4096, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 1, 1000, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 1, 1001, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 1, 1572864, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 10, 100, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 10, 4096, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 10, 1000, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 10, 1001, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 10, 1572864, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 72, 100, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 72, 4096, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 72, 1000, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 72, 1001, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_malloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::MALLOC, 72, 1572864, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 1, 100, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 1, 4096, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 1, 1000, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 1, 1001, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 1, 1572864, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 10, 100, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 10, 4096, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 10, 1000, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 10, 1001, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 10, 1572864, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 72, 100, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 72, 4096, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 72, 1000, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 72, 1001, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_calloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::CALLOC, 72, 1572864, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_1_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 1, 100, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_1_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 1, 4096, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_1_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 1, 1000, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_1_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 1, 1001, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_1_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 1, 1572864, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_10_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 10, 100, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_10_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 10, 4096, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_10_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 10, 1000, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_10_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 10, 1001, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_10_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 10, 1572864, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_72_thread_100_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 72, 100, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_72_thread_4096_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 72, 4096, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_72_thread_1000_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 72, 1000, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_72_thread_1001_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 72, 1001, 10000); } TEST_F(PmemAllocPerformanceTest, test_TC_MEMKIND_MEMKIND_PMEM_realloc_72_thread_1572864_bytes) { run_test(AllocatorTypes::MEMKIND_PMEM, FunctionCalls::REALLOC, 72, 1572864, 10000); }
8d6c9354d8e0507a46ad79f5069c7929ec03369f
2d926da3a7e99582bcc09e9a61e70a0d7175e8f8
/src/Magnum/Audio/Audio.cpp
3c8ab8a19ce1d83b0475a8012715545a0844d4a4
[ "MIT" ]
permissive
black6816/magnum
5879fdf569b19bd835c1db87d3d5ce2f211e6c9f
a49602987499379e4a2d155472961d99ddfc75ba
refs/heads/master
2022-12-12T23:11:44.387207
2022-11-16T16:53:06
2022-11-19T14:26:39
155,795,059
0
0
null
2018-11-02T01:01:51
2018-11-02T01:01:51
null
UTF-8
C++
false
false
2,781
cpp
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Vladimír Vondruš <[email protected]> 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 <type_traits> #include "Corrade/configure.h" #include "Magnum/Types.h" #if defined(CORRADE_TARGET_APPLE) && !defined(OPENAL_DEPRECATED) #define OPENAL_DEPRECATED /* Override deprecation warning macro to nothing */ #endif #include <al.h> namespace Magnum { namespace Audio { /* Verify types */ static_assert(std::is_same<ALubyte, UnsignedByte>::value, "ALubyte is not the same as UnsignedByte"); /* ALbyte is defined as `signed char` in OpenAL Soft and `char` in the official SDK from Creative and on Apple. Both are okay. */ static_assert(std::is_same<ALbyte, Byte>::value || (std::is_signed<ALbyte>::value && sizeof(ALbyte) == 1), "ALbyte does not have the characteristics as Byte"); static_assert(std::is_same<ALushort, UnsignedShort>::value, "ALushort is not the same as UnsignedShort"); static_assert(std::is_same<ALshort, Short>::value, "ALshort is not the same as Short"); static_assert(std::is_same<ALuint, UnsignedInt>::value, "ALuint is not the same as UnsignedInt"); static_assert(std::is_same<ALint, Int>::value, "ALint is not the same as Int"); static_assert(std::is_same<ALsizei, Int>::value, "ALsizei is not the same as Int"); static_assert(std::is_same<ALfloat, Float>::value, "ALfloat is not the same as Float"); static_assert(std::is_same<ALdouble, Double>::value, "ALdouble is not the same as Double"); /* Verify boolean values */ static_assert(AL_FALSE == false, "AL_FALSE is not the same as false"); static_assert(AL_TRUE == true, "AL_TRUE is not the same as true"); }}
a8cc3f11464f167cb35b9fa3adda8d2b8cde53b7
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/76/b2b6b0efbe6ed7/main.cpp
75d2cc8f4cc10a5f6e776d18ad0dec234e7e6ec0
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
214
cpp
#include <iostream> using namespace std; int main(int argc, char* argv[]) { cout << argc << endl; if (argc>0) { main(argc-1, argv+1); cout << "My arguments in reverse are: " << argv[0] << endl; } }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
9e88c5b768ea9f88d777efabfc67e794fb24c3c3
9c80d39d5c3d0420e9476da0e8dadb5dca365b0e
/repetier/Printer.cpp
27b1fa8d42bbc5e8952b1a486b9781e94b390be6
[]
no_license
cgspeck/theBeastFirmware
ca0b7c7973db2172518da563c1be3daa09c0389b
ea2706114d0e74ae284aaf84079bf3d96462c159
refs/heads/master
2021-01-01T17:25:50.376213
2017-07-23T03:03:46
2017-07-23T03:03:46
98,070,888
0
0
null
null
null
null
UTF-8
C++
false
false
93,605
cpp
/* This file is part of Repetier-Firmware. Repetier-Firmware 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. Repetier-Firmware 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 Repetier-Firmware. If not, see <http://www.gnu.org/licenses/>. */ #include "Repetier.h" #if USE_ADVANCE ufast8_t Printer::maxExtruderSpeed; ///< Timer delay for end extruder speed volatile int Printer::extruderStepsNeeded; ///< This many extruder steps are still needed, <0 = reverse steps needed. //uint8_t Printer::extruderAccelerateDelay; ///< delay between 2 speec increases #endif uint8_t Printer::unitIsInches = 0; ///< 0 = Units are mm, 1 = units are inches. //Stepper Movement Variables float Printer::axisStepsPerMM[E_AXIS_ARRAY] = {XAXIS_STEPS_PER_MM, YAXIS_STEPS_PER_MM, ZAXIS_STEPS_PER_MM, 1}; ///< Number of steps per mm needed. float Printer::invAxisStepsPerMM[E_AXIS_ARRAY]; ///< Inverse of axisStepsPerMM for faster conversion float Printer::maxFeedrate[E_AXIS_ARRAY] = {MAX_FEEDRATE_X, MAX_FEEDRATE_Y, MAX_FEEDRATE_Z}; ///< Maximum allowed feedrate. float Printer::homingFeedrate[Z_AXIS_ARRAY] = {HOMING_FEEDRATE_X, HOMING_FEEDRATE_Y, HOMING_FEEDRATE_Z}; #if RAMP_ACCELERATION // float max_start_speed_units_per_second[E_AXIS_ARRAY] = MAX_START_SPEED_UNITS_PER_SECOND; ///< Speed we can use, without acceleration. float Printer::maxAccelerationMMPerSquareSecond[E_AXIS_ARRAY] = {MAX_ACCELERATION_UNITS_PER_SQ_SECOND_X,MAX_ACCELERATION_UNITS_PER_SQ_SECOND_Y,MAX_ACCELERATION_UNITS_PER_SQ_SECOND_Z}; ///< X, Y, Z and E max acceleration in mm/s^2 for printing moves or retracts float Printer::maxTravelAccelerationMMPerSquareSecond[E_AXIS_ARRAY] = {MAX_TRAVEL_ACCELERATION_UNITS_PER_SQ_SECOND_X,MAX_TRAVEL_ACCELERATION_UNITS_PER_SQ_SECOND_Y,MAX_TRAVEL_ACCELERATION_UNITS_PER_SQ_SECOND_Z}; ///< X, Y, Z max acceleration in mm/s^2 for travel moves /** Acceleration in steps/s^3 in printing mode.*/ unsigned long Printer::maxPrintAccelerationStepsPerSquareSecond[E_AXIS_ARRAY]; /** Acceleration in steps/s^2 in movement mode.*/ unsigned long Printer::maxTravelAccelerationStepsPerSquareSecond[E_AXIS_ARRAY]; #endif #if NONLINEAR_SYSTEM long Printer::currentDeltaPositionSteps[E_TOWER_ARRAY]; uint8_t lastMoveID = 0; // Last move ID #else int32_t Printer::zCorrectionStepsIncluded = 0; #endif int16_t Printer::zBabystepsMissing = 0; uint8_t Printer::relativeCoordinateMode = false; ///< Determines absolute (false) or relative Coordinates (true). uint8_t Printer::relativeExtruderCoordinateMode = false; ///< Determines Absolute or Relative E Codes while in Absolute Coordinates mode. E is always relative in Relative Coordinates mode. long Printer::currentPositionSteps[E_AXIS_ARRAY]; float Printer::currentPosition[Z_AXIS_ARRAY]; float Printer::lastCmdPos[Z_AXIS_ARRAY]; long Printer::destinationSteps[E_AXIS_ARRAY]; float Printer::coordinateOffset[Z_AXIS_ARRAY] = {0,0,0}; uint8_t Printer::flag0 = 0; uint8_t Printer::flag1 = 0; uint8_t Printer::flag2 = 0; uint8_t Printer::debugLevel = 6; ///< Bitfield defining debug output. 1 = echo, 2 = info, 4 = error, 8 = dry run., 16 = Only communication, 32 = No moves fast8_t Printer::stepsPerTimerCall = 1; uint8_t Printer::menuMode = 0; uint8_t Printer::mode = DEFAULT_PRINTER_MODE; uint8_t Printer::fanSpeed = 0; // Last fan speed set with M106/M107 float Printer::extrudeMultiplyError = 0; float Printer::extrusionFactor = 1.0; uint8_t Printer::interruptEvent = 0; #if EEPROM_MODE != 0 float Printer::zBedOffset = HAL::eprGetFloat(EPR_Z_PROBE_Z_OFFSET); #else float Printer::zBedOffset = Z_PROBE_Z_OFFSET; #endif #if FEATURE_AUTOLEVEL float Printer::autolevelTransformation[9]; ///< Transformation matrix #endif uint32_t Printer::interval = 30000; ///< Last step duration in ticks. uint32_t Printer::timer; ///< used for acceleration/deceleration timing uint32_t Printer::stepNumber; ///< Step number in current move. #if USE_ADVANCE #if ENABLE_QUADRATIC_ADVANCE int32_t Printer::advanceExecuted; ///< Executed advance steps #endif int Printer::advanceStepsSet; #endif #if NONLINEAR_SYSTEM int32_t Printer::maxDeltaPositionSteps; floatLong Printer::deltaDiagonalStepsSquaredA; floatLong Printer::deltaDiagonalStepsSquaredB; floatLong Printer::deltaDiagonalStepsSquaredC; float Printer::deltaMaxRadiusSquared; float Printer::radius0; int32_t Printer::deltaFloorSafetyMarginSteps = 0; int32_t Printer::deltaAPosXSteps; int32_t Printer::deltaAPosYSteps; int32_t Printer::deltaBPosXSteps; int32_t Printer::deltaBPosYSteps; int32_t Printer::deltaCPosXSteps; int32_t Printer::deltaCPosYSteps; int32_t Printer::realDeltaPositionSteps[TOWER_ARRAY]; int16_t Printer::travelMovesPerSecond; int16_t Printer::printMovesPerSecond; #endif #if FEATURE_Z_PROBE || MAX_HARDWARE_ENDSTOP_Z || NONLINEAR_SYSTEM int32_t Printer::stepsRemainingAtZHit; #endif #if DRIVE_SYSTEM == DELTA int32_t Printer::stepsRemainingAtXHit; int32_t Printer::stepsRemainingAtYHit; #endif #if SOFTWARE_LEVELING int32_t Printer::levelingP1[3]; int32_t Printer::levelingP2[3]; int32_t Printer::levelingP3[3]; #endif float Printer::minimumSpeed; ///< lowest allowed speed to keep integration error small float Printer::minimumZSpeed; int32_t Printer::xMaxSteps; ///< For software endstops, limit of move in positive direction. int32_t Printer::yMaxSteps; ///< For software endstops, limit of move in positive direction. int32_t Printer::zMaxSteps; ///< For software endstops, limit of move in positive direction. int32_t Printer::xMinSteps; ///< For software endstops, limit of move in negative direction. int32_t Printer::yMinSteps; ///< For software endstops, limit of move in negative direction. int32_t Printer::zMinSteps; ///< For software endstops, limit of move in negative direction. float Printer::xLength; float Printer::xMin; float Printer::yLength; float Printer::yMin; float Printer::zLength; float Printer::zMin; float Printer::feedrate; ///< Last requested feedrate. int Printer::feedrateMultiply; ///< Multiplier for feedrate in percent (factor 1 = 100) unsigned int Printer::extrudeMultiply; ///< Flow multiplier in percdent (factor 1 = 100) float Printer::maxJerk; ///< Maximum allowed jerk in mm/s #if DRIVE_SYSTEM != DELTA float Printer::maxZJerk; ///< Maximum allowed jerk in z direction in mm/s #endif float Printer::offsetX; ///< X-offset for different extruder positions. float Printer::offsetY; ///< Y-offset for different extruder positions. float Printer::offsetZ; ///< Z-offset for different extruder positions. speed_t Printer::vMaxReached; ///< Maximumu reached speed uint32_t Printer::msecondsPrinting; ///< Milliseconds of printing time (means time with heated extruder) float Printer::filamentPrinted; ///< mm of filament printed since counting started #if ENABLE_BACKLASH_COMPENSATION float Printer::backlashX; float Printer::backlashY; float Printer::backlashZ; uint8_t Printer::backlashDir; #endif float Printer::memoryX; float Printer::memoryY; float Printer::memoryZ; float Printer::memoryE; float Printer::memoryF = -1; #if GANTRY int8_t Printer::motorX; int8_t Printer::motorYorZ; #endif #if FAN_THERMO_PIN > -1 float Printer::thermoMinTemp = FAN_THERMO_MIN_TEMP; float Printer::thermoMaxTemp = FAN_THERMO_MAX_TEMP; #endif #ifdef DEBUG_SEGMENT_LENGTH float Printer::maxRealSegmentLength = 0; #endif #ifdef DEBUG_REAL_JERK float Printer::maxRealJerk = 0; #endif #ifdef DEBUG_PRINT int debugWaitLoop = 0; #endif fast8_t Printer::wizardStackPos; wizardVar Printer::wizardStack[WIZARD_STACK_SIZE]; flag8_t Endstops::lastState = 0; flag8_t Endstops::lastRead = 0; flag8_t Endstops::accumulator = 0; #ifdef EXTENDED_ENDSTOPS flag8_t Endstops::lastState2 = 0; flag8_t Endstops::lastRead2 = 0; flag8_t Endstops::accumulator2 = 0; #endif void Endstops::update() { flag8_t newRead = 0; #ifdef EXTENDED_ENDSTOPS flag8_t newRead2 = 0; #endif #if (X_MIN_PIN > -1) && MIN_HARDWARE_ENDSTOP_X if(READ(X_MIN_PIN) != ENDSTOP_X_MIN_INVERTING) newRead |= ENDSTOP_X_MIN_ID; #endif #if (X_MAX_PIN > -1) && MAX_HARDWARE_ENDSTOP_X if(READ(X_MAX_PIN) != ENDSTOP_X_MAX_INVERTING) newRead |= ENDSTOP_X_MAX_ID; #endif #if (Y_MIN_PIN > -1) && MIN_HARDWARE_ENDSTOP_Y if(READ(Y_MIN_PIN) != ENDSTOP_Y_MIN_INVERTING) newRead |= ENDSTOP_Y_MIN_ID; #endif #if (Y_MAX_PIN > -1) && MAX_HARDWARE_ENDSTOP_Y if(READ(Y_MAX_PIN) != ENDSTOP_Y_MAX_INVERTING) newRead |= ENDSTOP_Y_MAX_ID; #endif #if (Z_MIN_PIN > -1) && MIN_HARDWARE_ENDSTOP_Z if(READ(Z_MIN_PIN) != ENDSTOP_Z_MIN_INVERTING) newRead |= ENDSTOP_Z_MIN_ID; #endif #if (Z_MAX_PIN > -1) && MAX_HARDWARE_ENDSTOP_Z if(READ(Z_MAX_PIN) != ENDSTOP_Z_MAX_INVERTING) newRead |= ENDSTOP_Z_MAX_ID; #endif #if (Z2_MINMAX_PIN > -1) && MINMAX_HARDWARE_ENDSTOP_Z2 if(READ(Z2_MINMAX_PIN) != ENDSTOP_Z2_MINMAX_INVERTING) newRead |= ENDSTOP_Z2_MINMAX_ID; #endif #if FEATURE_Z_PROBE if(Z_PROBE_ON_HIGH ? READ(Z_PROBE_PIN) : !READ(Z_PROBE_PIN)) newRead |= ENDSTOP_Z_PROBE_ID; #endif lastRead &= newRead; #ifdef EXTENDED_ENDSTOPS lastRead2 &= newRead2; #endif // EXTENDED_ENDSTOPS if(lastRead != lastState #ifdef EXTENDED_ENDSTOPS || (lastState2 != lastRead2) #endif ) { // Report endstop hit changes lastState = lastRead; accumulator |= lastState; #ifdef EXTENDED_ENDSTOPS lastState2 = lastRead2; accumulator2 |= lastState2; #endif #ifdef DEBUG_ENDSTOPS report(); #endif } else { lastState = lastRead; #ifdef EXTENDED_ENDSTOPS lastState2 = lastRead2; #endif } lastRead = newRead; #ifdef EXTENDED_ENDSTOPS lastRead2 = newRead2; #endif } void Endstops::report() { Com::printF(PSTR("endstops hit: ")); #if (X_MIN_PIN > -1) && MIN_HARDWARE_ENDSTOP_X Com::printF(Com::tXMinColon); Com::printF(xMin() ? Com::tHSpace : Com::tLSpace); #endif #if (X_MAX_PIN > -1) && MAX_HARDWARE_ENDSTOP_X Com::printF(Com::tXMaxColon); Com::printF(xMax() ? Com::tHSpace : Com::tLSpace); #endif #if (Y_MIN_PIN > -1) && MIN_HARDWARE_ENDSTOP_Y Com::printF(Com::tYMinColon); Com::printF(yMin() ? Com::tHSpace : Com::tLSpace); #endif #if (Y_MAX_PIN > -1) && MAX_HARDWARE_ENDSTOP_Y Com::printF(Com::tYMaxColon); Com::printF(yMax() ? Com::tHSpace : Com::tLSpace); #endif #if (Z_MIN_PIN > -1) && MIN_HARDWARE_ENDSTOP_Z Com::printF(Com::tZMinColon); Com::printF(zMin() ? Com::tHSpace : Com::tLSpace); #endif #if (Z_MAX_PIN > -1) && MAX_HARDWARE_ENDSTOP_Z Com::printF(Com::tZMaxColon); Com::printF(zMax() ? Com::tHSpace : Com::tLSpace); #endif #if (Z2_MINMAX_PIN > -1) && MINMAX_HARDWARE_ENDSTOP_Z2 Com::printF(Com::tZMinMaxColon); Com::printF(z2MinMax() ? Com::tHSpace : Com::tLSpace); #endif #if FEATURE_Z_PROBE Com::printF(Com::tZProbeState); Com::printF(zProbe() ? Com::tHSpace : Com::tLSpace); #endif Com::println(); } #if !NONLINEAR_SYSTEM void Printer::constrainDestinationCoords() { if(isNoDestinationCheck()) return; #if min_software_endstop_x if (destinationSteps[X_AXIS] < xMinSteps) Printer::destinationSteps[X_AXIS] = Printer::xMinSteps; #endif #if min_software_endstop_y if (destinationSteps[Y_AXIS] < yMinSteps) Printer::destinationSteps[Y_AXIS] = Printer::yMinSteps; #endif #if min_software_endstop_z if (isAutolevelActive() == false && destinationSteps[Z_AXIS] < zMinSteps && !isZProbingActive()) Printer::destinationSteps[Z_AXIS] = Printer::zMinSteps; #endif #if max_software_endstop_x if (destinationSteps[X_AXIS] > Printer::xMaxSteps) Printer::destinationSteps[X_AXIS] = Printer::xMaxSteps; #endif #if max_software_endstop_y if (destinationSteps[Y_AXIS] > Printer::yMaxSteps) Printer::destinationSteps[Y_AXIS] = Printer::yMaxSteps; #endif #if max_software_endstop_z if (isAutolevelActive() == false && destinationSteps[Z_AXIS] > Printer::zMaxSteps && !isZProbingActive()) Printer::destinationSteps[Z_AXIS] = Printer::zMaxSteps; #endif } #endif void Printer::setDebugLevel(uint8_t newLevel) { debugLevel = newLevel; Com::printFLN(PSTR("DebugLevel:"),(int)newLevel); } void Printer::toggleEcho() { setDebugLevel(debugLevel ^ 32); } void Printer::toggleInfo() { setDebugLevel(debugLevel ^ 2); } void Printer::toggleErrors() { setDebugLevel(debugLevel ^ 4); } void Printer::toggleDryRun() { setDebugLevel(debugLevel ^ 8); } void Printer::toggleCommunication() { setDebugLevel(debugLevel ^ 16); } void Printer::toggleNoMoves() { setDebugLevel(debugLevel ^ 32); } bool Printer::isPositionAllowed(float x,float y,float z) { if(isNoDestinationCheck()) return true; bool allowed = true; #if DRIVE_SYSTEM == DELTA allowed &= (z >= 0) && (z <= zLength + 0.05 + ENDSTOP_Z_BACK_ON_HOME); allowed &= (x * x + y * y <= deltaMaxRadiusSquared); #endif // DRIVE_SYSTEM if(!allowed) { Printer::updateCurrentPosition(true); Commands::printCurrentPosition(PSTR("isPositionAllowed ")); } return allowed; } void Printer::setFanSpeedDirectly(uint8_t speed) { #if FAN_PIN > -1 && FEATURE_FAN_CONTROL if(pwm_pos[PWM_FAN1] == speed) return; #if FAN_KICKSTART_TIME if(fanKickstart == 0 && speed > pwm_pos[PWM_FAN1] && speed < 85) { if(pwm_pos[PWM_FAN1]) fanKickstart = FAN_KICKSTART_TIME / 100; else fanKickstart = FAN_KICKSTART_TIME / 25; } #endif pwm_pos[PWM_FAN1] = speed; #endif } void Printer::setFan2SpeedDirectly(uint8_t speed) { #if FAN2_PIN > -1 && FEATURE_FAN2_CONTROL if(pwm_pos[PWM_FAN2] == speed) return; #if FAN_KICKSTART_TIME if(fan2Kickstart == 0 && speed > pwm_pos[PWM_FAN2] && speed < 85) { if(pwm_pos[PWM_FAN2]) fan2Kickstart = FAN_KICKSTART_TIME / 100; else fan2Kickstart = FAN_KICKSTART_TIME / 25; } #endif pwm_pos[PWM_FAN2] = speed; #endif } void Printer::reportPrinterMode() { switch(Printer::mode) { case PRINTER_MODE_FFF: Com::printFLN(Com::tPrinterModeFFF); break; case PRINTER_MODE_LASER: Com::printFLN(Com::tPrinterModeLaser); break; case PRINTER_MODE_CNC: Com::printFLN(Com::tPrinterModeCNC); break; } } void Printer::updateDerivedParameter() { #if DRIVE_SYSTEM == DELTA travelMovesPerSecond = EEPROM::deltaSegmentsPerSecondMove(); printMovesPerSecond = EEPROM::deltaSegmentsPerSecondPrint(); axisStepsPerMM[X_AXIS] = axisStepsPerMM[Y_AXIS] = axisStepsPerMM[Z_AXIS]; maxAccelerationMMPerSquareSecond[X_AXIS] = maxAccelerationMMPerSquareSecond[Y_AXIS] = maxAccelerationMMPerSquareSecond[Z_AXIS]; homingFeedrate[X_AXIS] = homingFeedrate[Y_AXIS] = homingFeedrate[Z_AXIS]; maxFeedrate[X_AXIS] = maxFeedrate[Y_AXIS] = maxFeedrate[Z_AXIS]; maxTravelAccelerationMMPerSquareSecond[X_AXIS] = maxTravelAccelerationMMPerSquareSecond[Y_AXIS] = maxTravelAccelerationMMPerSquareSecond[Z_AXIS]; zMaxSteps = axisStepsPerMM[Z_AXIS] * (zLength); towerAMinSteps = axisStepsPerMM[A_TOWER] * xMin; towerBMinSteps = axisStepsPerMM[B_TOWER] * yMin; towerCMinSteps = axisStepsPerMM[C_TOWER] * zMin; //radius0 = EEPROM::deltaHorizontalRadius(); float radiusA = radius0 + EEPROM::deltaRadiusCorrectionA(); float radiusB = radius0 + EEPROM::deltaRadiusCorrectionB(); float radiusC = radius0 + EEPROM::deltaRadiusCorrectionC(); deltaAPosXSteps = floor(radiusA * cos(EEPROM::deltaAlphaA() * M_PI / 180.0f) * axisStepsPerMM[Z_AXIS] + 0.5f); deltaAPosYSteps = floor(radiusA * sin(EEPROM::deltaAlphaA() * M_PI / 180.0f) * axisStepsPerMM[Z_AXIS] + 0.5f); deltaBPosXSteps = floor(radiusB * cos(EEPROM::deltaAlphaB() * M_PI / 180.0f) * axisStepsPerMM[Z_AXIS] + 0.5f); deltaBPosYSteps = floor(radiusB * sin(EEPROM::deltaAlphaB() * M_PI / 180.0f) * axisStepsPerMM[Z_AXIS] + 0.5f); deltaCPosXSteps = floor(radiusC * cos(EEPROM::deltaAlphaC() * M_PI / 180.0f) * axisStepsPerMM[Z_AXIS] + 0.5f); deltaCPosYSteps = floor(radiusC * sin(EEPROM::deltaAlphaC() * M_PI / 180.0f) * axisStepsPerMM[Z_AXIS] + 0.5f); deltaDiagonalStepsSquaredA.l = static_cast<uint32_t>((EEPROM::deltaDiagonalCorrectionA() + EEPROM::deltaDiagonalRodLength())*axisStepsPerMM[Z_AXIS]); deltaDiagonalStepsSquaredB.l = static_cast<uint32_t>((EEPROM::deltaDiagonalCorrectionB() + EEPROM::deltaDiagonalRodLength())*axisStepsPerMM[Z_AXIS]); deltaDiagonalStepsSquaredC.l = static_cast<uint32_t>((EEPROM::deltaDiagonalCorrectionC() + EEPROM::deltaDiagonalRodLength())*axisStepsPerMM[Z_AXIS]); if(deltaDiagonalStepsSquaredA.l > 65534 || 2 * radius0*axisStepsPerMM[Z_AXIS] > 65534) { setLargeMachine(true); #ifdef SUPPORT_64_BIT_MATH deltaDiagonalStepsSquaredA.L = RMath::sqr(static_cast<uint64_t>(deltaDiagonalStepsSquaredA.l)); deltaDiagonalStepsSquaredB.L = RMath::sqr(static_cast<uint64_t>(deltaDiagonalStepsSquaredB.l)); deltaDiagonalStepsSquaredC.L = RMath::sqr(static_cast<uint64_t>(deltaDiagonalStepsSquaredC.l)); #else deltaDiagonalStepsSquaredA.f = RMath::sqr(static_cast<float>(deltaDiagonalStepsSquaredA.l)); deltaDiagonalStepsSquaredB.f = RMath::sqr(static_cast<float>(deltaDiagonalStepsSquaredB.l)); deltaDiagonalStepsSquaredC.f = RMath::sqr(static_cast<float>(deltaDiagonalStepsSquaredC.l)); #endif } else { setLargeMachine(false); deltaDiagonalStepsSquaredA.l = RMath::sqr(deltaDiagonalStepsSquaredA.l); deltaDiagonalStepsSquaredB.l = RMath::sqr(deltaDiagonalStepsSquaredB.l); deltaDiagonalStepsSquaredC.l = RMath::sqr(deltaDiagonalStepsSquaredC.l); } deltaMaxRadiusSquared = RMath::sqr(EEPROM::deltaMaxRadius()); long cart[Z_AXIS_ARRAY], delta[TOWER_ARRAY]; cart[X_AXIS] = cart[Y_AXIS] = 0; cart[Z_AXIS] = zMaxSteps; transformCartesianStepsToDeltaSteps(cart, delta); maxDeltaPositionSteps = delta[0]; xMaxSteps = yMaxSteps = zMaxSteps; xMinSteps = yMinSteps = zMinSteps = 0; deltaFloorSafetyMarginSteps = DELTA_FLOOR_SAFETY_MARGIN_MM * axisStepsPerMM[Z_AXIS]; #elif DRIVE_SYSTEM == TUGA deltaDiagonalStepsSquared.l = uint32_t(EEPROM::deltaDiagonalRodLength() * axisStepsPerMM[X_AXIS]); if(deltaDiagonalStepsSquared.l > 65534) { setLargeMachine(true); deltaDiagonalStepsSquared.f = float(deltaDiagonalStepsSquared.l) * float(deltaDiagonalStepsSquared.l); } else deltaDiagonalStepsSquared.l = deltaDiagonalStepsSquared.l * deltaDiagonalStepsSquared.l; deltaBPosXSteps = static_cast<int32_t>(EEPROM::deltaDiagonalRodLength() * axisStepsPerMM[X_AXIS]); xMaxSteps = static_cast<int32_t>(axisStepsPerMM[X_AXIS] * (xMin + xLength)); yMaxSteps = static_cast<int32_t>(axisStepsPerMM[Y_AXIS] * yLength); zMaxSteps = static_cast<int32_t>(axisStepsPerMM[Z_AXIS] * (zMin + zLength)); xMinSteps = static_cast<int32_t>(axisStepsPerMM[X_AXIS] * xMin); yMinSteps = 0; zMinSteps = static_cast<int32_t>(axisStepsPerMM[Z_AXIS] * zMin); #else xMaxSteps = static_cast<int32_t>(axisStepsPerMM[X_AXIS] * (xMin + xLength)); yMaxSteps = static_cast<int32_t>(axisStepsPerMM[Y_AXIS] * (yMin + yLength)); zMaxSteps = static_cast<int32_t>(axisStepsPerMM[Z_AXIS] * (zMin + zLength)); xMinSteps = static_cast<int32_t>(axisStepsPerMM[X_AXIS] * xMin); yMinSteps = static_cast<int32_t>(axisStepsPerMM[Y_AXIS] * yMin); zMinSteps = static_cast<int32_t>(axisStepsPerMM[Z_AXIS] * zMin); // For which directions do we need backlash compensation #if ENABLE_BACKLASH_COMPENSATION backlashDir &= XYZ_DIRPOS; if(backlashX != 0) backlashDir |= 8; if(backlashY != 0) backlashDir |= 16; if(backlashZ != 0) backlashDir |= 32; #endif #endif for(uint8_t i = 0; i < E_AXIS_ARRAY; i++) { invAxisStepsPerMM[i] = 1.0f/axisStepsPerMM[i]; #ifdef RAMP_ACCELERATION /** Acceleration in steps/s^3 in printing mode.*/ maxPrintAccelerationStepsPerSquareSecond[i] = maxAccelerationMMPerSquareSecond[i] * axisStepsPerMM[i]; /** Acceleration in steps/s^2 in movement mode.*/ maxTravelAccelerationStepsPerSquareSecond[i] = maxTravelAccelerationMMPerSquareSecond[i] * axisStepsPerMM[i]; #endif } float accel = RMath::max(maxAccelerationMMPerSquareSecond[X_AXIS], maxTravelAccelerationMMPerSquareSecond[X_AXIS]); minimumSpeed = accel * sqrt(2.0f / (axisStepsPerMM[X_AXIS]*accel)); accel = RMath::max(maxAccelerationMMPerSquareSecond[Z_AXIS], maxTravelAccelerationMMPerSquareSecond[Z_AXIS]); minimumZSpeed = accel * sqrt(2.0f / (axisStepsPerMM[Z_AXIS] * accel)); #if DISTORTION_CORRECTION distortion.updateDerived(); #endif // DISTORTION_CORRECTION Printer::updateAdvanceFlags(); EVENT_UPDATE_DERIVED; } /** \brief Stop heater and stepper motors. Disable power,if possible. */ void Printer::kill(uint8_t only_steppers) { EVENT_KILL(only_steppers); if(areAllSteppersDisabled() && only_steppers) return; if(Printer::isAllKilled()) return; setAllSteppersDiabled(); #if defined(NUM_MOTOR_DRIVERS) && NUM_MOTOR_DRIVERS > 0 disableAllMotorDrivers(); #endif // defined disableXStepper(); disableYStepper(); #if !defined(PREVENT_Z_DISABLE_ON_STEPPER_TIMEOUT) disableZStepper(); #else if(!only_steppers) disableZStepper(); #endif Extruder::disableAllExtruderMotors(); if(!only_steppers) { for(uint8_t i = 0; i < NUM_TEMPERATURE_LOOPS; i++) Extruder::setTemperatureForExtruder(0, i); Extruder::setHeatedBedTemperature(0); UI_STATUS_UPD_F(Com::translatedF(UI_TEXT_STANDBY_ID)); #if defined(PS_ON_PIN) && PS_ON_PIN>-1 //pinMode(PS_ON_PIN,INPUT); SET_OUTPUT(PS_ON_PIN); //GND WRITE(PS_ON_PIN, (POWER_INVERTING ? LOW : HIGH)); Printer::setPowerOn(false); #endif Printer::setAllKilled(true); } else UI_STATUS_UPD_F(Com::translatedF(UI_TEXT_STEPPER_DISABLED_ID)); #if FAN_BOARD_PIN > -1 #if HAVE_HEATED_BED if(heatedBedController.targetTemperatureC < 15) // turn off FAN_BOARD only if bed heater is off #endif pwm_pos[PWM_BOARD_FAN] = 0; #endif // FAN_BOARD_PIN } void Printer::updateAdvanceFlags() { Printer::setAdvanceActivated(false); #if USE_ADVANCE for(uint8_t i = 0; i < NUM_EXTRUDER; i++) { if(extruder[i].advanceL != 0) { Printer::setAdvanceActivated(true); } #if ENABLE_QUADRATIC_ADVANCE if(extruder[i].advanceK != 0) Printer::setAdvanceActivated(true); #endif } #endif } // This is for untransformed move to coordinates in printers absolute cartesian space uint8_t Printer::moveTo(float x,float y,float z,float e,float f) { if(x != IGNORE_COORDINATE) destinationSteps[X_AXIS] = (x + Printer::offsetX) * axisStepsPerMM[X_AXIS]; if(y != IGNORE_COORDINATE) destinationSteps[Y_AXIS] = (y + Printer::offsetY) * axisStepsPerMM[Y_AXIS]; if(z != IGNORE_COORDINATE) destinationSteps[Z_AXIS] = (z + Printer::offsetZ) * axisStepsPerMM[Z_AXIS]; if(e != IGNORE_COORDINATE) destinationSteps[E_AXIS] = e * axisStepsPerMM[E_AXIS]; if(f != IGNORE_COORDINATE) feedrate = f; #if NONLINEAR_SYSTEM // Disable software endstop or we get wrong distances when length < real length if (!PrintLine::queueDeltaMove(ALWAYS_CHECK_ENDSTOPS, true, false)) { Com::printWarningFLN(PSTR("moveTo / queueDeltaMove returns error")); return 0; } #else PrintLine::queueCartesianMove(ALWAYS_CHECK_ENDSTOPS, true); #endif updateCurrentPosition(false); return 1; } // Move to transformed cartesian coordinates, mapping real (model) space to printer space uint8_t Printer::moveToReal(float x, float y, float z, float e, float f,bool pathOptimize) { if(x == IGNORE_COORDINATE) x = currentPosition[X_AXIS]; else currentPosition[X_AXIS] = x; if(y == IGNORE_COORDINATE) y = currentPosition[Y_AXIS]; else currentPosition[Y_AXIS] = y; if(z == IGNORE_COORDINATE) z = currentPosition[Z_AXIS]; else currentPosition[Z_AXIS] = z; #if FEATURE_AUTOLEVEL if(isAutolevelActive()) transformToPrinter(x + Printer::offsetX, y + Printer::offsetY, z + Printer::offsetZ, x, y, z); else #endif // FEATURE_AUTOLEVEL { x += Printer::offsetX; y += Printer::offsetY; z += Printer::offsetZ; } // There was conflicting use of IGNOR_COORDINATE destinationSteps[X_AXIS] = static_cast<int32_t>(floor(x * axisStepsPerMM[X_AXIS] + 0.5f)); destinationSteps[Y_AXIS] = static_cast<int32_t>(floor(y * axisStepsPerMM[Y_AXIS] + 0.5f)); destinationSteps[Z_AXIS] = static_cast<int32_t>(floor(z * axisStepsPerMM[Z_AXIS] + 0.5f)); if(e != IGNORE_COORDINATE && !Printer::debugDryrun() #if MIN_EXTRUDER_TEMP > 30 && (Extruder::current->tempControl.currentTemperatureC > MIN_EXTRUDER_TEMP || Printer::isColdExtrusionAllowed()) #endif ) destinationSteps[E_AXIS] = e * axisStepsPerMM[E_AXIS]; if(f != IGNORE_COORDINATE) feedrate = f; #if NONLINEAR_SYSTEM if (!PrintLine::queueDeltaMove(ALWAYS_CHECK_ENDSTOPS, pathOptimize, true)) { Com::printWarningFLN(PSTR("moveToReal / queueDeltaMove returns error")); SHOWM(x); SHOWM(y); SHOWM(z); return 0; } #else PrintLine::queueCartesianMove(ALWAYS_CHECK_ENDSTOPS, pathOptimize); #endif return 1; } void Printer::setOrigin(float xOff, float yOff, float zOff) { coordinateOffset[X_AXIS] = xOff; coordinateOffset[Y_AXIS] = yOff; coordinateOffset[Z_AXIS] = zOff; } /** Computes currentPosition from currentPositionSteps including correction for offset. */ void Printer::updateCurrentPosition(bool copyLastCmd) { currentPosition[X_AXIS] = static_cast<float>(currentPositionSteps[X_AXIS]) * invAxisStepsPerMM[X_AXIS]; currentPosition[Y_AXIS] = static_cast<float>(currentPositionSteps[Y_AXIS]) * invAxisStepsPerMM[Y_AXIS]; #if NONLINEAR_SYSTEM currentPosition[Z_AXIS] = static_cast<float>(currentPositionSteps[Z_AXIS]) * invAxisStepsPerMM[Z_AXIS]; #else currentPosition[Z_AXIS] = static_cast<float>(currentPositionSteps[Z_AXIS] - zCorrectionStepsIncluded) * invAxisStepsPerMM[Z_AXIS]; #endif #if FEATURE_AUTOLEVEL if(isAutolevelActive()) transformFromPrinter(currentPosition[X_AXIS], currentPosition[Y_AXIS], currentPosition[Z_AXIS], currentPosition[X_AXIS], currentPosition[Y_AXIS], currentPosition[Z_AXIS]); #endif // FEATURE_AUTOLEVEL currentPosition[X_AXIS] -= Printer::offsetX; currentPosition[Y_AXIS] -= Printer::offsetY; currentPosition[Z_AXIS] -= Printer::offsetZ; if(copyLastCmd) { lastCmdPos[X_AXIS] = currentPosition[X_AXIS]; lastCmdPos[Y_AXIS] = currentPosition[Y_AXIS]; lastCmdPos[Z_AXIS] = currentPosition[Z_AXIS]; } } /** \brief Sets the destination coordinates to values stored in com. For the computation of the destination, the following facts are considered: - Are units inches or mm. - Reltive or absolute positioning with special case only extruder relative. - Offset in x and y direction for multiple extruder support. */ uint8_t Printer::setDestinationStepsFromGCode(GCode *com) { register int32_t p; float x, y, z; #if FEATURE_RETRACTION if(com->hasNoXYZ() && com->hasE() && isAutoretract()) { // convert into autoretract if(relativeCoordinateMode || relativeExtruderCoordinateMode) { Extruder::current->retract(com->E < 0,false); } else { p = convertToMM(com->E * axisStepsPerMM[E_AXIS]); // current position Extruder::current->retract(com->E < p,false); } return 0; // Fake no move so nothing gets added } #endif if(!relativeCoordinateMode) { if(com->hasX()) lastCmdPos[X_AXIS] = currentPosition[X_AXIS] = convertToMM(com->X) - coordinateOffset[X_AXIS]; if(com->hasY()) lastCmdPos[Y_AXIS] = currentPosition[Y_AXIS] = convertToMM(com->Y) - coordinateOffset[Y_AXIS]; if(com->hasZ()) lastCmdPos[Z_AXIS] = currentPosition[Z_AXIS] = convertToMM(com->Z) - coordinateOffset[Z_AXIS]; } else { if(com->hasX()) currentPosition[X_AXIS] = (lastCmdPos[X_AXIS] += convertToMM(com->X)); if(com->hasY()) currentPosition[Y_AXIS] = (lastCmdPos[Y_AXIS] += convertToMM(com->Y)); if(com->hasZ()) currentPosition[Z_AXIS] = (lastCmdPos[Z_AXIS] += convertToMM(com->Z)); } #if FEATURE_AUTOLEVEL if(isAutolevelActive()) { transformToPrinter(lastCmdPos[X_AXIS] + Printer::offsetX, lastCmdPos[Y_AXIS] + Printer::offsetY, lastCmdPos[Z_AXIS] + Printer::offsetZ, x, y, z); } else #endif // FEATURE_AUTOLEVEL { x = lastCmdPos[X_AXIS] + Printer::offsetX; y = lastCmdPos[Y_AXIS] + Printer::offsetY; z = lastCmdPos[Z_AXIS] + Printer::offsetZ; } destinationSteps[X_AXIS] = static_cast<int32_t>(floor(x * axisStepsPerMM[X_AXIS] + 0.5f)); destinationSteps[Y_AXIS] = static_cast<int32_t>(floor(y * axisStepsPerMM[Y_AXIS] + 0.5f)); destinationSteps[Z_AXIS] = static_cast<int32_t>(floor(z * axisStepsPerMM[Z_AXIS] + 0.5f)); if(com->hasE() && !Printer::debugDryrun()) { p = convertToMM(com->E * axisStepsPerMM[E_AXIS]); if(relativeCoordinateMode || relativeExtruderCoordinateMode) { if( #if MIN_EXTRUDER_TEMP > 20 (Extruder::current->tempControl.currentTemperatureC < MIN_EXTRUDER_TEMP && !Printer::isColdExtrusionAllowed()) || #endif fabs(com->E) * extrusionFactor > EXTRUDE_MAXLENGTH) p = 0; destinationSteps[E_AXIS] = currentPositionSteps[E_AXIS] + p; } else { if( #if MIN_EXTRUDER_TEMP > 20 (Extruder::current->tempControl.currentTemperatureC < MIN_EXTRUDER_TEMP && !Printer::isColdExtrusionAllowed()) || #endif fabs(p - currentPositionSteps[E_AXIS]) * extrusionFactor > EXTRUDE_MAXLENGTH * axisStepsPerMM[E_AXIS]) currentPositionSteps[E_AXIS] = p; destinationSteps[E_AXIS] = p; } } else Printer::destinationSteps[E_AXIS] = Printer::currentPositionSteps[E_AXIS]; if(com->hasF()) { if(unitIsInches) feedrate = com->F * 0.0042333f * (float)feedrateMultiply; // Factor is 25.5/60/100 else feedrate = com->F * (float)feedrateMultiply * 0.00016666666f; } if(!Printer::isPositionAllowed(lastCmdPos[X_AXIS], lastCmdPos[Y_AXIS], lastCmdPos[Z_AXIS])) { currentPositionSteps[E_AXIS] = destinationSteps[E_AXIS]; return false; // ignore move } return !com->hasNoXYZ() || (com->hasE() && destinationSteps[E_AXIS] != currentPositionSteps[E_AXIS]); // ignore unproductive moves } void Printer::setup() { HAL::stopWatchdog(); #if FEATURE_CONTROLLER == CONTROLLER_VIKI HAL::delayMilliseconds(100); #endif // FEATURE_CONTROLLER #if UI_DISPLAY_TYPE != NO_DISPLAY Com::selectLanguage(0); // just make sure we have a language in case someone uses it early #endif //HAL::delayMilliseconds(500); // add a delay at startup to give hardware time for initalization #if defined(EEPROM_AVAILABLE) && defined(EEPROM_SPI_ALLIGATOR) && EEPROM_AVAILABLE == EEPROM_SPI_ALLIGATOR HAL::spiBegin(); #endif HAL::hwSetup(); #ifdef ANALYZER // Channel->pin assignments #if ANALYZER_CH0>=0 SET_OUTPUT(ANALYZER_CH0); #endif #if ANALYZER_CH1>=0 SET_OUTPUT(ANALYZER_CH1); #endif #if ANALYZER_CH2>=0 SET_OUTPUT(ANALYZER_CH2); #endif #if ANALYZER_CH3>=0 SET_OUTPUT(ANALYZER_CH3); #endif #if ANALYZER_CH4>=0 SET_OUTPUT(ANALYZER_CH4); #endif #if ANALYZER_CH5>=0 SET_OUTPUT(ANALYZER_CH5); #endif #if ANALYZER_CH6>=0 SET_OUTPUT(ANALYZER_CH6); #endif #if ANALYZER_CH7>=0 SET_OUTPUT(ANALYZER_CH7); #endif #endif #if defined(ENABLE_POWER_ON_STARTUP) && ENABLE_POWER_ON_STARTUP && (PS_ON_PIN>-1) SET_OUTPUT(PS_ON_PIN); //GND WRITE(PS_ON_PIN, (POWER_INVERTING ? HIGH : LOW)); Printer::setPowerOn(true); #else #if PS_ON_PIN > -1 SET_OUTPUT(PS_ON_PIN); //GND Printer::setPowerOn(false); #else Printer::setPowerOn(true); #endif #endif #if SDSUPPORT //power to SD reader #if SDPOWER > -1 SET_OUTPUT(SDPOWER); WRITE(SDPOWER, HIGH); #endif #if defined(SDCARDDETECT) && SDCARDDETECT > -1 SET_INPUT(SDCARDDETECT); PULLUP(SDCARDDETECT, HIGH); #endif #endif //Initialize Step Pins SET_OUTPUT(X_STEP_PIN); SET_OUTPUT(Y_STEP_PIN); SET_OUTPUT(Z_STEP_PIN); //Initialize Dir Pins #if X_DIR_PIN > -1 SET_OUTPUT(X_DIR_PIN); #endif #if Y_DIR_PIN > -1 SET_OUTPUT(Y_DIR_PIN); #endif #if Z_DIR_PIN > -1 SET_OUTPUT(Z_DIR_PIN); #endif //Steppers default to disabled. #if X_ENABLE_PIN > -1 SET_OUTPUT(X_ENABLE_PIN); WRITE(X_ENABLE_PIN, !X_ENABLE_ON); #endif #if Y_ENABLE_PIN > -1 SET_OUTPUT(Y_ENABLE_PIN); WRITE(Y_ENABLE_PIN, !Y_ENABLE_ON); #endif #if Z_ENABLE_PIN > -1 SET_OUTPUT(Z_ENABLE_PIN); WRITE(Z_ENABLE_PIN, !Z_ENABLE_ON); #endif #if FEATURE_TWO_XSTEPPER SET_OUTPUT(X2_STEP_PIN); SET_OUTPUT(X2_DIR_PIN); #if X2_ENABLE_PIN > -1 SET_OUTPUT(X2_ENABLE_PIN); WRITE(X2_ENABLE_PIN, !X_ENABLE_ON); #endif #endif #if FEATURE_TWO_YSTEPPER SET_OUTPUT(Y2_STEP_PIN); SET_OUTPUT(Y2_DIR_PIN); #if Y2_ENABLE_PIN > -1 SET_OUTPUT(Y2_ENABLE_PIN); WRITE(Y2_ENABLE_PIN, !Y_ENABLE_ON); #endif #endif #if FEATURE_TWO_ZSTEPPER SET_OUTPUT(Z2_STEP_PIN); SET_OUTPUT(Z2_DIR_PIN); #if Z2_ENABLE_PIN > -1 SET_OUTPUT(Z2_ENABLE_PIN); WRITE(Z2_ENABLE_PIN, !Z_ENABLE_ON); #endif #endif #if FEATURE_THREE_ZSTEPPER SET_OUTPUT(Z3_STEP_PIN); SET_OUTPUT(Z3_DIR_PIN); #if Z3_ENABLE_PIN > -1 SET_OUTPUT(Z3_ENABLE_PIN); WRITE(Z3_ENABLE_PIN, !Z_ENABLE_ON); #endif #endif //end stop pull ups #if MIN_HARDWARE_ENDSTOP_X #if X_MIN_PIN > -1 SET_INPUT(X_MIN_PIN); #if ENDSTOP_PULLUP_X_MIN PULLUP(X_MIN_PIN, HIGH); #endif #else #error You have defined hardware x min endstop without pin assignment. Set pin number for X_MIN_PIN #endif #endif #if MIN_HARDWARE_ENDSTOP_Y #if Y_MIN_PIN > -1 SET_INPUT(Y_MIN_PIN); #if ENDSTOP_PULLUP_Y_MIN PULLUP(Y_MIN_PIN, HIGH); #endif #else #error You have defined hardware y min endstop without pin assignment. Set pin number for Y_MIN_PIN #endif #endif #if MIN_HARDWARE_ENDSTOP_Z #if Z_MIN_PIN > -1 SET_INPUT(Z_MIN_PIN); #if ENDSTOP_PULLUP_Z_MIN PULLUP(Z_MIN_PIN, HIGH); #endif #else #error You have defined hardware z min endstop without pin assignment. Set pin number for Z_MIN_PIN #endif #endif #if MAX_HARDWARE_ENDSTOP_X #if X_MAX_PIN > -1 SET_INPUT(X_MAX_PIN); #if ENDSTOP_PULLUP_X_MAX PULLUP(X_MAX_PIN, HIGH); #endif #else #error You have defined hardware x max endstop without pin assignment. Set pin number for X_MAX_PIN #endif #endif #if MAX_HARDWARE_ENDSTOP_Y #if Y_MAX_PIN > -1 SET_INPUT(Y_MAX_PIN); #if ENDSTOP_PULLUP_Y_MAX PULLUP(Y_MAX_PIN, HIGH); #endif #else #error You have defined hardware y max endstop without pin assignment. Set pin number for Y_MAX_PIN #endif #endif #if MAX_HARDWARE_ENDSTOP_Z #if Z_MAX_PIN>-1 SET_INPUT(Z_MAX_PIN); #if ENDSTOP_PULLUP_Z_MAX PULLUP(Z_MAX_PIN, HIGH); #endif #else #error You have defined hardware z max endstop without pin assignment. Set pin number for Z_MAX_PIN #endif #endif #if FEATURE_Z_PROBE && Z_PROBE_PIN>-1 SET_INPUT(Z_PROBE_PIN); #if Z_PROBE_PULLUP PULLUP(Z_PROBE_PIN, HIGH); #endif #endif // FEATURE_FEATURE_Z_PROBE #if FAN_PIN > -1 && FEATURE_FAN_CONTROL SET_OUTPUT(FAN_PIN); WRITE(FAN_PIN, LOW); #endif #if FAN2_PIN > -1 && FEATURE_FAN2_CONTROL SET_OUTPUT(FAN2_PIN); WRITE(FAN2_PIN, LOW); #endif #if FAN_THERMO_PIN > -1 SET_OUTPUT(FAN_THERMO_PIN); WRITE(FAN_THERMO_PIN, LOW); #endif #if FAN_BOARD_PIN>-1 SET_OUTPUT(FAN_BOARD_PIN); WRITE(FAN_BOARD_PIN, LOW); #endif #if defined(EXT0_HEATER_PIN) && EXT0_HEATER_PIN>-1 SET_OUTPUT(EXT0_HEATER_PIN); WRITE(EXT0_HEATER_PIN, HEATER_PINS_INVERTED); #endif #if defined(EXT1_HEATER_PIN) && EXT1_HEATER_PIN>-1 && NUM_EXTRUDER>1 SET_OUTPUT(EXT1_HEATER_PIN); WRITE(EXT1_HEATER_PIN, HEATER_PINS_INVERTED); #endif #if defined(EXT2_HEATER_PIN) && EXT2_HEATER_PIN>-1 && NUM_EXTRUDER>2 SET_OUTPUT(EXT2_HEATER_PIN); WRITE(EXT2_HEATER_PIN, HEATER_PINS_INVERTED); #endif #if defined(EXT3_HEATER_PIN) && EXT3_HEATER_PIN>-1 && NUM_EXTRUDER>3 SET_OUTPUT(EXT3_HEATER_PIN); WRITE(EXT3_HEATER_PIN, HEATER_PINS_INVERTED); #endif #if defined(EXT4_HEATER_PIN) && EXT4_HEATER_PIN>-1 && NUM_EXTRUDER>4 SET_OUTPUT(EXT4_HEATER_PIN); WRITE(EXT4_HEATER_PIN, HEATER_PINS_INVERTED); #endif #if defined(EXT5_HEATER_PIN) && EXT5_HEATER_PIN>-1 && NUM_EXTRUDER>5 SET_OUTPUT(EXT5_HEATER_PIN); WRITE(EXT5_HEATER_PIN, HEATER_PINS_INVERTED); #endif #if defined(EXT0_EXTRUDER_COOLER_PIN) && EXT0_EXTRUDER_COOLER_PIN>-1 SET_OUTPUT(EXT0_EXTRUDER_COOLER_PIN); WRITE(EXT0_EXTRUDER_COOLER_PIN, LOW); #endif #if defined(EXT1_EXTRUDER_COOLER_PIN) && EXT1_EXTRUDER_COOLER_PIN > -1 && NUM_EXTRUDER > 1 SET_OUTPUT(EXT1_EXTRUDER_COOLER_PIN); WRITE(EXT1_EXTRUDER_COOLER_PIN, LOW); #endif #if defined(EXT2_EXTRUDER_COOLER_PIN) && EXT2_EXTRUDER_COOLER_PIN > -1 && NUM_EXTRUDER > 2 SET_OUTPUT(EXT2_EXTRUDER_COOLER_PIN); WRITE(EXT2_EXTRUDER_COOLER_PIN, LOW); #endif #if defined(EXT3_EXTRUDER_COOLER_PIN) && EXT3_EXTRUDER_COOLER_PIN > -1 && NUM_EXTRUDER > 3 SET_OUTPUT(EXT3_EXTRUDER_COOLER_PIN); WRITE(EXT3_EXTRUDER_COOLER_PIN, LOW); #endif #if defined(EXT4_EXTRUDER_COOLER_PIN) && EXT4_EXTRUDER_COOLER_PIN > -1 && NUM_EXTRUDER > 4 SET_OUTPUT(EXT4_EXTRUDER_COOLER_PIN); WRITE(EXT4_EXTRUDER_COOLER_PIN, LOW); #endif #if defined(EXT5_EXTRUDER_COOLER_PIN) && EXT5_EXTRUDER_COOLER_PIN > -1 && NUM_EXTRUDER > 5 SET_OUTPUT(EXT5_EXTRUDER_COOLER_PIN); WRITE(EXT5_EXTRUDER_COOLER_PIN, LOW); #endif // Initialize jam sensors #if defined(EXT0_JAM_PIN) && EXT0_JAM_PIN > -1 SET_INPUT(EXT0_JAM_PIN); PULLUP(EXT0_JAM_PIN, EXT0_JAM_PULLUP); #endif // defined #if defined(EXT1_JAM_PIN) && EXT1_JAM_PIN > -1 SET_INPUT(EXT1_JAM_PIN); PULLUP(EXT1_JAM_PIN, EXT1_JAM_PULLUP); #endif // defined #if defined(EXT2_JAM_PIN) && EXT2_JAM_PIN > -1 SET_INPUT(EXT2_JAM_PIN); PULLUP(EXT2_JAM_PIN, EXT2_JAM_PULLUP); #endif // defined #if defined(EXT3_JAM_PIN) && EXT3_JAM_PIN > -1 SET_INPUT(EXT3_JAM_PIN); PULLUP(EXT3_JAM_PIN, EXT3_JAM_PULLUP); #endif // defined #if defined(EXT4_JAM_PIN) && EXT4_JAM_PIN > -1 SET_INPUT(EXT4_JAM_PIN); PULLUP(EXT4_JAM_PIN, EXT4_JAM_PULLUP); #endif // defined #if defined(EXT5_JAM_PIN) && EXT5_JAM_PIN > -1 SET_INPUT(EXT5_JAM_PIN); PULLUP(EXT5_JAM_PIN, EXT5_JAM_PULLUP); #endif // defined #if CASE_LIGHTS_PIN >= 0 SET_OUTPUT(CASE_LIGHTS_PIN); WRITE(CASE_LIGHTS_PIN, CASE_LIGHT_DEFAULT_ON); #endif // CASE_LIGHTS_PIN #if defined(UI_VOLTAGE_LEVEL) && defined(EXP_VOLTAGE_LEVEL_PIN) && EXP_VOLTAGE_LEVEL_PIN >-1 SET_OUTPUT(EXP_VOLTAGE_LEVEL_PIN); WRITE(EXP_VOLTAGE_LEVEL_PIN,UI_VOLTAGE_LEVEL); #endif // UI_VOLTAGE_LEVEL #if defined(SUPPORT_LASER) && SUPPORT_LASER LaserDriver::initialize(); #endif // defined #if defined(SUPPORT_CNC) && SUPPORT_CNC CNCDriver::initialize(); #endif // defined #if GANTRY Printer::motorX = 0; Printer::motorYorZ = 0; #endif #ifdef RED_BLUE_STATUS_LEDS SET_OUTPUT(RED_STATUS_LED); SET_OUTPUT(BLUE_STATUS_LED); WRITE(BLUE_STATUS_LED,HIGH); WRITE(RED_STATUS_LED,LOW); #endif // RED_BLUE_STATUS_LEDS #if STEPPER_CURRENT_CONTROL != CURRENT_CONTROL_MANUAL motorCurrentControlInit(); // Set current if it is firmware controlled #endif #if defined(NUM_MOTOR_DRIVERS) && NUM_MOTOR_DRIVERS > 0 initializeAllMotorDrivers(); #endif // defined microstepInit(); #if FEATURE_AUTOLEVEL resetTransformationMatrix(true); #endif // FEATURE_AUTOLEVEL feedrate = 50; ///< Current feedrate in mm/s. feedrateMultiply = 100; extrudeMultiply = 100; lastCmdPos[X_AXIS] = lastCmdPos[Y_AXIS] = lastCmdPos[Z_AXIS] = 0; #if USE_ADVANCE #if ENABLE_QUADRATIC_ADVANCE advanceExecuted = 0; #endif advanceStepsSet = 0; #endif for(uint8_t i = 0; i < NUM_EXTRUDER + 3; i++) pwm_pos[i] = 0; maxJerk = MAX_JERK; #if DRIVE_SYSTEM != DELTA maxZJerk = MAX_ZJERK; #endif offsetX = offsetY = offsetZ = 0; interval = 5000; stepsPerTimerCall = 1; msecondsPrinting = 0; filamentPrinted = 0; flag0 = PRINTER_FLAG0_STEPPER_DISABLED; xLength = X_MAX_LENGTH; yLength = Y_MAX_LENGTH; zLength = Z_MAX_LENGTH; xMin = X_MIN_POS; yMin = Y_MIN_POS; zMin = Z_MIN_POS; #if NONLINEAR_SYSTEM radius0 = ROD_RADIUS; #endif #if ENABLE_BACKLASH_COMPENSATION backlashX = X_BACKLASH; backlashY = Y_BACKLASH; backlashZ = Z_BACKLASH; backlashDir = 0; #endif #if USE_ADVANCE extruderStepsNeeded = 0; #endif EEPROM::initBaudrate(); HAL::serialSetBaudrate(baudrate); Com::printFLN(Com::tStart); HAL::showStartReason(); Extruder::initExtruder(); // sets auto leveling in eeprom init EEPROM::init(); // Read settings from eeprom if wanted UI_INITIALIZE; for(uint8_t i = 0; i < E_AXIS_ARRAY; i++) { currentPositionSteps[i] = 0; } currentPosition[X_AXIS] = currentPosition[Y_AXIS]= currentPosition[Z_AXIS] = 0.0; //setAutolevelActive(false); // fixme delete me //Commands::printCurrentPosition(PSTR("Printer::setup 0 ")); #if DISTORTION_CORRECTION distortion.init(); #endif // DISTORTION_CORRECTION updateDerivedParameter(); Commands::checkFreeMemory(); Commands::writeLowestFreeRAM(); HAL::setupTimer(); #if NONLINEAR_SYSTEM transformCartesianStepsToDeltaSteps(Printer::currentPositionSteps, Printer::currentDeltaPositionSteps); #if DELTA_HOME_ON_POWER homeAxis(true,true,true); #endif setAutoretract(EEPROM_BYTE(AUTORETRACT_ENABLED)); Commands::printCurrentPosition(PSTR("Printer::setup ")); #endif // DRIVE_SYSTEM Extruder::selectExtruderById(0); #if FEATURE_WATCHDOG HAL::startWatchdog(); #endif // FEATURE_WATCHDOG #if SDSUPPORT sd.mount(); #endif #if FEATURE_SERVO // set servos to neutral positions at power_up #if defined(SERVO0_NEUTRAL_POS) && SERVO0_NEUTRAL_POS >= 500 HAL::servoMicroseconds(0,SERVO0_NEUTRAL_POS, 1000); #endif #if defined(SERVO1_NEUTRAL_POS) && SERVO1_NEUTRAL_POS >= 500 HAL::servoMicroseconds(1,SERVO1_NEUTRAL_POS, 1000); #endif #if defined(SERVO2_NEUTRAL_POS) && SERVO2_NEUTRAL_POS >= 500 HAL::servoMicroseconds(2,SERVO2_NEUTRAL_POS, 1000); #endif #if defined(SERVO3_NEUTRAL_POS) && SERVO3_NEUTRAL_POS >= 500 HAL::servoMicroseconds(3,SERVO3_NEUTRAL_POS, 1000); #endif #endif EVENT_INITIALIZE; #ifdef STARTUP_GCODE GCode::executeFString(Com::tStartupGCode); #endif #if EEPROM_MODE != 0 && UI_DISPLAY_TYPE != NO_DISPLAY if(EEPROM::getStoredLanguage() == 254) { Com::printFLN(PSTR("Needs language selection")); uid.showLanguageSelectionWizard(); } #endif // EEPROM_MODE } void Printer::defaultLoopActions() { Commands::checkForPeriodicalActions(true); //check heater every n milliseconds UI_MEDIUM; // do check encoder millis_t curtime = HAL::timeInMilliseconds(); if(PrintLine::hasLines() || isMenuMode(MENU_MODE_SD_PAUSED)) previousMillisCmd = curtime; else { curtime -= previousMillisCmd; if(maxInactiveTime != 0 && curtime > maxInactiveTime ) Printer::kill(false); else Printer::setAllKilled(false); // prevent repeated kills if(stepperInactiveTime != 0 && curtime > stepperInactiveTime ) Printer::kill(true); } #if SDCARDDETECT > -1 && SDSUPPORT sd.automount(); #endif DEBUG_MEMORY; } void Printer::MemoryPosition() { Commands::waitUntilEndOfAllMoves(); updateCurrentPosition(false); realPosition(memoryX, memoryY, memoryZ); memoryE = currentPositionSteps[E_AXIS] * invAxisStepsPerMM[E_AXIS]; memoryF = feedrate; } void Printer::GoToMemoryPosition(bool x, bool y, bool z, bool e, float feed) { if(memoryF < 0) return; // Not stored before call, so we ignore it bool all = !(x || y || z); moveToReal((all || x ? (lastCmdPos[X_AXIS] = memoryX) : IGNORE_COORDINATE) ,(all || y ?(lastCmdPos[Y_AXIS] = memoryY) : IGNORE_COORDINATE) ,(all || z ? (lastCmdPos[Z_AXIS] = memoryZ) : IGNORE_COORDINATE) ,(e ? memoryE : IGNORE_COORDINATE), feed); feedrate = memoryF; updateCurrentPosition(false); } #if DRIVE_SYSTEM == DELTA void Printer::deltaMoveToTopEndstops(float feedrate) { for (fast8_t i = 0; i < 3; i++) Printer::currentPositionSteps[i] = 0; Printer::stepsRemainingAtXHit = -1; Printer::stepsRemainingAtYHit = -1; Printer::stepsRemainingAtZHit = -1; setHoming(true); transformCartesianStepsToDeltaSteps(currentPositionSteps, currentDeltaPositionSteps); PrintLine::moveRelativeDistanceInSteps(0, 0, (zMaxSteps + EEPROM::deltaDiagonalRodLength()*axisStepsPerMM[Z_AXIS]) * 1.5, 0, feedrate, true, true); offsetX = offsetY = offsetZ = 0; setHoming(false); } void Printer::homeXAxis() { destinationSteps[X_AXIS] = 0; if (!PrintLine::queueDeltaMove(true,false,false)) { Com::printWarningFLN(PSTR("homeXAxis / queueDeltaMove returns error")); } } void Printer::homeYAxis() { Printer::destinationSteps[Y_AXIS] = 0; if (!PrintLine::queueDeltaMove(true,false,false)) { Com::printWarningFLN(PSTR("homeYAxis / queueDeltaMove returns error")); } } void Printer::homeZAxis() // Delta z homing { bool homingSuccess = false; Endstops::resetAccumulator(); deltaMoveToTopEndstops(Printer::homingFeedrate[Z_AXIS]); // New safe homing routine by Kyrre Aalerud // This method will safeguard against sticky endstops such as may be gotten cheaply from china. // This can lead to headcrashes and even fire, thus a safer algorithm to ensure the endstops actually respond as expected. //Endstops::report(); // Check that all endstops (XYZ) were hit Endstops::fillFromAccumulator(); if (Endstops::xMax() && Endstops::yMax() && Endstops::zMax()) { // Back off for retest PrintLine::moveRelativeDistanceInSteps(0, 0, axisStepsPerMM[Z_AXIS] * -ENDSTOP_Z_BACK_MOVE, 0, Printer::homingFeedrate[Z_AXIS]/ENDSTOP_X_RETEST_REDUCTION_FACTOR, true, true); //Endstops::report(); // Check for proper release of all (XYZ) endstops if (!(Endstops::xMax() || Endstops::yMax() || Endstops::zMax())) { // Rehome with reduced speed Endstops::resetAccumulator(); deltaMoveToTopEndstops(Printer::homingFeedrate[Z_AXIS] / ENDSTOP_Z_RETEST_REDUCTION_FACTOR); Endstops::fillFromAccumulator(); //Endstops::report(); // Check that all endstops (XYZ) were hit again if (Endstops::xMax() && Endstops::yMax() && Endstops::zMax()) { homingSuccess = true; // Assume success in case there is no back move #if defined(ENDSTOP_Z_BACK_ON_HOME) if(ENDSTOP_Z_BACK_ON_HOME > 0) { PrintLine::moveRelativeDistanceInSteps(0, 0, axisStepsPerMM[Z_AXIS] * -ENDSTOP_Z_BACK_ON_HOME * Z_HOME_DIR,0,homingFeedrate[Z_AXIS], true, true); //Endstops::report(); // Check for missing release of any (XYZ) endstop if (Endstops::xMax() || Endstops::yMax() || Endstops::zMax()) { homingSuccess = false; // Reset success flag } } #endif } } } // Check if homing failed. If so, request pause! if (!homingSuccess) { setHomed(false); // Clear the homed flag Com::printFLN(PSTR("RequestPause:Homing failed!")); } // Correct different endstop heights // These can be adjusted by two methods. You can use offsets stored by determining the center // or you can use the xyzMinSteps from G100 calibration. Both have the same effect but only one // should be measuredas both have the same effect. long dx = -xMinSteps - EEPROM::deltaTowerXOffsetSteps(); long dy = -yMinSteps - EEPROM::deltaTowerYOffsetSteps(); long dz = -zMinSteps - EEPROM::deltaTowerZOffsetSteps(); long dm = RMath::min(dx, dy, dz); //Com::printFLN(Com::tTower1,dx); //Com::printFLN(Com::tTower2,dy); //Com::printFLN(Com::tTower3,dz); dx -= dm; // now all dxyz are positive dy -= dm; dz -= dm; currentPositionSteps[X_AXIS] = 0; // here we should be currentPositionSteps[Y_AXIS] = 0; currentPositionSteps[Z_AXIS] = zMaxSteps; transformCartesianStepsToDeltaSteps(currentPositionSteps,currentDeltaPositionSteps); currentDeltaPositionSteps[A_TOWER] -= dx; currentDeltaPositionSteps[B_TOWER] -= dy; currentDeltaPositionSteps[C_TOWER] -= dz; PrintLine::moveRelativeDistanceInSteps(0, 0, dm, 0, homingFeedrate[Z_AXIS], true, false); currentPositionSteps[X_AXIS] = 0; // now we are really here currentPositionSteps[Y_AXIS] = 0; currentPositionSteps[Z_AXIS] = zMaxSteps - zBedOffset * axisStepsPerMM[Z_AXIS]; // Extruder is now exactly in the delta center coordinateOffset[X_AXIS] = 0; coordinateOffset[Y_AXIS] = 0; coordinateOffset[Z_AXIS] = 0; transformCartesianStepsToDeltaSteps(currentPositionSteps, currentDeltaPositionSteps); realDeltaPositionSteps[A_TOWER] = currentDeltaPositionSteps[A_TOWER]; realDeltaPositionSteps[B_TOWER] = currentDeltaPositionSteps[B_TOWER]; realDeltaPositionSteps[C_TOWER] = currentDeltaPositionSteps[C_TOWER]; //maxDeltaPositionSteps = currentDeltaPositionSteps[X_AXIS]; #if defined(ENDSTOP_Z_BACK_ON_HOME) if(ENDSTOP_Z_BACK_ON_HOME > 0) maxDeltaPositionSteps += axisStepsPerMM[Z_AXIS] * ENDSTOP_Z_BACK_ON_HOME; #endif Extruder::selectExtruderById(Extruder::current->id); } // This home axis is for delta void Printer::homeAxis(bool xaxis,bool yaxis,bool zaxis) // Delta homing code { bool autoLevel = isAutolevelActive(); setAutolevelActive(false); setHomed(true); if (!(X_MAX_PIN > -1 && Y_MAX_PIN > -1 && Z_MAX_PIN > -1 && MAX_HARDWARE_ENDSTOP_X && MAX_HARDWARE_ENDSTOP_Y && MAX_HARDWARE_ENDSTOP_Z)) { Com::printErrorFLN(PSTR("Hardware setup inconsistent. Delta cannot home wihtout max endstops.")); } // The delta has to have home capability to zero and set position, // so the redundant check is only an opportunity to // gratuitously fail due to incorrect settings. // The following movements would be meaningless unless it was zeroed for example. UI_STATUS_UPD_F(Com::translatedF(UI_TEXT_HOME_DELTA_ID)); // Homing Z axis means that you must home X and Y homeZAxis(); moveToReal(0,0,Printer::zLength - zBedOffset,IGNORE_COORDINATE,homingFeedrate[Z_AXIS]); // Move to designed coordinates including translation updateCurrentPosition(true); UI_CLEAR_STATUS Commands::printCurrentPosition(PSTR("homeAxis ")); setAutolevelActive(autoLevel); } #else #if DRIVE_SYSTEM == TUGA // Tuga printer homing void Printer::homeXAxis() { long steps; if ((MIN_HARDWARE_ENDSTOP_X && X_MIN_PIN > -1 && X_HOME_DIR == -1 && MIN_HARDWARE_ENDSTOP_Y && Y_MIN_PIN > -1 && Y_HOME_DIR == -1) || (MAX_HARDWARE_ENDSTOP_X && X_MAX_PIN > -1 && X_HOME_DIR == 1 && MAX_HARDWARE_ENDSTOP_Y && Y_MAX_PIN > -1 && Y_HOME_DIR == 1)) { long offX = 0,offY = 0; #if NUM_EXTRUDER>1 for(uint8_t i = 0; i < NUM_EXTRUDER; i++) { #if X_HOME_DIR < 0 offX = RMath::max(offX,extruder[i].xOffset); offY = RMath::max(offY,extruder[i].yOffset); #else offX = RMath::min(offX,extruder[i].xOffset); offY = RMath::min(offY,extruder[i].yOffset); #endif } // Reposition extruder that way, that all extruders can be selected at home pos. #endif UI_STATUS_UPD(UI_TEXT_HOME_X); steps = (Printer::xMaxSteps-Printer::xMinSteps) * X_HOME_DIR; currentPositionSteps[X_AXIS] = -steps; currentPositionSteps[Y_AXIS] = 0; setHoming(true); transformCartesianStepsToDeltaSteps(currentPositionSteps, currentDeltaPositionSteps); PrintLine::moveRelativeDistanceInSteps(2*steps,0,0,0,homingFeedrate[X_AXIS],true,true); currentPositionSteps[X_AXIS] = (X_HOME_DIR == -1) ? xMinSteps-offX : xMaxSteps+offX; currentPositionSteps[Y_AXIS] = 0; //(Y_HOME_DIR == -1) ? yMinSteps-offY : yMaxSteps+offY; //PrintLine::moveRelativeDistanceInSteps(axisStepsPerMM[X_AXIS]*-ENDSTOP_X_BACK_MOVE * X_HOME_DIR,axisStepsPerMM[Y_AXIS]*-ENDSTOP_X_BACK_MOVE * Y_HOME_DIR,0,0,homingFeedrate[X_AXIS]/ENDSTOP_X_RETEST_REDUCTION_FACTOR,true,false); // PrintLine::moveRelativeDistanceInSteps(axisStepsPerMM[X_AXIS]*2*ENDSTOP_X_BACK_MOVE * X_HOME_DIR,axisStepsPerMM[Y_AXIS]*2*ENDSTOP_X_BACK_MOVE * Y_HOME_DIR,0,0,homingFeedrate[X_AXIS]/ENDSTOP_X_RETEST_REDUCTION_FACTOR,true,true); PrintLine::moveRelativeDistanceInSteps(axisStepsPerMM[X_AXIS]*-ENDSTOP_X_BACK_MOVE * X_HOME_DIR,0,0,0,homingFeedrate[X_AXIS]/ENDSTOP_X_RETEST_REDUCTION_FACTOR,true,false); PrintLine::moveRelativeDistanceInSteps(axisStepsPerMM[X_AXIS]*2*ENDSTOP_X_BACK_MOVE * X_HOME_DIR,0,0,0,homingFeedrate[X_AXIS]/ENDSTOP_X_RETEST_REDUCTION_FACTOR,true,true); setHoming(false); #if defined(ENDSTOP_X_BACK_ON_HOME) if(ENDSTOP_X_BACK_ON_HOME > 0) PrintLine::moveRelativeDistanceInSteps(axisStepsPerMM[X_AXIS]*-ENDSTOP_X_BACK_ON_HOME * X_HOME_DIR,0,0,0,homingFeedrate[X_AXIS],true,false); // PrintLine::moveRelativeDistanceInSteps(axisStepsPerMM[X_AXIS]*-ENDSTOP_X_BACK_ON_HOME * X_HOME_DIR,axisStepsPerMM[Y_AXIS]*-ENDSTOP_Y_BACK_ON_HOME * Y_HOME_DIR,0,0,homingFeedrate[X_AXIS],true,false); #endif currentPositionSteps[X_AXIS] = (X_HOME_DIR == -1) ? xMinSteps-offX : xMaxSteps+offX; currentPositionSteps[Y_AXIS] = 0; //(Y_HOME_DIR == -1) ? yMinSteps-offY : yMaxSteps+offY; coordinateOffset[X_AXIS] = 0; coordinateOffset[Y_AXIS] = 0; transformCartesianStepsToDeltaSteps(currentPositionSteps, currentDeltaPositionSteps); #if NUM_EXTRUDER>1 PrintLine::moveRelativeDistanceInSteps((Extruder::current->xOffset-offX) * X_HOME_DIR,(Extruder::current->yOffset-offY) * Y_HOME_DIR,0,0,homingFeedrate[X_AXIS],true,false); #endif } } void Printer::homeYAxis() { // Dummy function x and y homing must occur together } #else // cartesian printer void Printer::homeXAxis() { long steps; if ((MIN_HARDWARE_ENDSTOP_X && X_MIN_PIN > -1 && X_HOME_DIR == -1) || (MAX_HARDWARE_ENDSTOP_X && X_MAX_PIN > -1 && X_HOME_DIR == 1)) { long offX = 0; #if NUM_EXTRUDER > 1 for(uint8_t i = 0; i < NUM_EXTRUDER; i++) #if X_HOME_DIR < 0 offX = RMath::max(offX,extruder[i].xOffset); #else offX = RMath::min(offX,extruder[i].xOffset); #endif // Reposition extruder that way, that all extruders can be selected at home pos. #endif // NUM_EXTRUDER > 1 UI_STATUS_UPD_F(Com::translatedF(UI_TEXT_HOME_X_ID)); steps = (Printer::xMaxSteps - Printer::xMinSteps) * X_HOME_DIR; currentPositionSteps[X_AXIS] = -steps; setHoming(true); PrintLine::moveRelativeDistanceInSteps(2 * steps, 0, 0, 0, homingFeedrate[X_AXIS], true, true); currentPositionSteps[X_AXIS] = (X_HOME_DIR == -1) ? xMinSteps - offX : xMaxSteps + offX; PrintLine::moveRelativeDistanceInSteps(axisStepsPerMM[X_AXIS] * -ENDSTOP_X_BACK_MOVE * X_HOME_DIR,0,0,0,homingFeedrate[X_AXIS] / ENDSTOP_X_RETEST_REDUCTION_FACTOR, true, false); PrintLine::moveRelativeDistanceInSteps(axisStepsPerMM[X_AXIS] * 2 * ENDSTOP_X_BACK_MOVE * X_HOME_DIR,0,0,0,homingFeedrate[X_AXIS] / ENDSTOP_X_RETEST_REDUCTION_FACTOR, true, true); setHoming(false); #if defined(ENDSTOP_X_BACK_ON_HOME) if(ENDSTOP_X_BACK_ON_HOME > 0) PrintLine::moveRelativeDistanceInSteps(axisStepsPerMM[X_AXIS] * -ENDSTOP_X_BACK_ON_HOME * X_HOME_DIR,0,0,0,homingFeedrate[X_AXIS], true, true); #endif currentPositionSteps[X_AXIS] = (X_HOME_DIR == -1) ? xMinSteps - offX : xMaxSteps + offX; #if NUM_EXTRUDER > 1 #if X_HOME_DIR < 0 PrintLine::moveRelativeDistanceInSteps((Extruder::current->xOffset - offX) * X_HOME_DIR,0,0,0,homingFeedrate[X_AXIS], true, true); #else PrintLine::moveRelativeDistanceInSteps(-(Extruder::current->xOffset - offX) * X_HOME_DIR,0,0,0,homingFeedrate[X_AXIS], true, true); #endif #endif } } void Printer::homeYAxis() { long steps; if ((MIN_HARDWARE_ENDSTOP_Y && Y_MIN_PIN > -1 && Y_HOME_DIR == -1) || (MAX_HARDWARE_ENDSTOP_Y && Y_MAX_PIN > -1 && Y_HOME_DIR == 1)) { long offY = 0; #if NUM_EXTRUDER > 1 for(uint8_t i = 0; i < NUM_EXTRUDER; i++) #if Y_HOME_DIR < 0 offY = RMath::max(offY,extruder[i].yOffset); #else offY = RMath::min(offY,extruder[i].yOffset); #endif // Reposition extruder that way, that all extruders can be selected at home pos. #endif UI_STATUS_UPD_F(Com::translatedF(UI_TEXT_HOME_Y_ID)); steps = (yMaxSteps-Printer::yMinSteps) * Y_HOME_DIR; currentPositionSteps[Y_AXIS] = -steps; setHoming(true); PrintLine::moveRelativeDistanceInSteps(0,2 * steps,0,0,homingFeedrate[Y_AXIS],true,true); currentPositionSteps[Y_AXIS] = (Y_HOME_DIR == -1) ? yMinSteps-offY : yMaxSteps+offY; PrintLine::moveRelativeDistanceInSteps(0,axisStepsPerMM[Y_AXIS] * -ENDSTOP_Y_BACK_MOVE * Y_HOME_DIR,0,0,homingFeedrate[Y_AXIS] / ENDSTOP_X_RETEST_REDUCTION_FACTOR,true,false); PrintLine::moveRelativeDistanceInSteps(0,axisStepsPerMM[Y_AXIS] * 2 * ENDSTOP_Y_BACK_MOVE * Y_HOME_DIR,0,0,homingFeedrate[Y_AXIS] / ENDSTOP_X_RETEST_REDUCTION_FACTOR,true,true); setHoming(false); #if defined(ENDSTOP_Y_BACK_ON_HOME) if(ENDSTOP_Y_BACK_ON_HOME > 0) PrintLine::moveRelativeDistanceInSteps(0,axisStepsPerMM[Y_AXIS] * -ENDSTOP_Y_BACK_ON_HOME * Y_HOME_DIR,0,0,homingFeedrate[Y_AXIS],true,false); #endif currentPositionSteps[Y_AXIS] = (Y_HOME_DIR == -1) ? yMinSteps - offY : yMaxSteps + offY; #if NUM_EXTRUDER > 1 #if Y_HOME_DIR < 0 PrintLine::moveRelativeDistanceInSteps(0,(Extruder::current->yOffset - offY) * Y_HOME_DIR,0,0,homingFeedrate[Y_AXIS],true,false); #else PrintLine::moveRelativeDistanceInSteps(0,-(Extruder::current->yOffset - offY) * Y_HOME_DIR,0,0,homingFeedrate[Y_AXIS],true,false); #endif #endif } } #endif void Printer::homeZAxis() // cartesian homing { long steps; if ((MIN_HARDWARE_ENDSTOP_Z && Z_MIN_PIN > -1 && Z_HOME_DIR == -1) || (MAX_HARDWARE_ENDSTOP_Z && Z_MAX_PIN > -1 && Z_HOME_DIR == 1)) { UI_STATUS_UPD_F(Com::translatedF(UI_TEXT_HOME_Z_ID)); steps = (zMaxSteps - zMinSteps) * Z_HOME_DIR; currentPositionSteps[Z_AXIS] = -steps; setHoming(true); PrintLine::moveRelativeDistanceInSteps(0,0,2 * steps,0,homingFeedrate[Z_AXIS],true,true); currentPositionSteps[Z_AXIS] = (Z_HOME_DIR == -1) ? zMinSteps : zMaxSteps; PrintLine::moveRelativeDistanceInSteps(0,0,axisStepsPerMM[Z_AXIS] * -ENDSTOP_Z_BACK_MOVE * Z_HOME_DIR,0,homingFeedrate[Z_AXIS] / ENDSTOP_Z_RETEST_REDUCTION_FACTOR,true,false); #if defined(ZHOME_WAIT_UNSWING) && ZHOME_WAIT_UNSWING > 0 HAL::delayMilliseconds(ZHOME_WAIT_UNSWING); #endif PrintLine::moveRelativeDistanceInSteps(0,0,axisStepsPerMM[Z_AXIS] * 2 * ENDSTOP_Z_BACK_MOVE * Z_HOME_DIR,0,homingFeedrate[Z_AXIS] / ENDSTOP_Z_RETEST_REDUCTION_FACTOR,true,true); setHoming(false); int32_t zCorrection = 0; #if MIN_HARDWARE_ENDSTOP_Z && FEATURE_Z_PROBE && Z_PROBE_PIN==Z_MIN_PIN // Fix error from z probe testing zCorrection -= axisStepsPerMM[Z_AXIS]*EEPROM::zProbeHeight(); #endif #if defined(ENDSTOP_Z_BACK_ON_HOME) // If we want to go up a bit more for some reason if(ENDSTOP_Z_BACK_ON_HOME > 0) zCorrection -= axisStepsPerMM[Z_AXIS]*ENDSTOP_Z_BACK_ON_HOME * Z_HOME_DIR; #endif #if Z_HOME_DIR < 0 // Fix bed coating zCorrection += axisStepsPerMM[Z_AXIS] * Printer::zBedOffset; #endif PrintLine::moveRelativeDistanceInSteps(0,0,zCorrection,0,homingFeedrate[Z_AXIS],true,false); currentPositionSteps[Z_AXIS] = ((Z_HOME_DIR == -1) ? zMinSteps : zMaxSteps - Printer::zBedOffset * axisStepsPerMM[Z_AXIS]); #if NUM_EXTRUDER > 0 currentPositionSteps[Z_AXIS] -= Extruder::current->zOffset; #endif #if DRIVE_SYSTEM == TUGA currentDeltaPositionSteps[C_TOWER] = currentPositionSteps[Z_AXIS]; #endif } } void Printer::homeAxis(bool xaxis,bool yaxis,bool zaxis) // home non-delta printer { float startX,startY,startZ; realPosition(startX, startY, startZ); setHomed(true); #if !defined(HOMING_ORDER) #define HOMING_ORDER HOME_ORDER_XYZ #endif #if HOMING_ORDER == HOME_ORDER_XYZ if(xaxis) homeXAxis(); if(yaxis) homeYAxis(); if(zaxis) homeZAxis(); #elif HOMING_ORDER == HOME_ORDER_XZY if(xaxis) homeXAxis(); if(zaxis) homeZAxis(); if(yaxis) homeYAxis(); #elif HOMING_ORDER == HOME_ORDER_YXZ if(yaxis) homeYAxis(); if(xaxis) homeXAxis(); if(zaxis) homeZAxis(); #elif HOMING_ORDER == HOME_ORDER_YZX if(yaxis) homeYAxis(); if(zaxis) homeZAxis(); if(xaxis) homeXAxis(); #elif HOMING_ORDER == HOME_ORDER_ZXY if(zaxis) homeZAxis(); if(xaxis) homeXAxis(); if(yaxis) homeYAxis(); #elif HOMING_ORDER == HOME_ORDER_ZYX if(zaxis) homeZAxis(); if(yaxis) homeYAxis(); if(xaxis) homeXAxis(); #elif HOMING_ORDER == HOME_ORDER_ZXYTZ { float actTemp[NUM_EXTRUDER]; for(int i = 0;i < NUM_EXTRUDER; i++) actTemp[i] = extruder[i].tempControl.targetTemperatureC; if(zaxis) { homeZAxis(); Printer::moveToReal(IGNORE_COORDINATE,IGNORE_COORDINATE,ZHOME_HEAT_HEIGHT,IGNORE_COORDINATE,homingFeedrate[Z_AXIS]); Commands::waitUntilEndOfAllMoves(); #if ZHOME_HEAT_ALL for(int i = 0; i < NUM_EXTRUDER; i++) { Extruder::setTemperatureForExtruder(RMath::max(actTemp[i],static_cast<float>(ZHOME_MIN_TEMPERATURE)),i,false,false); } for(int i = 0; i < NUM_EXTRUDER; i++) { if(extruder[i].tempControl.currentTemperatureC < ZHOME_MIN_TEMPERATURE) Extruder::setTemperatureForExtruder(RMath::max(actTemp[i],static_cast<float>(ZHOME_MIN_TEMPERATURE)),i,false,true); } #else if(extruder[Extruder::current->id].tempControl.currentTemperatureC < ZHOME_MIN_TEMPERATURE) Extruder::setTemperatureForExtruder(RMath::max(actTemp[Extruder::current->id],static_cast<float>(ZHOME_MIN_TEMPERATURE)),Extruder::current->id,false,true); #endif } #if ZHOME_X_POS == IGNORE_COORDINATE if(xaxis) #else if(xaxis || zaxis) #endif { homeXAxis(); //#if ZHOME_X_POS == IGNORE_COORDINATE if(X_HOME_DIR < 0) startX = Printer::xMin; else startX = Printer::xMin + Printer::xLength; //#else // startX = ZHOME_X_POS; //#endif } #if ZHOME_Y_POS == IGNORE_COORDINATE if(yaxis) #else if(yaxis || zaxis) #endif { homeYAxis(); //#if ZHOME_Y_POS == IGNORE_COORDINATE if(Y_HOME_DIR < 0) startY = Printer::yMin; else startY = Printer::yMin + Printer::yLength; //#else // startY = ZHOME_Y_POS; //#endif } if(zaxis) { #if ZHOME_X_POS != IGNORE_COORDINATE || ZHOME_Y_POS != IGNORE_COORDINATE moveToReal(ZHOME_X_POS,ZHOME_Y_POS,IGNORE_COORDINATE,IGNORE_COORDINATE,homingFeedrate[Y_AXIS]); Commands::waitUntilEndOfAllMoves(); #endif homeZAxis(); #if DISTORTION_CORRECTION && Z_HOME_DIR < 0 && Z_PROBE_PIN == Z_MIN_PIN // Special case where z probe is z min endstop and distortion correction is enabled if(Printer::distortion.isEnabled()) { Printer::zCorrectionStepsIncluded = Printer::distortion.correct(Printer::currentPositionSteps[X_AXIS],currentPositionSteps[Y_AXIS],currentPositionSteps[Z_AXIS]); currentPositionSteps[Z_AXIS] += Printer::zCorrectionStepsIncluded; } #endif if(Z_HOME_DIR < 0) startZ = Printer::zMin; else startZ = Printer::zMin + Printer::zLength - zBedOffset; moveToReal(IGNORE_COORDINATE, IGNORE_COORDINATE, ZHOME_HEAT_HEIGHT, IGNORE_COORDINATE, homingFeedrate[X_AXIS]); #if ZHOME_HEAT_ALL for(int i = 0; i < NUM_EXTRUDER; i++) Extruder::setTemperatureForExtruder(actTemp[i],i,false,false); for(int i = 0; i < NUM_EXTRUDER; i++) Extruder::setTemperatureForExtruder(actTemp[i],i,false,true); #else Extruder::setTemperatureForExtruder(actTemp[Extruder::current->id], Extruder::current->id, false, actTemp[Extruder::current->id] > MAX_ROOM_TEMPERATURE); #endif } } #endif #if HOMING_ORDER != HOME_ORDER_ZXYTZ if(xaxis) { if(X_HOME_DIR < 0) startX = Printer::xMin; else startX = Printer::xMin + Printer::xLength; } if(yaxis) { if(Y_HOME_DIR < 0) startY = Printer::yMin; else startY = Printer::yMin + Printer::yLength; } if(zaxis) { if(Z_HOME_DIR < 0) startZ = Printer::zMin; else startZ = Printer::zMin + Printer::zLength - Printer::zBedOffset; } #endif updateCurrentPosition(true); #if defined(Z_UP_AFTER_HOME) && Z_HOME_DIR < 0 //PrintLine::moveRelativeDistanceInSteps(0,0,axisStepsPerMM[Z_AXIS]*Z_UP_AFTER_HOME * Z_HOME_DIR,0,homingFeedrate[Z_AXIS],true,false); if(zaxis) startZ = Z_UP_AFTER_HOME; #endif moveToReal(startX, startY, startZ, IGNORE_COORDINATE, homingFeedrate[X_AXIS]); updateCurrentPosition(true); UI_CLEAR_STATUS Commands::printCurrentPosition(PSTR("homeAxis ")); } #endif // Not delta printer void Printer::zBabystep() { bool dir = zBabystepsMissing > 0; if(dir) zBabystepsMissing--; else zBabystepsMissing++; #if DRIVE_SYSTEM == DELTA Printer::enableXStepper(); Printer::enableYStepper(); #endif Printer::enableZStepper(); Printer::unsetAllSteppersDisabled(); #if DRIVE_SYSTEM == DELTA bool xDir = Printer::getXDirection(); bool yDir = Printer::getYDirection(); #endif bool zDir = Printer::getZDirection(); #if DRIVE_SYSTEM == DELTA Printer::setXDirection(dir); Printer::setYDirection(dir); #endif Printer::setZDirection(dir); #if defined(DIRECTION_DELAY) && DIRECTION_DELAY > 0 HAL::delayMicroseconds(DIRECTION_DELAY); #else HAL::delayMicroseconds(10); #endif #if DRIVE_SYSTEM == DELTA startXStep(); startYStep(); #endif // Drive system 3 startZStep(); HAL::delayMicroseconds(STEPPER_HIGH_DELAY + 2); Printer::endXYZSteps(); HAL::delayMicroseconds(10); #if DRIVE_SYSTEM == 3 Printer::setXDirection(xDir); Printer::setYDirection(yDir); #endif Printer::setZDirection(zDir); #if defined(DIRECTION_DELAY) && DIRECTION_DELAY > 0 HAL::delayMicroseconds(DIRECTION_DELAY); #endif //HAL::delayMicroseconds(STEPPER_HIGH_DELAY + 1); } void Printer::setCaseLight(bool on) { #if CASE_LIGHTS_PIN > -1 WRITE(CASE_LIGHTS_PIN,on); reportCaseLightStatus(); #endif } void Printer::reportCaseLightStatus() { #if CASE_LIGHTS_PIN > -1 if(READ(CASE_LIGHTS_PIN)) Com::printInfoFLN(PSTR("Case lights on")); else Com::printInfoFLN(PSTR("Case lights off")); #else Com::printInfoFLN(PSTR("No case lights")); #endif } void Printer::handleInterruptEvent() { if(interruptEvent == 0) return; int event = interruptEvent; interruptEvent = 0; switch(event) { #if EXTRUDER_JAM_CONTROL case PRINTER_INTERRUPT_EVENT_JAM_DETECTED: EVENT_JAM_DETECTED; Com::printFLN(PSTR("important:Extruder jam detected")); UI_ERROR_P(Com::translatedF(UI_TEXT_EXTRUDER_JAM_ID)); #if JAM_ACTION == 1 // start dialog Printer::setUIErrorMessage(false); #if UI_DISPLAY_TYPE != NO_DISPLAY uid.executeAction(UI_ACTION_WIZARD_JAM_EOF, true); #endif #elif JAM_ACTION == 2 // pause host/print #if SDSUPPORT if(sd.sdmode == 2) { sd.pausePrint(true); break; } #endif // SDSUPPORT Com::printFLN(PSTR("RequestPause:Extruder Jam Detected!")); #endif // JAM_ACTION break; case PRINTER_INTERRUPT_EVENT_JAM_SIGNAL0: case PRINTER_INTERRUPT_EVENT_JAM_SIGNAL1: case PRINTER_INTERRUPT_EVENT_JAM_SIGNAL2: case PRINTER_INTERRUPT_EVENT_JAM_SIGNAL3: case PRINTER_INTERRUPT_EVENT_JAM_SIGNAL4: case PRINTER_INTERRUPT_EVENT_JAM_SIGNAL5: { if(isJamcontrolDisabled()) break; fast8_t extruderIndex = event - PRINTER_INTERRUPT_EVENT_JAM_SIGNAL0; int16_t steps = abs(extruder[extruderIndex].jamStepsOnSignal); EVENT_JAM_SIGNAL_CHANGED(extruderIndex,steps); if(steps > JAM_SLOWDOWN_STEPS && !extruder[extruderIndex].tempControl.isSlowedDown()) { extruder[extruderIndex].tempControl.setSlowedDown(true); Commands::changeFeedrateMultiply(JAM_SLOWDOWN_TO); UI_ERROR_P(Com::tFilamentSlipping); } if(isDebugJam()) { Com::printF(PSTR("Jam signal steps:"),steps); int32_t percent = static_cast<int32_t>(steps) * 100 / JAM_STEPS; Com::printF(PSTR(" / "),percent); Com::printFLN(PSTR("% on "),(int)extruderIndex); } } break; #endif // EXTRUDER_JAM_CONTROL case PRINTER_INTERRUPT_EVENT_JAM_DETECTED: } } #define START_EXTRUDER_CONFIG(i) Com::printF(Com::tConfig);Com::printF(Com::tExtrDot,i+1);Com::print(':'); void Printer::showConfiguration() { Com::config(PSTR("Baudrate:"),baudrate); #ifndef EXTERNALSERIAL Com::config(PSTR("InputBuffer:"),SERIAL_BUFFER_SIZE - 1); #endif Com::config(PSTR("NumExtruder:"),NUM_EXTRUDER); Com::config(PSTR("MixingExtruder:"),MIXING_EXTRUDER); Com::config(PSTR("HeatedBed:"),HAVE_HEATED_BED); Com::config(PSTR("SDCard:"),SDSUPPORT); Com::config(PSTR("Fan:"),FAN_PIN > -1 && FEATURE_FAN_CONTROL); #if FEATURE_FAN2_CONTROL && defined(FAN2_PIN) && FAN2_PIN > -1 Com::config(PSTR("Fan2:1")); #else Com::config(PSTR("Fan2:0")); #endif Com::config(PSTR("LCD:"),FEATURE_CONTROLLER != NO_CONTROLLER); Com::config(PSTR("SoftwarePowerSwitch:"),PS_ON_PIN > -1); Com::config(PSTR("XHomeDir:"),X_HOME_DIR); Com::config(PSTR("YHomeDir:"),Y_HOME_DIR); Com::config(PSTR("ZHomeDir:"),Z_HOME_DIR); Com::config(PSTR("SupportG10G11:"),FEATURE_RETRACTION); Com::config(PSTR("SupportLocalFilamentchange:"),FEATURE_RETRACTION); Com::config(PSTR("CaseLights:"),CASE_LIGHTS_PIN > -1); Com::config(PSTR("ZProbe:"),FEATURE_Z_PROBE); Com::config(PSTR("Autolevel:"),FEATURE_AUTOLEVEL); Com::config(PSTR("EEPROM:"),EEPROM_MODE != 0); Com::config(PSTR("PrintlineCache:"), PRINTLINE_CACHE_SIZE); Com::config(PSTR("JerkXY:"),maxJerk); #if DRIVE_SYSTEM != DELTA Com::config(PSTR("JerkZ:"),maxZJerk); #endif #if FEATURE_RETRACTION Com::config(PSTR("RetractionLength:"),EEPROM_FLOAT(RETRACTION_LENGTH)); Com::config(PSTR("RetractionLongLength:"),EEPROM_FLOAT(RETRACTION_LONG_LENGTH)); Com::config(PSTR("RetractionSpeed:"),EEPROM_FLOAT(RETRACTION_SPEED)); Com::config(PSTR("RetractionZLift:"),EEPROM_FLOAT(RETRACTION_Z_LIFT)); Com::config(PSTR("RetractionUndoExtraLength:"),EEPROM_FLOAT(RETRACTION_UNDO_EXTRA_LENGTH)); Com::config(PSTR("RetractionUndoExtraLongLength:"),EEPROM_FLOAT(RETRACTION_UNDO_EXTRA_LONG_LENGTH)); Com::config(PSTR("RetractionUndoSpeed:"),EEPROM_FLOAT(RETRACTION_UNDO_SPEED)); #endif // FEATURE_RETRACTION Com::config(PSTR("XMin:"),xMin); Com::config(PSTR("YMin:"),yMin); Com::config(PSTR("ZMin:"),zMin); Com::config(PSTR("XMax:"),xMin + xLength); Com::config(PSTR("YMax:"),yMin + yLength); Com::config(PSTR("ZMax:"),zMin + zLength); Com::config(PSTR("XSize:"), xLength); Com::config(PSTR("YSize:"), yLength); Com::config(PSTR("ZSize:"), zLength); Com::config(PSTR("XPrintAccel:"), maxAccelerationMMPerSquareSecond[X_AXIS]); Com::config(PSTR("YPrintAccel:"), maxAccelerationMMPerSquareSecond[Y_AXIS]); Com::config(PSTR("ZPrintAccel:"), maxAccelerationMMPerSquareSecond[Z_AXIS]); Com::config(PSTR("XTravelAccel:"), maxTravelAccelerationMMPerSquareSecond[X_AXIS]); Com::config(PSTR("YTravelAccel:"), maxTravelAccelerationMMPerSquareSecond[Y_AXIS]); Com::config(PSTR("ZTravelAccel:"), maxTravelAccelerationMMPerSquareSecond[Z_AXIS]); #if DRIVE_SYSTEM == DELTA Com::config(PSTR("PrinterType:Delta")); #else Com::config(PSTR("PrinterType:Cartesian")); #endif // DRIVE_SYSTEM Com::config(PSTR("MaxBedTemp:"), HEATED_BED_MAX_TEMP); for(fast8_t i = 0; i < NUM_EXTRUDER; i++) { START_EXTRUDER_CONFIG(i) Com::printFLN(PSTR("Jerk:"),extruder[i].maxStartFeedrate); START_EXTRUDER_CONFIG(i) Com::printFLN(PSTR("MaxSpeed:"),extruder[i].maxFeedrate); START_EXTRUDER_CONFIG(i) Com::printFLN(PSTR("Acceleration:"),extruder[i].maxAcceleration); START_EXTRUDER_CONFIG(i) Com::printFLN(PSTR("Diameter:"),extruder[i].diameter); START_EXTRUDER_CONFIG(i) Com::printFLN(PSTR("MaxTemp:"),MAXTEMP); } } #if DISTORTION_CORRECTION Distortion Printer::distortion; void Printer::measureDistortion(void) { distortion.measure(); } Distortion::Distortion() { } void Distortion::init() { updateDerived(); #if !DISTORTION_PERMANENT resetCorrection(); #endif #if EEPROM_MODE != 0 enabled = EEPROM::isZCorrectionEnabled(); Com::printFLN(PSTR("zDistortionCorrection:"),(int)enabled); #else enabled = false; #endif } void Distortion::updateDerived() { #if DRIVE_SYSTEM == DELTA step = (2 * Printer::axisStepsPerMM[Z_AXIS] * DISTORTION_CORRECTION_R) / (DISTORTION_CORRECTION_POINTS - 1.0f); radiusCorrectionSteps = DISTORTION_CORRECTION_R * Printer::axisStepsPerMM[Z_AXIS]; #else xCorrectionSteps = (DISTORTION_XMAX - DISTORTION_XMIN) * Printer::axisStepsPerMM[X_AXIS] / DISTORTION_CORRECTION_POINTS; xOffsetSteps = DISTORTION_XMIN * Printer::axisStepsPerMM[X_AXIS]; yCorrectionSteps = (DISTORTION_YMAX - DISTORTION_YMIN) * Printer::axisStepsPerMM[Y_AXIS] / DISTORTION_CORRECTION_POINTS; yOffsetSteps = DISTORTION_YMIN * Printer::axisStepsPerMM[Y_AXIS]; #endif zStart = DISTORTION_START_DEGRADE * Printer::axisStepsPerMM[Z_AXIS]; zEnd = DISTORTION_END_HEIGHT * Printer::axisStepsPerMM[Z_AXIS]; } void Distortion::enable(bool permanent) { enabled = true; #if DISTORTION_PERMANENT && EEPROM_MODE != 0 if(permanent) EEPROM::setZCorrectionEnabled(enabled); #endif Com::printFLN(Com::tZCorrectionEnabled); } void Distortion::disable(bool permanent) { enabled = false; #if DISTORTION_PERMANENT && EEPROM_MODE != 0 if(permanent) EEPROM::setZCorrectionEnabled(enabled); #endif #if DRIVE_SYSTEM != DELTA Printer::zCorrectionStepsIncluded = 0; #endif Printer::updateCurrentPosition(false); Com::printFLN(Com::tZCorrectionDisabled); } void Distortion::reportStatus() { Com::printFLN(enabled ? Com::tZCorrectionEnabled : Com::tZCorrectionDisabled); } void Distortion::resetCorrection(void) { Com::printInfoFLN(PSTR("Resetting Z correction")); for(int i = 0; i < DISTORTION_CORRECTION_POINTS * DISTORTION_CORRECTION_POINTS; i++) setMatrix(0, i); } int Distortion::matrixIndex(fast8_t x, fast8_t y) const { return static_cast<int>(y) * DISTORTION_CORRECTION_POINTS + x; } int32_t Distortion::getMatrix(int index) const { #if DISTORTION_PERMANENT return EEPROM::getZCorrection(index); #else return matrix[index]; #endif } void Distortion::setMatrix(int32_t val, int index) { #if DISTORTION_PERMANENT #if EEPROM_MODE != 0 EEPROM::setZCorrection(val, index); #endif #else matrix[index] = val; #endif } bool Distortion::isCorner(fast8_t i, fast8_t j) const { return (i == 0 || i == DISTORTION_CORRECTION_POINTS - 1) && (j == 0 || j == DISTORTION_CORRECTION_POINTS - 1); } /** Extrapolates the changes from p1 to p2 to p3 which has the same distance as p1-p2. */ inline int32_t Distortion::extrapolatePoint(fast8_t x1, fast8_t y1, fast8_t x2, fast8_t y2) const { return 2 * getMatrix(matrixIndex(x2,y2)) - getMatrix(matrixIndex(x1,y1)); } void Distortion::extrapolateCorner(fast8_t x, fast8_t y, fast8_t dx, fast8_t dy) { setMatrix((extrapolatePoint(x + 2 * dx, y, x + dx, y) + extrapolatePoint(x, y + 2 * dy, x, y + dy)) / 2.0, matrixIndex(x,y)); } void Distortion::extrapolateCorners() { const fast8_t m = DISTORTION_CORRECTION_POINTS - 1; extrapolateCorner(0, 0, 1, 1); extrapolateCorner(0, m, 1,-1); extrapolateCorner(m, 0,-1, 1); extrapolateCorner(m, m,-1,-1); } void Distortion::measure(void) { fast8_t ix, iy; float z = EEPROM::zProbeBedDistance() + (EEPROM::zProbeHeight() > 0 ? EEPROM::zProbeHeight() : 0); disable(false); //Com::printFLN(PSTR("radiusCorr:"), radiusCorrectionSteps); //Com::printFLN(PSTR("steps:"), step); int32_t zCorrection = 0; #if Z_HOME_DIR < 0 zCorrection += Printer::zBedOffset * Printer::axisStepsPerMM[Z_AXIS]; #endif #if Z_HOME_DIR < 0 && Z_PROBE_Z_OFFSET_MODE == 1 zCorrection += Printer::zBedOffset * Printer::axisStepsPerMM[Z_AXIS]; #endif for (iy = DISTORTION_CORRECTION_POINTS - 1; iy >= 0; iy--) for (ix = 0; ix < DISTORTION_CORRECTION_POINTS; ix++) { #if (DRIVE_SYSTEM == DELTA) && DISTORTION_EXTRAPOLATE_CORNERS if (isCorner(ix, iy)) continue; #endif #if DRIVE_SYSTEM == DELTA float mtx = Printer::invAxisStepsPerMM[X_AXIS] * (ix * step - radiusCorrectionSteps); float mty = Printer::invAxisStepsPerMM[Y_AXIS] * (iy * step - radiusCorrectionSteps); #else float mtx = Printer::invAxisStepsPerMM[X_AXIS] * (ix * xCorrectionSteps + xOffsetSteps); float mty = Printer::invAxisStepsPerMM[Y_AXIS] * (iy * xCorrectionSteps + yOffsetSteps); #endif //Com::printF(PSTR("mx "),mtx); //Com::printF(PSTR("my "),mty); //Com::printF(PSTR("ix "),(int)ix); //Com::printFLN(PSTR("iy "),(int)iy); Printer::moveToReal(mtx, mty, z, IGNORE_COORDINATE, EEPROM::zProbeXYSpeed()); #if DISTORTION_EXTRAPOLATE_CORNERS && DRIVE_SYSTEM == DELTA setMatrix(floor(0.5f + Printer::axisStepsPerMM[Z_AXIS] * (z - Printer::runZProbe(ix == 1 && iy == DISTORTION_CORRECTION_POINTS - 1, ix == DISTORTION_CORRECTION_POINTS - 2 && iy == 0, Z_PROBE_REPETITIONS))) + zCorrection, matrixIndex(ix,iy)); #else setMatrix(floor(0.5f + Printer::axisStepsPerMM[Z_AXIS] * (z - Printer::runZProbe(ix == 0 && iy == DISTORTION_CORRECTION_POINTS - 1, ix == DISTORTION_CORRECTION_POINTS - 1 && iy == 0, Z_PROBE_REPETITIONS))) + zCorrection, matrixIndex(ix,iy)); #endif } #if (DRIVE_SYSTEM == DELTA) && DISTORTION_EXTRAPOLATE_CORNERS extrapolateCorners(); #endif // make average center // Disabled since we can use grid measurement to get average plane if that is what we want. // Shifting z with each measuring is a pain and can result in unexpected behavior. /* float sum = 0; for(int k = 0;k < DISTORTION_CORRECTION_POINTS * DISTORTION_CORRECTION_POINTS; k++) sum += getMatrix(k); sum /= static_cast<float>(DISTORTION_CORRECTION_POINTS * DISTORTION_CORRECTION_POINTS); for(int k = 0;k < DISTORTION_CORRECTION_POINTS * DISTORTION_CORRECTION_POINTS; k++) setMatrix(getMatrix(k) - sum, k); Printer::zLength -= sum * Printer::invAxisStepsPerMM[Z_AXIS]; */ #if EEPROM_MODE EEPROM::storeDataIntoEEPROM(); #endif // print matrix Com::printInfoFLN(PSTR("Distortion correction matrix:")); for (iy = DISTORTION_CORRECTION_POINTS - 1; iy >=0 ; iy--) { for(ix = 0; ix < DISTORTION_CORRECTION_POINTS; ix++) Com::printF(ix ? PSTR(", ") : PSTR(""), getMatrix(matrixIndex(ix,iy))); Com::println(); } showMatrix(); enable(true); //Printer::homeAxis(false, false, true); } int32_t Distortion::correct(int32_t x, int32_t y, int32_t z) const { if (!enabled || z > zEnd || Printer::isZProbingActive()) return 0.0f; if(false && z == 0) { Com::printF(PSTR("correcting ("), x); Com::printF(PSTR(","), y); } #if DRIVE_SYSTEM == DELTA x += radiusCorrectionSteps; y += radiusCorrectionSteps; int32_t fxFloor = (x - (x < 0 ? step - 1 : 0)) / step; // special case floor for negative integers! int32_t fyFloor = (y - (y < 0 ? step -1 : 0)) / step; #else x -= xOffsetSteps; y -= yOffsetSteps; int32_t fxFloor = (x - (x < 0 ? xCorrectionSteps - 1 : 0)) / xCorrectionSteps; // special case floor for negative integers! int32_t fyFloor = (y - (y < 0 ? yCorrectionSteps -1 : 0)) / yCorrectionSteps; #endif // indexes to the matrix if (fxFloor < 0) fxFloor = 0; else if (fxFloor > DISTORTION_CORRECTION_POINTS - 2) fxFloor = DISTORTION_CORRECTION_POINTS - 2; if (fyFloor < 0) fyFloor = 0; else if (fyFloor > DISTORTION_CORRECTION_POINTS - 2) fyFloor = DISTORTION_CORRECTION_POINTS - 2; // position between cells of matrix, range=0 to 1 - outside of the matrix the value will be outside this range and the value will be extrapolated #if DRIVE_SYSTEM == DELTA int32_t fx = x - fxFloor * step; // Grid normalized coordinates int32_t fy = y - fyFloor * step; int32_t idx11 = matrixIndex(fxFloor, fyFloor); int32_t m11 = getMatrix(idx11), m12 = getMatrix(idx11 + 1); int32_t m21 = getMatrix(idx11 + DISTORTION_CORRECTION_POINTS); int32_t m22 = getMatrix(idx11 + DISTORTION_CORRECTION_POINTS + 1); int32_t zx1 = m11 + ((m12 - m11) * fx) / step; int32_t zx2 = m21 + ((m22 - m21) * fx) / step; int32_t correction_z = zx1 + ((zx2 - zx1) * fy) / step; #else int32_t fx = x - fxFloor * xCorrectionSteps; // Grid normalized coordinates int32_t fy = y - fyFloor * yCorrectionSteps; int32_t idx11 = matrixIndex(fxFloor, fyFloor); int32_t m11 = getMatrix(idx11), m12 = getMatrix(idx11 + 1); int32_t m21 = getMatrix(idx11 + DISTORTION_CORRECTION_POINTS); int32_t m22 = getMatrix(idx11 + DISTORTION_CORRECTION_POINTS + 1); int32_t zx1 = m11 + ((m12 - m11) * fx) / xCorrectionSteps; int32_t zx2 = m21 + ((m22 - m21) * fx) / xCorrectionSteps; int32_t correction_z = zx1 + ((zx2 - zx1) * fy) / yCorrectionSteps; #endif if(false && z == 0) { Com::printF(PSTR(") by "), correction_z); Com::printF(PSTR(" ix= "), fxFloor); Com::printF(PSTR(" fx= "), fx); Com::printF(PSTR(" iy= "), fyFloor); Com::printFLN(PSTR(" fy= "), fy); } if (z > zStart && z > 0) correction_z *= (zEnd - z) / (zEnd - zStart); /* if(correction_z > 20 || correction_z < -20) { Com::printFLN(PSTR("Corr. error too big:"),correction_z); Com::printF(PSTR("fxf"),(int)fxFloor); Com::printF(PSTR(" fyf"),(int)fyFloor); Com::printF(PSTR(" fx"),fx); Com::printF(PSTR(" fy"),fy); Com::printF(PSTR(" x"),x); Com::printFLN(PSTR(" y"),y); Com::printF(PSTR(" m11:"),m11); Com::printF(PSTR(" m12:"),m12); Com::printF(PSTR(" m21:"),m21); Com::printF(PSTR(" m22:"),m22); Com::printFLN(PSTR(" step:"),step); correction_z = 0; }*/ return correction_z; } void Distortion::set(float x,float y,float z) { #if DRIVE_SYSTEM == DELTA int ix = (x * Printer::axisStepsPerMM[Z_AXIS] + radiusCorrectionSteps + step / 2) / step; int iy = (y * Printer::axisStepsPerMM[Z_AXIS] + radiusCorrectionSteps + step / 2) / step; #else int ix = (x * Printer::axisStepsPerMM[X_AXIS] - xOffsetSteps + xCorrectionSteps / 2) / xCorrectionSteps; int iy = (y * Printer::axisStepsPerMM[Y_AXIS] - yOffsetSteps + yCorrectionSteps / 2) / yCorrectionSteps; #endif if(ix < 0) ix = 0; if(iy < 0) iy = 0; if(ix >= DISTORTION_CORRECTION_POINTS-1) ix = DISTORTION_CORRECTION_POINTS-1; if(iy >= DISTORTION_CORRECTION_POINTS-1) iy = DISTORTION_CORRECTION_POINTS-1; int32_t idx = matrixIndex(ix, iy); setMatrix(z * Printer::axisStepsPerMM[Z_AXIS],idx); } void Distortion::showMatrix() { for(int ix = 0;ix < DISTORTION_CORRECTION_POINTS; ix++) { for(int iy = 0;iy < DISTORTION_CORRECTION_POINTS; iy++) { #if DRIVE_SYSTEM == DELTA float x = (-radiusCorrectionSteps + ix * step) * Printer::invAxisStepsPerMM[Z_AXIS]; float y = (-radiusCorrectionSteps + iy * step) * Printer::invAxisStepsPerMM[Z_AXIS]; #else float x = (xOffsetSteps + ix * xCorrectionSteps) * Printer::invAxisStepsPerMM[X_AXIS]; float y = (yOffsetSteps + iy * yCorrectionSteps) * Printer::invAxisStepsPerMM[Y_AXIS]; #endif int32_t idx = matrixIndex(ix, iy); float z = getMatrix(idx) * Printer::invAxisStepsPerMM[Z_AXIS]; Com::printF(PSTR("Distortion correction at px:"),x,2); Com::printF(PSTR(" py:"),y,2); Com::printFLN(PSTR(" zCoorection:"),z,3); } } } #endif // DISTORTION_CORRECTION #if JSON_OUTPUT void Printer::showJSONStatus(int type) { bool firstOccurrence; Com::printF(PSTR("{\"status\": \"")); if (PrintLine::linesCount == 0) { Com::print('I'); // IDLING #if SDSUPPORT } else if (sd.sdactive) { Com::print('P'); // SD PRINTING #endif } else { Com::print('B'); // SOMETHING ELSE, BUT SOMETHIG } Com::printF(PSTR("\",\"coords\": {")); Com::printF(PSTR("\"axesHomed\":[")); Com::printF(isHomed() ? PSTR("1, 1, 1") : PSTR("0, 0, 0")); Com::printF(PSTR("],\"extr\":[")); firstOccurrence = true; for (int i = 0; i < NUM_EXTRUDER; i++) { if (!firstOccurrence) Com::print(','); Com::print(extruder[i].extrudePosition / extruder[i].stepsPerMM); firstOccurrence = false; } Com::printF(PSTR("],\"xyz\":[")); Com::print(currentPosition[X_AXIS]); // X Com::print(','); Com::print(currentPosition[Y_AXIS]); // Y Com::print(','); Com::print(currentPosition[Z_AXIS]); // Z Com::printF(PSTR("]},\"currentTool\":")); Com::print(Extruder::current->id); Com::printF(PSTR(",\"params\": {\"atxPower\":")); Com::print(isPowerOn()?'1':'0'); Com::printF(PSTR(",\"fanPercent\":[")); #if FEATURE_FAN_CONTROL Com::print(getFanSpeed() / 2.55f); #endif #if FEATURE_FAN2_CONTROL Com::printF(Com::tComma,getFan2Speed() / 2.55f); #endif Com::printF(PSTR("],\"speedFactor\":")); Com::print(Printer::feedrateMultiply); Com::printF(PSTR(",\"extrFactors\":[")); firstOccurrence = true; for (int i = 0; i < NUM_EXTRUDER; i++) { if (!firstOccurrence) Com::print(','); Com::print((int)Printer::extrudeMultiply); // Really *100? 100 is normal firstOccurrence = false; } Com::printF(PSTR("]},")); // SEQ?? Com::printF(PSTR("\"temps\": {")); #if HAVE_HEATED_BED Com::printF(PSTR("\"bed\": {\"current\":")); Com::print(heatedBedController.currentTemperatureC); Com::printF(PSTR(",\"active\":")); Com::print(heatedBedController.targetTemperatureC); Com::printF(PSTR(",\"state\":")); Com::print(heatedBedController.targetTemperatureC > 0 ? '2' : '1'); Com::printF(PSTR("},")); #endif Com::printF(PSTR("\"heads\": {\"current\": [")); firstOccurrence = true; for (int i = 0; i < NUM_EXTRUDER; i++) { if (!firstOccurrence) Com::print(','); Com::print(extruder[i].tempControl.currentTemperatureC); firstOccurrence = false; } Com::printF(PSTR("],\"active\": [")); firstOccurrence = true; for (int i = 0; i < NUM_EXTRUDER; i++) { if (!firstOccurrence) Com::print(','); Com::print(extruder[i].tempControl.targetTemperatureC); firstOccurrence = false; } Com::printF(PSTR("],\"state\": [")); firstOccurrence = true; for (int i = 0; i < NUM_EXTRUDER; i++) { if (!firstOccurrence) Com::print(','); Com::print(extruder[i].tempControl.targetTemperatureC > EXTRUDER_FAN_COOL_TEMP?'2':'1'); firstOccurrence = false; } Com::printF(PSTR("]}},\"time\":")); Com::print(HAL::timeInMilliseconds()); switch (type) { default: case 0: case 1: break; case 2: // UNTIL PRINT ESTIMATE TIMES ARE IMPLEMENTED // NO DURATION INFO IS SUPPORTED Com::printF(PSTR(",\"coldExtrudeTemp\":0,\"coldRetractTemp\":0.0,\"geometry\":\"")); #if (DRIVE_SYSTEM == DELTA) Com::printF(PSTR("delta")); #elif (DRIVE_SYSTEM == CARTESIAN) Com::printF(PSTR("cartesian")); #elif ((DRIVE_SYSTEM == XY_GANTRY) || (DRIVE_SYSTEM == YX_GANTRY)) Com::printF(PSTR("coreXY")); #elif (DRIVE_SYSTEM == XZ_GANTRY) Com::printF(PSTR("coreXZ")); #endif Com::printF(PSTR("\",\"name\":\"")); Com::printF(PSTR(UI_PRINTER_NAME)); Com::printF(PSTR("\",\"tools\":[")); firstOccurrence = true; for (int i = 0; i < NUM_EXTRUDER; i++) { if (!firstOccurrence) Com::print(','); Com::printF(PSTR("{\"number\":")); Com::print(i); Com::printF(PSTR(",\"heaters\":[1],\"drives\":[1]")); Com::print('}'); firstOccurrence = false; } Com::printFLN(PSTR("]")); break; case 3: Com::printF(PSTR(",\"currentLayer\":")); #if SDSUPPORT if (sd.sdactive && sd.fileInfo.layerHeight > 0) { // ONLY CAN TELL WHEN SD IS PRINTING Com::print((int) (currentPosition[Z_AXIS] / sd.fileInfo.layerHeight)); } else Com::print('0'); #else Com::printF(PSTR("-1")); #endif Com::printF(PSTR("\",extrRaw\":[")); firstOccurrence = true; for (int i = 0; i < NUM_EXTRUDER; i++) { if (!firstOccurrence) Com::print(','); Com::print(extruder[i].extrudePosition * Printer::extrudeMultiply); firstOccurrence = false; } Com::printF(PSTR("],")); #if SDSUPPORT if (sd.sdactive) { Com::printF(PSTR("\"fractionPrinted\":")); float fraction; if (sd.filesize < 2000000) fraction = sd.sdpos / sd.filesize; else fraction = (sd.sdpos >> 8) / (sd.filesize >> 8); Com::print((float) floorf(fraction * 1000) / 1000); // ONE DECIMAL, COULD BE DONE BY SHIFTING, BUT MEH Com::print(','); } #endif Com::printF(PSTR("\"firstLayerHeight\":")); #if SDSUPPORT if (sd.sdactive) { Com::print(sd.fileInfo.layerHeight); } else Com::print('0'); #else Com::print('0'); #endif break; case 4: case 5: Com::printF(PSTR(",\"axisMins\":[")); Com::print((int) X_MIN_POS); Com::print(','); Com::print((int) Y_MIN_POS); Com::print(','); Com::print((int) Z_MIN_POS); Com::printF(PSTR("],\"axisMaxes\":[")); Com::print((int) X_MAX_LENGTH); Com::print(','); Com::print((int) Y_MAX_LENGTH); Com::print(','); Com::print((int) Z_MAX_LENGTH); Com::printF(PSTR("],\"accelerations\":[")); Com::print(maxAccelerationMMPerSquareSecond[X_AXIS]); Com::print(','); Com::print(maxAccelerationMMPerSquareSecond[Y_AXIS]); Com::print(','); Com::print(maxAccelerationMMPerSquareSecond[Z_AXIS]); for (int i = 0; i < NUM_EXTRUDER; i++) { Com::print(','); Com::print(extruder[i].maxAcceleration); } Com::printF(PSTR("],\"firmwareElectronics\":\"")); #ifdef RAMPS_V_1_3 Com::printF(PSTR("RAMPS")); #elif (CPU_ARCH == ARCH_ARM) Com::printF(PSTR("Arduino Due")); #else Com::printF(PSTR("AVR")); #endif Com::printF(PSTR("\",\"firmwareName\":\"Repetier\",\"firmwareVersion\":\"")); Com::printF(PSTR(REPETIER_VERSION)); Com::printF(PSTR("\",\"minFeedrates\":[0,0,0")); for (int i = 0; i < NUM_EXTRUDER; i++) { Com::printF(PSTR(",0")); } Com::printF(PSTR("],\"maxFeedrates\":[")); Com::print(maxFeedrate[X_AXIS]); Com::print(','); Com::print(maxFeedrate[Y_AXIS]); Com::print(','); Com::print(maxFeedrate[Z_AXIS]); for (int i = 0; i < NUM_EXTRUDER; i++) { Com::print(','); Com::print(extruder[i].maxFeedrate); } Com::printFLN(PSTR("]")); break; } Com::printFLN(PSTR("}")); } #endif // JSON_OUTPUT #if defined(CUSTOM_EVENTS) #include "CustomEventsImpl.h" #endif
780e60b36509274bff1befb15f1a5e544e1f89ba
767fbd64895f6a308ec4d14cc01b66053242774b
/src/MScene.h
820498f2c02cb37494206b7ff6a85bf5f7cd68d5
[]
no_license
barmaxence/RT
7d8835e6d5a310c3c05c341cae241b6a5d63fe69
1e992f4fa39b76ce86422f2be80b5afe5a43fb91
refs/heads/master
2020-04-09T09:04:07.202316
2018-12-03T16:21:45
2018-12-03T16:21:45
160,219,858
0
0
null
null
null
null
UTF-8
C++
false
false
703
h
#pragma once #include "MWindow.h" #include "MCamera.h" #include "MObject.h" #include "MLight.h" #include "MSmartPointer.h" #include <list> #include <memory> class MScene { public: MScene(void); MScene(const MScene& src); MScene(MScene&& src); MScene(const MWindow& window, const MCamera& camera); virtual ~MScene(void); MScene& operator=(const MScene& rhs); MScene& operator=(MScene&& rhs); virtual const std::string toDebugString(void) const; MWindow window = MWindow(); MCamera camera = MCamera(); std::list<MSmartPointer<MObject>> objects; std::list<MSmartPointer<MLight>> lights; MColor bColor = MColor(55.0, 55.0, 55.0); protected: private: };
0057393d554ca88ddbb2b18fc44741205f630f76
b799c972367cd014a1ffed4288a9deb72f590bec
/project/NetServices/if/net/nettcpsocket.cpp
810408c9e6c6639e06e461e8b7491614042926cd
[]
no_license
intervigilium/csm213a-embedded
647087de8f831e3c69e05d847d09f5fa12b468e6
ae4622be1eef8eb6e4d1677a9b2904921be19a9e
refs/heads/master
2021-01-13T02:22:42.397072
2011-12-11T22:50:37
2011-12-11T22:50:37
2,832,079
2
1
null
null
null
null
UTF-8
C++
false
false
2,165
cpp
/* Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "nettcpsocket.h" //#define __DEBUG #include "dbg/dbg.h" NetTcpSocket::NetTcpSocket() : m_host(), m_client(), m_refs(0), m_closed(false), m_removed(false), m_pCbItem(NULL), m_pCbMeth(NULL), m_events() { Net::registerNetTcpSocket(this); } NetTcpSocket::~NetTcpSocket() //close() { Net::unregisterNetTcpSocket(this); } //Callbacks #ifdef __LINKER_BUG_SOLVED__ void NetTcpSocket::setOnEvent() { m_pCbItem = (CDummy*) pItem; m_pCbMeth = (void (CDummy::*)(NetTcpSocketEvent)) pMethod; } #endif void NetTcpSocket::resetOnEvent() { m_pCbItem = NULL; m_pCbMeth = NULL; } void NetTcpSocket::queueEvent(NetTcpSocketEvent e) { m_events.push(e); } void NetTcpSocket::discardEvents() { while( !m_events.empty() ) { m_events.pop(); } } void NetTcpSocket::flushEvents() //To be called during polling { while( !m_events.empty() ) { onEvent(m_events.front()); m_events.pop(); } } void NetTcpSocket::onEvent(NetTcpSocketEvent e) //To be called during polling { if(m_pCbItem && m_pCbMeth) (m_pCbItem->*m_pCbMeth)(e); }
a67e66a019b1cce0cea356c7672eacfa80a994e9
b58d467ded99f268f0c1ebc4957ddb30d8271494
/srcs/InputBlock.class.cpp
1e5084db60f532a8320e531217a8941eb0da15b2
[]
no_license
mdufaud/gomoku
77d9beca7d55a7b1fd52c05ae5da3ec5ac362fcc
1d01901bdcbb97b4bd0dfd751578b5b45c7d21bc
refs/heads/master
2022-03-20T02:41:05.518900
2019-12-19T22:14:36
2019-12-19T22:14:36
197,841,725
0
0
null
null
null
null
UTF-8
C++
false
false
3,714
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* InputBlock.class.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mdufaud <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/04/30 22:47:41 by mdufaud #+# #+# */ /* Updated: 2016/07/01 11:24:31 by rcherik ### ########.fr */ /* */ /* ************************************************************************** */ #include "InputBlock.class.hpp" #include "Graph.class.hpp" InputBlock::InputBlock(Graph *graph, SDL_Rect & blockDef): ABlock(graph, blockDef) { _selectable = true; _inputTextTexture = NULL; _type = INPUTBLOCK_TYPE; SDL_SetTextInputRect(&blockDef); } InputBlock::InputBlock(Graph *graph, SDL_Rect & blockDef, std::string background): ABlock(graph, blockDef, background) { _selectable = true; _inputTextTexture = NULL; _type = INPUTBLOCK_TYPE; SDL_SetTextInputRect(&blockDef); } InputBlock::~InputBlock() { } bool InputBlock::action(int x, int y) { (void)x; (void)y; return (false); } void InputBlock::addText(std::string text) { if (text.find_first_not_of(' ') == std::string::npos || text.find_first_not_of('\t') == std::string::npos) return ; if (_inputText.length() + text.length() > MAX_INPUTS) return ; _inputText += text; if ((TTF_SizeText(_font, _inputText.c_str(), &_inputRect.w, &_inputRect.h) < 0)) sdl_error("Size Text"); this->setMessage(&_inputTextTexture, _inputText, &_inputRect); } void InputBlock::backDel(void) { if (_inputText.length() > 0) { _inputText = _inputText.substr(0, _inputText.length() - 1); if (_inputText.empty()) _inputText = " "; this->setMessage(&_inputTextTexture, _inputText, &_inputRect); } } std::string InputBlock::getInput(void) { if (_inputText.find_first_not_of(' ') == std::string::npos) _inputText = ""; else if (_inputText.find_first_not_of('\t') == std::string::npos) _inputText = ""; return (_inputText); } void InputBlock::draw() { if (_background) SDL_RenderCopy(_graph->getRenderer(), _backgroundTexture, NULL, &_backgroundRect); if (!_background || (_background && (_selected || _hoovered))) { SDL_Rect tmp = {_backgroundRect.x - 1, _backgroundRect.y - 1, _backgroundRect.w + 2, _backgroundRect.h + 2}; SDL_SetRenderDrawColor(_graph->getRenderer(), 0xFF, 0xFF, 0xFF, 0x00); SDL_RenderDrawRect(_graph->getRenderer(), &tmp); if (_selected || _hoovered) { SDL_Rect tmp = {_backgroundRect.x - 2, _backgroundRect.y - 2, _backgroundRect.w + 4, _backgroundRect.h + 4}; SDL_SetRenderDrawColor(_graph->getRenderer(), 0xFF, 0xFF, 0xFF, 0x00); SDL_RenderDrawRect(_graph->getRenderer(), &tmp); } if (_selected && _hoovered) { SDL_Rect tmp = {_backgroundRect.x - 3, _backgroundRect.y - 3, _backgroundRect.w + 6, _backgroundRect.h + 6}; SDL_SetRenderDrawColor(_graph->getRenderer(), 0xFF, 0xFF, 0xFF, 0x00); SDL_RenderDrawRect(_graph->getRenderer(), &tmp); } } SDL_RenderCopy(_graph->getRenderer(), _inputTextTexture, NULL, &_inputRect); } int InputBlock::selected(void) { SDL_StartTextInput(); return (ABlock::selected()); } void InputBlock::unselect(void) { SDL_StopTextInput(); ABlock::unselect(); }
d80d605fd8d55ef3dab3bd974803f3ea829c56db
42059e1bb5eda9013c1db41deee389f5726c7867
/CLSD/data.h
0c890b882e06832c836c88819918f5c44fffd32e
[]
no_license
dbuw/master
89d756bc28f8b7aeed69d2601e31af8d514b02e4
e7e2d194afb0b779f5608a79c2046d4381738fa1
refs/heads/master
2021-01-22T09:54:59.468029
2014-05-25T20:36:05
2014-05-25T20:36:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,930
h
#ifndef DATA_H_INCLUDED #define DATA_H_INCLUDED #include "../util/util.h" class Data { public: typedef std::vector<int> container; typedef container::const_iterator const_iterator; Data() {} //setters void setJ(int i) {J = i;}; void setT(int i) {T = i;}; void setD(const container& i){d = i;}; void setC(const container& i){C = i;}; void setP(const container& i){p = i;}; void setH(const container& i){h = i;}; void setSC(const container& i){c = i;}; void setST(const container& i){s = i;}; //getters int getJ() {return J;}; int getT() {return T;}; int getD(int j, int t) {return d[index(j,t,T)];}; int getC(int t) {return C[t];}; int getP(int j) {return p[j];}; int getH(int j) {return h[j];}; int getSC(int i, int j) {return c[index(i,j,J)];}; int getST(int i, int j) {return s[index(i,j,J)];}; //getters container getD() {return d;}; const_iterator dBegin() {return d.begin();}; const_iterator dEnd() {return d.end();}; container getC() {return C;}; const_iterator CBegin() {return C.begin();}; const_iterator CEnd() {return C.end();}; container getP() {return p;}; const_iterator pBegin() {return p.begin();}; const_iterator pEnd() {return p.end();}; container getH() {return h;}; const_iterator hBegin() {return h.begin();}; const_iterator hEnd() {return h.end();}; container getSC() {return c;}; const_iterator cBegin() {return c.begin();}; const_iterator cEnd() {return c.end();}; container getST() {return s;}; const_iterator sBegin() {return s.begin();}; const_iterator sEnd() {return s.end();}; private: int J; //number of items int T; //number of periods container d; //demand for item j in period t container C; //capacity in period t container p; //processing times container h; //holding costs container c; //sequence dependent setup costs container s; //sequence dependent setup times }; #endif // DATA_H_INCLUDED
5993cc917a28ff35659490eec600d263161ed015
5fb4409abe9e4796c8dc17cc51233c779b9e24bc
/app/src/main/cpp/wechat/zxing/common/decoder_result.hpp
cb7ee144a1455719b2054e180b2c389c49989470
[]
no_license
BlackSuns/LearningAndroidOpenCV
6be52f71cd9f3a1d5546da31f71c04064f0c7cac
79dc25e383c740c73cae67f36027abf13ab17922
refs/heads/master
2023-07-10T02:08:10.923992
2021-08-09T02:09:19
2021-08-09T02:09:34
297,529,216
0
0
null
2021-08-09T14:06:05
2020-09-22T03:52:46
C++
UTF-8
C++
false
false
2,665
hpp
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Tencent is pleased to support the open source community by making WeChat QRCode available. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Modified from ZXing. Copyright ZXing authors. // Licensed under the Apache License, Version 2.0 (the "License"). #ifndef __ZXING_COMMON_DECODER_RESULT_HPP__ #define __ZXING_COMMON_DECODER_RESULT_HPP__ #include "../qrcode/decoder/qrcode_decoder_metadata.hpp" #include "array.hpp" #include "counted.hpp" #include "str.hpp" namespace zxing { class DecoderResult : public Counted { private: ArrayRef<char> rawBytes_; Ref<String> text_; ArrayRef<ArrayRef<char> > byteSegments_; std::string ecLevel_; std::string outputCharset_; int qrcodeVersion_; std::string charsetMode_; Ref<qrcode::QRCodeDecoderMetaData> other_; string otherClassName; public: DecoderResult(ArrayRef<char> rawBytes, Ref<String> text, ArrayRef<ArrayRef<char> > &byteSegments, std::string const &ecLevel); DecoderResult(ArrayRef<char> rawBytes, Ref<String> text, ArrayRef<ArrayRef<char> > &byteSegments, std::string const &ecLevel, std::string outputCharset); DecoderResult(ArrayRef<char> rawBytes, Ref<String> text, ArrayRef<ArrayRef<char> > &byteSegments, std::string const &ecLevel, std::string outputCharset, int qrcodeVersion, std::string &charsetMode); DecoderResult(ArrayRef<char> rawBytes, Ref<String> text); DecoderResult(ArrayRef<char> rawBytes, Ref<String> text, std::string outputCharset); ArrayRef<char> getRawBytes(); Ref<String> getText(); std::string getCharset(); void setOther(Ref<qrcode::QRCodeDecoderMetaData> other) { other_ = other; otherClassName = "QRCodeDecoderMetaData"; }; Ref<qrcode::QRCodeDecoderMetaData> getOther() { // className = otherClassName; return other_; }; string getOtherClassName() { return otherClassName; }; int getQRCodeVersion() const { return qrcodeVersion_; }; void setText(Ref<String> text) { text_ = text; }; string getEcLevel() { return ecLevel_; } string getCharsetMode() { return charsetMode_; } }; } // namespace zxing #endif // __ZXING_COMMON_DECODER_RESULT_HPP__
07220aa7aed588200c8584ae88c606f2b8177a8d
0179363e16864f8c9fa5445898c1237ef2e83901
/Linked List(Day 3)/remove duplicates from LL.cpp
ffdc3e51d5e766efbcd676d6ba2d52ae2950a0a6
[]
no_license
himanshu-sagar/CP_CipherSchools
4a051efe010e10a0745e6561f9268d5075a8dfaf
1c824f06d8d5d78330e5b509bf24a486c7102796
refs/heads/master
2023-03-10T21:06:35.063386
2021-02-22T17:22:17
2021-02-22T17:22:17
338,584,675
1
0
null
null
null
null
UTF-8
C++
false
false
1,083
cpp
#include <iostream> using namespace std; class Node { public: int data; Node *next; Node(int data) { this->data = data; this->next = NULL; } }; Node *removeDuplicates(Node *head) { if(head==NULL) { return head; } Node *temp1=head; while(head->next!=NULL) { if(head->next->data==head->data) { Node *temp=head->next; head->next=temp->next; delete []temp; } else { head=head->next; } } return temp1; } Node *takeinput() { int data; cin >> data; Node *head = NULL, *tail = NULL; while (data != -1) { Node *newnode = new Node(data); if (head == NULL) { head = newnode; tail = newnode; } else { tail->next = newnode; tail = newnode; } cin >> data; } return head; } void print(Node *head) { Node *temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } int main() { Node *head = takeinput(); head = removeDuplicates(head); print(head); }
b2b111c53329b6a15b2db419d803f047b5d0f330
f0a044b13e89aa41f5ea7c85d772873d33f7bd94
/XTypo/blendersplitter.h
2cde6c4dce64c6161abdff67d7a69b5040138904
[]
no_license
peterkiss/QtProjects
40881c51f8b62354ebd2793a0a61a549bc4aa5fd
97c42273e38e14d7ec9e4a6b4c2483968aa85852
refs/heads/master
2016-09-06T08:30:39.082337
2015-03-31T16:06:40
2015-03-31T16:06:40
33,254,212
0
0
null
null
null
null
UTF-8
C++
false
false
867
h
#ifndef BLENDERSPLITTER_H #define BLENDERSPLITTER_H #include <QSplitter> #include "drawarea.h" #include <QDebug> class BlenderSplitter : public QSplitter { Q_OBJECT public: explicit BlenderSplitter(QWidget *parent = 0); void reOrganize(QPointF dif, WorkFrame *frame); void addWidget(QWidget *widget) ; ~BlenderSplitter(); const bool root; void reOrganize(BlenderSplitter *splitter, WorkFrame *frame); void moveSplitter(QPointF pos, int index); BlenderSplitter(BlenderSplitter *parent, WorkFrame* PrimaryWidget, WorkFrame* SecondaryWidget); signals: public slots: void mouseMoveEvent(QMouseEvent *me){if(me->buttons()==Qt::LeftButton) qDebug()<<"mouseMove";} void mouseReleaseEvent(QMouseEvent *){ qDebug()<<"mouseRel";} private: QWidget* primaryWidget; QWidget* secondaryWidget; }; #endif // BLENDERSPLITTER_H
7edd0e26aabb5311381bdf51bfe4c02b43503743
f8e754dc3969b9d9540edb72263b9547cec7231f
/ofApp.h
7db34d557d2d6835df66d556f01c5b3caf33edc2
[]
no_license
junkiyoshi/Insta20180302
e6e10f5935c3ffbb0d7f903f3de0eb0ecbbbc73b
4caa39cf9a25cd395e98b5283a3e10fe97dbf595
refs/heads/master
2021-01-25T13:19:18.498006
2018-03-02T09:26:50
2018-03-02T09:26:50
123,559,033
0
0
null
null
null
null
UTF-8
C++
false
false
580
h
#include "ofMain.h" class ofApp : public ofBaseApp { public: void setup(); void update(); void draw(); void keyPressed(int key) {}; void keyReleased(int key) {}; void mouseMoved(int x, int y) {}; void mouseDragged(int x, int y, int button) {}; void mousePressed(int x, int y, int button) {}; void mouseReleased(int x, int y, int button) {}; void mouseEntered(int x, int y) {}; void mouseExited(int x, int y) {}; void windowResized(int w, int h) {}; void dragEvent(ofDragInfo dragInfo) {}; void gotMessage(ofMessage msg) {}; ofEasyCam cam; float noise_value; };
7dfb1de9258cb3170a674add6440b70e686c0e5a
70418d8faa76b41715c707c54a8b0cddfb393fb3
/12215.cpp
c7e08cffdeca3037e5e21b3ed541bf319da82fbe
[]
no_license
evandrix/UVa
ca79c25c8bf28e9e05cae8414f52236dc5ac1c68
17a902ece2457c8cb0ee70c320bf0583c0f9a4ce
refs/heads/master
2021-06-05T01:44:17.908960
2017-10-22T18:59:42
2017-10-22T18:59:42
107,893,680
3
1
null
null
null
null
UTF-8
C++
false
false
4,989
cpp
#include <bits/stdc++.h> using namespace std; // 1,2,...,N: to form a matrix of R * N by stacking R stage permutation of N // Find a single matrix when the maximum value of R. // However, the matrix have to satisfy the following constraints: // D[i][j] := (the number of j placed on the i-th column) // E[i][j] := max(D[i][j]-C[i][j],0) // and // - With all i, Σ_j E[i][j] <= A[i] // - In all j, Σ_i E[i][j] <= B[j] // I flow to the flow numbers from column // Send double each vertex representing a column vertices of digits, // divided into parts which may or may not overflowing C #define rep(i, n) for (int i = 0; i < (n); i++) const int INF = 1 << 29; // MAXFLOW // const int V_MAX = 4 * 30 + 2; const int E_MAX = 4 * 30 + 2 * 30 * 30; template <class T> struct graph { int n, m, head[V_MAX], next[2 * E_MAX], to[2 * E_MAX]; T capa[2 * E_MAX], flow[2 * E_MAX]; void init(int N) { n = N; m = 0; rep(u, n) head[u] = -1; } void add_directed_edge(int u, int v, T ca) { next[m] = head[u]; head[u] = m; to[m] = v; capa[m] = ca; flow[m] = 0; m++; next[m] = head[v]; head[v] = m; to[m] = u; capa[m] = 0; flow[m] = 0; m++; } }; int layer[V_MAX], now[V_MAX]; template <class T> bool make_layer(const graph<T> &G, int s, int t) { int n = G.n; rep(u, n) layer[u] = (u == s ? 0 : -1); int head = 0, tail = 0; static int Q[V_MAX]; Q[tail++] = s; while (head < tail && layer[t] == -1) { int u = Q[head++]; for (int e = G.head[u]; e != -1; e = G.next[e]) { int v = G.to[e]; T capa = G.capa[e], flow = G.flow[e]; if (capa - flow > 0 && layer[v] == -1) { layer[v] = layer[u] + 1; Q[tail++] = v; } } } return layer[t] != -1; } template <class T> T augment(graph<T> &G, int u, int t, T water) { if (u == t) { return water; } for (int &e = now[u]; e != -1; e = G.next[e]) { int v = G.to[e]; T capa = G.capa[e], flow = G.flow[e]; if (capa - flow > 0 && layer[v] > layer[u]) { T w = augment(G, v, t, min(water, capa - flow)); if (w > 0) { G.flow[e] += w; G.flow[e ^ 1] -= w; return w; } } } return 0; } template <class T> T Dinic(graph<T> &G, int s, int t) { int n = G.n; T ans = 0; while (make_layer(G, s, t)) { rep(u, n) now[u] = G.head[u]; for (T water = 1; water > 0; ans += water) { water = augment(G, s, t, INF); } } return ans; } // BIPARTITE MATCHING // bool augment(int u, bool *vis, int match[2][V_MAX], const vector<int> *G) { if (u == -1) { return true; } rep(i, G[u].size()) { int v = G[u][i]; if (!vis[v]) { vis[v] = true; if (augment(match[1][v], vis, match, G)) { match[0][u] = v; match[1][v] = u; return true; } } } return false; } int match[2][V_MAX]; int bipartite_matching(int L, int R, const vector<int> *G) { rep(u, L) match[0][u] = -1; rep(v, R) match[1][v] = -1; int res = 0; static bool vis[V_MAX]; rep(u, L) { rep(v, R) vis[v] = false; if (augment(u, vis, match, G)) { res++; } } return res; } // LIBRARY END // void solve() { int n; scanf("%d", &n); int A[30], B[30], C[30][30]; rep(i, n) scanf("%d", A + i); rep(i, n) scanf("%d", B + i); rep(i, n) rep(j, n) scanf("%d", C[i] + j); int s = 4 * n, t = s + 1; static graph<int> G; int lo = 0, hi = 150; while (lo < hi) { int mi = (lo + hi + 1) / 2, R = mi; G.init(4 * n + 2); rep(i, n) { G.add_directed_edge(s, i, R); G.add_directed_edge(3 * n + i, t, R); G.add_directed_edge(i, n + i, A[i]); G.add_directed_edge(2 * n + i, 3 * n + i, B[i]); } rep(i, n) rep(j, n) { G.add_directed_edge(i, 3 * n + j, C[i][j]); G.add_directed_edge(n + i, 2 * n + j, R); } if (Dinic(G, s, t) == n * R) { lo = mi; } else { hi = mi - 1; } } int R = lo; G.init(4 * n + 2); rep(i, n) { G.add_directed_edge(s, i, R); G.add_directed_edge(3 * n + i, t, R); G.add_directed_edge(i, n + i, A[i]); G.add_directed_edge(2 * n + i, 3 * n + i, B[i]); } rep(i, n) rep(j, n) { G.add_directed_edge(i, 3 * n + j, C[i][j]); G.add_directed_edge(n + i, 2 * n + j, R); } Dinic(G, s, t); // recovered ranks int D[30][30] = {};// D in question rep(u, 2 * n) for (int e = G.head[u]; e != -1; e = G.next[e]) { int v = G.to[e]; if (u < n) { if (3 * n <= v && v < 4 * n) { D[u][v - 3 * n] += G.flow[e]; } } else { if (2 * n <= v && v < 3 * n) { D[u - n][v - 2 * n] += G.flow[e]; } } } printf("%d\n", R); while (R--) { //Go to restore step-by-step to seek the perfect matching of the bipartite graph //Unknown why R times worth it be restored properly in this vector<int> BG[30]; rep(i, n) rep(j, n) if (D[i][j] > 0) { BG[i].push_back(j); } bipartite_matching(n, n, BG); rep(i, n) { int j = match[0][i]; D[i][j]--; printf("%d%c", j, i < n - 1 ? ' ' : '\n'); } } } int main() { int T; scanf("%d", &T); for (int cas = 1; cas <= T; cas++) { printf("Case %d: ", cas), solve(); } return 0; }
e4cf7d3d1e3471569dcd6a7597c0552b9d24ceb1
1f7e760a50b25c64a723bf7d4d1931bc2caa0a87
/moc_CPictureFlowWidget.cpp
935f9d5317d5f4145b961914e8e1e4d0b2e0caad
[]
no_license
an4rchy/Gallery-Misc
d8b7fda7f2169b058cc503a72615b61502f43c9c
b23b195ba6d3ef918755f474ea4bb2ce0ee7a0d6
refs/heads/master
2021-01-02T14:46:41.544523
2012-05-14T13:19:38
2012-05-14T13:19:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,483
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'CPictureFlowWidget.hpp' ** ** Created: Thu Apr 5 07:01:47 2012 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.4) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "CPictureFlowWidget.hpp" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'CPictureFlowWidget.hpp' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.4. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_CPictureFlowWidget[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 16, 14, // methods 4, 94, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 4, // signalCount // signals: signature, parameters, type, tag, flags 26, 20, 19, 19, 0x05, 61, 50, 19, 19, 0x05, 84, 19, 19, 19, 0x05, 95, 19, 19, 19, 0x05, // slots: signature, parameters, type, tag, flags 113, 107, 19, 19, 0x0a, 137, 130, 19, 19, 0x0a, 167, 155, 19, 19, 0x0a, 201, 188, 19, 19, 0x0a, 223, 20, 19, 19, 0x0a, 243, 19, 19, 19, 0x0a, 251, 19, 19, 19, 0x0a, 266, 19, 19, 19, 0x0a, 277, 20, 19, 19, 0x0a, 292, 19, 19, 19, 0x0a, 301, 19, 19, 19, 0x0a, 317, 19, 19, 19, 0x08, // properties: name, type, flags 342, 335, 0x43095103, 364, 358, 0x15095103, 378, 374, 0x02095001, 389, 374, 0x02095103, 0 // eod }; static const char qt_meta_stringdata_CPictureFlowWidget[] = { "CPictureFlowWidget\0\0index\0" "centerIndexChanged(int)\0slideindex\0" "centerItemClicked(int)\0moveLeft()\0" "moveRight()\0image\0addSlide(QImage)\0" "pixmap\0addSlide(QPixmap)\0index,image\0" "setSlide(int,QImage)\0index,pixmap\0" "setSlide(int,QPixmap)\0setCenterIndex(int)\0" "clear()\0showPrevious()\0showNext()\0" "showSlide(int)\0render()\0triggerRender()\0" "updateAnimation()\0QColor\0backgroundColor\0" "QSize\0slideSize\0int\0slideCount\0" "centerIndex\0" }; const QMetaObject CPictureFlowWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_CPictureFlowWidget, qt_meta_data_CPictureFlowWidget, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CPictureFlowWidget::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CPictureFlowWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CPictureFlowWidget::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CPictureFlowWidget)) return static_cast<void*>(const_cast< CPictureFlowWidget*>(this)); return QWidget::qt_metacast(_clname); } int CPictureFlowWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: centerIndexChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: centerItemClicked((*reinterpret_cast< int(*)>(_a[1]))); break; case 2: moveLeft(); break; case 3: moveRight(); break; case 4: addSlide((*reinterpret_cast< const QImage(*)>(_a[1]))); break; case 5: addSlide((*reinterpret_cast< const QPixmap(*)>(_a[1]))); break; case 6: setSlide((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QImage(*)>(_a[2]))); break; case 7: setSlide((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QPixmap(*)>(_a[2]))); break; case 8: setCenterIndex((*reinterpret_cast< int(*)>(_a[1]))); break; case 9: clear(); break; case 10: showPrevious(); break; case 11: showNext(); break; case 12: showSlide((*reinterpret_cast< int(*)>(_a[1]))); break; case 13: render(); break; case 14: triggerRender(); break; case 15: updateAnimation(); break; default: ; } _id -= 16; } #ifndef QT_NO_PROPERTIES else if (_c == QMetaObject::ReadProperty) { void *_v = _a[0]; switch (_id) { case 0: *reinterpret_cast< QColor*>(_v) = backgroundColor(); break; case 1: *reinterpret_cast< QSize*>(_v) = slideSize(); break; case 2: *reinterpret_cast< int*>(_v) = slideCount(); break; case 3: *reinterpret_cast< int*>(_v) = centerIndex(); break; } _id -= 4; } else if (_c == QMetaObject::WriteProperty) { void *_v = _a[0]; switch (_id) { case 0: setBackgroundColor(*reinterpret_cast< QColor*>(_v)); break; case 1: setSlideSize(*reinterpret_cast< QSize*>(_v)); break; case 3: setCenterIndex(*reinterpret_cast< int*>(_v)); break; } _id -= 4; } else if (_c == QMetaObject::ResetProperty) { _id -= 4; } else if (_c == QMetaObject::QueryPropertyDesignable) { _id -= 4; } else if (_c == QMetaObject::QueryPropertyScriptable) { _id -= 4; } else if (_c == QMetaObject::QueryPropertyStored) { _id -= 4; } else if (_c == QMetaObject::QueryPropertyEditable) { _id -= 4; } else if (_c == QMetaObject::QueryPropertyUser) { _id -= 4; } #endif // QT_NO_PROPERTIES return _id; } // SIGNAL 0 void CPictureFlowWidget::centerIndexChanged(int _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void CPictureFlowWidget::centerItemClicked(int _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void CPictureFlowWidget::moveLeft() { QMetaObject::activate(this, &staticMetaObject, 2, 0); } // SIGNAL 3 void CPictureFlowWidget::moveRight() { QMetaObject::activate(this, &staticMetaObject, 3, 0); } QT_END_MOC_NAMESPACE
5a167e2c2cffee6a5f920382572b040f2463950f
132f349e01e0cc8b526b01ddcf6f3199be9e06d1
/Challenges/NotSoMobile.cpp
70e43c2ca5edf0a28f11aa9a1d92cfad9bb5e27a
[]
no_license
vkstrm/prog-challenges
dad4b2cec399ab78c914004e999383800e0b62a8
91c6e8b0486cf3d41a31ec698f4df97f77aa5837
refs/heads/master
2020-03-23T10:00:28.655175
2019-04-26T11:30:13
2019-04-26T11:30:13
141,420,599
0
0
null
null
null
null
UTF-8
C++
false
false
864
cpp
/* ID: 839 */ #include <iostream> #include <string> bool same; int foo() { int wl, dl, wr, dr; int left, right; std::cin >> wl >> dl >> wr >> dr; left = wl; right = wr; if(!wl) { left = foo(); } if(!wr) { right = foo(); } //std::cout << "l * dl: " << l * dl << " r * dr: " << r * dr << "\n"; if(left * dl != right * dr) same = false; return left + right; } int main() { int cases; std::string line; std::cin >> cases; getline(std::cin, line); //Get rid of first blank line while(cases--) { same = true; while(getline(std::cin, line)) { foo(); if(line.empty()) break; } if(same) std::cout << "YES\n"; else std::cout << "NO\n"; if(cases) std::cout << "\n"; } return 0; }
f233213db831e7760f329351ac23b692a4124f5e
c76b8156b33a702dc1a282f87e7ffed9d5975671
/AndroidC++/jni/SpaceGame.cpp
936c3779e2c1846ed17bfbcdc4077530713d7f6d
[ "Apache-2.0" ]
permissive
BenjaminNitschke/MobileCourse
17247a2699f3c22f8b43e44e62861893acb9eda8
802ce81f7cd9ee44b35f13e4da302a9fbd29a2b6
refs/heads/master
2016-09-05T18:59:35.632999
2015-06-20T14:10:15
2015-06-20T14:10:15
37,622,478
1
0
null
null
null
null
UTF-8
C++
false
false
2,147
cpp
#include "SpaceGame.h" #include <functional> #include <algorithm> using namespace SpaceInvaders; SpaceGame::SpaceGame(AAssetManager* assets) : assets(assets) { CreateBackground(); CreateShip(); CreateEnemies(); } void SpaceGame::CreateBackground() { background = std::make_shared<Sprite>(std::make_shared<Texture>(assets, "Background.png"), 0.0f, 0.0f, 2.0f, 1.0f); } void SpaceGame::CreateShip() { ship = std::make_shared<Sprite>(std::make_shared<Texture>(assets, "Ship.png"), 0.0f, -0.8f, 0.075f, 0.075f); missileTexture = std::make_shared<Texture>(assets, "Missile.png"); } void SpaceGame::ControlShip() { if (lastTimeShot < time - 0.33f) FireMissile(); HandleMissiles(); } void SpaceGame::FireMissile() { lastTimeShot = time; activeMissiles.push_back(std::make_shared<Sprite>(missileTexture, shipPosition, -0.67f, 0.02f, 0.02f)); } void SpaceGame::HandleMissiles() { activeMissiles.erase(std::remove_if(activeMissiles.begin(), activeMissiles.end(), [=](std::shared_ptr<Sprite> missile) { return missile->IncreaseY(GetTimeDelta() * 3) || CollidingWithEnemyAndKilledIt(missile); }), activeMissiles.end()); } bool SpaceGame::CollidingWithEnemyAndKilledIt(std::shared_ptr<Sprite> missile) { for (auto enemy : enemies) if (enemy->DistanceTo(missile, enemiesPosition) < 0.05f) { enemy->IncreaseY(1.0f); // Move out of screen return true; } return false; } void SpaceGame::CreateEnemies() { auto enemyTexture = std::make_shared<Texture>(assets, "Enemy.png"); for (float y = 0.7f; y > 0.3f; y -= 0.3f) for (float x = -0.8f; x <= 0.8f; x += 0.2f) enemies.push_back(std::make_shared<Sprite>(enemyTexture, x, y, 0.05f, 0.05f)); } void SpaceGame::MoveEnemies() { enemiesPosition += (enemiesMovingRight ? 0.2f : -0.2f) * GetTimeDelta(); if (enemiesPosition < -0.1f || enemiesPosition > 0.1f) enemiesMovingRight = !enemiesMovingRight; } void SpaceGame::DrawAll() { ControlShip(); MoveEnemies(); if (background) background->Draw(); for (auto missile : activeMissiles) missile->Draw(); if (ship) ship->Draw(shipPosition); for (auto enemy : enemies) enemy->Draw(enemiesPosition); }
ed097021d4ab2abf3ce995d793405d27bad24551
08550fda2375beec7bcc515c5e2df66197728e6f
/td4/td4.cpp
1d0141d5a33a9ae2641517d180b6e674e69cede3
[]
no_license
mihaelatalpos/Td4test
0beb63676ba525d4e6f0dc486d98bea379442430
45c75df4bb94cd0d964043fd88efee42ed821c86
refs/heads/master
2020-04-04T12:05:51.188575
2018-11-02T20:11:57
2018-11-02T20:11:57
155,914,046
0
0
null
null
null
null
ISO-8859-1
C++
false
false
6,839
cpp
/* * Programme qui affiche 5 images fractales produites par systèmes de fonctions itérées. * \file TD4.cpp * \author Sofia Alvarez (1894016) et Mihaela Talpos (1894329) * \date 30 octobre 2018 * Créé le 22 octobre 2018 */ #include <iostream> #include <cmath> #include <cstdlib> #include <ctime> #include "ecrireimage.h" using namespace std; int tests(); int borneDansIntervalle(int valeur, int borneInf, int borneSup); bool estDansIntervalle(int valeur, int borneInf, int borneSup); void dessinePoint(Point2d coordonee, int intensite, Pixel image[tailleY][tailleX]); double aleatoireZeroUn(); int aleatoireSelonDistribution(double prob[]); void transformePoint(double& valeurX, double& valeurY, double transformation[]); void calculerImage(string ficSource, string ficSortie); int main() { tests(); calculerImage("Barnsley fern.txt", "IFS BarnsleyFern.bmp"); calculerImage("Golden dragon agrandi.txt", "IFS Golden dragon agrandi.bmp"); calculerImage("Golden dragon.txt", "IFS Golden dragon.bmp"); calculerImage("Heighway dragon.txt", "IFS Heighway dragon.bmp"); calculerImage("Sierpensky triangle.txt", "IFS Sierpensky triangle.bmp"); } /* * Prend une valeur et vérifie si elle est dans l'intervalle donnée. * Sinon, elle retourne la borne la plus proche de la valeur. * \param [in] valeur, borneInf, borneSup * \return Une valeur dans l'intervalle \p valeur, borneInf ou borneSup. */ int borneDansIntervalle(int valeur, int borneInf, int borneSup) { if (valeur <= borneSup && valeur >= borneInf) return valeur; else if (valeur > borneSup) return borneSup; else return borneInf; } /* * Prend une valeur et vérifie si elle est dans l'intervalle donnée. * \param [in] valeur, borneInf, borneSup * \return Vrai ou faux. */ bool estDansIntervalle(int valeur, int borneInf, int borneSup) { if (valeur <= borneSup && valeur >= borneInf) return true; else return false; } /* * Prend une point et change l'intensité d'une image (tableau) à la coordonnée correspondante. * \param [in] coordonnee, intensite * \param [inout] image * \return void */ void dessinePoint(Point2d coordonee, int intensite, Pixel image[tailleY][tailleX]) { if (estDansIntervalle(coordonee.x, 0, 499) && estDansIntervalle(coordonee.y, 0, 499)) { int nouvelleIntensite = image[(int)coordonee.y][(int)coordonee.x] - intensite; image[(int)coordonee.y][(int)coordonee.x] = borneDansIntervalle(nouvelleIntensite, 0, 255); } } /* * Génère une valeur aléatoire entre 0 et 1. * \return Une valeur aléatoire entre 0 et 1. */ double aleatoireZeroUn() { return rand() % RAND_MAX / (double)RAND_MAX; } /* * Vérifie où se trouve le nombre aléatoire de la fonction précédente * dans la distribution d'un tableau de probabilités cumulatives. * \param [in] prob * \return L'indice de la position de la valeur immédiatement plus grande que le nombre aléatoire \p i. */ int aleatoireSelonDistribution(double prob[]) { double x = aleatoireZeroUn(); int i = 0; while (1) { if (x <= prob[i]) return i; i++; } } /* * Modifie une coordonnée donnée par transformation linéaire selon un tableau de transformation donné. * \param [in] transformation * \param [inout] valeurX, valeurY * \return La coordonnée modifiée selon le tableau de transformation fourni \p valeurX, valeurY */ void transformePoint(double& valeurX, double& valeurY, double transformation[]) { double x = valeurX; double y = valeurY; valeurX = (transformation[0] * x) + (transformation[1] * y) + transformation[4]; valeurY = (transformation[2] * x) + (transformation[3] * y) + transformation[5]; } struct DataDuFichier { int nPtsDepart, nTransfTotal, nTransfDebut, intensite; double transformationAffichage[6]; double transfIFS[10][7]; }; /* * Produit une image fractale par systèmes de fonctions itérées. * \param [in] ficSource * \param [inout] ficSortie * \return void */ void calculerImage(string ficSource, string ficSortie) { DataDuFichier imgSource; ifstream fichier(ficSource); //declaration du tableau de probabilités cumulatives en dehors de la boucle double prob[10]; if (fichier.fail()) cout << "Le fichier n'existe pas."; else { fichier >> imgSource.nPtsDepart >> imgSource.nTransfTotal >> imgSource.nTransfDebut >> imgSource.intensite; for (int i = 0; i < 6; i++) fichier >> imgSource.transformationAffichage[i]; int i = 0; while (!ws(fichier).eof()) { for (int j = 0; j < 7; j++) { fichier >> imgSource.transfIFS[i][j]; if (j == 6) prob[i] = (imgSource.transfIFS[i][j]) / 100.0; } i++; } } Pixel image[tailleX][tailleY]; for (int i = 0; i < 500; i++) { for (int j = 0; j < 500; j++) { image[i][j] = 255; } } Point2d point; for (int i = 0; i < imgSource.nPtsDepart; i++) { point.x = aleatoireZeroUn(); point.y = aleatoireZeroUn(); for (int j = 0; j < imgSource.nTransfTotal; j++) { int indice = aleatoireSelonDistribution(prob); transformePoint(point.x, point.y, imgSource.transfIFS[indice]); if (j >= imgSource.nTransfDebut) { double x = point.x; double y = point.y; transformePoint(x, y, imgSource.transformationAffichage); dessinePoint({ x, y }, imgSource.intensite, image); } } } ecrireImage(image, ficSortie); } // Vérifie si les fonctions sont bien écrites. int tests() { //vérification de borneDansIntervalle cout << "Les valeurs bornees sont : "; for (int i = -1; i <= 4; i++) { int valeur = borneDansIntervalle(i, 1, 3); cout << valeur << " "; } cout << endl; //vérification de estDansIntervalle cout << "La valeur entree est dans l'intervalle : "; for (int i = -1; i <= 4; i++) { bool valeur = estDansIntervalle(i, 1, 3); cout << valeur << " "; } cout << endl; //vérification de dessinePoint Pixel image[tailleX][tailleY]; for (int i = 0; i < 500; i++) { for (int j = 0; j < 500; j++) { image[i][j] = 255; } } dessinePoint({ 10, 10 }, 255, image); dessinePoint({ 20, 15 }, 100, image); dessinePoint({ 30, 20 }, 128, image); dessinePoint({ -1, 1 }, 255, image); dessinePoint({ 500, 1 }, 255, image); dessinePoint({ 1, -1 }, 255, image); dessinePoint({ 1, 500 }, 255, image); dessinePoint({ 30, 20 }, 128, image); ecrireImage(image, "imageTest.bmp"); //vérification de aleatoireSelonDistribution et aleatoireZeroUn int valeurUn = 0; double prob[] = { 0.1, 0.35 , 1.0 }; cout << "L'indice 1 est apparru "; for (int i = 0; i < 1000; i++) { int indice = aleatoireSelonDistribution(prob); if (indice == 1) { valeurUn++; } } cout << valeurUn << " fois." << endl; //verification de transformePoint double transformation[6] = { 0.5, -0.5, 0.25, 0.75, 2.0, 3.0 }; double y = 0.7; double x = 0.2; transformePoint(x, y, transformation); cout << endl << "x: " << x << " y: " << y << endl; return 0; }
b44beb3c6f6ec0ff0dc5a37c7488b0e1e3d40e10
4ae933888b37a6969475d3a1f6d8020bcd4e315a
/mp2/robotest_work.cc
a766fa0627e2100f9a3d74300fe66377322998a3
[]
no_license
mcguiremichael/CS424
3ea31552963bae8b14489a632bad0128f42aca58
b134d288b301da63b9c1f766e9c5656c3f35b9ac
refs/heads/master
2020-11-29T18:54:06.974584
2019-12-26T04:22:43
2019-12-26T04:22:43
230,193,976
0
0
null
null
null
null
UTF-8
C++
false
false
12,072
cc
#include <chrono> #include <iostream> #include <opencv2/calib3d.hpp> #include <opencv2/core.hpp> #include <opencv2/features2d.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/opencv.hpp> #include <opencv2/xfeatures2d.hpp> #include <SerialStream.h> #include "irobot-create.hh" #include <ctime> #include <thread> #include <raspicam/raspicam_cv.h> #include <opencv2/imgproc/imgproc.hpp> #include <mutex> #include <semaphore.h> #include <dirent.h> #include <vector> #include <string> #include <sys/types.h> #include <errno.h> using namespace cv; using namespace cv::xfeatures2d; using std::chrono::duration; using std::chrono::steady_clock; using std::cout; using std::endl; using std::string; using std::vector; using namespace iRobot; using namespace LibSerial; using namespace std; vector<Mat> query_image; bool alignPerspective(vector<Point2f>& query, vector<Point2f>& scene, Mat& img_query, Mat& img_scene, vector<Point2f>& scene_corners); void cropBottom(Mat& img_scene_full, Mat& img_scene, float crop_fraction); void drawProjection(Mat& img_matches, Mat& img_query, vector<Point2f>& scene_corners); string type2str(int type); void usage(); bool object_indetification(Mat img_query, Mat img_scene_full, float keep_top_fraction); void getFiles (string dir, vector<Mat> &files) { files.clear(); DIR *dp; struct dirent *dirp; if((dp = opendir(dir.c_str())) == NULL) { cout << "Error(" << errno << ") opening " << dir << endl; return ; } while ((dirp = readdir(dp)) != NULL) { string file_name(string(dirp->d_name)); string end = ".jpg"; if(file_name.find(end) != string::npos){ Mat imgfile = imread(dir+file_name,IMREAD_GRAYSCALE); files.push_back(imgfile); } //files.push_back(string(dirp->d_name)); } closedir(dp); return ; } void init_Image(){ getFiles("object_identification/query-image/",query_image); } int main() { //char serial_loc[] = "/dev/ttyUSB0"; try { // Keep this //std::thread mythread = std::thread(thread_test); //cout << "mythread" << mythread.get_id() << endl; // Keep this // pthread_cancel(mythread.native_handle()); raspicam::RaspiCam_Cv Camera; cv::Mat rgb_image, bgr_image; if (!Camera.open()) { cerr << "Error opening the camera" << endl; return -1; } //Make sure various robot components are set up correctly cout << "Opened Camera" << endl; cv::Mat img_capture,img_scene; Camera.grab(); Camera.retrieve(img_capture); cvtColor( img_capture, img_scene, CV_BGR2GRAY ); cv::imwrite("irobot_capture.jpg",img_scene ); getFiles("object_identification/query-image/",query_image); for(int i = 0; i<query_image.size(); i++){ bool res = object_indetification(query_image[i],img_scene,0.85); if(res){ cout<<"Object Matched !!"<<endl; cv::imwrite("irobot_image.jpg",img_scene ); //delete the mathced element from the query_image list } else { cout << "Image not matched !!"<<endl; } } } catch (InvalidArgument &e) { cerr << e.what() << endl; return 3; } catch (CommandNotAvailable &e) { cerr << e.what() << endl; return 4; } } bool object_indetification(Mat img_query, Mat img_scene_full, float keep_top_fraction) { if(!img_query.data || !img_scene_full.data) { cout<< "Error reading images" << endl; return -1; } Mat img_scene; // Crop bottom // Images taken by mounting the camera on the robot will have some portion // of the side of the robot at the bottom. To reduce ambiguity during // detection and to speed up feature extraction, we crop it. // The fraction of cropping will be different depending on where the camera // is mounted on the robot. We find the useful portion of the picture is // the top 62.5% when camera mounted on front. When camera mounted on the // left side its the top 85% that contains useful information. cropBottom(img_scene_full, img_scene, keep_top_fraction); // Detect the keypoints and extract descriptors using SURF // Surf keypoint detector and descriptor. int minHessian = 100; int nOctaves = 4; int nOctaveLayers = 3; Ptr<SURF> detector = SURF::create( minHessian, nOctaves, nOctaveLayers, true); vector<KeyPoint> keypoints_query, keypoints_scene; Mat descriptors_query, descriptors_scene; auto sttime = steady_clock::now(); detector->detectAndCompute( img_query, Mat(), keypoints_query, descriptors_query); cout << "Feature extraction query image " << (duration <double>(steady_clock::now() - sttime)).count() << " sec" << endl; sttime = steady_clock::now(); detector->detectAndCompute( img_scene, Mat(), keypoints_scene, descriptors_scene); cout << "Feature extraction scene image " << (duration <double>(steady_clock::now() - sttime)).count() << " sec" << endl; sttime = steady_clock::now(); // Matching descriptor vectors using Brute Force matcher BFMatcher matcher(NORM_L2); vector<vector<DMatch>> matches; matcher.knnMatch(descriptors_query, descriptors_scene, matches, 2); vector<DMatch> good_matches; for(int i = 0; i < descriptors_query.rows; i++) { if (matches[i][0].distance < 0.75 * matches[i][1].distance) good_matches.push_back(matches[i][0]); } // Find the location of the query in the scene vector<Point2f> query; vector<Point2f> scene; for(size_t i = 0; i < good_matches.size(); i++) { query.push_back(keypoints_query[good_matches[i].queryIdx].pt); scene.push_back(keypoints_scene[good_matches[i].trainIdx].pt); } vector<Point2f> scene_corners(4); bool res = alignPerspective( query, scene, img_query, img_scene, scene_corners); if(res){ //store the image } return res; /*cout << "Matching and alignment " << (duration <double>(steady_clock::now() - sttime)).count() << " sec" << endl; // Write output to file Mat img_matches; drawMatches(img_query, keypoints_query, img_scene, keypoints_scene, good_matches, img_matches, Scalar::all(-1), Scalar::all(-1), vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); // Fill the extra area in almost white (Saves ink when printing) if (img_query.rows < img_scene.rows) { rectangle(img_matches, Point2f(0, img_query.rows), Point2f(img_query.cols - 1, img_scene.rows - 1), Scalar(255, 240, 240), CV_FILLED); } else if (img_scene.rows < img_query.rows) { rectangle(img_matches, Point2f(img_query.cols, img_scene.rows), Point2f(img_query.cols + img_scene.cols - 1, img_query.rows - 1), Scalar(255, 240, 240), CV_FILLED); } if (res) { cout << "Object found" << endl; drawProjection(img_matches, img_query, scene_corners); } else { cout << "Object not found" << endl; } // Write result to a file cv::imwrite(output_file, img_matches);*/ } // return 0; void cropBottom(Mat& img_scene_full, Mat& img_scene, float crop_fraction) { // Crop the lower part of the scene cv::Rect crop; crop.x = 0; crop.y = 0; crop.width = img_scene_full.size().width; crop.height = img_scene_full.size().height * crop_fraction; img_scene = img_scene_full(crop); } bool alignPerspective(vector<Point2f>& query, vector<Point2f>& scene, Mat& img_query, Mat& img_scene, vector<Point2f>& scene_corners) { Mat H = findHomography(query, scene, RANSAC); if (H.rows == 0 && H.cols == 0) { cout << "Failed rule0: Empty homography" << endl; return false; } vector<Point2f> query_corners(4); query_corners[0] = cvPoint(0,0); query_corners[1] = cvPoint(img_query.cols, 0); query_corners[2] = cvPoint(img_query.cols, img_query.rows); query_corners[3] = cvPoint(0, img_query.rows ); perspectiveTransform(query_corners, scene_corners, H); float min_area = 32.0 * 32.0; double max_area = img_scene.rows * img_scene.cols; float ratio_inside = 0.75; float min_angle_sin = 0.173; // Minimum 10 degree angle required // Geometric verification heuristics // Rule 1: Must be a convex hull. // Rule 2: Area can’t be less than 32x32 // Rule 3: The detected projection can’t have more than 100% area // Rule 4: Projection can't contain very small angle < 10 degree // Rule 5: More than 75% of the area of the detected projection should have // to be within image bounds // Rule 1: Must be a convex hull. vector<Point2f> sc_vec(4); // Generate 4 vectors from the 4 scene corners for(int i = 0; i < 4; i++) { sc_vec[i] = scene_corners[(i + 1) % 4] - scene_corners[i]; } vector<float> sc_cross(4); // Calculate cross product of pairwise vectors for(int i = 0; i < 4; i++) { sc_cross[i] = sc_vec[i].cross(sc_vec[(i+1) % 4]); } // Check for convex hull if (!(sc_cross[0] < 0 && sc_cross[1] < 0 && sc_cross[2] < 0 && sc_cross[3] < 0) && !(sc_cross[0] > 0 && sc_cross[1] > 0 && sc_cross[2] > 0 && sc_cross[3] > 0)) { cout << "Failed rule1: Not a convex hull" << endl; return false; } // Rule 2: Area can’t be less than 32x32 // Rule 3: The detected projection can’t have more than 100% area float area = (sc_cross[0] + sc_cross[2]) / 2.0; if (fabs(area) < min_area) { cout << "Failed rule2: Projection too small" << endl; return false; } else if (fabs(area) > max_area) { cout << "Failed rule3: Projection too large" << endl; return false; } // Rule 4: Can't contain very small angle < 10 degree inside projection. // Check for angles vector<float> sc_norm(4); for (int i = 0; i < 4; i++) { sc_norm[i] = norm(sc_vec[i]); } for (int i = 0; i < 4; i++) { float sint = sc_cross[i] / (sc_norm[i] * sc_norm[(i + 1) % 4]); if (fabs(sint) < min_angle_sin) { cout << "Failed rule4: Contains very small angle" << endl; return false; } } // Rule 5: More than 75% of the area of the detected projection should // have to be within image bounds. // Approximate mechanism by determining the bounding rectangle. cv::Rect bound = boundingRect(scene_corners); cv::Rect scene_rect(0.0, 0.0, img_scene.cols, img_scene.rows); cv::Rect isect = bound & scene_rect; if (isect.width * isect.height < ratio_inside * bound.width * bound.height ) { cout << "Failed rule5: Large proportion outside scene" << endl; return false; } return true; } // Show the projection void drawProjection(Mat& img_matches, Mat& img_query, vector<Point2f>& scene_corners) { line(img_matches, scene_corners[0] + Point2f(img_query.cols, 0), scene_corners[1] + Point2f(img_query.cols, 0), Scalar(0, 255, 0), 4); line(img_matches, scene_corners[1] + Point2f(img_query.cols, 0), scene_corners[2] + Point2f(img_query.cols, 0), Scalar(0, 255, 0), 4); line(img_matches, scene_corners[2] + Point2f(img_query.cols, 0), scene_corners[3] + Point2f(img_query.cols, 0), Scalar(0, 255, 0), 4); line(img_matches, scene_corners[3] + Point2f(img_query.cols, 0), scene_corners[0] + Point2f(img_query.cols, 0), Scalar(0, 255, 0), 4); } string type2str(int type) { std::string r; uchar depth = type & CV_MAT_DEPTH_MASK; uchar chans = 1 + (type >> CV_CN_SHIFT); switch (depth) { case CV_8U: r = "8U"; break; case CV_8S: r = "8S"; break; case CV_16U: r = "16U"; break; case CV_16S: r = "16S"; break; case CV_32S: r = "32S"; break; case CV_32F: r = "32F"; break; case CV_64F: r = "64F"; break; default: r = "User"; break; } r += "C"; r += (chans + '0'); return r; } void usage() { cout << " Usage: ./robovision <query-image> <crop-bottom>" << endl; }
e16581b0fc08194d88021eb65236f21bc1eaa0d3
17bfead5d654d6b71d3b2c70bf053fac0d9d6ff3
/collectives/AllgathervBench.h
57626462e82b15925634f5dd5ca403c8615dee73
[]
no_license
jgphpc/jub1
763a2e22f5520511e159a33e42e17dfebd1ce601
ab98a74077b2ea9774a3b170d325d0b57dc04d21
refs/heads/master
2016-09-09T18:22:31.960327
2015-01-07T15:01:22
2015-01-07T15:01:22
28,918,764
0
0
null
null
null
null
UTF-8
C++
false
false
601
h
#ifndef __Allgatherv_BENCH_H__ #define __Allgatherv_BENCH_H__ #include "CollectivesBench.h" namespace CMSB { /** * Represents Allgatherv benchmark. */ class AllgathervBench : public CMSB::CollectivesBench { public: AllgathervBench (unsigned int messageSize); virtual ~AllgathervBench (); virtual void init (MPI_Comm worldComm, CMSB::MicroBench::MicroBenchInfo* benchInfo); virtual const char* getMicroBenchName () const; virtual void writeResultToProfile () const; protected: virtual void performMPICollectiveFunc (); }; } #endif // __Allgatherv_BENCH_H__
d195874ce03d59b94b2b89845fa0d168657922e0
7605544c28082e1a1f1f5e61645fc23ecafc930f
/src/ipuerta_comp/ArgParser.h
637b5ec4af5ea24cf39d979d556aea16de12ecac
[]
no_license
diegonc/Sistemas-Distribuidos-TP-Museo
46ed94d280685139b8192f2e07b74b9674881ce1
35cad26e8136bad1f5793dbf71a8b9e5fd70964a
refs/heads/master
2021-01-20T19:48:58.702778
2015-08-04T02:36:00
2015-08-04T02:36:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
672
h
#ifndef ARGPARSER_H #define ARGPARSER_H #include <argp.h> #include <string> #include <utils/NonCopyable.h> class ArgParser : private NonCopyable { private: std::string _idServer; std::string _broker; std::string _recursos; int _idLocal; ArgParser(); ~ArgParser(); friend int parserFunc (int key, char *arg, struct argp_state *state); public: static ArgParser& getInstance(); void parse (int argc, char **argv); const std::string& idServer () const { return _idServer; } const std::string& broker () const { return _broker; } const std::string& recursos () const { return _recursos; } int idLocal () const { return _idLocal; } }; #endif
875fd04293dc4437a12c9f21d97492a8fbd1a305
9f647e28ca39804e11bb2c1dac8e780de1d0e2b3
/src/game/main.cpp
aff01187836538943a08c2ae8eb0420c6d3d0bb7
[]
no_license
AshMagorian/ComputeShaderParticles
128782c56c7399e184b47c24676af91a1789177f
775547de1609de067671b820ccd22231ac7f6ed7
refs/heads/master
2022-10-21T20:21:48.399913
2020-06-16T14:41:43
2020-06-16T14:41:43
272,299,977
0
0
null
null
null
null
UTF-8
C++
false
false
169
cpp
#include <CSEngine/CSEngine.h> int main(int argc, char *argv[]) { std::shared_ptr<Application> application = Application::Init(); application->Run(); return 0; }
41eb0090a66d6c7635b2b83bfe9065c2ead8ac98
4fe4d00c0c9a98d888d1626dedfbf8bd06451e2a
/computorv1/src/token.cpp
49f3bf140009c9dd5bcde36bcc135d95c7ab9137
[]
no_license
gguichard/42-workspace
00234e3e1108d1e0f2b7de067b875713df6b6362
9fafb1f3f536f2277cb454cb96a306504dd178b4
refs/heads/master
2021-07-10T13:02:37.527351
2020-06-25T07:40:59
2020-06-25T07:40:59
156,335,619
0
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
#include <string> #include <ostream> #include "token.hpp" Token::Token(Token::Type type, std::string lexeme) : m_type(type), m_lexeme(lexeme) { } Token::Type Token::type() const { return m_type; } const std::string &Token::lexeme() const { return m_lexeme; } bool Token::isType(Token::Type tokenType) const { return m_type == tokenType; } std::ostream &operator<<(std::ostream &os, const Token &token) { os << token.m_lexeme; return os; }
276bc6026877dcc5f23b7a7ad566f4bef699a634
91d6c82cf7e7c86f1770786033f91edc039535fa
/PlayBox/dev/prj/PlayBox/src/AppConfig/config/SetBaseCtrls/SetBaseButton.cpp
94d303558867c02d9ebf9e6f966aa01cabea203a
[]
no_license
linjianbjfu/PlayBox
147c23ab304e9cc94d7b5a430c97fdc847e1819d
83672444459b21d91ad68a9e6c1b4b9c04b18da8
refs/heads/master
2020-05-19T11:03:33.892941
2013-03-25T16:01:28
2013-03-25T16:01:28
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
624
cpp
#include "stdafx.h" #include "SetBaseButton.h" // SetBaseButton IMPLEMENT_DYNAMIC(SetBaseButton, CButton) SetBaseButton::SetBaseButton() { } SetBaseButton::~SetBaseButton() { } BEGIN_MESSAGE_MAP(SetBaseButton, CButton) //ON_WM_CTLCOLOR_REFLECT() //ON_WM_ERASEBKGND() END_MESSAGE_MAP() HBRUSH SetBaseButton::CtlColor( CDC* pDC, UINT nCtlColor ) { pDC->SetBkMode( TRANSPARENT ); pDC->SetBkColor( RGB(255,255,255) ); pDC->SetTextColor( RGB(0,0,0) ); HBRUSH hbr = ::CreateSolidBrush( RGB(255,255,255) ); return hbr; } BOOL SetBaseButton::OnEraseBkgnd(CDC* pDC) { //½ûÖ¹»æÖƵ×É« return TRUE; }
bd346bc97c33325f7e9aaf3495630b3704d31d07
6802c917823fa477961958f7b23eb6c94a31977e
/2d matrix search.cpp
3e2c3edf5189f60b9d0c6ae90c697c6389c1fc03
[]
no_license
seothichowdhury/my-codes
1506839ee4bc8318a06be73487693e7f9e66b522
f8fc55c186afcd095c9ea47f43afa7ab22585fe2
refs/heads/main
2023-07-15T06:38:07.432467
2021-08-30T11:37:51
2021-08-30T11:37:51
401,320,786
0
0
null
null
null
null
UTF-8
C++
false
false
431
cpp
#include<iostream> using namespace std; int main() { int n, m; cin >> n >> m; int target; cin >> target; int mat[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> mat[i][j]; } } bool found = false; int r = 0, c = n - 1; while (r < n && c >= 0) { if (mat[r][c] == target) { found = true; } mat[r][c] > target ? c-- : r++; } if (found) cout << "Found"; else cout << "Not Found"; }
d69c217f195c2d9a85e2ef4ec29eb06f82e331aa
ec68c973b7cd3821dd70ed6787497a0f808e18e1
/Cpp/SDK/Emote_Storytelling_classes.h
eb4177a941af99502d6336847065e97afe3e47c1
[]
no_license
Hengle/zRemnant-SDK
05be5801567a8cf67e8b03c50010f590d4e2599d
be2d99fb54f44a09ca52abc5f898e665964a24cb
refs/heads/main
2023-07-16T04:44:43.113226
2021-08-27T14:26:40
2021-08-27T14:26:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
688
h
#pragma once // Name: Remnant, Version: 1.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Emote_Storytelling.Emote_Storytelling_C // 0x0000 class UEmote_Storytelling_C : public UDialog_Emote { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Emote_Storytelling.Emote_Storytelling_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
d98e638425382a14eee850733a999b9f378d3ba0
e740520065b12eb15e0e59b16362679464b69c42
/LintCode/LintCode/RotateString.cpp
06e130329a06237b10c7c625b05639f17cc460ad
[]
no_license
watsonyanghx/algorithm
ad8fa73ec1672129879bd761e8990a20919106bf
afea8ea4f9f22ac049e9229e64de4905f6939668
refs/heads/master
2021-06-18T08:31:54.164042
2017-03-13T10:57:41
2017-03-13T10:57:41
53,142,005
0
0
null
null
null
null
UTF-8
C++
false
false
774
cpp
#include <stdio.h> #include <stdlib.h> #include <vector> using namespace std; class Solution { public: /** * @param str: a string * @param offset: an integer * @return: nothing */ void rotateString(string &str, int offset) { //wirte your code here string s = trim(str); if (s == "") return; string tem = ""; int n = offset % str.size(); for (int i = 0; i < n; i++) { tem = str[str.size() - 1]; str.insert(0, tem); str.erase(str.size() - 1); } } string& trim(string s) { if (s.empty()) { return s; } s.erase(0, s.find_first_not_of(" ")); s.erase(s.find_last_not_of(" ") + 1); return s; } };
51f963a89bf62fc52fc7ccc5dbe6fe79ace608e6
24a0e0b288ee1e30f9285d1719a13fabef0e320b
/inheritance 1.cpp
8844c284ab23c35ef7ccb50bb30c5cf92ef0358b
[]
no_license
utkarsh235/CPP-Programming
db3569a8ad5e6605462147583346566245ddaa56
d8faa7089d7fbb4ef6a7bb328c10fa78a7ed1751
refs/heads/main
2023-03-05T21:07:07.952797
2021-02-13T19:28:35
2021-02-13T19:28:35
330,452,704
0
0
null
null
null
null
UTF-8
C++
false
false
536
cpp
#include<iostream> using namespace std; class stud1 { public : int a; void getdata() { cout << "enter the value of a "; cin >> a; } }; class stud2 : public stud1 { public : int b; void showdata() { cout << "the value of a entered is " << a; b = a; } }; class stud3 : public stud1 , public stud2 { public : void print() { showdata(); } }; int main() { stud3 obj; obj.getdata(); obj.showdata(); obj.print(); return 0 ; }
c6774f9e646b3b2a8a2a4f7ea27e19ac111f67c6
bc1584aa5dbd7d7dac2dd895c92ee2b0dcf581fc
/src/Mixer.cc
80d1a13aeb4dcfaa99dd9bf165b4c6d19b1d0ca1
[]
no_license
ColinKinloch/Muzak
e00a770c56ca19b1d94574d8f43d9b659fbcbaec
ad777d3c4df2de4d96e18985a326f7151651a09c
refs/heads/master
2018-12-28T17:35:21.375538
2014-10-29T01:16:52
2014-10-29T01:16:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
886
cc
// Copyright © 2014 Colin Kinloch <[email protected]> - All Rights Reserved // Licence in LICENSE #include <Muzak/Mixer.hh> #include <cstdio> Muzak::Mixer::Mixer(): Muzak::Mixer::Mixer(0.f) {} Muzak::Mixer::Mixer(double Rate): Muzak::Node::Node(Rate) { tempSize = 0; tempBuff = new float[tempSize](); } Muzak::Mixer::~Mixer() { delete tempBuff; } void Muzak::Mixer::update(double t, long frames) { Muzak::Node::update(t, frames); if(tempSize<frames) { delete tempBuff; tempSize = frames; tempBuff = new float[tempSize]; } for(int i=0; i<frames; i++) tempBuff[i] = 0.f; auto it = inputs.begin(); auto end = inputs.end(); for(;it!=end;it++) { (*it)->update(t, frames); float* inbuff = (*it)->getBuffer(); for(int i=0;frames>i;i++) tempBuff[i] += inbuff[i]; } for(int i=0;frames>i;i++) buffer[i] = tempBuff[i]; }
94ff011e7624f50caab788a85da5f6ae315d049b
e2f17433b6cf978ad98b7a1277375a8b1c44aff3
/libboost_actor_core/src/singletons.cpp
f68f883a88ee82cf5bc7e1e5d97487b6777278a0
[ "BSL-1.0" ]
permissive
nk0leg/boost.actor
dd01bc36704e560660981fefcd0e2370fad15111
6b39bbf859007308cf4e20e62d3d31b1dae56b84
refs/heads/master
2021-01-12T08:22:01.320872
2015-08-31T15:44:29
2015-08-31T15:44:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,818
cpp
/******************************************************************************\ * * * ____ _ _ _ * * | __ ) ___ ___ ___| |_ / \ ___| |_ ___ _ __ * * | _ \ / _ \ / _ \/ __| __| / _ \ / __| __/ _ \| '__| * * | |_) | (_) | (_) \__ \ |_ _ / ___ \ (__| || (_) | | * * |____/ \___/ \___/|___/\__(_)_/ \_\___|\__\___/|_| * * * * * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include <atomic> #include "boost/actor/message.hpp" #include "boost/actor/exception.hpp" #include "boost/actor/scheduler.hpp" #include "boost/actor/local_actor.hpp" #include "boost/actor/scheduler/abstract_coordinator.hpp" #include "boost/actor/detail/logging.hpp" #include "boost/actor/detail/singletons.hpp" #include "boost/actor/detail/group_manager.hpp" #include "boost/actor/detail/actor_registry.hpp" #include "boost/actor/detail/uniform_type_info_map.hpp" namespace boost { namespace actor { namespace detail { namespace { std::atomic<abstract_singleton*> s_plugins[singletons::max_plugins]; std::mutex s_plugins_mtx; std::atomic<scheduler::abstract_coordinator*> s_scheduling_coordinator; std::mutex s_scheduling_coordinator_mtx; std::atomic<uniform_type_info_map*> s_uniform_type_info_map; std::mutex s_uniform_type_info_map_mtx; std::atomic<actor_registry*> s_actor_registry; std::mutex s_actor_registry_mtx; std::atomic<group_manager*> s_group_manager; std::mutex s_group_manager_mtx; std::atomic<node_id::data*> s_node_id; std::mutex s_node_id_mtx; std::atomic<logging*> s_logger; std::mutex s_logger_mtx; } // namespace <anonymous> abstract_singleton::~abstract_singleton() { // nop } std::mutex& singletons::get_plugin_mutex() { return s_plugins_mtx; } void singletons::stop_singletons() { // stop singletons, i.e., make sure no background threads/actors are running BOOST_ACTOR_LOGF_DEBUG("stop plugins"); for (auto& plugin : s_plugins) { stop(plugin); } BOOST_ACTOR_LOGF_DEBUG("stop group manager"); stop(s_group_manager); BOOST_ACTOR_LOGF_DEBUG("stop actor registry"); stop(s_actor_registry); BOOST_ACTOR_LOGF_DEBUG("stop scheduler"); stop(s_scheduling_coordinator); BOOST_ACTOR_LOGF_DEBUG("wait for all detached threads"); scheduler::await_detached_threads(); // dispose singletons, i.e., release memory BOOST_ACTOR_LOGF_DEBUG("dispose plugins"); for (auto& plugin : s_plugins) { dispose(plugin); } BOOST_ACTOR_LOGF_DEBUG("dispose group manager"); dispose(s_group_manager); BOOST_ACTOR_LOGF_DEBUG("dispose scheduler"); dispose(s_scheduling_coordinator); BOOST_ACTOR_LOGF_DEBUG("dispose registry"); dispose(s_actor_registry); // final steps BOOST_ACTOR_LOGF_DEBUG("stop and dispose logger, bye"); stop(s_logger); stop(s_uniform_type_info_map); stop(s_node_id); dispose(s_logger); dispose(s_uniform_type_info_map); dispose(s_node_id); } actor_registry* singletons::get_actor_registry() { return lazy_get(s_actor_registry, s_actor_registry_mtx); } uniform_type_info_map* singletons::get_uniform_type_info_map() { return lazy_get(s_uniform_type_info_map, s_uniform_type_info_map_mtx); } group_manager* singletons::get_group_manager() { return lazy_get(s_group_manager, s_group_manager_mtx); } scheduler::abstract_coordinator* singletons::get_scheduling_coordinator() { // when creating the scheduler, make sure the registry // is in place as well, because our shutdown sequence assumes // a certain order for stopping singletons auto f = []() -> scheduler::abstract_coordinator* { get_actor_registry(); return scheduler::abstract_coordinator::create_singleton(); }; return lazy_get(s_scheduling_coordinator, s_scheduling_coordinator_mtx, f); } bool singletons::set_scheduling_coordinator(scheduler::abstract_coordinator*p) { auto f = [p]() -> scheduler::abstract_coordinator* { get_actor_registry(); // see comment above return p; }; auto x = lazy_get(s_scheduling_coordinator, s_scheduling_coordinator_mtx, f); return x == p; } node_id singletons::get_node_id() { return node_id{lazy_get(s_node_id, s_node_id_mtx)}; } bool singletons::set_node_id(node_id::data* ptr) { auto res = lazy_get(s_node_id, s_node_id_mtx, [ptr] { return ptr; }); return res == ptr; } logging* singletons::get_logger() { return lazy_get(s_logger, s_logger_mtx); } std::atomic<abstract_singleton*>& singletons::get_plugin_singleton(size_t id) { BOOST_ACTOR_ASSERT(id < max_plugins); return s_plugins[id]; } } // namespace detail } // namespace actor } // namespace boost
700a47e940c26c8af1162a68109ed281c5d349bd
5bccf2d2118008c0af6a51a92a042e967e4f2abe
/Support/Modules/RapidJSON/stringbuffer.h
cc7501561fc5481fc76be25262e3385effdeb016
[ "Apache-2.0", "MIT" ]
permissive
graphisoft-python/DGLib
fa42fadebedcd8daaddde1e6173bd8c33545041d
66d8717eb4422b968444614ff1c0c6c1bf50d080
refs/heads/master
2020-06-13T21:38:18.089834
2020-06-12T07:27:54
2020-06-12T07:27:54
194,795,808
3
0
Apache-2.0
2020-06-12T07:27:55
2019-07-02T05:45:00
C++
UTF-8
C++
false
false
1,323
h
#ifndef RAPIDJSON_STRINGBUFFER_H_ #define RAPIDJSON_STRINGBUFFER_H_ #include "rapidjson.h" #include "internal/stack.h" namespace rapidjson { //! Represents an in-memory output stream. /*! \tparam Encoding Encoding of the stream. \tparam Allocator type for allocating memory buffer. \implements Stream */ template <typename Encoding, typename Allocator = CrtAllocator> struct GenericStringBuffer { typedef typename Encoding::Ch Ch; GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} void Put(Ch c) { *stack_.template Push<Ch>() = c; } void Clear() { stack_.Clear(); } const char* GetString() const { // Push and pop a null terminator. This is safe. *stack_.template Push<Ch>() = '\0'; stack_.template Pop<Ch>(1); return stack_.template Bottom<Ch>(); } size_t Size() const { return stack_.Size(); } static const size_t kDefaultCapacity = 256; mutable internal::Stack<Allocator> stack_; }; typedef GenericStringBuffer<UTF8<> > StringBuffer; //! Implement specialized version of PutN() with memset() for better performance. template<> inline void PutN(GenericStringBuffer<UTF8<> >& stream, char c, size_t n) { memset(stream.stack_.Push<char>(n), c, n * sizeof(c)); } } // namespace rapidjson #endif // RAPIDJSON_STRINGBUFFER_H_
[ "445212619@qqcom" ]
445212619@qqcom
338588698db1d56a25b6d73e5d20a6770043f809
1b5f95f026c7df33209c3176ab35a89c00af4161
/mt_2.hpp
11cd62f79de8f3e827e924a5ce45bd0b9be7841b
[ "BSL-1.0" ]
permissive
alexey-malov/course-nimble_cpp
40aaf5487e25fda01067e1f4729e51d24161e7e4
8059da2a78b958b108c9e1ada1b7dc1f17126c69
refs/heads/master
2020-03-19T01:25:46.716786
2018-04-19T15:53:24
2018-04-19T15:53:24
135,544,607
1
0
null
2018-05-31T06:55:29
2018-05-31T06:55:29
null
UTF-8
C++
false
false
2,072
hpp
#include "util.hpp" //////////////////////////// TASK 2 //////////////////////////// struct naive_read_write_var_t { std::atomic<int> variable{0}; int load() const { return variable; } void store(int i) { variable = i; } } naive_read_write_var; struct optim_read_write_var_t { std::atomic<int> variable{0}; int load() const { return variable.load(); } void store(int i) { variable.store(i); } } optim_read_write_var; //////////////////////////// DETAIL //////////////////////////// enum class bench_t { LOAD, STORE, LOAD_STORE }; template <class Functor> static void mt_load_store(benchmark::State& state, bench_t t, Functor& f) { const std::size_t iteratrions_count = 8 << 10; const auto do_stores = [&f,iteratrions_count](){ for (unsigned i = 0; i < iteratrions_count; ++i) { f.store(i); } }; const auto do_loads = [&f,iteratrions_count](){ for (unsigned i = 0; i < iteratrions_count; ++i) { const int val = f.load(); benchmark::DoNotOptimize(val); } }; switch (t) { case bench_t::LOAD: for (auto _ : state) { do_loads(); do_loads(); do_loads(); do_loads(); }; break; case bench_t::STORE:for (auto _ : state) { do_stores(); do_stores(); do_stores(); do_stores(); }; break; default: for (auto _ : state) { do_loads(); do_loads(); do_loads(); do_stores(); }; break; } } BENCH(mt_load_store, naive_LOAD, bench_t::LOAD, naive_read_write_var)->ThreadRange(1, 8); BENCH(mt_load_store, optim_LOAD, bench_t::LOAD, optim_read_write_var)->ThreadRange(1, 8); BENCH(mt_load_store, naive_STORE, bench_t::STORE, naive_read_write_var)->ThreadRange(1, 8); BENCH(mt_load_store, optim_STORE, bench_t::STORE, optim_read_write_var)->ThreadRange(1, 8); BENCH(mt_load_store, naive_MIXED, bench_t::LOAD_STORE, naive_read_write_var)->ThreadRange(1, 8); BENCH(mt_load_store, optim_MIXED, bench_t::LOAD_STORE, optim_read_write_var)->ThreadRange(1, 8);